blob: 837c2ae1f30f0c0efb493ab7e92619e02555daa8 [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
avm999633eae4522021-04-22 01:14:27 +0200245// TODO(avm99963): This is a prototype. DON'T FORGET TO ADD ERROR HANDLING.
246function injectAvatars(node) {
247 var header = node.querySelector(
248 'ec-thread-summary .main-header .panel-description a.header');
249 if (header === null) return;
250
251 var link = parseUrl(header.href);
252 if (link === false) return;
253
254 var APIRequestUrl = 'https://support.google.com/s/community/api/ViewThread' +
255 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
256
257 fetch(APIRequestUrl, {
258 'headers': {
259 'content-type': 'text/plain; charset=utf-8',
260 },
261 'body': JSON.stringify({
262 1: link.forum,
263 2: link.thread,
264 3: {
265 1: {2: 15},
266 3: true,
267 5: true,
268 10: true,
269 16: true,
270 18: true,
271 }
272 }),
273 'method': 'POST',
274 'mode': 'cors',
275 'credentials': 'omit',
276 })
277 .then(res => {
278 if (res.status == 200 || res.status == 400) {
279 return res.json().then(data => ({
280 status: res.status,
281 body: data,
282 }));
283 } else {
284 throw new Error('Status code ' + res.status + ' was not expected.');
285 }
286 })
287 .then(res => {
288 if (res.status == 400) {
289 throw new Error(
290 res.body[4] ||
291 ('Response status: 400. Error code: ' + res.body[2]));
292 }
293
294 return res.body;
295 })
296 .then(data => {
297 if (!('1' in data) || !('8' in data['1'])) return false;
298
299 var messages = data['1']['8'];
300 if (messages == 0) return;
301
302 var avatarUrls = [];
303
304 if (!('3' in data['1'])) return false;
305 for (var m of data['1']['3']) {
306 if (!('3' in m) || !('1' in m['3']) || !('2' in m['3']['1']))
307 continue;
308
309 var url = m['3']['1']['2'];
310
311 if (!avatarUrls.includes(url)) avatarUrls.push(url);
312
313 if (avatarUrls.length == 3) break;
314 }
315
316 var avatarsContainer = document.createElement('div');
317 avatarsContainer.classList.add('TWPT-avatars');
318
319 var count = Math.floor(Math.random() * 4);
320
321 for (var i = 0; i < avatarUrls.length; ++i) {
322 var avatar = document.createElement('div');
323 avatar.classList.add('TWPT-avatar');
avm99963a007d492021-05-02 12:32:03 +0200324 avatar.style.backgroundImage = 'url(\'' + avatarUrls[i] + '\')';
avm999633eae4522021-04-22 01:14:27 +0200325 avatarsContainer.appendChild(avatar);
326 }
327
328 header.appendChild(avatarsContainer);
329 });
330}
331
avm99963a007d492021-05-02 12:32:03 +0200332var autoRefresh = {
333 isLookingForUpdates: false,
334 isUpdatePromptShown: false,
335 lastTimestamp: null,
336 filter: null,
337 path: null,
338 snackbar: null,
339 interval: null,
340 firstCallTimeout: null,
341 intervalMs: 3 * 60 * 1000, // 3 minutes
342 firstCallDelayMs: 3 * 1000, // 3 seconds
343 getStartupData() {
344 return JSON.parse(
345 document.querySelector('html').getAttribute('data-startup'));
346 },
347 isOrderedByTimestampDescending() {
348 var startup = this.getStartupData();
349 // Returns orderOptions.by == TIMESTAMP && orderOptions.desc == true
350 return (
351 startup?.[1]?.[1]?.[3]?.[14]?.[1] == 1 &&
352 startup?.[1]?.[1]?.[3]?.[14]?.[2] == true);
353 },
354 getCustomFilter(path) {
355 var searchRegex = /^\/s\/community\/search\/([^\/]*)/;
356 var matches = path.match(searchRegex);
357 if (matches !== null && matches.length > 1) {
358 var search = decodeURIComponent(matches[1]);
359 var params = new URLSearchParams(search);
360 return params.get('query') || '';
361 }
362
363 return '';
364 },
365 filterHasOverride(filter, override) {
366 var escapedOverride = override.replace(/([^\w\d\s])/gi, '\\$1');
367 var regex = new RegExp('[^a-zA-Z0-9]?' + escapedOverride + ':');
368 return regex.test(filter);
369 },
370 getFilter(path) {
371 var query = this.getCustomFilter(path);
372
373 // Note: This logic has been copied and adapted from the
374 // _buildQuery$1$threadId function in the Community Console
375 var conditions = '';
376 var startup = this.getStartupData();
377
378 // TODO(avm99963): if the selected forums are changed without reloading the
379 // page, this will get the old selected forums. Fix this.
380 var forums = startup?.[1]?.[1]?.[3]?.[8] ?? [];
381 if (!this.filterHasOverride(query, 'forum') && forums !== null &&
382 forums.length > 0)
383 conditions += ' forum:(' + forums.join(' | ') + ')';
384
385 var langs = startup?.[1]?.[1]?.[3]?.[5] ?? [];
386 if (!this.filterHasOverride(query, 'lang') && langs !== null &&
387 langs.length > 0)
388 conditions += ' lang:(' + langs.map(l => '"' + l + '"').join(' | ') + ')';
389
390 if (query.length !== 0 && conditions.length !== 0)
391 return '(' + query + ')' + conditions;
392 return query + conditions;
393 },
394 getLastTimestamp() {
395 var APIRequestUrl = 'https://support.google.com/s/community/api/ViewForum' +
396 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
397
398 return fetch(APIRequestUrl, {
399 'headers': {
400 'content-type': 'text/plain; charset=utf-8',
401 },
402 'body': JSON.stringify({
403 1: '0', // TODO: Change, when only a forum is selected, it
404 // should be set here
405 2: {
406 1: {
407 2: 2,
408 },
409 2: {
410 1: 1,
411 2: true,
412 },
413 12: this.filter,
414 },
415 }),
416 'method': 'POST',
417 'mode': 'cors',
418 'credentials': 'include',
419 })
420 .then(res => {
421 if (res.status == 200 || res.status == 400) {
422 return res.json().then(data => ({
423 status: res.status,
424 body: data,
425 }));
426 } else {
427 throw new Error('Status code ' + res.status + ' was not expected.');
428 }
429 })
430 .then(res => {
431 if (res.status == 400) {
432 throw new Error(
433 res.body[4] ||
434 ('Response status: 400. Error code: ' + res.body[2]));
435 }
436
437 return res.body;
438 })
439 .then(body => {
440 var timestamp = body?.[1]?.[2]?.[0]?.[2]?.[17];
441 if (timestamp === undefined)
442 throw new Error(
443 'Unexpected body of response (' +
444 (body?.[1]?.[2]?.[0] === undefined ?
445 'no threads were returned' :
446 'the timestamp value is not present in the first thread') +
447 ').');
448
449 return timestamp;
450 });
451 // TODO(avm99963): Add retry mechanism (sometimes thread lists are empty,
452 // but when loading the next page the thread appears).
453 //
454 // NOTE(avm99963): It seems like loading the first 2 threads instead of only
455 // the first one fixes this (empty lists are now rarely returned).
456 },
457 unregister() {
458 console.debug('autorefresh_list: unregistering');
459
460 if (!this.isLookingForUpdates) return;
461
462 window.clearTimeout(this.firstCallTimeout);
463 window.clearInterval(this.interval);
464 this.isUpdatePromptShown = false;
465 this.isLookingForUpdates = false;
466 },
467 showUpdatePrompt() {
468 this.snackbar.classList.remove('TWPT-hidden');
469 document.title = '[!!!] ' + document.title.replace('[!!!] ', '');
470 this.isUpdatePromptShown = true;
471 },
472 hideUpdatePrompt() {
473 this.snackbar.classList.add('TWPT-hidden');
474 document.title = document.title.replace('[!!!] ', '');
475 this.isUpdatePromptShown = false;
476 },
477 injectUpdatePrompt() {
478 var pane = document.createElement('div');
479 pane.classList.add('TWPT-pane-for-snackbar');
480
481 var snackbar = document.createElement('material-snackbar-panel');
482 snackbar.classList.add('TWPT-snackbar');
483 snackbar.classList.add('TWPT-hidden');
484
485 var ac = document.createElement('div');
486 ac.classList.add('TWPT-animation-container');
487
488 var nb = document.createElement('div');
489 nb.classList.add('TWPT-notification-bar');
490
491 var ft = document.createElement('focus-trap');
492
493 var content = document.createElement('div');
494 content.classList.add('TWPT-focus-content-wrapper');
495
496 var badge = createExtBadge();
497
498 var message = document.createElement('div');
499 message.classList.add('TWPT-message');
500 message.textContent =
501 chrome.i18n.getMessage('inject_autorefresh_list_snackbar_message');
502
503 var action = document.createElement('div');
504 action.classList.add('TWPT-action');
505 action.textContent =
506 chrome.i18n.getMessage('inject_autorefresh_list_snackbar_action');
507
508 action.addEventListener('click', e => {
509 this.hideUpdatePrompt();
510 document.querySelector('.app-title-button').click();
511 });
512
513 content.append(badge, message, action);
514 ft.append(content);
515 nb.append(ft);
516 ac.append(nb);
517 snackbar.append(ac);
518 pane.append(snackbar);
519 document.getElementById('default-acx-overlay-container').append(pane);
520 this.snackbar = snackbar;
521 },
522 checkUpdate() {
523 if (location.pathname != this.path) {
524 this.unregister();
525 return;
526 }
527
528 if (this.isUpdatePromptShown) return;
529
530 console.debug('Checking for update at: ', new Date());
531
532 this.getLastTimestamp()
533 .then(timestamp => {
534 if (timestamp != this.lastTimestamp) this.showUpdatePrompt();
535 })
536 .catch(
537 err => console.error(
538 'Coudln\'t get last timestamp (while updating): ', err));
539 },
540 firstCall() {
541 console.debug(
542 'autorefresh_list: now performing first call to finish setup (filter: [' +
543 this.filter + '])');
544
545 if (location.pathname != this.path) {
546 this.unregister();
547 return;
548 }
549
550 this.getLastTimestamp()
551 .then(timestamp => {
552 this.lastTimestamp = timestamp;
553 var checkUpdateCallback = this.checkUpdate.bind(this);
554 this.interval =
555 window.setInterval(checkUpdateCallback, this.intervalMs);
556 })
557 .catch(
558 err => console.error(
559 'Couldn\'t get last timestamp (while setting up): ', err));
560 },
561 setUp() {
562 if (!this.isOrderedByTimestampDescending()) return;
563
564 this.unregister();
565
566 console.debug('autorefresh_list: starting set up...');
567
568 if (this.snackbar === null) this.injectUpdatePrompt();
569 this.isLookingForUpdates = true;
570 this.path = location.pathname;
571 this.filter = this.getFilter(this.path);
572
573 var firstCall = this.firstCall.bind(this);
574 this.firstCallTimeout = window.setTimeout(firstCall, this.firstCallDelayMs);
575 },
576};
577
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200578function isDarkThemeOn() {
579 if (!options.ccdarktheme) return false;
580
581 if (options.ccdarktheme_mode == 'switch')
582 return options.ccdarktheme_switch_status;
583
584 return window.matchMedia &&
585 window.matchMedia('(prefers-color-scheme: dark)').matches;
586}
587
588var unifiedProfilesFix = {
589 checkIframe(iframe) {
590 var srcRegex = /support.*\.google\.com\/profile\//;
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200591 return srcRegex.test(iframe.src ?? '');
592 },
593 fixIframe(iframe) {
594 console.info('[unifiedProfilesFix] Fixing unified profiles iframe');
595 var url = new URL(iframe.src);
596 url.searchParams.set('dark', 1);
597 iframe.src = url.href;
598 },
599};
600
avm9996390cc2e32021-02-05 18:14:16 +0100601function injectPreviousPostsLinks(nameElement) {
602 var mainCardContent = getNParent(nameElement, 3);
603 if (mainCardContent === null) {
604 console.error(
605 '[previousposts] Couldn\'t find |.main-card-content| element.');
606 return;
avm99963490114d2021-02-05 16:12:20 +0100607 }
avm9996390cc2e32021-02-05 18:14:16 +0100608
609 var forumId = location.href.split('/forum/')[1].split('/')[0] || '0';
610
avm99963193233a2021-05-29 15:49:29 +0200611 var nameTag =
612 (nameElement.tagName == 'EC-DISPLAY-NAME-EDITOR' ?
613 nameElement.querySelector('.top-section > span') ?? nameElement :
614 nameElement);
615 var name = escapeUsername(nameTag.textContent);
avm9996390cc2e32021-02-05 18:14:16 +0100616 var query1 = encodeURIComponent(
617 '(creator:"' + name + '" | replier:"' + name + '") forum:' + forumId);
618 var query2 = encodeURIComponent(
619 '(creator:"' + name + '" | replier:"' + name + '") forum:any');
620
621 var container = document.createElement('div');
622 container.classList.add('TWPT-previous-posts');
623
624 var badge = createExtBadge();
625 container.appendChild(badge);
626
627 var linkContainer = document.createElement('div');
628 linkContainer.classList.add('TWPT-previous-posts--links');
629
630 addProfileHistoryLink(linkContainer, 'forum', query1);
631 addProfileHistoryLink(linkContainer, 'all', query2);
632
633 container.appendChild(linkContainer);
634
635 mainCardContent.appendChild(container);
avm99963490114d2021-02-05 16:12:20 +0100636}
637
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200638// Send a request to mark the current thread as read
639function markCurrentThreadAsRead() {
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200640 console.debug(
641 '[forceMarkAsRead] %cTrying to mark a thread as read.',
642 'color: #1a73e8;');
643
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200644 var threadRegex =
645 /\/s\/community\/?.*\/forum\/([0-9]+)\/?.*\/thread\/([0-9]+)/;
646
647 var url = location.href;
648 var matches = url.match(threadRegex);
649 if (matches !== null && matches.length > 2) {
650 var forumId = matches[1];
651 var threadId = matches[2];
652
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200653 console.debug('[forceMarkAsRead] Thread details:', {forumId, threadId});
654
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200655 return CCApi(
656 'ViewThread', {
657 1: forumId,
658 2: threadId,
659 // options
660 3: {
661 // pagination
662 1: {
663 2: 0, // maxNum
664 },
665 3: false, // withMessages
666 5: false, // withUserProfile
667 6: true, // withUserReadState
668 9: false, // withRequestorProfile
669 10: false, // withPromotedMessages
670 11: false, // withExpertResponder
671 },
672 },
673 authuser)
674 .then(thread => {
675 if (thread?.[1]?.[6] === true) {
676 console.debug(
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200677 '[forceMarkAsRead] This thread is already marked as read, but marking it as read anyways.');
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200678 }
679
680 var lastMessageId = thread?.[1]?.[2]?.[10];
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200681
Adrià Vilanova Martínezfe8acef2021-07-07 17:27:23 +0200682 console.debug('[forceMarkAsRead] lastMessageId is:', lastMessageId);
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200683
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200684 if (lastMessageId === undefined)
685 throw new Error(
686 'Couldn\'t find lastMessageId in the ViewThread response.');
687
688 return CCApi(
689 'SetUserReadStateBulk', {
690 1: [{
691 1: forumId,
692 2: threadId,
693 3: lastMessageId,
694 }],
695 },
696 authuser);
697 })
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200698 .then(_ => {
699 console.debug(
700 '[forceMarkAsRead] %cSuccessfully set as read!',
701 'color: #1e8e3e;');
702 })
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200703 .catch(err => {
704 console.error(
705 '[forceMarkAsRead] Error while marking current thread as read: ',
706 err);
707 });
Adrià Vilanova Martínezcb6fdba2021-07-07 14:42:38 +0200708 } else {
709 console.error(
710 '[forceMarkAsRead] Couldn\'t retrieve forumId and threadId from the current URL.',
711 url);
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200712 }
713}
714
avm99963490114d2021-02-05 16:12:20 +0100715const watchedNodesSelectors = [
avm9996328fddc62021-02-05 20:33:48 +0100716 // App container (used to set up the intersection observer and inject the dark
717 // mode button)
avm9996311707032021-02-05 19:11:25 +0100718 'ec-app',
719
avm99963490114d2021-02-05 16:12:20 +0100720 // Load more bar (for the "load more"/"load all" buttons)
721 '.load-more-bar',
722
avm99963b3e89862021-05-15 19:58:21 +0200723 // Username span/editor inside ec-user (user profile view)
avm9996390cc2e32021-02-05 18:14:16 +0100724 'ec-user .main-card .header > .name > span',
avm99963b3e89862021-05-15 19:58:21 +0200725 'ec-user .main-card .header > .name > ec-display-name-editor',
avm99963490114d2021-02-05 16:12:20 +0100726
727 // Rich text editor
728 'ec-movable-dialog',
729 'ec-rich-text-editor',
730
731 // Read/unread bulk action in the list of thread, for the batch lock feature
732 'ec-bulk-actions material-button[debugid="mark-read-button"]',
733 'ec-bulk-actions material-button[debugid="mark-unread-button"]',
avm999633eae4522021-04-22 01:14:27 +0200734
735 // Thread list items (used to inject the avatars)
736 'li',
avm99963a007d492021-05-02 12:32:03 +0200737
738 // Thread list (used for the autorefresh feature)
739 'ec-thread-list',
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200740
741 // Unified profile iframe
742 'iframe',
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200743
744 // Thread component
745 'ec-thread',
avm99963490114d2021-02-05 16:12:20 +0100746];
747
748function handleCandidateNode(node) {
749 if (typeof node.classList !== 'undefined') {
avm9996328fddc62021-02-05 20:33:48 +0100750 if (('tagName' in node) && node.tagName == 'EC-APP') {
751 // Set up the intersectionObserver
752 if (typeof intersectionObserver === 'undefined') {
753 var scrollableContent = node.querySelector('.scrollable-content');
754 if (scrollableContent !== null) {
755 intersectionOptions = {
756 root: scrollableContent,
757 rootMargin: '0px',
758 threshold: 1.0,
759 };
avm9996311707032021-02-05 19:11:25 +0100760
avm9996328fddc62021-02-05 20:33:48 +0100761 intersectionObserver = new IntersectionObserver(
762 intersectionCallback, intersectionOptions);
763 }
764 }
765
766 // Inject the dark mode button
767 if (options.ccdarktheme && options.ccdarktheme_mode == 'switch') {
768 var rightControl = node.querySelector('header .right-control');
769 if (rightControl !== null) injectDarkModeButton(rightControl);
avm99963d24e2db2021-02-05 20:03:55 +0100770 }
avm99963490114d2021-02-05 16:12:20 +0100771 }
772
avm9996311707032021-02-05 19:11:25 +0100773 // Start the intersectionObserver for the "load more"/"load all" buttons
774 // inside a thread
775 if ((options.thread || options.threadall) &&
776 node.classList.contains('load-more-bar')) {
777 if (typeof intersectionObserver !== 'undefined') {
778 if (options.thread)
779 intersectionObserver.observe(node.querySelector('.load-more-button'));
780 if (options.threadall)
781 intersectionObserver.observe(node.querySelector('.load-all-button'));
782 } else {
783 console.warn(
784 '[infinitescroll] ' +
785 'The intersectionObserver is not ready yet.');
786 }
avm99963490114d2021-02-05 16:12:20 +0100787 }
788
789 // Show the "previous posts" links
790 // Here we're selecting the 'ec-user > div' element (unique child)
avm9996390cc2e32021-02-05 18:14:16 +0100791 if (options.history &&
avm99963b3e89862021-05-15 19:58:21 +0200792 (node.matches('ec-user .main-card .header > .name > span') ||
793 node.matches(
794 'ec-user .main-card .header > .name > ec-display-name-editor'))) {
avm99963490114d2021-02-05 16:12:20 +0100795 injectPreviousPostsLinks(node);
796 }
797
798 // Fix the drag&drop issue with the rich text editor
799 //
800 // We target both tags because in different contexts different
801 // elements containing the text editor get added to the DOM structure.
802 // Sometimes it's a EC-MOVABLE-DIALOG which already contains the
803 // EC-RICH-TEXT-EDITOR, and sometimes it's the EC-RICH-TEXT-EDITOR
804 // directly.
805 if (options.ccdragndropfix && ('tagName' in node) &&
806 (node.tagName == 'EC-MOVABLE-DIALOG' ||
807 node.tagName == 'EC-RICH-TEXT-EDITOR')) {
808 applyDragAndDropFix(node);
809 }
810
811 // Inject the batch lock button in the thread list
812 if (options.batchlock && nodeIsReadToggleBtn(node)) {
813 addBatchLockBtn(node);
814 }
avm999633eae4522021-04-22 01:14:27 +0200815
816 // Inject avatar links to threads in the thread list
817 if (options.threadlistavatars && ('tagName' in node) &&
818 (node.tagName == 'LI') &&
819 node.querySelector('ec-thread-summary') !== null) {
820 injectAvatars(node);
821 }
avm99963a007d492021-05-02 12:32:03 +0200822
823 // Set up the autorefresh list feature
824 if (options.autorefreshlist && ('tagName' in node) &&
825 node.tagName == 'EC-THREAD-LIST') {
826 autoRefresh.setUp();
827 }
Adrià Vilanova Martínezc6aacfa2021-06-09 14:16:11 +0200828
829 // Redirect unified profile iframe to dark version if applicable
830 if (node.tagName == 'IFRAME' && isDarkThemeOn() &&
831 unifiedProfilesFix.checkIframe(node)) {
832 unifiedProfilesFix.fixIframe(node);
833 }
Adrià Vilanova Martíneza10fff22021-06-29 21:07:40 +0200834
835 // Force mark thread as read
836 if (options.forcemarkasread && node.tagName == 'EC-THREAD') {
837 markCurrentThreadAsRead();
838 }
avm99963a007d492021-05-02 12:32:03 +0200839 }
840}
841
842function handleRemovedNode(node) {
843 // Remove snackbar when exiting thread list view
Adrià Vilanova Martínez148f75c2021-07-07 13:47:34 +0200844 if (options.autorefreshlist && 'tagName' in node &&
845 node.tagName == 'EC-THREAD-LIST') {
avm99963a007d492021-05-02 12:32:03 +0200846 autoRefresh.hideUpdatePrompt();
avm99963490114d2021-02-05 16:12:20 +0100847 }
848}
849
avm99963847ee632019-03-27 00:57:44 +0100850function mutationCallback(mutationList, observer) {
851 mutationList.forEach((mutation) => {
avm99963b69eb3d2020-08-20 02:03:44 +0200852 if (mutation.type == 'childList') {
853 mutation.addedNodes.forEach(function(node) {
avm99963490114d2021-02-05 16:12:20 +0100854 handleCandidateNode(node);
avm99963847ee632019-03-27 00:57:44 +0100855 });
avm99963a007d492021-05-02 12:32:03 +0200856
857 mutation.removedNodes.forEach(function(node) {
858 handleRemovedNode(node);
859 });
avm99963847ee632019-03-27 00:57:44 +0100860 }
861 });
862}
863
avm99963adf90862020-04-12 13:27:45 +0200864function intersectionCallback(entries, observer) {
avm99963847ee632019-03-27 00:57:44 +0100865 entries.forEach(entry => {
866 if (entry.isIntersecting) {
867 entry.target.click();
868 }
869 });
870};
871
872var observerOptions = {
873 childList: true,
avm99963b69eb3d2020-08-20 02:03:44 +0200874 subtree: true,
avm99963129fb502020-08-28 05:18:53 +0200875};
avm99963847ee632019-03-27 00:57:44 +0100876
avm99963129fb502020-08-28 05:18:53 +0200877chrome.storage.sync.get(null, function(items) {
878 options = items;
avm99963cbea3142019-03-28 00:48:15 +0100879
avm99963a2945b62020-11-27 00:32:02 +0100880 var startup =
881 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
882 authuser = startup[2][1] || '0';
883
avm99963490114d2021-02-05 16:12:20 +0100884 // Before starting the mutation Observer, check whether we missed any
avm9996311707032021-02-05 19:11:25 +0100885 // mutations by manually checking whether some watched nodes already
886 // exist.
avm99963490114d2021-02-05 16:12:20 +0100887 var cssSelectors = watchedNodesSelectors.join(',');
888 document.querySelectorAll(cssSelectors)
889 .forEach(node => handleCandidateNode(node));
890
avm99963129fb502020-08-28 05:18:53 +0200891 mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100892 mutationObserver.observe(document.body, observerOptions);
avm99963cbea3142019-03-28 00:48:15 +0100893
avm99963129fb502020-08-28 05:18:53 +0200894 if (options.fixedtoolbar) {
895 injectStyles(
avm999630bc113a2020-09-07 13:02:11 +0200896 'ec-bulk-actions{position: sticky; top: 0; background: var(--TWPT-primary-background, #fff); z-index: 96;}');
avm99963129fb502020-08-28 05:18:53 +0200897 }
avm99963ae6a26d2020-04-12 14:03:51 +0200898
avm99963129fb502020-08-28 05:18:53 +0200899 if (options.increasecontrast) {
avm999630bc113a2020-09-07 13:02:11 +0200900 injectStyles(
avm99963a2a06442020-11-25 21:11:10 +0100901 '.thread-summary.read:not(.checked){background: var(--TWPT-thread-read-background, #ecedee)!important;}');
avm99963129fb502020-08-28 05:18:53 +0200902 }
avm999630f9503f2020-07-27 13:56:52 +0200903
avm99963129fb502020-08-28 05:18:53 +0200904 if (options.stickysidebarheaders) {
905 injectStyles(
avm999630bc113a2020-09-07 13:02:11 +0200906 'material-drawer .main-header{background: var(--TWPT-drawer-background, #fff)!important; position: sticky; top: 0; z-index: 1;}');
907 }
908
avm99963698d3762021-02-16 01:19:54 +0100909 if (options.enhancedannouncementsdot) {
910 injectStylesheet(
911 chrome.runtime.getURL('injections/enhanced_announcements_dot.css'));
912 }
913
avm99963d98126f2021-02-17 10:44:36 +0100914 if (options.repositionexpandthread) {
915 injectStylesheet(
916 chrome.runtime.getURL('injections/reposition_expand_thread.css'));
917 }
918
avm99963129942f2020-09-08 02:07:18 +0200919 if (options.ccforcehidedrawer) {
920 var drawer = document.querySelector('material-drawer');
921 if (drawer !== null && drawer.classList.contains('mat-drawer-expanded')) {
922 document.querySelector('.material-drawer-button').click();
923 }
924 }
avm99963f5923962020-12-07 16:44:37 +0100925
926 if (options.batchlock) {
927 injectScript(chrome.runtime.getURL('injections/batchlock_inject.js'));
Adrià Vilanova Martínez74273ee2021-06-25 19:23:27 +0200928 injectStylesheet(chrome.runtime.getURL('injections/batchlock_inject.css'));
avm99963f5923962020-12-07 16:44:37 +0100929 }
avm999633eae4522021-04-22 01:14:27 +0200930
931 if (options.threadlistavatars) {
932 injectStylesheet(
933 chrome.runtime.getURL('injections/thread_list_avatars.css'));
934 }
avm99963a007d492021-05-02 12:32:03 +0200935
936 if (options.autorefreshlist) {
937 injectStylesheet(chrome.runtime.getURL('injections/autorefresh_list.css'));
938 }
avm99963129fb502020-08-28 05:18:53 +0200939});