blob: d501c2604ea426c7868837ac4c1b1c8f7e0babc2 [file] [log] [blame]
avm9996311707032021-02-05 19:11:25 +01001var mutationObserver, intersectionObserver, intersectionOptions, options,
2 authuser;
avm99963cbea3142019-03-28 00:48:15 +01003
avm99963f5923962020-12-07 16:44:37 +01004function removeChildNodes(node) {
5 while (node.firstChild) {
6 node.removeChild(node.firstChild);
avm99963af7860e2019-06-04 03:33:26 +02007 }
avm99963f5923962020-12-07 16:44:37 +01008}
avm99963af7860e2019-06-04 03:33:26 +02009
avm9996390cc2e32021-02-05 18:14:16 +010010function getNParent(node, n) {
11 if (n <= 0) return node;
12 if (!('parentNode' in node)) return null;
13 return getNParent(node.parentNode, n - 1);
14}
15
avm999633eae4522021-04-22 01:14:27 +020016function parseUrl(url) {
17 var forum_a = url.match(/forum\/([0-9]+)/i);
18 var thread_a = url.match(/thread\/([0-9]+)/i);
19
20 if (forum_a === null || thread_a === null) {
21 return false;
22 }
23
24 return {
25 'forum': forum_a[1],
26 'thread': thread_a[1],
27 };
28}
29
avm99963f5923962020-12-07 16:44:37 +010030function createExtBadge() {
31 var badge = document.createElement('div');
32 badge.classList.add('TWPT-badge');
33 badge.setAttribute(
34 'title', chrome.i18n.getMessage('inject_extension_badge_helper', [
35 chrome.i18n.getMessage('appName')
36 ]));
37
38 var badgeI = document.createElement('i');
39 badgeI.classList.add('material-icon-i', 'material-icons-extended');
40 badgeI.textContent = 'repeat';
41
42 badge.append(badgeI);
43 return badge;
avm99963af7860e2019-06-04 03:33:26 +020044}
45
avm99963943b8492020-08-31 23:40:43 +020046function addProfileHistoryLink(node, type, query) {
47 var urlpart = encodeURIComponent('query=' + query);
avm99963a2945b62020-11-27 00:32:02 +010048 var authuserpart =
49 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
avm99963943b8492020-08-31 23:40:43 +020050 var container = document.createElement('div');
51 container.style.margin = '3px 0';
52
53 var link = document.createElement('a');
54 link.setAttribute(
avm99963a2945b62020-11-27 00:32:02 +010055 'href',
56 'https://support.google.com/s/community/search/' + urlpart +
57 authuserpart);
avm99963943b8492020-08-31 23:40:43 +020058 link.innerText = chrome.i18n.getMessage('inject_previousposts_' + type);
59
60 container.appendChild(link);
avm9996306167752020-09-08 00:50:36 +020061 node.appendChild(container);
avm99963943b8492020-08-31 23:40:43 +020062}
63
avm999638e0c1002020-12-03 16:54:20 +010064function applyDragAndDropFix(node) {
65 console.debug('Adding link drag&drop fix to ', node);
66 node.addEventListener('drop', e => {
67 if (e.dataTransfer.types.includes('text/uri-list')) {
68 e.stopImmediatePropagation();
69 console.debug('Stopping link drop event propagation.');
70 }
71 }, true);
72}
73
avm99963f5923962020-12-07 16:44:37 +010074function nodeIsReadToggleBtn(node) {
75 return ('tagName' in node) && node.tagName == 'MATERIAL-BUTTON' &&
76 node.getAttribute('debugid') !== null &&
77 (node.getAttribute('debugid') == 'mark-read-button' ||
78 node.getAttribute('debugid') == 'mark-unread-button') &&
79 ('parentNode' in node) && node.parentNode !== null &&
80 ('parentNode' in node.parentNode) &&
81 node.parentNode.querySelector('[debugid="batchlock"]') === null &&
82 node.parentNode.parentNode !== null &&
83 ('tagName' in node.parentNode.parentNode) &&
84 node.parentNode.parentNode.tagName == 'EC-BULK-ACTIONS';
85}
86
avm9996328fddc62021-02-05 20:33:48 +010087function injectDarkModeButton(rightControl) {
88 var darkThemeSwitch = document.createElement('material-button');
89 darkThemeSwitch.classList.add('TWPT-dark-theme', 'TWPT-btn--with-badge');
90 darkThemeSwitch.setAttribute('button', '');
91 darkThemeSwitch.setAttribute(
92 'title', chrome.i18n.getMessage('inject_ccdarktheme_helper'));
93
94 darkThemeSwitch.addEventListener('click', e => {
95 chrome.storage.sync.get(null, currentOptions => {
96 currentOptions.ccdarktheme_switch_status =
97 !options.ccdarktheme_switch_status;
98 chrome.storage.sync.set(currentOptions, _ => {
99 location.reload();
100 });
101 });
102 });
103
104 var switchContent = document.createElement('div');
105 switchContent.classList.add('content');
106
107 var icon = document.createElement('material-icon');
108
109 var i = document.createElement('i');
110 i.classList.add('material-icon-i', 'material-icons-extended');
111 i.textContent = 'brightness_4';
112
113 icon.appendChild(i);
114 switchContent.appendChild(icon);
115 darkThemeSwitch.appendChild(switchContent);
116
117 var badgeContent = createExtBadge();
118
119 darkThemeSwitch.appendChild(badgeContent);
120
121 rightControl.style.width =
122 (parseInt(window.getComputedStyle(rightControl).width) + 58) + 'px';
123 rightControl.insertAdjacentElement('afterbegin', darkThemeSwitch);
124}
125
avm99963f5923962020-12-07 16:44:37 +0100126function addBatchLockBtn(readToggle) {
127 var clone = readToggle.cloneNode(true);
128 clone.setAttribute('debugid', 'batchlock');
129 clone.classList.add('TWPT-btn--with-badge');
130 clone.setAttribute('title', chrome.i18n.getMessage('inject_lockbtn'));
131 clone.querySelector('material-icon').setAttribute('icon', 'lock');
132 clone.querySelector('i.material-icon-i').textContent = 'lock';
133
134 var badge = createExtBadge();
135 clone.append(badge);
136
137 clone.addEventListener('click', function() {
138 var modal = document.querySelector('.pane[pane-id="default-1"]');
139
140 var dialog = document.createElement('material-dialog');
141 dialog.setAttribute('role', 'dialog');
142 dialog.setAttribute('aria-modal', 'true');
143 dialog.classList.add('TWPT-dialog');
144
145 var header = document.createElement('header');
146 header.setAttribute('role', 'presentation');
147 header.classList.add('TWPT-dialog-header');
148
149 var title = document.createElement('div');
150 title.classList.add('TWPT-dialog-header--title', 'title');
151 title.textContent = chrome.i18n.getMessage('inject_lockbtn');
152
153 header.append(title);
154
155 var main = document.createElement('main');
156 main.setAttribute('role', 'presentation');
157 main.classList.add('TWPT-dialog-main');
158
159 var p = document.createElement('p');
160 p.textContent = chrome.i18n.getMessage('inject_lockdialog_desc');
161
162 main.append(p);
163
164 dialog.append(header, main);
165
166 var footers = [['lock', 'unlock', 'cancel'], ['reload', 'close']];
167
168 for (var i = 0; i < footers.length; ++i) {
169 var footer = document.createElement('footer');
170 footer.setAttribute('role', 'presentation');
171 footer.classList.add('TWPT-dialog-footer');
172 footer.setAttribute('data-footer-id', i);
173
174 if (i > 0) footer.classList.add('is-hidden');
175
176 footers[i].forEach(action => {
177 var btn = document.createElement('material-button');
178 btn.setAttribute('role', 'button');
179 btn.classList.add('TWPT-dialog-footer-btn');
180 if (i == 1) btn.classList.add('is-disabled');
181
182 switch (action) {
183 case 'lock':
184 case 'unlock':
185 btn.addEventListener('click', _ => {
186 if (btn.classList.contains('is-disabled')) return;
187 var message = {
188 action,
189 prefix: 'TWPT-batchlock',
190 };
191 window.postMessage(message, '*');
192 });
193 break;
194
195 case 'cancel':
196 case 'close':
197 btn.addEventListener('click', _ => {
198 if (btn.classList.contains('is-disabled')) return;
199 modal.classList.remove('visible');
200 modal.style.display = 'none';
201 removeChildNodes(modal);
202 });
203 break;
204
205 case 'reload':
206 btn.addEventListener('click', _ => {
207 if (btn.classList.contains('is-disabled')) return;
208 window.location.reload()
209 });
210 break;
211 }
212
213 var content = document.createElement('div');
214 content.classList.add('content', 'TWPT-dialog-footer-btn--content');
215 content.textContent =
216 chrome.i18n.getMessage('inject_lockdialog_btn_' + action);
217
218 btn.append(content);
219 footer.append(btn);
220 });
221
222 var clear = document.createElement('div');
223 clear.style.clear = 'both';
224
225 footer.append(clear);
226 dialog.append(footer);
227 }
228
229 removeChildNodes(modal);
230 modal.append(dialog);
231 modal.classList.add('visible', 'modal');
232 modal.style.display = 'flex';
233 });
Adrià Vilanova Martínez74273ee2021-06-25 19:23:27 +0200234
235 var duplicateBtn =
236 readToggle.parentNode.querySelector('[debugid="mark-duplicate-button"]');
237 if (duplicateBtn)
238 duplicateBtn.parentNode.insertBefore(
239 clone, (duplicateBtn.nextSibling || duplicateBtn));
240 else
241 readToggle.parentNode.insertBefore(
242 clone, (readToggle.nextSibling || readToggle));
avm99963f5923962020-12-07 16:44:37 +0100243}
244
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200245var avatars = {
246 isFilterSetUp: false,
247 privateForums: [],
avm999633eae4522021-04-22 01:14:27 +0200248
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200249 // Gets a list of private forums. If it is already cached, the cached list is
250 // returned; otherwise it is also computed and cached.
251 getPrivateForums() {
252 return new Promise((resolve, reject) => {
253 if (this.isFilterSetUp) return resolve(this.privateForums);
avm999633eae4522021-04-22 01:14:27 +0200254
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200255 if (!document.documentElement.hasAttribute('data-startup'))
256 return reject('[threadListAvatars] Couldn\'t get startup data.');
avm999633eae4522021-04-22 01:14:27 +0200257
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200258 var startupData =
259 JSON.parse(document.documentElement.getAttribute('data-startup'));
260 var forums = startupData?.['1']?.['2'];
261 if (forums === undefined)
262 return reject(
263 '[threadListAvatars] Couldn\'t retrieve forums from startup data.');
264
265 for (var f of forums) {
266 var forumId = f?.['2']?.['1']?.['1'];
267 var forumVisibility = f?.['2']?.['18'];
268 if (forumId === undefined || forumVisibility === undefined) {
269 console.warn(
270 '[threadListAvatars] Coudln\'t retrieve forum id and/or forum visibility for the following forum:',
271 f);
272 continue;
273 }
274
275 // forumVisibility's value 1 means "PUBLIC".
276 if (forumVisibility != 1) this.privateForums.push(forumId);
avm999633eae4522021-04-22 01:14:27 +0200277 }
avm999633eae4522021-04-22 01:14:27 +0200278
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200279 // Forum 51488989 is marked as public but it is in fact private.
280 this.privateForums.push('51488989');
avm999633eae4522021-04-22 01:14:27 +0200281
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200282 this.isFilterSetUp = true;
283 return resolve(this.privateForums);
284 });
285 },
avm999633eae4522021-04-22 01:14:27 +0200286
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200287 // Some threads belong to private forums, and this feature will not be able to
288 // get its avatars since it makes an anonymomus call to get the contents of
289 // the thread.
290 //
291 // This function returns whether avatars should be retrieved depending on if
292 // the thread belongs to a known private forum.
293 shouldRetrieveAvatars(thread) {
294 return this.getPrivateForums().then(privateForums => {
295 return !privateForums.includes(thread.forum);
296 });
297 },
298
299 // Get an array with the first |num| messages from the thread |thread|.
300 getFirstMessages(thread, num = 15) {
301 return CCApi(
302 'ViewThread', {
303 1: thread.forum,
304 2: thread.thread,
305 // options
306 3: {
307 // pagination
308 1: {
309 2: num, // maxNum
310 },
311 3: true, // withMessages
312 5: true, // withUserProfile
313 10: false, // withPromotedMessages
314 16: false, // withThreadNotes
315 18: true, // sendNewThreadIfMoved
316 }
317 },
318 // |authentication| is false because otherwise this would mark
319 // the thread as read as a side effect, and that would mark all
320 // threads in the list as read.
321 //
322 // Due to the fact that we have to call this endpoint
323 // anonymously, this means we can't retrieve information about
324 // threads in private forums.
325 /* authentication = */ false)
326 .then(data => {
327 var numMessages = data?.['1']?.['8'];
328 if (numMessages == undefined)
329 throw new Error(
330 'Request to view thread doesn\'t include the number of messages');
331 if (numMessages == 0) return [];
332
333 var messages = data?.['1']['3'];
334 if (messages == undefined)
335 throw new Error(
336 'numMessages was ' + numMessages +
337 ' but the response didn\'t include any message.');
338 return messages;
339 });
340 },
341
342 // Get a list of at most |num| avatars for thread |thread|
343 getVisibleAvatars(thread, num = 3) {
344 return this.shouldRetrieveAvatars(thread).then(shouldRetrieve => {
345 if (!shouldRetrieve) {
346 console.debug('[threadListAvatars] Skipping thread', thread);
347 return [];
348 }
349
350 return this.getFirstMessages(thread).then(messages => {
avm999633eae4522021-04-22 01:14:27 +0200351 var avatarUrls = [];
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200352 for (var m of messages) {
353 var url = m?.['3']?.['1']?.['2'];
avm999633eae4522021-04-22 01:14:27 +0200354
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200355 if (url === undefined) continue;
avm999633eae4522021-04-22 01:14:27 +0200356 if (!avatarUrls.includes(url)) avatarUrls.push(url);
avm999633eae4522021-04-22 01:14:27 +0200357 if (avatarUrls.length == 3) break;
358 }
359
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200360 return avatarUrls;
avm999633eae4522021-04-22 01:14:27 +0200361 });
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200362 });
363 },
364
365 // Inject avatars for thread summary (thread item) |node| in a thread list.
366 inject(node) {
367 var header = node.querySelector(
368 'ec-thread-summary .main-header .panel-description a.header');
369 if (header === null) {
370 console.error(
371 '[threadListAvatars] Header is not present in the thread item\'s DOM.');
372 return;
373 }
374
375 var thread = parseUrl(header.href);
376 if (thread === false) {
377 console.error('[threadListAvatars] Thread\'s link cannot be parsed.');
378 return;
379 }
380
381 this.getVisibleAvatars(thread)
382 .then(avatarUrls => {
383 var avatarsContainer = document.createElement('div');
384 avatarsContainer.classList.add('TWPT-avatars');
385
386 var count = Math.floor(Math.random() * 4);
387
388 for (var i = 0; i < avatarUrls.length; ++i) {
389 var avatar = document.createElement('div');
390 avatar.classList.add('TWPT-avatar');
391 avatar.style.backgroundImage = 'url(\'' + avatarUrls[i] + '\')';
392 avatarsContainer.appendChild(avatar);
393 }
394
395 header.appendChild(avatarsContainer);
396 })
397 .catch(err => {
398 console.error(
399 '[threadListAvatars] Could not retrieve avatars for thread',
400 thread, err);
401 });
402 },
403};
avm999633eae4522021-04-22 01:14:27 +0200404
avm99963a007d492021-05-02 12:32:03 +0200405var autoRefresh = {
406 isLookingForUpdates: false,
407 isUpdatePromptShown: false,
408 lastTimestamp: null,
409 filter: null,
410 path: null,
411 snackbar: null,
412 interval: null,
413 firstCallTimeout: null,
414 intervalMs: 3 * 60 * 1000, // 3 minutes
415 firstCallDelayMs: 3 * 1000, // 3 seconds
416 getStartupData() {
417 return JSON.parse(
418 document.querySelector('html').getAttribute('data-startup'));
419 },
420 isOrderedByTimestampDescending() {
421 var startup = this.getStartupData();
422 // Returns orderOptions.by == TIMESTAMP && orderOptions.desc == true
423 return (
424 startup?.[1]?.[1]?.[3]?.[14]?.[1] == 1 &&
425 startup?.[1]?.[1]?.[3]?.[14]?.[2] == true);
426 },
427 getCustomFilter(path) {
428 var searchRegex = /^\/s\/community\/search\/([^\/]*)/;
429 var matches = path.match(searchRegex);
430 if (matches !== null && matches.length > 1) {
431 var search = decodeURIComponent(matches[1]);
432 var params = new URLSearchParams(search);
433 return params.get('query') || '';
434 }
435
436 return '';
437 },
438 filterHasOverride(filter, override) {
439 var escapedOverride = override.replace(/([^\w\d\s])/gi, '\\$1');
440 var regex = new RegExp('[^a-zA-Z0-9]?' + escapedOverride + ':');
441 return regex.test(filter);
442 },
443 getFilter(path) {
444 var query = this.getCustomFilter(path);
445
446 // Note: This logic has been copied and adapted from the
447 // _buildQuery$1$threadId function in the Community Console
448 var conditions = '';
449 var startup = this.getStartupData();
450
451 // TODO(avm99963): if the selected forums are changed without reloading the
452 // page, this will get the old selected forums. Fix this.
453 var forums = startup?.[1]?.[1]?.[3]?.[8] ?? [];
454 if (!this.filterHasOverride(query, 'forum') && forums !== null &&
455 forums.length > 0)
456 conditions += ' forum:(' + forums.join(' | ') + ')';
457
458 var langs = startup?.[1]?.[1]?.[3]?.[5] ?? [];
459 if (!this.filterHasOverride(query, 'lang') && langs !== null &&
460 langs.length > 0)
461 conditions += ' lang:(' + langs.map(l => '"' + l + '"').join(' | ') + ')';
462
463 if (query.length !== 0 && conditions.length !== 0)
464 return '(' + query + ')' + conditions;
465 return query + conditions;
466 },
467 getLastTimestamp() {
468 var APIRequestUrl = 'https://support.google.com/s/community/api/ViewForum' +
469 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
470
471 return fetch(APIRequestUrl, {
472 'headers': {
473 'content-type': 'text/plain; charset=utf-8',
474 },
475 'body': JSON.stringify({
476 1: '0', // TODO: Change, when only a forum is selected, it
477 // should be set here
478 2: {
479 1: {
480 2: 2,
481 },
482 2: {
483 1: 1,
484 2: true,
485 },
486 12: this.filter,
487 },
488 }),
489 'method': 'POST',
490 'mode': 'cors',
491 'credentials': 'include',
492 })
493 .then(res => {
494 if (res.status == 200 || res.status == 400) {
495 return res.json().then(data => ({
496 status: res.status,
497 body: data,
498 }));
499 } else {
500 throw new Error('Status code ' + res.status + ' was not expected.');
501 }
502 })
503 .then(res => {
504 if (res.status == 400) {
505 throw new Error(
506 res.body[4] ||
507 ('Response status: 400. Error code: ' + res.body[2]));
508 }
509
510 return res.body;
511 })
512 .then(body => {
513 var timestamp = body?.[1]?.[2]?.[0]?.[2]?.[17];
514 if (timestamp === undefined)
515 throw new Error(
516 'Unexpected body of response (' +
517 (body?.[1]?.[2]?.[0] === undefined ?
518 'no threads were returned' :
519 'the timestamp value is not present in the first thread') +
520 ').');
521
522 return timestamp;
523 });
524 // TODO(avm99963): Add retry mechanism (sometimes thread lists are empty,
525 // but when loading the next page the thread appears).
526 //
527 // NOTE(avm99963): It seems like loading the first 2 threads instead of only
528 // the first one fixes this (empty lists are now rarely returned).
529 },
530 unregister() {
531 console.debug('autorefresh_list: unregistering');
532
533 if (!this.isLookingForUpdates) return;
534
535 window.clearTimeout(this.firstCallTimeout);
536 window.clearInterval(this.interval);
537 this.isUpdatePromptShown = false;
538 this.isLookingForUpdates = false;
539 },
540 showUpdatePrompt() {
541 this.snackbar.classList.remove('TWPT-hidden');
542 document.title = '[!!!] ' + document.title.replace('[!!!] ', '');
543 this.isUpdatePromptShown = true;
544 },
545 hideUpdatePrompt() {
546 this.snackbar.classList.add('TWPT-hidden');
547 document.title = document.title.replace('[!!!] ', '');
548 this.isUpdatePromptShown = false;
549 },
550 injectUpdatePrompt() {
551 var pane = document.createElement('div');
552 pane.classList.add('TWPT-pane-for-snackbar');
553
554 var snackbar = document.createElement('material-snackbar-panel');
555 snackbar.classList.add('TWPT-snackbar');
556 snackbar.classList.add('TWPT-hidden');
557
558 var ac = document.createElement('div');
559 ac.classList.add('TWPT-animation-container');
560
561 var nb = document.createElement('div');
562 nb.classList.add('TWPT-notification-bar');
563
564 var ft = document.createElement('focus-trap');
565
566 var content = document.createElement('div');
567 content.classList.add('TWPT-focus-content-wrapper');
568
569 var badge = createExtBadge();
570
571 var message = document.createElement('div');
572 message.classList.add('TWPT-message');
573 message.textContent =
574 chrome.i18n.getMessage('inject_autorefresh_list_snackbar_message');
575
576 var action = document.createElement('div');
577 action.classList.add('TWPT-action');
578 action.textContent =
579 chrome.i18n.getMessage('inject_autorefresh_list_snackbar_action');
580
581 action.addEventListener('click', e => {
582 this.hideUpdatePrompt();
583 document.querySelector('.app-title-button').click();
584 });
585
586 content.append(badge, message, action);
587 ft.append(content);
588 nb.append(ft);
589 ac.append(nb);
590 snackbar.append(ac);
591 pane.append(snackbar);
592 document.getElementById('default-acx-overlay-container').append(pane);
593 this.snackbar = snackbar;
594 },
595 checkUpdate() {
596 if (location.pathname != this.path) {
597 this.unregister();
598 return;
599 }
600
601 if (this.isUpdatePromptShown) return;
602
603 console.debug('Checking for update at: ', new Date());
604
605 this.getLastTimestamp()
606 .then(timestamp => {
607 if (timestamp != this.lastTimestamp) this.showUpdatePrompt();
608 })
609 .catch(
610 err => console.error(
611 'Coudln\'t get last timestamp (while updating): ', err));
612 },
613 firstCall() {
614 console.debug(
615 'autorefresh_list: now performing first call to finish setup (filter: [' +
616 this.filter + '])');
617
618 if (location.pathname != this.path) {
619 this.unregister();
620 return;
621 }
622
623 this.getLastTimestamp()
624 .then(timestamp => {
625 this.lastTimestamp = timestamp;
626 var checkUpdateCallback = this.checkUpdate.bind(this);
627 this.interval =
628 window.setInterval(checkUpdateCallback, this.intervalMs);
629 })
630 .catch(
631 err => console.error(
632 'Couldn\'t get last timestamp (while setting up): ', err));
633 },
634 setUp() {
635 if (!this.isOrderedByTimestampDescending()) return;
636
637 this.unregister();
638
639 console.debug('autorefresh_list: starting set up...');
640
641 if (this.snackbar === null) this.injectUpdatePrompt();
642 this.isLookingForUpdates = true;
643 this.path = location.pathname;
644 this.filter = this.getFilter(this.path);
645
646 var firstCall = this.firstCall.bind(this);
647 this.firstCallTimeout = window.setTimeout(firstCall, this.firstCallDelayMs);
648 },
649};
650
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200651function isDarkThemeOn() {
652 if (!options.ccdarktheme) return false;
653
654 if (options.ccdarktheme_mode == 'switch')
655 return options.ccdarktheme_switch_status;
656
657 return window.matchMedia &&
658 window.matchMedia('(prefers-color-scheme: dark)').matches;
659}
660
661var unifiedProfilesFix = {
662 checkIframe(iframe) {
663 var srcRegex = /support.*\.google\.com\/profile\//;
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200664 return srcRegex.test(iframe.src ?? '');
665 },
666 fixIframe(iframe) {
667 console.info('[unifiedProfilesFix] Fixing unified profiles iframe');
668 var url = new URL(iframe.src);
669 url.searchParams.set('dark', 1);
670 iframe.src = url.href;
671 },
672};
673
avm9996390cc2e32021-02-05 18:14:16 +0100674function injectPreviousPostsLinks(nameElement) {
675 var mainCardContent = getNParent(nameElement, 3);
676 if (mainCardContent === null) {
677 console.error(
678 '[previousposts] Couldn\'t find |.main-card-content| element.');
679 return;
avm99963490114d2021-02-05 16:12:20 +0100680 }
avm9996390cc2e32021-02-05 18:14:16 +0100681
682 var forumId = location.href.split('/forum/')[1].split('/')[0] || '0';
683
avm99963193233a2021-05-29 15:49:29 +0200684 var nameTag =
685 (nameElement.tagName == 'EC-DISPLAY-NAME-EDITOR' ?
686 nameElement.querySelector('.top-section > span') ?? nameElement :
687 nameElement);
688 var name = escapeUsername(nameTag.textContent);
avm9996390cc2e32021-02-05 18:14:16 +0100689 var query1 = encodeURIComponent(
690 '(creator:"' + name + '" | replier:"' + name + '") forum:' + forumId);
691 var query2 = encodeURIComponent(
692 '(creator:"' + name + '" | replier:"' + name + '") forum:any');
693
694 var container = document.createElement('div');
695 container.classList.add('TWPT-previous-posts');
696
697 var badge = createExtBadge();
698 container.appendChild(badge);
699
700 var linkContainer = document.createElement('div');
701 linkContainer.classList.add('TWPT-previous-posts--links');
702
703 addProfileHistoryLink(linkContainer, 'forum', query1);
704 addProfileHistoryLink(linkContainer, 'all', query2);
705
706 container.appendChild(linkContainer);
707
708 mainCardContent.appendChild(container);
avm99963490114d2021-02-05 16:12:20 +0100709}
710
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200711// Send a request to mark the current thread as read
712function markCurrentThreadAsRead() {
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200713 console.debug(
714 '[forceMarkAsRead] %cTrying to mark a thread as read.',
715 'color: #1a73e8;');
716
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200717 var threadRegex =
718 /\/s\/community\/?.*\/forum\/([0-9]+)\/?.*\/thread\/([0-9]+)/;
719
720 var url = location.href;
721 var matches = url.match(threadRegex);
722 if (matches !== null && matches.length > 2) {
723 var forumId = matches[1];
724 var threadId = matches[2];
725
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200726 console.debug('[forceMarkAsRead] Thread details:', {forumId, threadId});
727
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200728 return CCApi(
729 'ViewThread', {
730 1: forumId,
731 2: threadId,
732 // options
733 3: {
734 // pagination
735 1: {
736 2: 0, // maxNum
737 },
738 3: false, // withMessages
739 5: false, // withUserProfile
740 6: true, // withUserReadState
741 9: false, // withRequestorProfile
742 10: false, // withPromotedMessages
743 11: false, // withExpertResponder
744 },
745 },
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200746 true, authuser)
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200747 .then(thread => {
748 if (thread?.[1]?.[6] === true) {
749 console.debug(
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200750 '[forceMarkAsRead] This thread is already marked as read, but marking it as read anyways.');
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200751 }
752
753 var lastMessageId = thread?.[1]?.[2]?.[10];
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200754
Adrià Vilanova Martínezfe8acef2021-07-07 17:27:23 +0200755 console.debug('[forceMarkAsRead] lastMessageId is:', lastMessageId);
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200756
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200757 if (lastMessageId === undefined)
758 throw new Error(
759 'Couldn\'t find lastMessageId in the ViewThread response.');
760
761 return CCApi(
762 'SetUserReadStateBulk', {
763 1: [{
764 1: forumId,
765 2: threadId,
766 3: lastMessageId,
767 }],
768 },
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200769 true, authuser);
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200770 })
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200771 .then(_ => {
772 console.debug(
773 '[forceMarkAsRead] %cSuccessfully set as read!',
774 'color: #1e8e3e;');
775 })
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200776 .catch(err => {
777 console.error(
778 '[forceMarkAsRead] Error while marking current thread as read: ',
779 err);
780 });
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200781 } else {
782 console.error(
783 '[forceMarkAsRead] Couldn\'t retrieve forumId and threadId from the current URL.',
784 url);
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200785 }
786}
787
avm99963490114d2021-02-05 16:12:20 +0100788const watchedNodesSelectors = [
avm9996328fddc62021-02-05 20:33:48 +0100789 // App container (used to set up the intersection observer and inject the dark
790 // mode button)
avm9996311707032021-02-05 19:11:25 +0100791 'ec-app',
792
avm99963490114d2021-02-05 16:12:20 +0100793 // Load more bar (for the "load more"/"load all" buttons)
794 '.load-more-bar',
795
avm99963b3e89862021-05-15 19:58:21 +0200796 // Username span/editor inside ec-user (user profile view)
avm9996390cc2e32021-02-05 18:14:16 +0100797 'ec-user .main-card .header > .name > span',
avm99963b3e89862021-05-15 19:58:21 +0200798 'ec-user .main-card .header > .name > ec-display-name-editor',
avm99963490114d2021-02-05 16:12:20 +0100799
800 // Rich text editor
801 'ec-movable-dialog',
802 'ec-rich-text-editor',
803
804 // Read/unread bulk action in the list of thread, for the batch lock feature
805 'ec-bulk-actions material-button[debugid="mark-read-button"]',
806 'ec-bulk-actions material-button[debugid="mark-unread-button"]',
avm999633eae4522021-04-22 01:14:27 +0200807
808 // Thread list items (used to inject the avatars)
809 'li',
avm99963a007d492021-05-02 12:32:03 +0200810
811 // Thread list (used for the autorefresh feature)
812 'ec-thread-list',
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200813
814 // Unified profile iframe
815 'iframe',
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200816
817 // Thread component
818 'ec-thread',
avm99963490114d2021-02-05 16:12:20 +0100819];
820
821function handleCandidateNode(node) {
822 if (typeof node.classList !== 'undefined') {
avm9996328fddc62021-02-05 20:33:48 +0100823 if (('tagName' in node) && node.tagName == 'EC-APP') {
824 // Set up the intersectionObserver
825 if (typeof intersectionObserver === 'undefined') {
826 var scrollableContent = node.querySelector('.scrollable-content');
827 if (scrollableContent !== null) {
828 intersectionOptions = {
829 root: scrollableContent,
830 rootMargin: '0px',
831 threshold: 1.0,
832 };
avm9996311707032021-02-05 19:11:25 +0100833
avm9996328fddc62021-02-05 20:33:48 +0100834 intersectionObserver = new IntersectionObserver(
835 intersectionCallback, intersectionOptions);
836 }
837 }
838
839 // Inject the dark mode button
840 if (options.ccdarktheme && options.ccdarktheme_mode == 'switch') {
841 var rightControl = node.querySelector('header .right-control');
842 if (rightControl !== null) injectDarkModeButton(rightControl);
avm99963d24e2db2021-02-05 20:03:55 +0100843 }
avm99963490114d2021-02-05 16:12:20 +0100844 }
845
avm9996311707032021-02-05 19:11:25 +0100846 // Start the intersectionObserver for the "load more"/"load all" buttons
847 // inside a thread
848 if ((options.thread || options.threadall) &&
849 node.classList.contains('load-more-bar')) {
850 if (typeof intersectionObserver !== 'undefined') {
851 if (options.thread)
852 intersectionObserver.observe(node.querySelector('.load-more-button'));
853 if (options.threadall)
854 intersectionObserver.observe(node.querySelector('.load-all-button'));
855 } else {
856 console.warn(
857 '[infinitescroll] ' +
858 'The intersectionObserver is not ready yet.');
859 }
avm99963490114d2021-02-05 16:12:20 +0100860 }
861
862 // Show the "previous posts" links
863 // Here we're selecting the 'ec-user > div' element (unique child)
avm9996390cc2e32021-02-05 18:14:16 +0100864 if (options.history &&
avm99963b3e89862021-05-15 19:58:21 +0200865 (node.matches('ec-user .main-card .header > .name > span') ||
866 node.matches(
867 'ec-user .main-card .header > .name > ec-display-name-editor'))) {
avm99963490114d2021-02-05 16:12:20 +0100868 injectPreviousPostsLinks(node);
869 }
870
871 // Fix the drag&drop issue with the rich text editor
872 //
873 // We target both tags because in different contexts different
874 // elements containing the text editor get added to the DOM structure.
875 // Sometimes it's a EC-MOVABLE-DIALOG which already contains the
876 // EC-RICH-TEXT-EDITOR, and sometimes it's the EC-RICH-TEXT-EDITOR
877 // directly.
878 if (options.ccdragndropfix && ('tagName' in node) &&
879 (node.tagName == 'EC-MOVABLE-DIALOG' ||
880 node.tagName == 'EC-RICH-TEXT-EDITOR')) {
881 applyDragAndDropFix(node);
882 }
883
884 // Inject the batch lock button in the thread list
885 if (options.batchlock && nodeIsReadToggleBtn(node)) {
886 addBatchLockBtn(node);
887 }
avm999633eae4522021-04-22 01:14:27 +0200888
889 // Inject avatar links to threads in the thread list
890 if (options.threadlistavatars && ('tagName' in node) &&
891 (node.tagName == 'LI') &&
892 node.querySelector('ec-thread-summary') !== null) {
Adrià Vilanova Martínez3c37e842021-07-10 19:14:47 +0200893 avatars.inject(node);
avm999633eae4522021-04-22 01:14:27 +0200894 }
avm99963a007d492021-05-02 12:32:03 +0200895
896 // Set up the autorefresh list feature
897 if (options.autorefreshlist && ('tagName' in node) &&
898 node.tagName == 'EC-THREAD-LIST') {
899 autoRefresh.setUp();
900 }
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200901
902 // Redirect unified profile iframe to dark version if applicable
903 if (node.tagName == 'IFRAME' && isDarkThemeOn() &&
904 unifiedProfilesFix.checkIframe(node)) {
905 unifiedProfilesFix.fixIframe(node);
906 }
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200907
908 // Force mark thread as read
909 if (options.forcemarkasread && node.tagName == 'EC-THREAD') {
910 markCurrentThreadAsRead();
911 }
avm99963a007d492021-05-02 12:32:03 +0200912 }
913}
914
915function handleRemovedNode(node) {
916 // Remove snackbar when exiting thread list view
Adrià Vilanova Martínez148f75c2021-07-07 13:47:34 +0200917 if (options.autorefreshlist && 'tagName' in node &&
918 node.tagName == 'EC-THREAD-LIST') {
avm99963a007d492021-05-02 12:32:03 +0200919 autoRefresh.hideUpdatePrompt();
avm99963490114d2021-02-05 16:12:20 +0100920 }
921}
922
avm99963847ee632019-03-27 00:57:44 +0100923function mutationCallback(mutationList, observer) {
924 mutationList.forEach((mutation) => {
avm99963b69eb3d2020-08-20 02:03:44 +0200925 if (mutation.type == 'childList') {
926 mutation.addedNodes.forEach(function(node) {
avm99963490114d2021-02-05 16:12:20 +0100927 handleCandidateNode(node);
avm99963847ee632019-03-27 00:57:44 +0100928 });
avm99963a007d492021-05-02 12:32:03 +0200929
930 mutation.removedNodes.forEach(function(node) {
931 handleRemovedNode(node);
932 });
avm99963847ee632019-03-27 00:57:44 +0100933 }
934 });
935}
936
avm99963adf90862020-04-12 13:27:45 +0200937function intersectionCallback(entries, observer) {
avm99963847ee632019-03-27 00:57:44 +0100938 entries.forEach(entry => {
939 if (entry.isIntersecting) {
940 entry.target.click();
941 }
942 });
943};
944
945var observerOptions = {
946 childList: true,
avm99963b69eb3d2020-08-20 02:03:44 +0200947 subtree: true,
avm99963129fb502020-08-28 05:18:53 +0200948};
avm99963847ee632019-03-27 00:57:44 +0100949
avm99963129fb502020-08-28 05:18:53 +0200950chrome.storage.sync.get(null, function(items) {
951 options = items;
avm99963cbea3142019-03-28 00:48:15 +0100952
avm99963a2945b62020-11-27 00:32:02 +0100953 var startup =
954 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
955 authuser = startup[2][1] || '0';
956
avm99963490114d2021-02-05 16:12:20 +0100957 // Before starting the mutation Observer, check whether we missed any
avm9996311707032021-02-05 19:11:25 +0100958 // mutations by manually checking whether some watched nodes already
959 // exist.
avm99963490114d2021-02-05 16:12:20 +0100960 var cssSelectors = watchedNodesSelectors.join(',');
961 document.querySelectorAll(cssSelectors)
962 .forEach(node => handleCandidateNode(node));
963
avm99963129fb502020-08-28 05:18:53 +0200964 mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100965 mutationObserver.observe(document.body, observerOptions);
avm99963cbea3142019-03-28 00:48:15 +0100966
avm99963129fb502020-08-28 05:18:53 +0200967 if (options.fixedtoolbar) {
968 injectStyles(
avm999630bc113a2020-09-07 13:02:11 +0200969 'ec-bulk-actions{position: sticky; top: 0; background: var(--TWPT-primary-background, #fff); z-index: 96;}');
avm99963129fb502020-08-28 05:18:53 +0200970 }
avm99963ae6a26d2020-04-12 14:03:51 +0200971
avm99963129fb502020-08-28 05:18:53 +0200972 if (options.increasecontrast) {
avm999630bc113a2020-09-07 13:02:11 +0200973 injectStyles(
avm99963a2a06442020-11-25 21:11:10 +0100974 '.thread-summary.read:not(.checked){background: var(--TWPT-thread-read-background, #ecedee)!important;}');
avm99963129fb502020-08-28 05:18:53 +0200975 }
avm999630f9503f2020-07-27 13:56:52 +0200976
avm99963129fb502020-08-28 05:18:53 +0200977 if (options.stickysidebarheaders) {
978 injectStyles(
avm999630bc113a2020-09-07 13:02:11 +0200979 'material-drawer .main-header{background: var(--TWPT-drawer-background, #fff)!important; position: sticky; top: 0; z-index: 1;}');
980 }
981
avm99963698d3762021-02-16 01:19:54 +0100982 if (options.enhancedannouncementsdot) {
983 injectStylesheet(
984 chrome.runtime.getURL('injections/enhanced_announcements_dot.css'));
985 }
986
avm99963d98126f2021-02-17 10:44:36 +0100987 if (options.repositionexpandthread) {
988 injectStylesheet(
989 chrome.runtime.getURL('injections/reposition_expand_thread.css'));
990 }
991
avm99963129942f2020-09-08 02:07:18 +0200992 if (options.ccforcehidedrawer) {
993 var drawer = document.querySelector('material-drawer');
994 if (drawer !== null && drawer.classList.contains('mat-drawer-expanded')) {
995 document.querySelector('.material-drawer-button').click();
996 }
997 }
avm99963f5923962020-12-07 16:44:37 +0100998
999 if (options.batchlock) {
1000 injectScript(chrome.runtime.getURL('injections/batchlock_inject.js'));
Adrià Vilanova Martínez74273ee2021-06-25 19:23:27 +02001001 injectStylesheet(chrome.runtime.getURL('injections/batchlock_inject.css'));
avm99963f5923962020-12-07 16:44:37 +01001002 }
avm999633eae4522021-04-22 01:14:27 +02001003
1004 if (options.threadlistavatars) {
1005 injectStylesheet(
1006 chrome.runtime.getURL('injections/thread_list_avatars.css'));
1007 }
avm99963a007d492021-05-02 12:32:03 +02001008
1009 if (options.autorefreshlist) {
1010 injectStylesheet(chrome.runtime.getURL('injections/autorefresh_list.css'));
1011 }
avm99963129fb502020-08-28 05:18:53 +02001012});