1 | const {
|
2 | getQueryParams,
|
3 | } = require('./util');
|
4 |
|
5 | function UrlParser() {
|
6 | for (const key of [
|
7 | 'parseProvider',
|
8 | 'parse',
|
9 | 'bind',
|
10 | 'create',
|
11 | ]) {
|
12 | this[key] = this[key].bind(this);
|
13 | }
|
14 | this.plugins = {};
|
15 | }
|
16 |
|
17 | module.exports = UrlParser;
|
18 |
|
19 | UrlParser.prototype.parseProvider = function(url) {
|
20 | var match = url.match(
|
21 | /(?:(?:https?:)?\/\/)?(?:[^.]+\.)?(\w+)\./i
|
22 | );
|
23 | return match ? match[1] : undefined;
|
24 | };
|
25 |
|
26 | UrlParser.prototype.parse = function(url) {
|
27 | if (typeof url === 'undefined') {
|
28 | return undefined;
|
29 | }
|
30 | var provider = this.parseProvider(url);
|
31 | var result;
|
32 | var plugin = this.plugins[provider];
|
33 | if (!provider || !plugin || !plugin.parse) {
|
34 | return undefined;
|
35 | }
|
36 | result = plugin.parse.call(
|
37 | plugin, url, getQueryParams(url)
|
38 | );
|
39 | if (result) {
|
40 | result = removeEmptyParameters(result);
|
41 | result.provider = plugin.provider;
|
42 | }
|
43 | return result;
|
44 | };
|
45 |
|
46 | UrlParser.prototype.bind = function(plugin) {
|
47 | this.plugins[plugin.provider] = plugin;
|
48 | if (plugin.alternatives) {
|
49 | for (var i = 0; i < plugin.alternatives.length; i += 1) {
|
50 | this.plugins[plugin.alternatives[i]] = plugin;
|
51 | }
|
52 | }
|
53 | };
|
54 |
|
55 | UrlParser.prototype.create = function(op) {
|
56 | var vi = op.videoInfo;
|
57 | var params = op.params;
|
58 | var plugin = this.plugins[vi.provider];
|
59 |
|
60 | params = (params === 'internal') ? vi.params : params || {};
|
61 |
|
62 | if (plugin) {
|
63 | op.format = op.format || plugin.defaultFormat;
|
64 | if (plugin.formats.hasOwnProperty(op.format)) {
|
65 | return plugin.formats[op.format].apply(plugin, [vi, Object.assign({}, params)]);
|
66 | }
|
67 | }
|
68 | return undefined;
|
69 | };
|
70 |
|
71 | function removeEmptyParameters(result) {
|
72 | if (result.params && Object.keys(result.params).length === 0) {
|
73 | delete result.params;
|
74 | }
|
75 | return result;
|
76 | } |
\ | No newline at end of file |