-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
191 lines (168 loc) · 4.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
'use strict';
const is = require('valido');
const axios = require('axios');
const Promise = require('bluebird');
const createError = require('custom-error-generator');
const soundcloud = require('./providers/soundcloud');
const spotify = require('./providers/spotify');
const vimeo = require('./providers/vimeo');
const youtube = require('./providers/youtube');
const providers = [soundcloud, spotify, vimeo, youtube];
const RequestError = createError('RequestError');
/**
* Factory that return Embedify instance
*
* @param {Object} [options]
* @returns {Embedify}
*/
function create(options) {
return new Embedify(options);
}
/**
* Constructor
*
* @param {Object} [options]
*/
function Embedify(options) {
this.providers = providers;
this.RequestError = RequestError;
this.parse = !(options && options.parse === false);
this.failSoft = options && options.failSoft === true;
this.client = options && options.client ? options.client : axios;
this.concurrency = options && is.natural(options.concurrency) ? options.concurrency : 10;
}
/**
* Gets the oEmbed information for a URL
* or list of URLs
*
* @param {String|Array} urls
* @returns {Promise}
*/
Embedify.prototype.get = function get(urls) {
const concurrency = this.concurrency;
return Promise.map(this.ensureUrls(urls), url => this.tryResolve(url), { concurrency })
.then(results => results.filter(r => is.existy(r)));
};
/**
* Tries to resolve oEmbed information for a URL
*
* @param {String} url
* @returns {Promise<Object>}
*/
Embedify.prototype.tryResolve = function tryResolve(url) {
return Promise.resolve()
.then(() => {
let match = null;
providers.some(provider => {
provider.regExp.some(re => {
const reMatch = url.match(re);
if (is.array(reMatch) && reMatch.length) {
match = {
url: provider.transform(reMatch),
apiUrl: provider.apiUrl,
};
}
return is.existy(match);
});
return is.existy(match);
});
return match ? this.fetch(match.apiUrl, match.url) : null;
});
};
/**
* Ensures that URLs are valid
*
* @param {String|Array} urls
* @returns {Promise<Array>}
*/
Embedify.prototype.ensureUrls = function ensureUrls(urls) {
return Promise.resolve()
.then(() => {
if (is.all.string(urls)) {
return urls;
} else if (is.string(urls)) {
return [urls];
}
throw new TypeError('Invalid URL or list of URLs');
});
};
/**
* Performs HTTP request
*
* @param {String} apiUrl
* @param {String} matchUrl
* @returns {Promise}
*/
Embedify.prototype.fetch = function fetch(apiUrl, matchUrl) {
return Promise.resolve()
.then(() => {
const options = {
params: { url: matchUrl },
headers: { 'User-Agent': 'Embedify' },
json: true,
};
return this.client.get(apiUrl, options)
.then(res => this.parseResponse(res))
.catch(err => {
// Throw immediately if this is no HTTP error
if (!err.response) {
throw err;
}
// Return empty result for HTTP 4xx errors
// if false option is set
const statusCode = err.response.status;
if (statusCode >= 400 && statusCode < 500 && this.failSoft) {
return null;
}
const message = `Item does not exist [${matchUrl}]. Set 'failSoft' option to ignore.`;
throw new this.RequestError(message);
});
});
};
/**
* Parses the oEmbed response
*
* @param {Object} response
* @param {boolean} shouldBePretty
* @returns {Object}
*/
Embedify.prototype.parseResponse = function parseResponse(response) {
const oEmbed = response.data;
if (!this.parse) {
return oEmbed;
}
const result = {
type: oEmbed.type,
version: oEmbed.version ? oEmbed.version.toString() : null,
title: oEmbed.title,
html: oEmbed.html,
author: {
name: oEmbed.author_name,
url: oEmbed.author_url,
},
provider: {
name: oEmbed.provider_name,
url: oEmbed.provider_url,
},
image: {
url: oEmbed.thumbnail_url,
width: parseInt(oEmbed.thumbnail_width, 10) || null,
height: parseInt(oEmbed.thumbnail_height, 10) || null,
},
width: parseInt(oEmbed.width, 10) || null,
height: parseInt(oEmbed.height, 10) || null,
};
deepCleanNull(result);
return result;
};
function deepCleanNull(obj) {
Object.getOwnPropertyNames(obj).forEach((name) => {
if (obj[name] === null || obj[name] === undefined) {
delete obj[name];
} else if (typeof obj[name] === 'object') {
deepCleanNull(obj[name]);
}
});
}
// Public
module.exports.create = create;