blob: 00428b7756714dd0846fc1205c6d3da7ca475afd [file] [log] [blame]
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +01001import {MDCTooltip} from '@material/tooltip';
2import {waitFor} from 'poll-until-promise';
3
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +01004import {parseUrl} from '../../common/commonUtils.js';
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +01005import {isOptionEnabled} from '../../common/optionsUtils.js';
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +01006import {createPlainTooltip} from '../../common/tooltip.js';
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +01007
8import {createExtBadge} from './utils/common.js';
9
10const kViewUnifiedUserResponseEvent = 'TWPT_ViewUnifiedUserResponse';
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +010011const kListCannedResponsesResponse = 'TWPT_ListCannedResponsesResponse';
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +010012const kViewThreadResponse = 'TWPT_ViewThreadResponse';
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +010013
14const kAbuseCategories = [
15 ['1', 'Account'],
16 ['2', 'Display name'],
17 ['3', 'Avatar'],
18];
19const kAbuseViolationCategories = {
20 0: 'NO_VIOLATION',
21 1: 'COMMUNITY_POLICY_VIOLATION',
22 2: 'LEGAL_VIOLATION',
23 3: 'CSAI_VIOLATION',
24 4: 'OTHER_VIOLATION',
25};
26const kAbuseViolationTypes = {
27 0: 'UNSPECIFIED',
28 23: 'ACCOUNT_DISABLED',
29 55: 'ACCOUNT_HAS_SERVICES_DISABLED',
30 35: 'ACCOUNT_HIJACKED',
31 96: 'ACCOUNT_LEAKED_CREDENTIALS',
32 92: 'ACCOUNT_NOT_SUPPORTED',
33 81: 'ARTISTIC_NUDITY',
34 66: 'BAD_BEHAVIOR_PATTERN',
35 78: 'BAD_ENGAGEMENT_BEHAVIOR_PATTERN',
36 79: 'BORDERLINE_HARASSMENT',
37 80: 'BORDERLINE_HATE_SPEECH',
38 38: 'BOTNET',
39 32: 'BRANDING_VIOLATION',
40 100: 'CAPITALIZING_TRAGIC_EVENTS',
41 105: 'CLOAKING',
42 49: 'COIN_MINING',
43 7: 'COMMERCIAL_CONTENT',
44 97: 'COPPA_REGULATED',
45 57: 'COPYRIGHT_CIRCUMVENTION',
46 8: 'COPYRIGHTED_CONTENT',
47 58: 'COURT_ORDER',
48 51: 'CSAI',
49 94: 'CSAI_INSPECT',
50 52: 'CSAI_CARTOON_HUMOR',
51 53: 'CSAI_SOLICITATION',
52 108: 'CSAI_NON_APPARENT',
53 67: 'DANGEROUS',
54 37: 'DATA_SCRAPING',
55 86: 'DECEPTIVE_OAUTH_IMPLEMENTATION',
56 46: 'DEFAMATORY_CONTENT',
57 36: 'DELINQUENT_BILLING',
58 30: 'DISRUPTION_ATTEMPT',
59 112: 'DOMESTIC_INTERFERENCE',
60 22: 'DOS',
61 9: 'DUPLICATE_CONTENT',
62 68: 'DUPLICATE_LOCAL_PAGE',
63 121: 'NON_QUALIFYING_ORGANIZATION',
64 115: 'EGREGIOUS_INTERACTION_WITH_MINOR',
65 83: 'ENGAGEMENT_COLLUSION',
66 41: 'EXPLOIT_ATTACKS',
67 65: 'FAKE_USER',
68 2: 'FRAUD',
69 21: 'FREE_TRIAL_VIOLATION',
70 43: 'GIBBERISH',
71 101: 'FOREIGN_INTERFERENCE',
72 59: 'GOVERNMENT_ORDER',
73 10: 'GRAPHICAL_VIOLENCE',
74 11: 'HARASSMENT',
75 12: 'HATE_SPEECH',
76 90: 'IDENTICAL_PRODUCT_NAME',
77 60: 'ILLEGAL_DRUGS',
78 13: 'IMPERSONATION',
79 69: 'IMPERSONATION_WITH_PII',
80 116: 'INAPPROPRIATE_INTERACTION_WITH_MINOR',
81 45: 'INAPPROPRIATE_CONTENT_SPEECH',
82 106: 'INTENTIONAL_THWARTING',
83 27: 'INTRUSION_ATTEMPT',
84 87: 'INVALID_API_USAGE',
85 14: 'INVALID_CONTENT',
86 20: 'INVALID_GCE_USAGE',
87 120: 'INVALID_STORAGE_USAGE',
88 15: 'INVALID_IMAGE_QUALITY',
89 88: 'INVALID_API_PRIVACY_POLICY_DISCLOSURE',
90 54: 'INVALID_USAGE_OF_IP_PROXYING',
91 99: 'KEYWORD_STUFFING',
92 61: 'LEGAL_COUNTERFEIT',
93 62: 'LEGAL_EXPORT',
94 63: 'LEGAL_PRIVACY',
95 33: 'LEGAL_REVIEW',
96 91: 'LEGAL_PROTECTED',
97 70: 'LOW_QUALITY_CONTENT',
98 93: 'LOW_REPUTATION_PHONE_NUMBER',
99 6: 'MALICIOUS_SOFTWARE',
100 40: 'MALWARE',
101 113: 'MISLEADING',
102 114: 'MISREP_OF_ID',
103 89: 'MEMBER_OF_ABUSIVE_GCE_NETWORK',
104 84: 'NON_CONSENSUAL_EXPLICIT_IMAGERY',
105 1: 'NONE',
106 102: 'OFF_TOPIC',
107 31: 'OPEN_PROXY',
108 28: 'PAYMENT_FRAUD',
109 16: 'PEDOPHILIA',
110 71: 'PERSONAL_INFORMATION_CONTENT',
111 25: 'PHISHING',
112 34: 'POLICY_REVIEW',
113 17: 'PORNOGRAPHY',
114 29: 'QUOTA_CIRCUMVENTION',
115 72: 'QUOTA_EXCEEDED',
116 73: 'REGULATED',
117 24: 'REPEATED_POLICY_VIOLATION',
118 104: 'RESOURCE_COMPROMISED',
119 107: 'REWARD_PROGRAMS_ABUSE',
120 74: 'ROGUE_PHARMA',
121 82: 'ESCORT',
122 75: 'SPAMMY_LOCAL_VERTICAL',
123 39: 'SEND_EMAIL_SPAM',
124 117: 'SEXTORTION',
125 118: 'SEX_TRAFFICKING',
126 44: 'SEXUALLY_EXPLICIT_CONTENT',
127 3: 'SHARDING',
128 95: 'SOCIAL_ENGINEERING',
129 109: 'SUSPICIOUS',
130 19: 'TRADEMARK_CONTENT',
131 50: 'TRAFFIC_PUMPING',
132 76: 'UNSAFE_RACY',
133 103: 'UNUSUAL_ACTIVITY_ALERT',
134 64: 'UNWANTED_CONTENT',
135 26: 'UNWANTED_SOFTWARE',
136 77: 'VIOLENT_EXTREMISM',
137 119: 'UNAUTH_IMAGES_OF_MINORS',
138 85: 'UNAUTHORIZED_SERVICE_RESELLING',
139 98: 'CSAI_EXTERNAL',
140 5: 'SPAM',
141 4: 'UNSAFE',
142 47: 'CHILD_PORNOGRAPHY_INCITATION',
143 18: 'TERRORISM_SUPPORT',
144 56: 'CSAI_WORST_OF_WORST',
145};
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100146const kItemMetadataState = {
147 0: 'UNDEFINED',
148 1: 'PUBLISHED',
149 2: 'DRAFT',
150 3: 'AUTOMATED_ABUSE_TAKE_DOWN_HIDE',
151 4: 'AUTOMATED_ABUSE_TAKE_DOWN_DELETE',
152 13: 'AUTOMATED_ABUSE_REINSTATE',
153 10: 'AUTOMATED_OFF_TOPIC_HIDE',
154 14: 'AUTOMATED_FLAGGED_PENDING_MANUAL_REVIEW',
155 5: 'USER_FLAGGED_PENDING_MANUAL_REVIEW',
156 6: 'OWNER_DELETED',
157 7: 'MANUAL_TAKE_DOWN_HIDE',
158 17: 'MANUAL_PROFILE_TAKE_DOWN_SUSPEND',
159 8: 'MANUAL_TAKE_DOWN_DELETE',
160 18: 'REINSTATE_PROFILE_TAKEDOWN',
161 9: 'REINSTATE_ABUSE_TAKEDOWN',
162 11: 'CLEAR_OFF_TOPIC',
163 12: 'CONFIRM_OFF_TOPIC',
164 15: 'GOOGLER_OFF_TOPIC_HIDE',
165 16: 'EXPERT_FLAGGED_PENDING_MANUAL_REVIEW',
166};
167const kShadowBlockReason = {
168 0: 'REASON_UNDEFINED',
169 1: 'ULTRON_LOW_QUALITY',
170};
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100171
172export default class ExtraInfo {
173 constructor() {
174 this.lastProfile = {
175 body: {},
176 id: -1,
177 timestamp: 0,
178 };
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100179 this.lastCRsList = {
180 body: {},
181 id: -1,
182 duplicateNames: new Set(),
183 };
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100184 this.lastThread = {
185 body: {},
186 id: -1,
187 timestamp: 0,
188 };
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100189 this.setUpHandlers();
190 }
191
192 setUpHandlers() {
193 window.addEventListener(kViewUnifiedUserResponseEvent, e => {
194 if (e.detail.id < this.lastProfile.id) return;
195
196 this.lastProfile = {
197 body: e.detail.body,
198 id: e.detail.id,
199 timestamp: Date.now(),
200 };
201 });
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100202 window.addEventListener(kListCannedResponsesResponse, e => {
203 if (e.detail.id < this.lastCRsList.id) return;
204
205 // Look if there are duplicate names
206 const crs = e.detail.body?.['1'] ?? [];
207 const names = crs.map(cr => cr?.['7']).slice().sort();
208 let duplicateNames = new Set();
209 for (let i = 1; i < names.length; i++)
210 if (names[i - 1] == names[i]) duplicateNames.add(names[i]);
211
212 this.lastCRsList = {
213 body: e.detail.body,
214 id: e.detail.id,
215 duplicateNames,
216 };
217 });
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100218 window.addEventListener(kViewThreadResponse, e => {
219 if (e.detail.id < this.lastThread.id) return;
220
221 this.lastThread = {
222 body: e.detail.body,
223 id: e.detail.id,
224 timestamp: Date.now(),
225 };
226 });
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100227 }
228
229 // Whether the feature is enabled
230 isEnabled() {
231 return isOptionEnabled('extrainfo');
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100232 }
233
234 // Add a pretty component which contains |info| to |node|.
235 addExtraInfoElement(info, node) {
236 // Don't create
237 if (info.length == 0) return;
238
239 let container = document.createElement('div');
240 container.classList.add('TWPT-extrainfo-container');
241
242 let badgeCell = document.createElement('div');
243 badgeCell.classList.add('TWPT-extrainfo-badge-cell');
244
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100245 const [badge, badgeTooltip] = createExtBadge();
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100246 badgeCell.append(badge);
247
248 let infoCell = document.createElement('div');
249 infoCell.classList.add('TWPT-extrainfo-info-cell');
250
251 for (const i of info) {
252 let iRow = document.createElement('div');
253 iRow.append(i);
254 infoCell.append(iRow);
255 }
256
257 container.append(badgeCell, infoCell);
258 node.append(container);
259 new MDCTooltip(badgeTooltip);
260 }
261
262 fieldInfo(field, value) {
263 let span = document.createElement('span');
264 span.append(document.createTextNode(field + ': '));
265
266 let valueEl = document.createElement('span');
267 valueEl.style.fontFamily = 'monospace';
268 valueEl.textContent = value;
269
270 span.append(valueEl);
271 return span;
272 }
273
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100274 /**
275 * Profile functionality
276 */
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100277 injectAtProfile(card) {
278 waitFor(
279 () => {
280 let now = Date.now();
281 if (now - this.lastProfile.timestamp < 15 * 1000)
282 return Promise.resolve(this.lastProfile);
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100283 return Promise.reject(
284 new Error('Didn\'t receive profile information'));
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100285 },
286 {
287 interval: 500,
288 timeout: 15 * 1000,
289 })
290 .then(profile => {
291 let info = [];
292 const abuseViolationCategory = profile.body?.['1']?.['6'];
293 if (abuseViolationCategory) {
294 info.push(this.fieldInfo(
295 'Abuse category',
296 kAbuseViolationCategories[abuseViolationCategory] ??
297 abuseViolationCategory));
298 }
299
300 const profileAbuse = profile.body?.['1']?.['1']?.['8'];
301
302 for (const [index, category] of kAbuseCategories) {
303 const violation = profileAbuse?.[index]?.['1']?.['1'];
304 if (violation) {
305 info.push(this.fieldInfo(
306 category + ' policy violation',
307 kAbuseViolationTypes[violation]));
308 }
309 }
310
311 const appealCount = profileAbuse?.['4'];
312 if (appealCount !== undefined)
313 info.push(this.fieldInfo('Number of appeals', appealCount));
314
315 this.addExtraInfoElement(info, card);
316 })
317 .catch(err => {
318 console.error(
319 'extraInfo: error while injecting profile extra info: ', err);
320 });
321 }
322
323 injectAtProfileIfEnabled(card) {
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100324 this.isEnabled().then(isEnabled => {
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100325 if (isEnabled) return this.injectAtProfile(card);
326 });
327 }
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100328
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100329 /**
330 * Canned responses (CRs) functionality
331 */
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100332 getCRName(tags, isExpanded) {
333 if (!isExpanded)
334 return tags.parentNode?.querySelector?.('.text .name')?.textContent;
335
336 // https://www.youtube.com/watch?v=Z6_ZNW1DACE
337 return tags.parentNode?.parentNode?.parentNode?.parentNode?.parentNode
338 ?.parentNode?.parentNode?.querySelector?.('.text .name')
339 ?.textContent;
340 }
341
342 // Inject usage stats in the |tags| component of a CR
343 injectAtCR(tags, isExpanded) {
344 waitFor(() => {
345 if (this.lastCRsList.id != -1) return Promise.resolve(this.lastCRsList);
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100346 return Promise.reject(new Error('Didn\'t receive canned responses list'));
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100347 }, {
348 interval: 500,
349 timeout: 15 * 1000,
350 }).then(crs => {
351 let name = this.getCRName(tags, isExpanded);
352
353 // If another CR has the same name, there's no easy way to distinguish
354 // them, so don't show the usage stats.
355 if (crs.duplicateNames.has(name)) return;
356
357 for (const cr of (crs.body?.['1'] ?? [])) {
358 if (cr['7'] == name) {
359 let tag = document.createElement('material-chip');
360 tag.classList.add('TWPT-tag');
361
362 let container = document.createElement('div');
363 container.classList.add('TWPT-chip-content-container');
364
365 let content = document.createElement('div');
366 content.classList.add('TWPT-content');
367
368 const [badge, badgeTooltip] = createExtBadge();
369
370 let label = document.createElement('span');
371 label.textContent = 'Used ' + (cr['8'] ?? '0') + ' times';
372
373 content.append(badge, label);
374 container.append(content);
375 tag.append(container);
376 tags.append(tag);
377
378 new MDCTooltip(badgeTooltip);
379
380 if (cr['9']) {
381 const lastUsedTime = Math.floor(parseInt(cr['9']) / 1e3);
382 let date = (new Date(lastUsedTime)).toLocaleString();
383 createPlainTooltip(label, 'Last used: ' + date);
384 }
385
386 break;
387 }
388 }
389 });
390 }
391
392 injectAtCRIfEnabled(tags, isExpanded) {
393 // If the tag has already been injected, exit.
394 if (tags.querySelector('.TWPT-tag')) return;
395
396 this.isEnabled().then(isEnabled => {
397 if (isEnabled) return this.injectAtCR(tags, isExpanded);
398 });
399 }
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100400
401 /**
402 * Thread view functionality
403 */
404
405 getPendingStateInfo(endPendingStateTimestampMicros) {
406 const endPendingStateTimestamp =
407 Math.floor(endPendingStateTimestampMicros / 1e3);
408 const now = Date.now();
409 if (endPendingStateTimestampMicros && endPendingStateTimestamp > now) {
410 let span = document.createElement('span');
411 span.textContent = 'Only visible to badged users';
412
413 let date = new Date(endPendingStateTimestamp).toLocaleString();
414 let pendingTooltip =
415 createPlainTooltip(span, 'Visible after ' + date, false);
416 return [span, pendingTooltip];
417 }
418
419 return [null, null];
420 }
421
422 getMetadataInfo(itemMetadata) {
423 let info = [];
424
425 const state = itemMetadata?.['1'];
426 if (state && state != 1)
427 info.push(this.fieldInfo('State', kItemMetadataState[state] ?? state));
428
429 const shadowBlockInfo = itemMetadata?.['10'];
430 const blockedTimestampMicros = shadowBlockInfo?.['2'];
431 if (blockedTimestampMicros) {
432 const isBlocked = shadowBlockInfo?.['1'];
433 let span = document.createElement('span');
434 span.textContent =
435 isBlocked ? 'Shadow block active' : 'Shadow block no longer active';
436 if (isBlocked) span.classList.add('TWPT-extrainfo-bad');
437 info.push(span);
438 }
439
440 return info;
441 }
442
443 getLiveReviewStatusInfo(liveReviewStatus) {
444 const verdict = liveReviewStatus?.['1'];
445 if (!verdict) return [null, null];
446 let label, labelClass;
447 switch (verdict) {
448 case 1: // LIVE_REVIEW_RELEVANT
449 label = 'Relevant';
450 labelClass = 'TWPT-extrainfo-good';
451 break;
452
453 case 2: // LIVE_REVIEW_OFF_TOPIC
454 label = 'Off-topic';
455 labelClass = 'TWPT-extrainfo-bad';
456 break;
457
458 case 3: // LIVE_REVIEW_ABUSE
459 label = 'Abuse';
460 labelClass = 'TWPT-extrainfo-bad';
461 break;
462 }
463 const reviewedBy = liveReviewStatus?.['2'];
464 const timestamp = liveReviewStatus?.['3'];
465 const date = (new Date(Math.floor(timestamp / 1e3))).toLocaleString();
466
467 let a = document.createElement('a');
468 a.href = 'https://support.google.com/s/community/user/' + reviewedBy;
469 a.classList.add(labelClass);
470 a.textContent = 'Live review verdict: ' + label;
471 let liveReviewTooltip = createPlainTooltip(a, date, false);
472 return [a, liveReviewTooltip];
473 }
474
475 injectAtQuestion(question) {
476 let currentPage = parseUrl(location.href);
477 if (currentPage === false) return;
478
479 let content = question.querySelector('ec-question > .content');
480 if (!content) return;
481
482 waitFor(() => {
483 let now = Date.now();
484 let threadInfo = this.lastThread.body['1']?.['2']?.['1'];
485 if (now - this.lastThread.timestamp < 15 * 1000 &&
486 threadInfo?.['1'] == currentPage.thread &&
487 threadInfo?.['3'] == currentPage.forum)
488 return Promise.resolve(this.lastThread);
489 return Promise.reject(new Error('Didn\'t receive thread information'));
490 }, {
491 interval: 500,
492 timeout: 15 * 1000,
493 }).then(thread => {
494 let info = [];
495
496 const endPendingStateTimestampMicros = thread.body['1']?.['2']?.['39'];
497 const [pendingStateInfo, pendingTooltip] =
498 this.getPendingStateInfo(endPendingStateTimestampMicros);
499 if (pendingStateInfo) info.push(pendingStateInfo);
500
501 // NOTE: These attributes don't seem to be included when calling
502 // ViewThread (but are included when calling ViewForum).
503 const isTrending = thread.body['1']?.['2']?.['25'];
504 const isTrendingAutoMarked = thread.body['1']?.['39'];
505 if (isTrendingAutoMarked)
506 info.push(document.createTextNode('Automatically marked as trending'));
507 else if (isTrending)
508 info.push(document.createTextNode('Trending'));
509
510 const itemMetadata = thread.body['1']?.['2']?.['12'];
511 const mdInfo = this.getMetadataInfo(itemMetadata);
512 info.push(...mdInfo);
513
514 const liveReviewStatus = thread.body['1']?.['2']?.['38'];
515 const [liveReviewInfo, liveReviewTooltip] =
516 this.getLiveReviewStatusInfo(liveReviewStatus);
517 if (liveReviewInfo) info.push(liveReviewInfo);
518
519 this.addExtraInfoElement(info, content);
520 if (pendingTooltip) new MDCTooltip(pendingTooltip);
521 if (liveReviewTooltip) new MDCTooltip(liveReviewTooltip);
522 });
523 }
524
525 injectAtQuestionIfEnabled(question) {
526 this.isEnabled().then(isEnabled => {
527 if (isEnabled) return this.injectAtQuestion(question);
528 });
529 }
530
531 getMessagesByType(thread, type) {
532 if (type === 'reply') return thread?.['1']?.['3'];
533 if (type === 'lastMessage') return thread?.['1']?.['17']?.['3'];
534 if (type === 'suggested') return thread?.['1']?.['17']?.['4'];
535 if (type === 'recommended') return thread?.['1']?.['17']?.['1'];
536 }
537
538 getMessageByTypeAndIndex(thread, type, index) {
539 return this.getMessagesByType(thread, type)?.[index];
540 }
541
542 // Returns true if the last message is included in the messages array (in the
543 // extension context, we say those messages are of the type "reply").
544 lastMessageInReplies(thread) {
545 const lastMessageId = thread?.['1']?.['17']?.['3']?.[0]?.['1']?.['1'];
546 if (!lastMessageId) return true;
547
548 // If the last message is included in the lastMessage array, check if it
549 // also exists in the messages/replies array.
550 const replies = thread?.['1']?.['3'];
551 if (!replies?.length) return false;
552 const lastReplyIndex = replies.length - 1;
553 const lastReplyId = replies[lastReplyIndex]?.['1']?.['1'];
554 return lastMessageId && lastMessageId == lastReplyId;
555 }
556
557 getMessageInfo(thread, message) {
558 const section = message.parentNode;
559
560 let type = 'reply';
561 if (section?.querySelector?.('.heading material-icon[icon="auto_awesome"]'))
562 type = 'suggested';
563 if (section?.querySelector?.('.heading material-icon[icon="check_circle"]'))
564 type = 'recommended';
565
566 let index = -1;
567 let messagesInDom = section.querySelectorAll('ec-message');
568
569 // Number of messages in the DOM.
570 const n = messagesInDom.length;
571
572 if (type !== 'reply') {
573 for (let i = 0; i < n; ++i) {
574 if (message.isEqualNode(messagesInDom[i])) {
575 index = i;
576 break;
577 }
578 }
579 } else {
580 // If the type of the message is a reply, things are slightly more
581 // complex, since replies are paginated and the last message should be
582 // treated separately (it is included diferently in the API response).
583 let lastMessageInReplies = this.lastMessageInReplies(thread);
584 if (message.isEqualNode(messagesInDom[n - 1]) && !lastMessageInReplies) {
585 type = 'lastMessage';
586 index = 0
587 } else {
588 // Number of messages in the current API response.
589 const messagesInResponse = this.getMessagesByType(thread, type);
590 const m = messagesInResponse.length;
591 // If the last message is included in the replies array, we also have to
592 // consider the last message in the DOM.
593 let modifier = lastMessageInReplies ? 1 : 0;
594 for (let k = 0; k < m; ++k) {
595 let i = n - 2 - k + modifier;
596 if (message.isEqualNode(messagesInDom[i])) {
597 index = m - 1 - k;
598 break;
599 }
600 }
601 }
602 }
603
604 return [type, index];
605 }
606
607 injectAtMessage(messageNode) {
608 let currentPage = parseUrl(location.href);
609 if (currentPage === false) return;
610
611 let footer = messageNode.querySelector('.footer-fill');
612 if (!footer) return;
613
614 const [type, index] =
615 this.getMessageInfo(this.lastThread.body, messageNode);
616
617 waitFor(() => {
618 let now = Date.now();
619 let threadInfo = this.lastThread.body['1']?.['2']?.['1'];
620 if (now - this.lastThread.timestamp < 15 * 1000 &&
621 threadInfo?.['1'] == currentPage.thread &&
622 threadInfo?.['3'] == currentPage.forum) {
623 const message =
624 this.getMessageByTypeAndIndex(this.lastThread.body, type, index);
625 if (message) return Promise.resolve(message);
626 }
627
628 return Promise.reject(new Error(
629 'Didn\'t receive thread information (type: ' + type +
630 ', index: ' + index + ')'));
631 }, {
632 interval: 1000,
633 timeout: 15 * 1000,
634 }).then(message => {
635 let info = [];
636
637 const endPendingStateTimestampMicros = message['1']?.['17'];
638 const [pendingStateInfo, pendingTooltip] =
639 this.getPendingStateInfo(endPendingStateTimestampMicros);
640 if (pendingStateInfo) info.push(pendingStateInfo);
641
642 const itemMetadata = message['1']?.['5'];
643 const mdInfo = this.getMetadataInfo(itemMetadata);
644 info.push(...mdInfo);
645
646 const liveReviewStatus = message['1']?.['36'];
647 const [liveReviewInfo, liveReviewTooltip] =
648 this.getLiveReviewStatusInfo(liveReviewStatus);
649 if (liveReviewInfo) info.push(liveReviewInfo);
650
651 this.addExtraInfoElement(info, footer);
652 if (pendingTooltip) new MDCTooltip(pendingTooltip);
653 if (liveReviewTooltip) new MDCTooltip(liveReviewTooltip);
654 });
655 }
656
657 injectAtMessageIfEnabled(message) {
658 this.isEnabled().then(isEnabled => {
659 if (isEnabled) return this.injectAtMessage(message);
660 });
661 }
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100662}