forked from itteco/iframely
-
Notifications
You must be signed in to change notification settings - Fork 0
/
oembedUtils.js
316 lines (258 loc) · 8.63 KB
/
oembedUtils.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
var sax = require('sax');
var urlLib = require('url');
var async = require('async');
var _ = require('underscore');
var utils = require('../../../utils');
var sysUtils = require('../../../../logging');
var cache = require('../../../cache');
var getUrl = utils.getUrl;
var getCharset = utils.getCharset;
var encodeText = utils.encodeText;
var lowerCaseKeys = utils.lowerCaseKeys;
exports.notPlugin = true;
/**
* @private
* Get the oembed uri via known providers
* @param {String} uri The page uri
* @return {String} The oembed uri
*/
function lookupStaticProviders(uri) {
var providers = require('./providers.json');
var protocolMatch = uri.match(/^(https?:\/\/)/);
if (!protocolMatch || /^https?:\/\/blog\./i.test(uri)) {
return null;
}
var uri2 = uri.substr(protocolMatch[1].length);
uri = uri.replace(/#.+$/, "");
var links;
for (var j = 0; j < providers.length; j++) {
var p = providers[j];
var match;
for (var i = 0; i < p.templates.length; i++) {
match = uri2.match(p.templates[i]);
if (match) break;
}
if (match) {
var endpoint = p.endpoint;
var groups = endpoint.match(/\{\d+\}/g);
if (groups) {
groups.forEach(function(g) {
var n = parseInt(g.match(/\{(\d+)\}/)[1]);
endpoint = endpoint.replace("{" + n + "}", match[n]);
});
} else if (endpoint.match(/\{url\}/)) {
endpoint = endpoint.replace(/\{url\}/, encodeURIComponent(uri));
} else {
endpoint = endpoint + '?url=' + encodeURIComponent(uri);
}
links = ['json', 'xml'].map(function(format) {
return {
href: endpoint.match(/\{format\}/)? endpoint.replace(/\{format\}/, format): endpoint + '&format=' + format,
rel: 'alternate',
type: 'application/' + format + '+oembed'
};
});
break;
}
}
return links;
}
module.exports.findOembedLinks = function(uri, meta) {
// Filter oembed from meta.
var alternate = meta && meta.alternate;
if (alternate && !(alternate instanceof Array)) {
alternate = [alternate];
meta.alternate = alternate;
}
var oembedLinks = meta && meta.alternate && meta.alternate.filter(function(link) {
return /^(application|text)\/(xml|json)\+oembed$/i.test(link.type);
});
if (uri && (!oembedLinks || !oembedLinks.length)) {
// Find oembed in static providers list.
oembedLinks = lookupStaticProviders(uri);
if (meta && oembedLinks) {
// Merge found links to meta.
meta.alternate = (meta.alternate || []).concat(oembedLinks);
}
}
if (oembedLinks && oembedLinks.length === 0) {
oembedLinks = null;
}
return oembedLinks;
};
/**
* @private
* Fetches and parses oEmbed by oEmbed URL got from discovery.
* @param {String} uri Full oEmbed endpoint plus URL and any needed format parameter.
* @param {Function} callback Completion callback function. The callback gets two arguments (error, oembed) where oembed is json parsed oEmbed object.
* */
module.exports.getOembed = function(uri, options, callback) {
if (typeof options === 'function') {
callback = options;
options = null;
}
var ADD_OEMBED_PARAMS = [];
if (options && options.ADD_OEMBED_PARAMS instanceof Array) {
ADD_OEMBED_PARAMS = ADD_OEMBED_PARAMS.concat(options.ADD_OEMBED_PARAMS);
}
if (CONFIG.ADD_OEMBED_PARAMS) {
ADD_OEMBED_PARAMS = ADD_OEMBED_PARAMS.concat(CONFIG.ADD_OEMBED_PARAMS);
}
try {
// TODO: make 'for'.
var params = _.find(ADD_OEMBED_PARAMS, function (params) {
return _.find(params.re, function (re) {
return uri.match(re);
});
});
if (params) {
var urlObj = urlLib.parse(uri, true, true);
var query = urlObj.query;
delete urlObj.search;
_.extend(query, params.params);
uri = urlLib.format(urlObj);
}
} catch(ex) {
console.error("Error using ADD_OEMBED_PARAMS", ex);
}
var oembed_key = 'meta:' + uri;
async.waterfall([
function(cb) {
if (options && options.refresh) {
cb(null, null);
} else {
cache.get(oembed_key, cb);
}
},
function(data, cb) {
if (data) {
sysUtils.log(' -- Using cached oembed for: ' + uri);
return cb(null, data);
}
// Reformat uri to escape not allowed get param characters.
var urlObj = urlLib.parse(uri, true);
delete urlObj.search;
uri = urlLib.format(urlObj);
getUrl(uri, {
maxRedirects: 3
})
.on('response', function(res) {
if (res.statusCode == 200) {
stream2oembed(res, function(error, oembed) {
if (error) {
return cb(error);
}
var result = {};
for(var key in oembed) {
var goodKey = key.replace(/-/g, "_");
result[goodKey] = oembed[key];
}
cb(null, result);
});
} else {
cb(res.statusCode);
}
})
.on('error', cb);
}
], function(error, data) {
if (!error && data) {
cache.set(oembed_key, data, {
ttl: options && options.cache_ttl
});
}
callback(error, data);
});
};
/**
* @private
* Convert XML or JSON stream to an oEmbed object.
*/
function stream2oembed(stream, callback) {
stream.headers['content-type'].match('xml') ?
xmlStream2oembed(stream, callback) :
jsonStream2oembed(stream, callback);
}
/**
* @private
* Convert XML stream to an oembed object
*/
function xmlStream2oembed(stream, callback) {
var oembed;
var prop;
var value;
var firstTag;
var charset = getCharset(stream.headers && stream.headers['content-type']);
var saxStream = sax.createStream();
saxStream.on('error', function(err) {
callback(err);
});
saxStream.on('opentag', function(tag) {
if (!firstTag) {
// Should be HEAD but HASH tag found on qik.
firstTag = tag.name;
oembed = {};
} else if (oembed) {
prop = tag.name.toLowerCase();
value = "";
}
});
saxStream.on('text', function(text) {
if (prop) value += text;
});
saxStream.on('cdata', function(text) {
if (prop) value += text;
});
saxStream.on('closetag', function(name) {
if (name === firstTag) {
callback(null, oembed);
} else {
if (prop) {
value = encodeText(charset, value);
if (prop.match(/(width|height)$/)) {
if (value.match(/^\d+(px)?$/)) {
value = parseInt(value, 10);
} else {
// For case like 100%.
value = undefined;
}
}
oembed[prop] = value;
}
prop = null;
}
});
stream.pipe(saxStream);
}
/**
* @private
* Convert JSON stream to an oembed object
*/
function jsonStream2oembed(stream, callback) {
var charset = getCharset(stream.headers && stream.headers['content-type']);
var data = "";
stream.on('data', function(chunk) {
data += chunk;
}).on('end', function() {
try {
data = JSON.parse(encodeText(charset, data));
} catch (e) {
callback(e);
return;
}
for(var prop in data) {
var value = data[prop];
if (prop.match(/(width|height)$/) && (typeof value === "string")) {
if (value.match(/^\d+(px)?$/)) {
value = parseInt(value, 10);
data[prop] = value;
} else {
// For case like 100%.
data[prop] = undefined;
}
}
}
lowerCaseKeys(data);
callback(null, data);
});
}