-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrsspreview.js
447 lines (354 loc) · 12.4 KB
/
rsspreview.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
(function() {
/**
* Check and set a global guard variable.
* If this content script is injected into the same page again,
* it will do nothing next time.
*/
if (window.hasRun) {
console.log('already run');
return;
}
window.hasRun = true;
// defaults
var options = {
doThumb: false,
doMaxWidth: true,
valMaxWidth: "900px",
doDetect: true,
preventPreview: false,
fullPreview: false,
doAuthor: false,
enableCss: false,
bypassCSP: false,
customCss: null,
newTab: true
};
let xml_parser = new XMLSerializer();
let html_parser = new DOMParser();
function xhrdoc(url, type, cb) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'document';
xhr.overrideMimeType('text/' + type);
xhr.onload = () => {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
let resp = type == 'xml' ? xhr.responseXML : xhr.response;
cb(resp);
}
}
};
xhr.send(null);
}
function applyxsl(xmlin, xsl, node, doc = document) {
let xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
xsltProcessor.setParameter(null, 'fullPreview', options.fullPreview);
xsltProcessor.setParameter(null, 'doAuthor', options.doAuthor);
let fragment = xsltProcessor.transformToFragment(xmlin, doc);
node.appendChild(fragment);
}
function getlang() {
return browser.i18n.getUILanguage();
}
function formatsubtitle() {
try {
let feed_desc = document.getElementById('feedSubtitleRaw');
let html_desc = html_parser.parseFromString(
'<h2 id="feedSubtitleText">' + feed_desc.innerText + '</h2>',
'text/html'
);
let xml_desc = xml_parser.serializeToString(html_desc.body.firstChild);
feed_desc.insertAdjacentHTML('afterend', xml_desc);
feed_desc.parentNode.removeChild(feed_desc);
} catch (e) {
console.error(e);
console.log(feed_desc.innerText);
}
}
function formatdescriptions(el = document) {
// unescapes descriptions to html then to xml
let tohtml = el.getElementsByClassName('feedRawContent');
for (let i = 0; i < tohtml.length; i++) {
try {
let html_txt = '';
if (tohtml[i].getAttribute('desctype') == 'text/plain') {
html_txt = '<div class="feedEntryContent" style="white-space: pre-wrap;" >' + tohtml[i].innerHTML + '</div>';
}
else if (tohtml[i].getAttribute('desctype') == 'xhtml') {
html_txt = '<div class="feedEntryContent">' + tohtml[i].innerHTML + '</div>';
}
else {
html_txt = '<div class="feedEntryContent">' + tohtml[i].textContent + '</div>';
}
let html_desc = html_parser.parseFromString(html_txt, 'text/html');
let xml_desc = xml_parser.serializeToString(
html_desc.body.firstChild
);
tohtml[i].insertAdjacentHTML('afterend', xml_desc);
tohtml[i].setAttribute('todel', 1);
} catch (e) {
console.error(e);
console.log(tohtml[i]);
}
}
el.querySelectorAll('.feedRawContent').forEach(a => {
if (a.getAttribute('todel') == '1') {
a.remove();
}
});
}
function removeemptyenclosures(el = document) {
let encs = el.getElementsByClassName('enclosures');
for (let i = 0; i < encs.length; i++)
if (!encs[i].firstChild) encs[i].style.display = 'none';
}
function formatfilenames(el = document) {
let encfn = el.getElementsByClassName('enclosureFilename');
for (let i = 0; i < encfn.length; i++) {
let url = new URL(encfn[i].innerText);
if (url) {
let fn = url.pathname.split('/').pop();
if (fn != '') encfn[i].innerText = fn;
}
}
}
function formatfilesizes(el = document) {
function humanfilesize(size) {
let i = 0;
if (size && size != '' && size > 0)
i = Math.floor(Math.log(size) / Math.log(1024));
return (
(size / Math.pow(1024, i)).toFixed(2) * 1 +
' ' +
['B', 'kB', 'MB', 'GB', 'TB'][i]
);
}
let encsz = el.getElementsByClassName('enclosureSize');
for (let i = 0; i < encsz.length; i++) {
let hsize = humanfilesize(encsz[i].innerText);
if (hsize) encsz[i].innerText = hsize;
}
}
function formattitles(el = document) {
let et = el.getElementsByClassName('entrytitle');
for (let i = 0; i < et.length; i++) {
//basically removes html content if there is some
//only do it if there's a tag to avoid doing it when text titles cointain a '&'
//(which can be caught but still displays an error in console, which is annoying)
if (et[i].innerText.indexOf('<') >= 0 || et[i].innerText.indexOf('&')) {
console.log(et[i].innerText);
let tmp = document.createElement('span');
try {
tmp.innerHTML = et[i].innerText;
et[i].innerText = tmp.textContent;
} catch (e) {
// if not parsable, display as text
console.error(e);
console.log(et[i].innerText);
}
}
}
}
function formatdates(el = document) {
let lang = getlang();
if (!lang) return;
let opts = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
};
let ed = el.getElementsByClassName('lastUpdated');
for (let i = 0; i < ed.length; i++) {
let d = new Date(ed[i].innerText);
if (isNaN(d)) continue;
let dstr =
d.toLocaleDateString(lang, opts) + ' ' + d.toLocaleTimeString(lang);
ed[i].innerText = dstr;
}
let lu = el.getElementById('feedLastUpdate');
if (lu && lu.innerText.trim() != "") {
lu.innerText = "Last updated: " + lu.innerText;
}
}
function extensionimages(el = document) {
let extimgs = el.getElementsByClassName('extImg');
for (let i = 0; i < extimgs.length; i++)
extimgs[i].src = chrome.runtime.getURL(
extimgs[i].attributes['data-src'].nodeValue
);
}
function applysettings() {
document.querySelectorAll('.mediaThumb').forEach((elem) => {
elem.style.display = options.doThumb ? "block" : "none";
});
document.querySelectorAll('img').forEach((elem) => {
if (options.doMaxWidth)
elem.style["max-width"] = options.valMaxWidth;
});
}
function makepreviewhtml() {
let doc = document.implementation.createHTMLDocument('');
doc.body.id = "rsspreviewBody";
let feedBody = doc.createElement('div');
feedBody.id = 'feedBody';
doc.body.appendChild(feedBody);
let css = doc.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute('href', chrome.runtime.getURL('preview.css'));
doc.head.appendChild(css);
if (options.enableCss && options.customCss) {
let node = doc.createElement('style');
node.innerHTML = options.customCss;
doc.head.appendChild(node);
}
return doc;
}
function detect() {
let rootNode = document.getRootNode().documentElement;
// for chrome
let d = document.getElementById('webkit-xml-viewer-source-xml');
if (d && d.firstChild) rootNode = d.firstChild;
const rootName = rootNode.nodeName.toLowerCase();
let isRSS1 = false;
if (rootName == 'rdf' || rootName == 'rdf:rdf')
if (rootNode.attributes['xmlns'])
isRSS1 = rootNode.attributes['xmlns'].nodeValue.search('rss') > 0;
if (
rootName == 'rss' ||
rootName == 'channel' || // rss2
rootName == 'feed' || // atom
isRSS1
)
return rootNode;
return null;
}
function main(feedNode) {
let feed_url = window.location.href;
let preview = makepreviewhtml();
xhrdoc(chrome.runtime.getURL('rss.xsl'), 'xml', xsl_xml => {
applyxsl(feedNode, xsl_xml, preview.getElementById('feedBody'), preview);
// replace the content with the preview document
document.replaceChild(
document.importNode(preview.documentElement, true),
document.documentElement
);
let t0 = performance.now();
formatsubtitle();
formatdescriptions();
removeemptyenclosures();
formatfilenames();
formatfilesizes();
formattitles();
formatdates();
extensionimages();
applysettings();
let t1 = performance.now();
//console.log("exec in: " + (t1 - t0) + "ms");
document.title = document.getElementById('feedTitleText').innerText;
});
}
function onOptions(opts) {
options = opts;
let feedRoot = detect();
if (feedRoot && !options.preventPreview) {
main(feedRoot);
}
else if (options.doDetect) {
findFeeds();
}
}
function onError(error) {
console.log(`Error on get options: ${error}`);
}
let getting = browser.storage.sync.get(options);
getting.then(onOptions, onError);
function registerFeeds(feeds) {
if (Object.keys(feeds).length > 0) {
function handleResponse(message) {
}
function handleError(error) {
//console.log(error);
}
browser.runtime.sendMessage(feeds).then(handleResponse, handleError);
}
}
function findiTunesPodcastsFeeds() {
let match = document.URL.match(/id(\d+)/)
if (match) {
let feeds = {};
let itunesid = match[1];
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://itunes.apple.com/lookup?id="+itunesid+"&entity=podcast");
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
let res = JSON.parse(xhr.responseText);
if ("results" in res) {
let pod = res["results"][0];
let title = pod["collectionName"] || document.title;
let url = pod["feedUrl"];
if (url) {
feeds[url] = title;
}
}
}
}
registerFeeds(feeds);
};
xhr.send();
}
}
function findYouTubeFeeds() {
// YouTube's canonical channel URLs look like /channel/AlphaNumericID
// It also supports named channels of the form /c/MyChannelName
// and handle links of the form /@MyChannelHandle.
// Match also on '%' to handle non-latin character codes
// Match on both of these to autodetect channel feeds on either URL
let idPattern = /channel\/([a-zA-Z0-9%_-]+)/;
let namePattern = /(?:c|user)\/[a-zA-Z0-9%_-]+/;
let handlePattern = /@[a-zA-Z0-9%_-]+/;
let urlPattern = new RegExp(`${idPattern.source}|${namePattern.source}|${handlePattern.source}`);
if (document.URL.match(urlPattern)) {
let feeds = {};
let canonicalUrl = document.querySelector("link[rel='canonical']").href;
let channelId = canonicalUrl.match(idPattern)[1];
let url = `https://www.youtube.com/feeds/videos.xml?channel_id=${channelId}`;
let title = document.title;
feeds[url] = title;
registerFeeds(feeds);
}
}
// The default function used to find feeds if a domain-specific function doesn't exist.
// Parse the document's HTML looking for link tags pointing to the feed URL.
function defaultFindFeeds() {
let feeds = {};
document.querySelectorAll("link[rel='alternate']").forEach( (elem) => {
let type_attr = elem.getAttribute('type');
if (!type_attr) {
return;
}
let type = type_attr.toLowerCase();
if (type.includes('rss') || type.includes('atom') || type.includes('feed')) {
let title = elem.getAttribute('title');
let url = elem.href;
if (url) {
feeds[url] = (title ? title : url);
}
}
});
registerFeeds(feeds);
}
const domainFeedFinders = new Map([
["itunes.apple.com", findiTunesPodcastsFeeds],
["podcasts.apple.com", findiTunesPodcastsFeeds],
["www.youtube.com", findYouTubeFeeds],
]);
function findFeeds() {
// Look up a feed detection function based on the domain.
// If a domain-specific function doesn't exist, fall back to a default.
let finder = domainFeedFinders.get(document.domain) || defaultFindFeeds;
finder();
}
})();