blob: db9e94add7cb508ab7c185363e8e6b94bb53cbb1 [file] [log] [blame]
avm99963e6166ed2021-08-26 10:45:17 +02001import {CCApi} from '../common/api.js';
Adrià Vilanova Martíneze7770472021-10-17 00:02:37 +02002import {createImmuneLink} from '../common/commonUtils.js';
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +02003import {escapeUsername} from '../common/communityConsoleUtils.js';
avm999632485a3e2021-09-08 22:18:38 +02004import {createPlainTooltip} from '../common/tooltip.js';
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +02005
avm99963e51444e2020-08-31 14:50:06 +02006var CCProfileRegex =
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +01007 /^(?:https:\/\/support\.google\.com)?\/s\/community(?:\/forum\/[0-9]*)?\/user\/(?:[0-9]+)(?:\?.*)?$/;
avm99963e51444e2020-08-31 14:50:06 +02008var CCRegex = /^https:\/\/support\.google\.com\/s\/community/;
9
10const OP_FIRST_POST = 0;
11const OP_OTHER_POSTS_READ = 1;
12const OP_OTHER_POSTS_UNREAD = 2;
13
14const OPClasses = {
avm99963ad65e752020-09-01 00:13:59 +020015 0: 'first-post',
16 1: 'other-posts-read',
17 2: 'other-posts-unread',
avm99963e51444e2020-08-31 14:50:06 +020018};
19
20const OPi18n = {
21 0: 'first_post',
22 1: 'other_posts_read',
23 2: 'other_posts_unread',
24};
25
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +010026const UI_COMMUNITY_CONSOLE = 0;
27const UI_TW_LEGACY = 1;
28const UI_TW_INTEROP = 2;
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +010029const UI_COMMUNITY_CONSOLE_INTEROP = 3;
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +010030
avm99963e51444e2020-08-31 14:50:06 +020031// Filter used as a workaround to speed up the ViewForum request.
32const FILTER_ALL_LANGUAGES =
33 'lang:(ar | bg | ca | "zh-hk" | "zh-cn" | "zh-tw" | hr | cs | da | nl | en | "en-au" | "en-gb" | et | fil | fi | fr | de | el | iw | hi | hu | id | it | ja | ko | lv | lt | ms | no | pl | "pt-br" | "pt-pt" | ro | ru | sr | sk | sl | es | "es-419" | sv | th | tr | uk | vi)';
34
avm99963ad65e752020-09-01 00:13:59 +020035const numPostsForumArraysToSum = [3, 4];
36
avm99963a2945b62020-11-27 00:32:02 +010037var authuser = null;
38
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +010039function isCommunityConsole(ui) {
40 return ui === UI_COMMUNITY_CONSOLE || ui === UI_COMMUNITY_CONSOLE_INTEROP;
41}
42
43function isInterop(ui) {
44 return ui === UI_TW_INTEROP || ui === UI_COMMUNITY_CONSOLE_INTEROP;
45}
46
avm99963e51444e2020-08-31 14:50:06 +020047
avm99963a2945b62020-11-27 00:32:02 +010048function getPosts(query, forumId) {
avm99963e6166ed2021-08-26 10:45:17 +020049 return CCApi(
50 'ViewForum', {
51 '1': forumId,
52 '2': {
53 '1': {
54 '2': 5,
55 },
56 '2': {
57 '1': 1,
58 '2': true,
59 },
60 '12': query,
61 },
avm99963a2945b62020-11-27 00:32:02 +010062 },
avm99963e6166ed2021-08-26 10:45:17 +020063 /* authenticated = */ true, authuser);
avm99963a2945b62020-11-27 00:32:02 +010064}
65
avm99963ad65e752020-09-01 00:13:59 +020066function getProfile(userId, forumId) {
avm99963e6166ed2021-08-26 10:45:17 +020067 return CCApi(
68 'ViewUser', {
69 '1': userId,
70 '2': 0,
71 '3': forumId,
72 '4': {
73 '20': true,
74 },
75 },
76 /* authenticated = */ true, authuser);
avm99963ad65e752020-09-01 00:13:59 +020077}
78
avm99963e51444e2020-08-31 14:50:06 +020079// Source:
80// https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response
avm99963ad65e752020-09-01 00:13:59 +020081var contentScriptRequest = (function() {
avm99963e51444e2020-08-31 14:50:06 +020082 var requestId = 0;
avm999633e238882020-12-07 18:38:54 +010083 var prefix = 'TWPT-profileindicator';
avm99963e51444e2020-08-31 14:50:06 +020084
avm99963ad65e752020-09-01 00:13:59 +020085 function sendRequest(data) {
avm99963e51444e2020-08-31 14:50:06 +020086 var id = requestId++;
87
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +020088 return new Promise(function(resolve) {
avm99963e51444e2020-08-31 14:50:06 +020089 var listener = function(evt) {
avm999633e238882020-12-07 18:38:54 +010090 if (evt.source === window && evt.data && evt.data.prefix === prefix &&
avm99963ad65e752020-09-01 00:13:59 +020091 evt.data.requestId == id) {
avm99963e51444e2020-08-31 14:50:06 +020092 // Deregister self
avm99963ad65e752020-09-01 00:13:59 +020093 window.removeEventListener('message', listener);
94 resolve(evt.data.data);
avm99963e51444e2020-08-31 14:50:06 +020095 }
96 };
97
avm99963ad65e752020-09-01 00:13:59 +020098 window.addEventListener('message', listener);
avm99963e51444e2020-08-31 14:50:06 +020099
avm999633e238882020-12-07 18:38:54 +0100100 var payload = {data, id, prefix};
avm99963e51444e2020-08-31 14:50:06 +0200101
avm99963ad65e752020-09-01 00:13:59 +0200102 window.dispatchEvent(
103 new CustomEvent('TWPT_sendRequest', {detail: payload}));
avm99963e51444e2020-08-31 14:50:06 +0200104 });
105 }
106
avm99963ad65e752020-09-01 00:13:59 +0200107 return {sendRequest: sendRequest};
avm99963e51444e2020-08-31 14:50:06 +0200108})();
109
avm99963ad65e752020-09-01 00:13:59 +0200110// Create profile indicator dot with a loading state, or return the numPosts
111// badge if it is already created.
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100112function createIndicatorDot(sourceNode, searchURL, options, ui) {
avm99963ad65e752020-09-01 00:13:59 +0200113 if (options.numPosts) return document.querySelector('.num-posts-indicator');
avm99963a1b23b62020-09-01 14:32:34 +0200114 var dotContainer = document.createElement('div');
avm99963ad65e752020-09-01 00:13:59 +0200115 dotContainer.classList.add('profile-indicator', 'profile-indicator--loading');
avm99963e51444e2020-08-31 14:50:06 +0200116
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +0100117 var dotLink = (isCommunityConsole(ui)) ? createImmuneLink() :
118 document.createElement('a');
avm99963e51444e2020-08-31 14:50:06 +0200119 dotLink.href = searchURL;
120 dotLink.innerText = '●';
121
122 dotContainer.appendChild(dotLink);
123 sourceNode.parentNode.appendChild(dotContainer);
124
avm999632485a3e2021-09-08 22:18:38 +0200125 contentScriptRequest
126 .sendRequest({
127 'action': 'geti18nMessage',
128 'msg': 'inject_profileindicator_loading'
129 })
130 .then(string => createPlainTooltip(dotContainer, string));
131
avm99963e51444e2020-08-31 14:50:06 +0200132 return dotContainer;
133}
134
avm99963ad65e752020-09-01 00:13:59 +0200135// Create badge indicating the number of posts with a loading state
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100136function createNumPostsBadge(sourceNode, searchURL, ui) {
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +0100137 var link = (isCommunityConsole(ui)) ? createImmuneLink() :
138 document.createElement('a');
avm99963ad65e752020-09-01 00:13:59 +0200139 link.href = searchURL;
140
141 var numPostsContainer = document.createElement('div');
142 numPostsContainer.classList.add(
143 'num-posts-indicator', 'num-posts-indicator--loading');
avm99963ad65e752020-09-01 00:13:59 +0200144
145 var numPostsSpan = document.createElement('span');
146 numPostsSpan.classList.add('num-posts-indicator--num');
147
148 numPostsContainer.appendChild(numPostsSpan);
149 link.appendChild(numPostsContainer);
150 sourceNode.parentNode.appendChild(link);
avm999632485a3e2021-09-08 22:18:38 +0200151
152 contentScriptRequest
153 .sendRequest({
154 'action': 'geti18nMessage',
155 'msg': 'inject_profileindicator_loading'
156 })
157 .then(string => createPlainTooltip(numPostsContainer, string));
158
avm99963ad65e752020-09-01 00:13:59 +0200159 return numPostsContainer;
160}
161
avm9996313658b92020-12-02 00:02:53 +0100162// Set the badge text
163function setNumPostsBadge(badge, text) {
164 badge.classList.remove('num-posts-indicator--loading');
165 badge.querySelector('span').classList.remove(
166 'num-posts-indicator--num--loading');
167 badge.querySelector('span').textContent = text;
168}
169
avm99963ad65e752020-09-01 00:13:59 +0200170// Get options and then handle all the indicators
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100171function getOptionsAndHandleIndicators(sourceNode, ui) {
avm99963ad65e752020-09-01 00:13:59 +0200172 contentScriptRequest.sendRequest({'action': 'getProfileIndicatorOptions'})
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100173 .then(options => handleIndicators(sourceNode, ui, options));
avm99963ad65e752020-09-01 00:13:59 +0200174}
175
176// Handle the profile indicator dot
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100177function handleIndicators(sourceNode, ui, options) {
178 let nameEl;
179 if (ui === UI_COMMUNITY_CONSOLE)
180 nameEl = sourceNode.querySelector('.name-text');
181 if (ui === UI_TW_LEGACY) nameEl = sourceNode.querySelector('span');
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +0100182 if (isInterop(ui)) nameEl = sourceNode;
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100183 var escapedUsername = escapeUsername(nameEl.textContent);
avm99963e51444e2020-08-31 14:50:06 +0200184
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +0200185 var threadLink;
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +0100186 if (isCommunityConsole(ui)) {
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +0200187 threadLink = document.location.href;
avm99963e51444e2020-08-31 14:50:06 +0200188 } else {
189 var CCLink = document.getElementById('onebar-community-console');
190 if (CCLink === null) {
191 console.error(
avm99963ad65e752020-09-01 00:13:59 +0200192 '[opindicator] The user is not a PE so the dot indicator cannot be shown in TW.');
avm99963e51444e2020-08-31 14:50:06 +0200193 return;
194 }
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +0200195 threadLink = CCLink.href;
avm99963e51444e2020-08-31 14:50:06 +0200196 }
197
198 var forumUrlSplit = threadLink.split('/forum/');
199 if (forumUrlSplit.length < 2) {
avm99963ad65e752020-09-01 00:13:59 +0200200 console.error('[opindicator] Can\'t get forum id.');
avm99963e51444e2020-08-31 14:50:06 +0200201 return;
202 }
203
204 var forumId = forumUrlSplit[1].split('/')[0];
avm99963ad65e752020-09-01 00:13:59 +0200205
avm99963e51444e2020-08-31 14:50:06 +0200206 var query = '(replier:"' + escapedUsername + '" | creator:"' +
Adrià Vilanova Martínez2b2d69c2022-01-28 15:03:03 +0100207 escapedUsername + '") ' + FILTER_ALL_LANGUAGES + ' forum:' + forumId;
208 var encodedQuery = encodeURIComponent(query);
avm99963a2945b62020-11-27 00:32:02 +0100209 var authuserPart =
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100210 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
211 var searchURL = 'https://support.google.com/s/community/search/' +
212 encodeURIComponent('query=' + encodedQuery) + authuserPart;
avm99963e51444e2020-08-31 14:50:06 +0200213
avm99963ad65e752020-09-01 00:13:59 +0200214 if (options.numPosts) {
215 var profileURL = new URL(sourceNode.href);
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +0100216 var userId = profileURL.pathname
217 .split(isCommunityConsole(ui) ? 'user/' : 'profile/')[1]
218 .split('?')[0]
219 .split('/')[0];
avm99963e51444e2020-08-31 14:50:06 +0200220
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100221 var numPostsContainer = createNumPostsBadge(sourceNode, searchURL, ui);
avm99963e51444e2020-08-31 14:50:06 +0200222
avm99963ad65e752020-09-01 00:13:59 +0200223 getProfile(userId, forumId)
224 .then(res => {
225 if (!('1' in res) || !('2' in res[1])) {
226 throw new Error('Unexpected profile response.');
avm99963ad65e752020-09-01 00:13:59 +0200227 }
avm99963e51444e2020-08-31 14:50:06 +0200228
avm99963ad65e752020-09-01 00:13:59 +0200229 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
230 .then(months => {
231 if (!options.indicatorDot)
232 contentScriptRequest
233 .sendRequest({
234 'action': 'geti18nMessage',
235 'msg': 'inject_profileindicatoralt_numposts',
236 'placeholders': [months]
237 })
238 .then(
239 string =>
avm999632485a3e2021-09-08 22:18:38 +0200240 createPlainTooltip(numPostsContainer, string));
avm99963e51444e2020-08-31 14:50:06 +0200241
avm99963ad65e752020-09-01 00:13:59 +0200242 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200243
avm99963ad65e752020-09-01 00:13:59 +0200244 for (const index of numPostsForumArraysToSum) {
245 if (!(index in res[1][2])) {
246 throw new Error('Unexpected profile response.');
avm99963ad65e752020-09-01 00:13:59 +0200247 }
avm99963e51444e2020-08-31 14:50:06 +0200248
avm99963ad65e752020-09-01 00:13:59 +0200249 var i = 0;
250 for (const month of res[1][2][index].reverse()) {
251 if (i == months) break;
252 numPosts += month[3] || 0;
253 ++i;
254 }
255 }
avm99963e51444e2020-08-31 14:50:06 +0200256
avm9996313658b92020-12-02 00:02:53 +0100257 setNumPostsBadge(numPostsContainer, numPosts);
avm99963ad65e752020-09-01 00:13:59 +0200258 })
259 .catch(
260 err => console.error('[opindicator] Unexpected error.', err));
261 })
avm9996313658b92020-12-02 00:02:53 +0100262 .catch(err => {
263 console.error(
264 '[opindicator] Unexpected error. Couldn\'t load profile.', err);
265 setNumPostsBadge(numPostsContainer, '?');
266 });
avm99963ad65e752020-09-01 00:13:59 +0200267 }
268
269 if (options.indicatorDot) {
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100270 var dotContainer = createIndicatorDot(sourceNode, searchURL, options, ui);
avm99963ad65e752020-09-01 00:13:59 +0200271
272 // Query threads in order to see what state the indicator should be in
273 getPosts(query, forumId)
274 .then(res => {
avm999639f586f42021-02-05 12:37:51 +0100275 // Throw an error when the replies array is not present in the reply.
avm99963ad65e752020-09-01 00:13:59 +0200276 if (!('1' in res) || !('2' in res['1'])) {
avm999639f586f42021-02-05 12:37:51 +0100277 // Throw a different error when the numThreads field exists and is
278 // equal to 0. This reply can be received, but is enexpected,
279 // because we know that the user has replied in at least 1 thread
280 // (the current one).
281 if (('1' in res) && ('4' in res['1']) && res['1']['4'] == 0)
282 throw new Error(
283 'Thread list is empty ' +
284 '(but the OP has participated in this thread, ' +
285 'so it shouldn\'t be empty).');
286
avm99963ad65e752020-09-01 00:13:59 +0200287 throw new Error('Unexpected thread list response.');
avm99963ad65e752020-09-01 00:13:59 +0200288 }
289
290 // Current thread ID
291 var threadUrlSplit = threadLink.split('/thread/');
292 if (threadUrlSplit.length < 2)
293 throw new Error('Can\'t get thread id.');
294
Adrià Vilanova Martínez2b2d69c2022-01-28 15:03:03 +0100295 var currId = threadUrlSplit[1].split('?')[0].split('/')[0];
avm99963ad65e752020-09-01 00:13:59 +0200296
297 var OPStatus = OP_FIRST_POST;
298
299 for (const thread of res['1']['2']) {
300 var id = thread['2']['1']['1'] || undefined;
301 if (id === undefined || id == currId) continue;
302
303 var isRead = thread['6'] || false;
304 if (isRead)
305 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
306 else
307 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
308 }
309
310 var dotContainerPrefix =
311 (options.numPosts ? 'num-posts-indicator' : 'profile-indicator');
312
313 if (!options.numPosts)
314 dotContainer.classList.remove(dotContainerPrefix + '--loading');
315 dotContainer.classList.add(
316 dotContainerPrefix + '--' + OPClasses[OPStatus]);
317 contentScriptRequest
318 .sendRequest({
319 'action': 'geti18nMessage',
320 'msg': 'inject_profileindicator_' + OPi18n[OPStatus]
321 })
avm999632485a3e2021-09-08 22:18:38 +0200322 .then(string => createPlainTooltip(dotContainer, string));
avm99963ad65e752020-09-01 00:13:59 +0200323 })
324 .catch(
325 err => console.error(
326 '[opindicator] Unexpected error. Couldn\'t load recent posts.',
327 err));
328 }
avm99963e51444e2020-08-31 14:50:06 +0200329}
330
331if (CCRegex.test(location.href)) {
332 // We are in the Community Console
avm99963a2945b62020-11-27 00:32:02 +0100333 var startup =
334 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
335
336 authuser = startup[2][1] || '0';
337
avm9996389812882021-02-02 20:51:25 +0100338 // When the OP's username is found, call getOptionsAndHandleIndicators
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +0200339 var mutationCallback = function(mutationList) {
avm99963e51444e2020-08-31 14:50:06 +0200340 mutationList.forEach((mutation) => {
341 if (mutation.type == 'childList') {
342 mutation.addedNodes.forEach(function(node) {
343 if (node.tagName == 'A' && ('href' in node) &&
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +0100344 CCProfileRegex.test(node.href)) {
345 if (node.matches(
346 'ec-question ec-message-header .name-section ec-user-link a')) {
347 console.info('Handling profile indicator via mutation callback.');
348 getOptionsAndHandleIndicators(node, UI_COMMUNITY_CONSOLE);
349 } else if (node.matches(
350 'sc-tailwind-thread-question-question-card ' +
351 'sc-tailwind-thread-post_header-user-info ' +
352 '.scTailwindThreadPost_headerUserinfoname a')) {
353 console.info(
354 'Handling interop profile indicator via mutation callback.');
355 getOptionsAndHandleIndicators(node, UI_COMMUNITY_CONSOLE_INTEROP);
356 }
avm99963e51444e2020-08-31 14:50:06 +0200357 }
358 });
359 }
360 });
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +0200361 }
avm99963e51444e2020-08-31 14:50:06 +0200362
363 var observerOptions = {
364 childList: true,
365 subtree: true,
366 }
367
avm9996389812882021-02-02 20:51:25 +0100368 // Before starting the mutation Observer, check if the OP's username link is
369 // already part of the page
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +0200370 let node = document.querySelector(
avm9996389812882021-02-02 20:51:25 +0100371 'ec-question ec-message-header .name-section ec-user-link a');
372 if (node !== null) {
373 console.info('Handling profile indicator via first check.');
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100374 getOptionsAndHandleIndicators(node, UI_COMMUNITY_CONSOLE);
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +0100375 } else {
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +0200376 node = document.querySelector(
Adrià Vilanova Martínezcb28fd92022-01-28 12:41:52 +0100377 'sc-tailwind-thread-question-question-card ' +
378 'sc-tailwind-thread-post_header-user-info ' +
379 '.scTailwindThreadPost_headerUserinfoname a');
380 if (node !== null) {
381 console.info('Handling interop profile indicator via first check.');
382 getOptionsAndHandleIndicators(node, UI_COMMUNITY_CONSOLE_INTEROP);
383 }
avm9996389812882021-02-02 20:51:25 +0100384 }
385
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +0200386 var mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100387 mutationObserver.observe(document.body, observerOptions);
avm99963e51444e2020-08-31 14:50:06 +0200388} else {
389 // We are in TW
avm99963a2945b62020-11-27 00:32:02 +0100390 authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
391
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +0200392 let node =
avm99963ad65e752020-09-01 00:13:59 +0200393 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200394 if (node !== null)
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100395 getOptionsAndHandleIndicators(node, UI_TW_LEGACY);
396 else {
397 // The user might be using the redesigned thread page.
Adrià Vilanova Martínez78ff4062023-07-06 20:03:29 +0200398 let node = document.querySelector(
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100399 'sc-tailwind-thread-question-question-card ' +
400 'sc-tailwind-thread-post_header-user-info ' +
401 '.scTailwindThreadPost_headerUserinfoname a');
402 if (node !== null)
403 getOptionsAndHandleIndicators(node, UI_TW_INTEROP);
404 else
405 console.error('[opindicator] Couldn\'t find username.');
406 }
avm99963e51444e2020-08-31 14:50:06 +0200407}