blob: ae96b3fd26289b43817dc9a6316572e8a5659b1f [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 =
avm99963a945acd2021-02-06 19:23:14 +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;
29
avm99963ad65e752020-09-01 00:13:59 +020030const indicatorTypes = ['numPosts', 'indicatorDot'];
31
avm99963e51444e2020-08-31 14:50:06 +020032// Filter used as a workaround to speed up the ViewForum request.
33const FILTER_ALL_LANGUAGES =
34 '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)';
35
avm99963ad65e752020-09-01 00:13:59 +020036const numPostsForumArraysToSum = [3, 4];
37
avm99963a2945b62020-11-27 00:32:02 +010038var authuser = null;
39
avm99963e51444e2020-08-31 14:50:06 +020040function isElementInside(element, outerTag) {
41 while (element !== null && ('tagName' in element)) {
42 if (element.tagName == outerTag) return true;
43 element = element.parentNode;
44 }
45
46 return false;
47}
48
avm99963a2945b62020-11-27 00:32:02 +010049function getPosts(query, forumId) {
avm99963e6166ed2021-08-26 10:45:17 +020050 return CCApi(
51 'ViewForum', {
52 '1': forumId,
53 '2': {
54 '1': {
55 '2': 5,
56 },
57 '2': {
58 '1': 1,
59 '2': true,
60 },
61 '12': query,
62 },
avm99963a2945b62020-11-27 00:32:02 +010063 },
avm99963e6166ed2021-08-26 10:45:17 +020064 /* authenticated = */ true, authuser);
avm99963a2945b62020-11-27 00:32:02 +010065}
66
avm99963ad65e752020-09-01 00:13:59 +020067function getProfile(userId, forumId) {
avm99963e6166ed2021-08-26 10:45:17 +020068 return CCApi(
69 'ViewUser', {
70 '1': userId,
71 '2': 0,
72 '3': forumId,
73 '4': {
74 '20': true,
75 },
76 },
77 /* authenticated = */ true, authuser);
avm99963ad65e752020-09-01 00:13:59 +020078}
79
avm99963e51444e2020-08-31 14:50:06 +020080// Source:
81// https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response
avm99963ad65e752020-09-01 00:13:59 +020082var contentScriptRequest = (function() {
avm99963e51444e2020-08-31 14:50:06 +020083 var requestId = 0;
avm999633e238882020-12-07 18:38:54 +010084 var prefix = 'TWPT-profileindicator';
avm99963e51444e2020-08-31 14:50:06 +020085
avm99963ad65e752020-09-01 00:13:59 +020086 function sendRequest(data) {
avm99963e51444e2020-08-31 14:50:06 +020087 var id = requestId++;
88
89 return new Promise(function(resolve, reject) {
90 var listener = function(evt) {
avm999633e238882020-12-07 18:38:54 +010091 if (evt.source === window && evt.data && evt.data.prefix === prefix &&
avm99963ad65e752020-09-01 00:13:59 +020092 evt.data.requestId == id) {
avm99963e51444e2020-08-31 14:50:06 +020093 // Deregister self
avm99963ad65e752020-09-01 00:13:59 +020094 window.removeEventListener('message', listener);
95 resolve(evt.data.data);
avm99963e51444e2020-08-31 14:50:06 +020096 }
97 };
98
avm99963ad65e752020-09-01 00:13:59 +020099 window.addEventListener('message', listener);
avm99963e51444e2020-08-31 14:50:06 +0200100
avm999633e238882020-12-07 18:38:54 +0100101 var payload = {data, id, prefix};
avm99963e51444e2020-08-31 14:50:06 +0200102
avm99963ad65e752020-09-01 00:13:59 +0200103 window.dispatchEvent(
104 new CustomEvent('TWPT_sendRequest', {detail: payload}));
avm99963e51444e2020-08-31 14:50:06 +0200105 });
106 }
107
avm99963ad65e752020-09-01 00:13:59 +0200108 return {sendRequest: sendRequest};
avm99963e51444e2020-08-31 14:50:06 +0200109})();
110
avm99963ad65e752020-09-01 00:13:59 +0200111// Create profile indicator dot with a loading state, or return the numPosts
112// badge if it is already created.
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100113function createIndicatorDot(sourceNode, searchURL, options, ui) {
avm99963ad65e752020-09-01 00:13:59 +0200114 if (options.numPosts) return document.querySelector('.num-posts-indicator');
avm99963a1b23b62020-09-01 14:32:34 +0200115 var dotContainer = document.createElement('div');
avm99963ad65e752020-09-01 00:13:59 +0200116 dotContainer.classList.add('profile-indicator', 'profile-indicator--loading');
avm99963e51444e2020-08-31 14:50:06 +0200117
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100118 var dotLink = (ui === UI_COMMUNITY_CONSOLE) ? createImmuneLink() :
119 document.createElement('a');
avm99963e51444e2020-08-31 14:50:06 +0200120 dotLink.href = searchURL;
121 dotLink.innerText = '●';
122
123 dotContainer.appendChild(dotLink);
124 sourceNode.parentNode.appendChild(dotContainer);
125
avm999632485a3e2021-09-08 22:18:38 +0200126 contentScriptRequest
127 .sendRequest({
128 'action': 'geti18nMessage',
129 'msg': 'inject_profileindicator_loading'
130 })
131 .then(string => createPlainTooltip(dotContainer, string));
132
avm99963e51444e2020-08-31 14:50:06 +0200133 return dotContainer;
134}
135
avm99963ad65e752020-09-01 00:13:59 +0200136// Create badge indicating the number of posts with a loading state
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100137function createNumPostsBadge(sourceNode, searchURL, ui) {
138 var link = (ui === UI_COMMUNITY_CONSOLE) ? createImmuneLink() :
139 document.createElement('a');
avm99963ad65e752020-09-01 00:13:59 +0200140 link.href = searchURL;
141
142 var numPostsContainer = document.createElement('div');
143 numPostsContainer.classList.add(
144 'num-posts-indicator', 'num-posts-indicator--loading');
avm99963ad65e752020-09-01 00:13:59 +0200145
146 var numPostsSpan = document.createElement('span');
147 numPostsSpan.classList.add('num-posts-indicator--num');
148
149 numPostsContainer.appendChild(numPostsSpan);
150 link.appendChild(numPostsContainer);
151 sourceNode.parentNode.appendChild(link);
avm999632485a3e2021-09-08 22:18:38 +0200152
153 contentScriptRequest
154 .sendRequest({
155 'action': 'geti18nMessage',
156 'msg': 'inject_profileindicator_loading'
157 })
158 .then(string => createPlainTooltip(numPostsContainer, string));
159
avm99963ad65e752020-09-01 00:13:59 +0200160 return numPostsContainer;
161}
162
avm9996313658b92020-12-02 00:02:53 +0100163// Set the badge text
164function setNumPostsBadge(badge, text) {
165 badge.classList.remove('num-posts-indicator--loading');
166 badge.querySelector('span').classList.remove(
167 'num-posts-indicator--num--loading');
168 badge.querySelector('span').textContent = text;
169}
170
avm99963ad65e752020-09-01 00:13:59 +0200171// Get options and then handle all the indicators
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100172function getOptionsAndHandleIndicators(sourceNode, ui) {
avm99963ad65e752020-09-01 00:13:59 +0200173 contentScriptRequest.sendRequest({'action': 'getProfileIndicatorOptions'})
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100174 .then(options => handleIndicators(sourceNode, ui, options));
avm99963ad65e752020-09-01 00:13:59 +0200175}
176
177// Handle the profile indicator dot
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100178function handleIndicators(sourceNode, ui, options) {
179 let nameEl;
180 if (ui === UI_COMMUNITY_CONSOLE)
181 nameEl = sourceNode.querySelector('.name-text');
182 if (ui === UI_TW_LEGACY) nameEl = sourceNode.querySelector('span');
183 if (ui === UI_TW_INTEROP) nameEl = sourceNode;
184 var escapedUsername = escapeUsername(nameEl.textContent);
avm99963e51444e2020-08-31 14:50:06 +0200185
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100186 if (ui === UI_COMMUNITY_CONSOLE) {
avm99963e51444e2020-08-31 14:50:06 +0200187 var threadLink = document.location.href;
188 } 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 }
195 var threadLink = CCLink.href;
196 }
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:"' +
207 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100208 var encodedQuery = encodeURIComponent(' forum:' + forumId);
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);
216 var userId =
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100217 profileURL.pathname
218 .split(ui === UI_COMMUNITY_CONSOLE ? 'user/' : 'profile/')[1]
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.');
227 return;
228 }
avm99963e51444e2020-08-31 14:50:06 +0200229
avm99963ad65e752020-09-01 00:13:59 +0200230 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
231 .then(months => {
232 if (!options.indicatorDot)
233 contentScriptRequest
234 .sendRequest({
235 'action': 'geti18nMessage',
236 'msg': 'inject_profileindicatoralt_numposts',
237 'placeholders': [months]
238 })
239 .then(
240 string =>
avm999632485a3e2021-09-08 22:18:38 +0200241 createPlainTooltip(numPostsContainer, string));
avm99963e51444e2020-08-31 14:50:06 +0200242
avm99963ad65e752020-09-01 00:13:59 +0200243 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200244
avm99963ad65e752020-09-01 00:13:59 +0200245 for (const index of numPostsForumArraysToSum) {
246 if (!(index in res[1][2])) {
247 throw new Error('Unexpected profile response.');
248 return;
249 }
avm99963e51444e2020-08-31 14:50:06 +0200250
avm99963ad65e752020-09-01 00:13:59 +0200251 var i = 0;
252 for (const month of res[1][2][index].reverse()) {
253 if (i == months) break;
254 numPosts += month[3] || 0;
255 ++i;
256 }
257 }
avm99963e51444e2020-08-31 14:50:06 +0200258
avm9996313658b92020-12-02 00:02:53 +0100259 setNumPostsBadge(numPostsContainer, numPosts);
avm99963ad65e752020-09-01 00:13:59 +0200260 })
261 .catch(
262 err => console.error('[opindicator] Unexpected error.', err));
263 })
avm9996313658b92020-12-02 00:02:53 +0100264 .catch(err => {
265 console.error(
266 '[opindicator] Unexpected error. Couldn\'t load profile.', err);
267 setNumPostsBadge(numPostsContainer, '?');
268 });
avm99963ad65e752020-09-01 00:13:59 +0200269 }
270
271 if (options.indicatorDot) {
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100272 var dotContainer = createIndicatorDot(sourceNode, searchURL, options, ui);
avm99963ad65e752020-09-01 00:13:59 +0200273
274 // Query threads in order to see what state the indicator should be in
275 getPosts(query, forumId)
276 .then(res => {
avm999639f586f42021-02-05 12:37:51 +0100277 // Throw an error when the replies array is not present in the reply.
avm99963ad65e752020-09-01 00:13:59 +0200278 if (!('1' in res) || !('2' in res['1'])) {
avm999639f586f42021-02-05 12:37:51 +0100279 // Throw a different error when the numThreads field exists and is
280 // equal to 0. This reply can be received, but is enexpected,
281 // because we know that the user has replied in at least 1 thread
282 // (the current one).
283 if (('1' in res) && ('4' in res['1']) && res['1']['4'] == 0)
284 throw new Error(
285 'Thread list is empty ' +
286 '(but the OP has participated in this thread, ' +
287 'so it shouldn\'t be empty).');
288
avm99963ad65e752020-09-01 00:13:59 +0200289 throw new Error('Unexpected thread list response.');
290 return;
291 }
292
293 // Current thread ID
294 var threadUrlSplit = threadLink.split('/thread/');
295 if (threadUrlSplit.length < 2)
296 throw new Error('Can\'t get thread id.');
297
298 var currId = threadUrlSplit[1].split('/')[0];
299
300 var OPStatus = OP_FIRST_POST;
301
302 for (const thread of res['1']['2']) {
303 var id = thread['2']['1']['1'] || undefined;
304 if (id === undefined || id == currId) continue;
305
306 var isRead = thread['6'] || false;
307 if (isRead)
308 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
309 else
310 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
311 }
312
313 var dotContainerPrefix =
314 (options.numPosts ? 'num-posts-indicator' : 'profile-indicator');
315
316 if (!options.numPosts)
317 dotContainer.classList.remove(dotContainerPrefix + '--loading');
318 dotContainer.classList.add(
319 dotContainerPrefix + '--' + OPClasses[OPStatus]);
320 contentScriptRequest
321 .sendRequest({
322 'action': 'geti18nMessage',
323 'msg': 'inject_profileindicator_' + OPi18n[OPStatus]
324 })
avm999632485a3e2021-09-08 22:18:38 +0200325 .then(string => createPlainTooltip(dotContainer, string));
avm99963ad65e752020-09-01 00:13:59 +0200326 })
327 .catch(
328 err => console.error(
329 '[opindicator] Unexpected error. Couldn\'t load recent posts.',
330 err));
331 }
avm99963e51444e2020-08-31 14:50:06 +0200332}
333
334if (CCRegex.test(location.href)) {
335 // We are in the Community Console
avm99963a2945b62020-11-27 00:32:02 +0100336 var startup =
337 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
338
339 authuser = startup[2][1] || '0';
340
avm9996389812882021-02-02 20:51:25 +0100341 // When the OP's username is found, call getOptionsAndHandleIndicators
avm99963e51444e2020-08-31 14:50:06 +0200342 function mutationCallback(mutationList, observer) {
343 mutationList.forEach((mutation) => {
344 if (mutation.type == 'childList') {
345 mutation.addedNodes.forEach(function(node) {
346 if (node.tagName == 'A' && ('href' in node) &&
347 CCProfileRegex.test(node.href) &&
avm999639f586f42021-02-05 12:37:51 +0100348 node.matches(
349 'ec-question ec-message-header .name-section ec-user-link a')) {
avm9996389812882021-02-02 20:51:25 +0100350 console.info('Handling profile indicator via mutation callback.');
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100351 getOptionsAndHandleIndicators(node, UI_COMMUNITY_CONSOLE);
avm99963e51444e2020-08-31 14:50:06 +0200352 }
353 });
354 }
355 });
356 };
357
358 var observerOptions = {
359 childList: true,
360 subtree: true,
361 }
362
avm9996389812882021-02-02 20:51:25 +0100363 // Before starting the mutation Observer, check if the OP's username link is
364 // already part of the page
365 var node = document.querySelector(
366 'ec-question ec-message-header .name-section ec-user-link a');
367 if (node !== null) {
368 console.info('Handling profile indicator via first check.');
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100369 getOptionsAndHandleIndicators(node, UI_COMMUNITY_CONSOLE);
avm9996389812882021-02-02 20:51:25 +0100370 }
371
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +0200372 var mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100373 mutationObserver.observe(document.body, observerOptions);
avm99963e51444e2020-08-31 14:50:06 +0200374} else {
375 // We are in TW
avm99963a2945b62020-11-27 00:32:02 +0100376 authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
377
avm99963ad65e752020-09-01 00:13:59 +0200378 var node =
379 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200380 if (node !== null)
Adrià Vilanova Martínezad6bedf2022-01-28 10:41:10 +0100381 getOptionsAndHandleIndicators(node, UI_TW_LEGACY);
382 else {
383 // The user might be using the redesigned thread page.
384 var node = document.querySelector(
385 'sc-tailwind-thread-question-question-card ' +
386 'sc-tailwind-thread-post_header-user-info ' +
387 '.scTailwindThreadPost_headerUserinfoname a');
388 if (node !== null)
389 getOptionsAndHandleIndicators(node, UI_TW_INTEROP);
390 else
391 console.error('[opindicator] Couldn\'t find username.');
392 }
avm99963e51444e2020-08-31 14:50:06 +0200393}