blob: 88a68be10ba94481c5fdd5a9db753b68ad2bca90 [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ínez17106dc2022-01-24 23:48:36 +01005import OptionsWatcher from '../../common/optionsWatcher.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ínez17106dc2022-01-24 23:48:36 +0100189 this.optionsWatcher = new OptionsWatcher(['extrainfo']);
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100190 this.setUpHandlers();
191 }
192
193 setUpHandlers() {
194 window.addEventListener(kViewUnifiedUserResponseEvent, e => {
195 if (e.detail.id < this.lastProfile.id) return;
196
197 this.lastProfile = {
198 body: e.detail.body,
199 id: e.detail.id,
200 timestamp: Date.now(),
201 };
202 });
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100203 window.addEventListener(kListCannedResponsesResponse, e => {
204 if (e.detail.id < this.lastCRsList.id) return;
205
206 // Look if there are duplicate names
207 const crs = e.detail.body?.['1'] ?? [];
208 const names = crs.map(cr => cr?.['7']).slice().sort();
209 let duplicateNames = new Set();
210 for (let i = 1; i < names.length; i++)
211 if (names[i - 1] == names[i]) duplicateNames.add(names[i]);
212
213 this.lastCRsList = {
214 body: e.detail.body,
215 id: e.detail.id,
216 duplicateNames,
217 };
218 });
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100219 window.addEventListener(kViewThreadResponse, e => {
220 if (e.detail.id < this.lastThread.id) return;
221
222 this.lastThread = {
223 body: e.detail.body,
224 id: e.detail.id,
225 timestamp: Date.now(),
226 };
227 });
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100228 }
229
230 // Whether the feature is enabled
231 isEnabled() {
Adrià Vilanova Martínez17106dc2022-01-24 23:48:36 +0100232 return this.optionsWatcher.isEnabled('extrainfo');
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100233 }
234
235 // Add a pretty component which contains |info| to |node|.
236 addExtraInfoElement(info, node) {
237 // Don't create
238 if (info.length == 0) return;
239
240 let container = document.createElement('div');
241 container.classList.add('TWPT-extrainfo-container');
242
243 let badgeCell = document.createElement('div');
244 badgeCell.classList.add('TWPT-extrainfo-badge-cell');
245
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100246 const [badge, badgeTooltip] = createExtBadge();
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100247 badgeCell.append(badge);
248
249 let infoCell = document.createElement('div');
250 infoCell.classList.add('TWPT-extrainfo-info-cell');
251
252 for (const i of info) {
253 let iRow = document.createElement('div');
254 iRow.append(i);
255 infoCell.append(iRow);
256 }
257
258 container.append(badgeCell, infoCell);
259 node.append(container);
260 new MDCTooltip(badgeTooltip);
261 }
262
263 fieldInfo(field, value) {
264 let span = document.createElement('span');
265 span.append(document.createTextNode(field + ': '));
266
267 let valueEl = document.createElement('span');
268 valueEl.style.fontFamily = 'monospace';
269 valueEl.textContent = value;
270
271 span.append(valueEl);
272 return span;
273 }
274
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100275 /**
276 * Profile functionality
277 */
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100278 injectAtProfile(card) {
279 waitFor(
280 () => {
281 let now = Date.now();
282 if (now - this.lastProfile.timestamp < 15 * 1000)
283 return Promise.resolve(this.lastProfile);
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100284 return Promise.reject(
285 new Error('Didn\'t receive profile information'));
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100286 },
287 {
288 interval: 500,
289 timeout: 15 * 1000,
290 })
291 .then(profile => {
292 let info = [];
293 const abuseViolationCategory = profile.body?.['1']?.['6'];
294 if (abuseViolationCategory) {
295 info.push(this.fieldInfo(
296 'Abuse category',
297 kAbuseViolationCategories[abuseViolationCategory] ??
298 abuseViolationCategory));
299 }
300
301 const profileAbuse = profile.body?.['1']?.['1']?.['8'];
302
303 for (const [index, category] of kAbuseCategories) {
304 const violation = profileAbuse?.[index]?.['1']?.['1'];
305 if (violation) {
306 info.push(this.fieldInfo(
307 category + ' policy violation',
308 kAbuseViolationTypes[violation]));
309 }
310 }
311
312 const appealCount = profileAbuse?.['4'];
313 if (appealCount !== undefined)
314 info.push(this.fieldInfo('Number of appeals', appealCount));
315
316 this.addExtraInfoElement(info, card);
317 })
318 .catch(err => {
319 console.error(
320 'extraInfo: error while injecting profile extra info: ', err);
321 });
322 }
323
324 injectAtProfileIfEnabled(card) {
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100325 this.isEnabled().then(isEnabled => {
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100326 if (isEnabled) return this.injectAtProfile(card);
327 });
328 }
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100329
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100330 /**
331 * Canned responses (CRs) functionality
332 */
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100333 getCRName(tags, isExpanded) {
334 if (!isExpanded)
335 return tags.parentNode?.querySelector?.('.text .name')?.textContent;
336
337 // https://www.youtube.com/watch?v=Z6_ZNW1DACE
338 return tags.parentNode?.parentNode?.parentNode?.parentNode?.parentNode
339 ?.parentNode?.parentNode?.querySelector?.('.text .name')
340 ?.textContent;
341 }
342
343 // Inject usage stats in the |tags| component of a CR
344 injectAtCR(tags, isExpanded) {
345 waitFor(() => {
346 if (this.lastCRsList.id != -1) return Promise.resolve(this.lastCRsList);
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100347 return Promise.reject(new Error('Didn\'t receive canned responses list'));
Adrià Vilanova Martínez74a25202022-01-23 23:36:58 +0100348 }, {
349 interval: 500,
350 timeout: 15 * 1000,
351 }).then(crs => {
352 let name = this.getCRName(tags, isExpanded);
353
354 // If another CR has the same name, there's no easy way to distinguish
355 // them, so don't show the usage stats.
356 if (crs.duplicateNames.has(name)) return;
357
358 for (const cr of (crs.body?.['1'] ?? [])) {
359 if (cr['7'] == name) {
360 let tag = document.createElement('material-chip');
361 tag.classList.add('TWPT-tag');
362
363 let container = document.createElement('div');
364 container.classList.add('TWPT-chip-content-container');
365
366 let content = document.createElement('div');
367 content.classList.add('TWPT-content');
368
369 const [badge, badgeTooltip] = createExtBadge();
370
371 let label = document.createElement('span');
372 label.textContent = 'Used ' + (cr['8'] ?? '0') + ' times';
373
374 content.append(badge, label);
375 container.append(content);
376 tag.append(container);
377 tags.append(tag);
378
379 new MDCTooltip(badgeTooltip);
380
381 if (cr['9']) {
382 const lastUsedTime = Math.floor(parseInt(cr['9']) / 1e3);
383 let date = (new Date(lastUsedTime)).toLocaleString();
384 createPlainTooltip(label, 'Last used: ' + date);
385 }
386
387 break;
388 }
389 }
390 });
391 }
392
393 injectAtCRIfEnabled(tags, isExpanded) {
394 // If the tag has already been injected, exit.
395 if (tags.querySelector('.TWPT-tag')) return;
396
397 this.isEnabled().then(isEnabled => {
398 if (isEnabled) return this.injectAtCR(tags, isExpanded);
399 });
400 }
Adrià Vilanova Martínez6e4a68d2022-01-24 21:44:32 +0100401
402 /**
403 * Thread view functionality
404 */
405
406 getPendingStateInfo(endPendingStateTimestampMicros) {
407 const endPendingStateTimestamp =
408 Math.floor(endPendingStateTimestampMicros / 1e3);
409 const now = Date.now();
410 if (endPendingStateTimestampMicros && endPendingStateTimestamp > now) {
411 let span = document.createElement('span');
412 span.textContent = 'Only visible to badged users';
413
414 let date = new Date(endPendingStateTimestamp).toLocaleString();
415 let pendingTooltip =
416 createPlainTooltip(span, 'Visible after ' + date, false);
417 return [span, pendingTooltip];
418 }
419
420 return [null, null];
421 }
422
423 getMetadataInfo(itemMetadata) {
424 let info = [];
425
426 const state = itemMetadata?.['1'];
427 if (state && state != 1)
428 info.push(this.fieldInfo('State', kItemMetadataState[state] ?? state));
429
430 const shadowBlockInfo = itemMetadata?.['10'];
431 const blockedTimestampMicros = shadowBlockInfo?.['2'];
432 if (blockedTimestampMicros) {
433 const isBlocked = shadowBlockInfo?.['1'];
434 let span = document.createElement('span');
435 span.textContent =
436 isBlocked ? 'Shadow block active' : 'Shadow block no longer active';
437 if (isBlocked) span.classList.add('TWPT-extrainfo-bad');
438 info.push(span);
439 }
440
441 return info;
442 }
443
444 getLiveReviewStatusInfo(liveReviewStatus) {
445 const verdict = liveReviewStatus?.['1'];
446 if (!verdict) return [null, null];
447 let label, labelClass;
448 switch (verdict) {
449 case 1: // LIVE_REVIEW_RELEVANT
450 label = 'Relevant';
451 labelClass = 'TWPT-extrainfo-good';
452 break;
453
454 case 2: // LIVE_REVIEW_OFF_TOPIC
455 label = 'Off-topic';
456 labelClass = 'TWPT-extrainfo-bad';
457 break;
458
459 case 3: // LIVE_REVIEW_ABUSE
460 label = 'Abuse';
461 labelClass = 'TWPT-extrainfo-bad';
462 break;
463 }
464 const reviewedBy = liveReviewStatus?.['2'];
465 const timestamp = liveReviewStatus?.['3'];
466 const date = (new Date(Math.floor(timestamp / 1e3))).toLocaleString();
467
468 let a = document.createElement('a');
469 a.href = 'https://support.google.com/s/community/user/' + reviewedBy;
470 a.classList.add(labelClass);
471 a.textContent = 'Live review verdict: ' + label;
472 let liveReviewTooltip = createPlainTooltip(a, date, false);
473 return [a, liveReviewTooltip];
474 }
475
476 injectAtQuestion(question) {
477 let currentPage = parseUrl(location.href);
478 if (currentPage === false) return;
479
480 let content = question.querySelector('ec-question > .content');
481 if (!content) return;
482
483 waitFor(() => {
484 let now = Date.now();
485 let threadInfo = this.lastThread.body['1']?.['2']?.['1'];
486 if (now - this.lastThread.timestamp < 15 * 1000 &&
487 threadInfo?.['1'] == currentPage.thread &&
488 threadInfo?.['3'] == currentPage.forum)
489 return Promise.resolve(this.lastThread);
490 return Promise.reject(new Error('Didn\'t receive thread information'));
491 }, {
492 interval: 500,
493 timeout: 15 * 1000,
494 }).then(thread => {
495 let info = [];
496
497 const endPendingStateTimestampMicros = thread.body['1']?.['2']?.['39'];
498 const [pendingStateInfo, pendingTooltip] =
499 this.getPendingStateInfo(endPendingStateTimestampMicros);
500 if (pendingStateInfo) info.push(pendingStateInfo);
501
502 // NOTE: These attributes don't seem to be included when calling
503 // ViewThread (but are included when calling ViewForum).
504 const isTrending = thread.body['1']?.['2']?.['25'];
505 const isTrendingAutoMarked = thread.body['1']?.['39'];
506 if (isTrendingAutoMarked)
507 info.push(document.createTextNode('Automatically marked as trending'));
508 else if (isTrending)
509 info.push(document.createTextNode('Trending'));
510
511 const itemMetadata = thread.body['1']?.['2']?.['12'];
512 const mdInfo = this.getMetadataInfo(itemMetadata);
513 info.push(...mdInfo);
514
515 const liveReviewStatus = thread.body['1']?.['2']?.['38'];
516 const [liveReviewInfo, liveReviewTooltip] =
517 this.getLiveReviewStatusInfo(liveReviewStatus);
518 if (liveReviewInfo) info.push(liveReviewInfo);
519
520 this.addExtraInfoElement(info, content);
521 if (pendingTooltip) new MDCTooltip(pendingTooltip);
522 if (liveReviewTooltip) new MDCTooltip(liveReviewTooltip);
523 });
524 }
525
526 injectAtQuestionIfEnabled(question) {
527 this.isEnabled().then(isEnabled => {
528 if (isEnabled) return this.injectAtQuestion(question);
529 });
530 }
531
532 getMessagesByType(thread, type) {
533 if (type === 'reply') return thread?.['1']?.['3'];
534 if (type === 'lastMessage') return thread?.['1']?.['17']?.['3'];
535 if (type === 'suggested') return thread?.['1']?.['17']?.['4'];
536 if (type === 'recommended') return thread?.['1']?.['17']?.['1'];
537 }
538
539 getMessageByTypeAndIndex(thread, type, index) {
540 return this.getMessagesByType(thread, type)?.[index];
541 }
542
543 // Returns true if the last message is included in the messages array (in the
544 // extension context, we say those messages are of the type "reply").
545 lastMessageInReplies(thread) {
546 const lastMessageId = thread?.['1']?.['17']?.['3']?.[0]?.['1']?.['1'];
547 if (!lastMessageId) return true;
548
549 // If the last message is included in the lastMessage array, check if it
550 // also exists in the messages/replies array.
551 const replies = thread?.['1']?.['3'];
552 if (!replies?.length) return false;
553 const lastReplyIndex = replies.length - 1;
554 const lastReplyId = replies[lastReplyIndex]?.['1']?.['1'];
555 return lastMessageId && lastMessageId == lastReplyId;
556 }
557
558 getMessageInfo(thread, message) {
559 const section = message.parentNode;
560
561 let type = 'reply';
562 if (section?.querySelector?.('.heading material-icon[icon="auto_awesome"]'))
563 type = 'suggested';
564 if (section?.querySelector?.('.heading material-icon[icon="check_circle"]'))
565 type = 'recommended';
566
567 let index = -1;
568 let messagesInDom = section.querySelectorAll('ec-message');
569
570 // Number of messages in the DOM.
571 const n = messagesInDom.length;
572
573 if (type !== 'reply') {
574 for (let i = 0; i < n; ++i) {
575 if (message.isEqualNode(messagesInDom[i])) {
576 index = i;
577 break;
578 }
579 }
580 } else {
581 // If the type of the message is a reply, things are slightly more
582 // complex, since replies are paginated and the last message should be
583 // treated separately (it is included diferently in the API response).
584 let lastMessageInReplies = this.lastMessageInReplies(thread);
585 if (message.isEqualNode(messagesInDom[n - 1]) && !lastMessageInReplies) {
586 type = 'lastMessage';
587 index = 0
588 } else {
589 // Number of messages in the current API response.
590 const messagesInResponse = this.getMessagesByType(thread, type);
591 const m = messagesInResponse.length;
592 // If the last message is included in the replies array, we also have to
593 // consider the last message in the DOM.
594 let modifier = lastMessageInReplies ? 1 : 0;
595 for (let k = 0; k < m; ++k) {
596 let i = n - 2 - k + modifier;
597 if (message.isEqualNode(messagesInDom[i])) {
598 index = m - 1 - k;
599 break;
600 }
601 }
602 }
603 }
604
605 return [type, index];
606 }
607
608 injectAtMessage(messageNode) {
609 let currentPage = parseUrl(location.href);
610 if (currentPage === false) return;
611
612 let footer = messageNode.querySelector('.footer-fill');
613 if (!footer) return;
614
615 const [type, index] =
616 this.getMessageInfo(this.lastThread.body, messageNode);
617
618 waitFor(() => {
619 let now = Date.now();
620 let threadInfo = this.lastThread.body['1']?.['2']?.['1'];
621 if (now - this.lastThread.timestamp < 15 * 1000 &&
622 threadInfo?.['1'] == currentPage.thread &&
623 threadInfo?.['3'] == currentPage.forum) {
624 const message =
625 this.getMessageByTypeAndIndex(this.lastThread.body, type, index);
626 if (message) return Promise.resolve(message);
627 }
628
629 return Promise.reject(new Error(
630 'Didn\'t receive thread information (type: ' + type +
631 ', index: ' + index + ')'));
632 }, {
633 interval: 1000,
634 timeout: 15 * 1000,
635 }).then(message => {
636 let info = [];
637
638 const endPendingStateTimestampMicros = message['1']?.['17'];
639 const [pendingStateInfo, pendingTooltip] =
640 this.getPendingStateInfo(endPendingStateTimestampMicros);
641 if (pendingStateInfo) info.push(pendingStateInfo);
642
643 const itemMetadata = message['1']?.['5'];
644 const mdInfo = this.getMetadataInfo(itemMetadata);
645 info.push(...mdInfo);
646
647 const liveReviewStatus = message['1']?.['36'];
648 const [liveReviewInfo, liveReviewTooltip] =
649 this.getLiveReviewStatusInfo(liveReviewStatus);
650 if (liveReviewInfo) info.push(liveReviewInfo);
651
652 this.addExtraInfoElement(info, footer);
653 if (pendingTooltip) new MDCTooltip(pendingTooltip);
654 if (liveReviewTooltip) new MDCTooltip(liveReviewTooltip);
655 });
656 }
657
658 injectAtMessageIfEnabled(message) {
659 this.isEnabled().then(isEnabled => {
660 if (isEnabled) return this.injectAtMessage(message);
661 });
662 }
Adrià Vilanova Martínez7e8796c2022-01-23 21:46:46 +0100663}