-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuserscript.js
360 lines (316 loc) · 9.49 KB
/
userscript.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
// ==UserScript==
// @name New York Times Byline Restorer
// @namespace https://danstillman.com/
// @version 2.0.0
// @description Restores author bylines to the New York Times homepage and section pages
// @author Dan Stillman
// @homepage https://danstillman.com/nyt_byline_restorer/
// @icon https://nyt-byline-restorer.s3.amazonaws.com/images/icon32.png
// @icon64 https://nyt-byline-restorer.s3.amazonaws.com/images/icon128.png
// @downloadURL https://raw.githubusercontent.com/dstillman/nyt-byline-restorer/master/userscript.js
// @match https://www.nytimes.com/*
// @run-at document-end
// @grant none
// ==/UserScript==
(function() {
var currentVersion = 1;
var feedURLs = [
'https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml',
'https://rss.nytimes.com/services/xml/rss/nyt/MostViewed.xml',
'https://content.api.nytimes.com/svc/news/v3/all/recent.rss'
];
var debug = false;
function log(msg) {
if (!debug) return;
console.log(msg);
}
var isExtension = typeof chrome != 'undefined';
var base = window.location.href.match(/https:\/\/[^\/]+([^\?]+)/)[1];
var isHomepage = base == '/';
// Match /section/foo and /section/foo/bar, since sometimes the latter has bylines
// (e.g., /section/technology/personaltech)
var isSection = base.match(/^\/section\/[a-z\-]+/);
if (isExtension) {
chrome.storage.sync.get(
{
lastVersion: 0,
restoreBylines: true,
removeMinRead: false,
},
function (options) {
main(options);
}
);
}
// Userscript
else {
main({
restoreBylines: true,
removeMinRead: false,
});
}
function main(options = {}) {
if (isHomepage) {
if (isExtension && options.lastVersion < currentVersion) {
showAnnouncement();
}
if (options.removeMinRead) {
removeMinRead();
}
let urls = feedURLs.slice();
var urlMap = new Map();
let i = 0;
function processNextFeedURL() {
let url = urls.shift();
if (!url) {
// Once all feeds have been processed, check all bylines again after a short delay,
// both for elements that were added after the page load and to restore bylines that
// were removed by JS updating components on the page (particularly when clicking
// Back from an article).
setTimeout(() => addBylines(urlMap), 750);
setTimeout(() => addBylines(urlMap), 2500);
setTimeout(() => addBylines(urlMap), 5000);
return;
}
let feedIndex = i++;
log("Fetching " + url);
fetch(url)
.then(r => r.text())
.then((text) => {
log("Running text for " + url);
var doc = (new DOMParser).parseFromString(text, 'text/xml');
var items = doc.querySelectorAll('item');
for (let item of items) {
// Get relative paths without query strings from the feed item URLs
let url = item.querySelector('link:not([rel])').textContent;
if (!url) continue;
url = url.match(/https:\/\/[^\/]+([^\?]+)/)[1];
// Ignore URLs we already have
if (urlMap.has(url)) {
continue;
}
// Opinion pieces already show authors
if (url.includes('/opinion/')) {
continue;
}
// Fix capitalization of author names
let creator = item.querySelector('creator');
if (!creator) {
continue;
}
let authorString = creator.textContent;
if (authorString.startsWith('By ')) {
authorString = authorString.substr(3);
}
authorString = authorString
.split(/ and /g)
.map(author => titleCase(author))
.join(' and ');
if (!authorString) {
continue;
}
urlMap.set(
url,
{
id: null,
authorString,
feed: feedIndex
}
);
}
log("Adding bylines for " + url);
addBylines(urlMap);
})
.catch((e) => {
console.log(e);
})
.then(() => {
processNextFeedURL();
});
}
if (options.restoreBylines) {
processNextFeedURL();
}
}
else if (isSection) {
if (options.restoreBylines) {
unhideBylines();
}
}
}
function addBylines(urlMap) {
var present = 0;
var added = 0;
var notFound = 0;
var feedCounts = {};
for (let i = 0; i < feedURLs.length; i++) {
feedCounts[i] = 0;
}
urlMap.forEach((info, url) => {
if (info.id) {
if (document.getElementById(info.id)) {
log(url + " is already present -- skipping");
present++;
return;
}
info.id = null;
}
let links = document.querySelectorAll(`a[href*="${url}"]`);
if (links.length) {
log(`Found ${url}`);
added++;
feedCounts[info.feed] = ++feedCounts[info.feed];
let byline = document.createElement('div');
byline.id = 'byline-' + Math.floor(Math.random() * (9999999999));
byline.className = 'article-byline';
byline.textContent = info.authorString;
let target = links[0];
log(`Found ${links.length} links for ${url}`);
log(links);
for (let link of links) {
let h2 = link.querySelector('h2, .hed');
if (h2) {
// Avoid gap between large top headlines and byline
let h2Size = getComputedStyle(h2).getPropertyValue('font-size');
if (h2Size.endsWith('px') && h2Size > "31") {
target = h2;
}
// Normally we add the byline after the containing div, which makes for
// better spacing below headlines with keylines
else {
target = h2.parentNode;
}
// If the headline is centered, center the byline too
if (getComputedStyle(h2).getPropertyValue('text-align') == 'center') {
byline.classList.add('article-byline-centered');
}
break;
}
}
target.parentNode.insertBefore(byline, target.nextSibling);
info.id = byline.id;
log(`Added ${url} with ${info.id}`);
}
else {
log(`Didn't find ${url}`);
notFound++;
}
});
if (debug) {
log(`Present: ${present} Added: ${added} Not Found: ${notFound}`);
let countStrings = [];
for (let i in feedCounts) {
countStrings.push(feedURLs[i].match(/[^\/]+$/)[0] + ': ' + feedCounts[i]);
}
if (countStrings.length) {
log(countStrings.join(' '));
}
}
}
// From https://gist.github.com/johnhawkinson/7400d0f19158b1bbcc2b5319bbc8d451
function titleCase(s) {
var n, i, o, olower;
n = s.charAt(0);
for (i = 1; i < s.length; i++) {
o = s.charAt(i - 1);
olower = o.toLowerCase();
if (o !== olower) {
n += s.charAt(i).toLowerCase();
}
else {
n += s.charAt(i);
}
}
return n;
}
/**
* Bylines on section pages are present but hidden, so just unhide them (and the date)
*/
function unhideBylines() {
// Sections with css-* classes (e.g., https://www.nytimes.com/section/multimedia)
elems = document.querySelectorAll('span[itemprop="name"]');
for (let elem of elems) {
let parent = elem.closest('p');
if (getComputedStyle(parent).getPropertyValue('display') == 'none') {
if (parent.childNodes.length == 3) {
parent.style.display = 'flex';
}
}
}
// Sections with explicit classes, which may not be used anymore (9/2022)
var elems = document.querySelectorAll('.byline');
for (let elem of elems) {
if (getComputedStyle(elem).getPropertyValue('display') == 'none') {
elem.style.display = 'flex';
}
}
}
function removeMinRead() {
// Remove "x min read"
for (let p of document.querySelectorAll('p')) {
if (/min read$/.test(p.textContent)) {
p.hidden = true;
}
}
// Remove stylesheet we added to hide "x min read" before we could remove them more precisely
var styleStart = document.getElementById('nyt-byline-restorer-style-start');
if (styleStart) {
styleStart.parentNode.removeChild(styleStart);
}
}
function showAnnouncement() {
var iframe = document.createElement('iframe');
iframe.style.position = 'fixed';
iframe.style.zIndex = 2147483647;
iframe.style.top = '15px';
iframe.style.right = '20px';
iframe.style.width = '325px';
iframe.style.height = '200px';
iframe.style.border = 'none';
function closeIframe() {
chrome.storage.sync.set({
lastVersion: currentVersion
});
iframe.parentNode.removeChild(iframe);
}
window.addEventListener('message', function (event) {
if (event.origin + '/' == chrome.runtime.getURL('/')) {
if (event.data.type == 'announcement-close') {
closeIframe();
return;
}
if (event.data.type == 'setting-change') {
switch (event.data.key) {
case 'removeMinRead':
chrome.storage.sync.set({
[event.data.key]: !!event.data.value
});
break;
}
if (event.data.key == 'removeMinRead' && event.data.value) {
removeMinRead();
}
closeIframe();
}
}
});
iframe.setAttribute('src', chrome.runtime.getURL("announcement1.html"));
document.body.appendChild(iframe);
}
if (isHomepage) {
function GM_addStyle(css) {
const style = document.getElementById("GM_addStyleNYTBR") || (function() {
const style = document.createElement('style');
style.type = 'text/css';
style.id = "GM_addStyleNYTBR";
document.head.appendChild(style);
return style;
})();
const sheet = style.sheet;
sheet.insertRule(css, (sheet.rules || sheet.cssRules || []).length);
}
GM_addStyle('.article-byline {font-family: nyt-cheltenham-small;color: #a19d9d;font-size: 12px;margin-top: 8px;margin-bottom: 8px;}');
GM_addStyle('.article-byline-centered {text-align: center;}');
GM_addStyle('section[data-block-tracking-id="Briefings"] .article-byline {margin-top: 0;}');
}
})();