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