-
Notifications
You must be signed in to change notification settings - Fork 22
/
OpenGraphParser.js
310 lines (260 loc) · 9.08 KB
/
OpenGraphParser.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
import { AllHtmlEntities } from 'html-entities';
const entities = new AllHtmlEntities();
function findOGTags(content, url) {
const metaTagOGRegex = /<meta[^>]*(?:property=[ '"]*og:([^'"]*))?[^>]*(?:content=["]([^"]*)["])?[^>]*>/gi;
const matches = content.match(metaTagOGRegex);
const meta = {};
if (matches) {
const metaPropertyRegex = /<meta[^>]*property=[ "]*og:([^"]*)[^>]*>/i;
const metaContentRegex = /<meta[^>]*content=[ "]([^"]*)[^>]*>/i;
for (let i = matches.length; i--;) {
let propertyMatch;
let contentMatch;
let metaName;
let metaValue;
try {
propertyMatch = metaPropertyRegex.exec(matches[i]);
contentMatch = metaContentRegex.exec(matches[i]);
if (!propertyMatch || !contentMatch) {
continue;
}
metaName = propertyMatch[1].trim();
metaValue = contentMatch[1].trim();
if (!metaName || !metaValue) {
continue;
}
} catch (error) {
if (__DEV__) {
console.log('Error on ', matches[i]);
console.log('propertyMatch', propertyMatch);
console.log('contentMatch', contentMatch);
console.log(error);
}
continue;
}
if (metaValue.length > 0) {
if (metaValue[0] === '/') {
if (metaValue.length <= 1 || metaValue[1] !== '/') {
if (url[url.length - 1] === '/') {
metaValue = url + metaValue.substring(1);
} else {
metaValue = url + metaValue;
}
} else {
// handle protocol agnostic meta URLs
if (url.indexOf('https://') === 0) {
metaValue = `https:${metaValue}`;
} else if (url.indexOf('http://') === 0) {
metaValue = `http:${metaValue}`;
}
}
}
} else {
continue;
}
meta[metaName] = entities.decode(metaValue);
}
}
return meta;
}
function findHTMLMetaTags(content, url) {
const metaTagHTMLRegex = /<meta(?:[^>]*(?:name|itemprop)=[ '"]([^'"]*))?[^>]*(?:[^>]*content=["]([^"]*)["])?[^>]*>/gi;
const matches = content.match(metaTagHTMLRegex);
const meta = {};
if (matches) {
const metaPropertyRegex = /<meta[^>]*(?:name|itemprop)=[ "]([^"]*)[^>]*>/i;
const metaContentRegex = /<meta[^>]*content=[ "]([^"]*)[^>]*>/i;
for (let i = matches.length; i--;) {
let propertyMatch;
let contentMatch;
let metaName;
let metaValue;
try {
propertyMatch = metaPropertyRegex.exec(matches[i]);
contentMatch = metaContentRegex.exec(matches[i]);
if (!propertyMatch || !contentMatch) {
continue;
}
metaName = propertyMatch[1].trim();
metaValue = contentMatch[1].trim();
if (!metaName || !metaValue) {
continue;
}
} catch (error) {
if (__DEV__) {
console.log('Error on ', matches[i]);
console.log('propertyMatch', propertyMatch);
console.log('contentMatch', contentMatch);
console.log(error);
}
continue;
}
if (metaValue.length > 0) {
if (metaValue[0] === '/') {
if (metaValue.length <= 1 || metaValue[1] !== '/') {
if (url[url.length - 1] === '/') {
metaValue = url + metaValue.substring(1);
} else {
metaValue = url + metaValue;
}
} else {
// handle protocol agnostic meta URLs
if (url.indexOf('https://') === 0) {
metaValue = `https:${metaValue}`;
} else if (url.indexOf('http://') === 0) {
metaValue = `http:${metaValue}`;
}
}
}
} else {
continue;
}
meta[metaName] = entities.decode(metaValue);
}
if (!meta.title) {
const titleRegex = /<title>([^>]*)<\/title>/i;
const titleMatch = content.match(titleRegex);
if (titleMatch) {
meta.title = entities.decode(titleMatch[1]);
}
}
}
return meta;
}
function parseMeta(html, url, options) {
let meta = findOGTags(html, url);
if (options.fallbackOnHTMLTags) {
try {
meta = {
...findHTMLMetaTags(html, url),
...meta,
};
} catch (error) {
if (__DEV__) {
console.log('Error in fallback', error);
}
}
}
return meta;
}
async function fetchHtml(urlToFetch, forceGoogle = false) {
let result;
let userAgent
= 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36';
if (forceGoogle) {
userAgent
= 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
}
try {
result = await fetch(urlToFetch, {
method: 'GET',
headers: {
'user-agent': userAgent,
},
});
if (result.status >= 400) {
throw result;
}
return result.text().then((resultParsed) => resultParsed);
} catch (responseOrError) {
if (responseOrError.message && __DEV__) {
if (responseOrError.message === 'Network request failed') {
console.log(urlToFetch, 'could not be fetched');
} else {
console.log(responseOrError);
}
return null;
}
return responseOrError.text().then((error) => {
if (__DEV__) {
console.log(
'An error has occured while fetching url content',
error
);
}
return null;
});
}
}
async function fetchJSON(urlToFetch, urlOfVideo) {
try {
const result = await fetch(urlToFetch, { method: 'GET' });
if (result.status >= 400) {
throw result;
}
const resultParsed = await result.json();
return {
title: resultParsed.title,
image: resultParsed.thumbnail_url,
url: urlOfVideo,
};
} catch (error) {
if (__DEV__) {
console.log(error);
}
return null;
}
}
function getUrls(contentToMatch) {
const regexp = /(?:(?=[\s`!()\[\]{};:'".,<>?«»“”‘’])|\b)((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/|[a-z0-9.\-]+[.](?:com|org|net))(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))*(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]|\b))/gi;
const urls = contentToMatch.match(regexp);
const urlsToReturn = [];
if (urls && urls.length) {
urls.forEach((url) => {
if (url.toLowerCase().indexOf('http') === 0) {
urlsToReturn.push(url);
} else {
urlsToReturn.push(`http://${url}`);
}
});
} else {
if (__DEV__) {
console.log('Could not find an html link');
}
}
return urlsToReturn;
}
async function extractMeta(
textContent = '',
options = { fallbackOnHTMLTags: true }
) {
try {
const urls = getUrls(textContent);
const metaData = [];
let i = 0;
while (i < urls.length) {
if (urls[i].indexOf('youtube.com') >= 0) {
metaData.push(
await fetchJSON(
`https://www.youtube.com/oembed?url=${
urls[i]
}&format=json`,
urls[i]
)
);
} else { /* eslint-disable no-loop-func */
metaData.push(
await fetchHtml(urls[i])
.then((html) => ({
...html ? parseMeta(html, urls[i], options) : {},
url: urls[i],
}))
);
}
i++;
}
return metaData;
} catch (e) {
console.log(e);
return {};
}
}
const exporting = {
extractMeta,
// Exporting for testing
findOGTags,
findHTMLMetaTags,
};
// For testing
module.exports = exporting;
export default exporting;