blob: 408c736cd4f2c71fe8a45040df599fb1c3d6552f [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
avm99963ad65e752020-09-01 00:13:59 +020026const indicatorTypes = ['numPosts', 'indicatorDot'];
27
avm99963e51444e2020-08-31 14:50:06 +020028// Filter used as a workaround to speed up the ViewForum request.
29const FILTER_ALL_LANGUAGES =
30 '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)';
31
avm99963ad65e752020-09-01 00:13:59 +020032const numPostsForumArraysToSum = [3, 4];
33
avm99963a2945b62020-11-27 00:32:02 +010034var authuser = null;
35
avm99963e51444e2020-08-31 14:50:06 +020036function isElementInside(element, outerTag) {
37 while (element !== null && ('tagName' in element)) {
38 if (element.tagName == outerTag) return true;
39 element = element.parentNode;
40 }
41
42 return false;
43}
44
avm99963a2945b62020-11-27 00:32:02 +010045function getPosts(query, forumId) {
avm99963e6166ed2021-08-26 10:45:17 +020046 return CCApi(
47 'ViewForum', {
48 '1': forumId,
49 '2': {
50 '1': {
51 '2': 5,
52 },
53 '2': {
54 '1': 1,
55 '2': true,
56 },
57 '12': query,
58 },
avm99963a2945b62020-11-27 00:32:02 +010059 },
avm99963e6166ed2021-08-26 10:45:17 +020060 /* authenticated = */ true, authuser);
avm99963a2945b62020-11-27 00:32:02 +010061}
62
avm99963ad65e752020-09-01 00:13:59 +020063function getProfile(userId, forumId) {
avm99963e6166ed2021-08-26 10:45:17 +020064 return CCApi(
65 'ViewUser', {
66 '1': userId,
67 '2': 0,
68 '3': forumId,
69 '4': {
70 '20': true,
71 },
72 },
73 /* authenticated = */ true, authuser);
avm99963ad65e752020-09-01 00:13:59 +020074}
75
avm99963e51444e2020-08-31 14:50:06 +020076// Source:
77// https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response
avm99963ad65e752020-09-01 00:13:59 +020078var contentScriptRequest = (function() {
avm99963e51444e2020-08-31 14:50:06 +020079 var requestId = 0;
avm999633e238882020-12-07 18:38:54 +010080 var prefix = 'TWPT-profileindicator';
avm99963e51444e2020-08-31 14:50:06 +020081
avm99963ad65e752020-09-01 00:13:59 +020082 function sendRequest(data) {
avm99963e51444e2020-08-31 14:50:06 +020083 var id = requestId++;
84
85 return new Promise(function(resolve, reject) {
86 var listener = function(evt) {
avm999633e238882020-12-07 18:38:54 +010087 if (evt.source === window && evt.data && evt.data.prefix === prefix &&
avm99963ad65e752020-09-01 00:13:59 +020088 evt.data.requestId == id) {
avm99963e51444e2020-08-31 14:50:06 +020089 // Deregister self
avm99963ad65e752020-09-01 00:13:59 +020090 window.removeEventListener('message', listener);
91 resolve(evt.data.data);
avm99963e51444e2020-08-31 14:50:06 +020092 }
93 };
94
avm99963ad65e752020-09-01 00:13:59 +020095 window.addEventListener('message', listener);
avm99963e51444e2020-08-31 14:50:06 +020096
avm999633e238882020-12-07 18:38:54 +010097 var payload = {data, id, prefix};
avm99963e51444e2020-08-31 14:50:06 +020098
avm99963ad65e752020-09-01 00:13:59 +020099 window.dispatchEvent(
100 new CustomEvent('TWPT_sendRequest', {detail: payload}));
avm99963e51444e2020-08-31 14:50:06 +0200101 });
102 }
103
avm99963ad65e752020-09-01 00:13:59 +0200104 return {sendRequest: sendRequest};
avm99963e51444e2020-08-31 14:50:06 +0200105})();
106
avm99963ad65e752020-09-01 00:13:59 +0200107// Create profile indicator dot with a loading state, or return the numPosts
108// badge if it is already created.
Adrià Vilanova Martíneze7770472021-10-17 00:02:37 +0200109function createIndicatorDot(sourceNode, searchURL, options, isCC) {
avm99963ad65e752020-09-01 00:13:59 +0200110 if (options.numPosts) return document.querySelector('.num-posts-indicator');
avm99963a1b23b62020-09-01 14:32:34 +0200111 var dotContainer = document.createElement('div');
avm99963ad65e752020-09-01 00:13:59 +0200112 dotContainer.classList.add('profile-indicator', 'profile-indicator--loading');
avm99963e51444e2020-08-31 14:50:06 +0200113
Adrià Vilanova Martíneze7770472021-10-17 00:02:37 +0200114 var dotLink = isCC ? createImmuneLink() : document.createElement('a');
avm99963e51444e2020-08-31 14:50:06 +0200115 dotLink.href = searchURL;
116 dotLink.innerText = '●';
117
118 dotContainer.appendChild(dotLink);
119 sourceNode.parentNode.appendChild(dotContainer);
120
avm999632485a3e2021-09-08 22:18:38 +0200121 contentScriptRequest
122 .sendRequest({
123 'action': 'geti18nMessage',
124 'msg': 'inject_profileindicator_loading'
125 })
126 .then(string => createPlainTooltip(dotContainer, string));
127
avm99963e51444e2020-08-31 14:50:06 +0200128 return dotContainer;
129}
130
avm99963ad65e752020-09-01 00:13:59 +0200131// Create badge indicating the number of posts with a loading state
Adrià Vilanova Martíneze7770472021-10-17 00:02:37 +0200132function createNumPostsBadge(sourceNode, searchURL, isCC) {
133 var link = isCC ? createImmuneLink() : document.createElement('a');
avm99963ad65e752020-09-01 00:13:59 +0200134 link.href = searchURL;
135
136 var numPostsContainer = document.createElement('div');
137 numPostsContainer.classList.add(
138 'num-posts-indicator', 'num-posts-indicator--loading');
avm99963ad65e752020-09-01 00:13:59 +0200139
140 var numPostsSpan = document.createElement('span');
141 numPostsSpan.classList.add('num-posts-indicator--num');
142
143 numPostsContainer.appendChild(numPostsSpan);
144 link.appendChild(numPostsContainer);
145 sourceNode.parentNode.appendChild(link);
avm999632485a3e2021-09-08 22:18:38 +0200146
147 contentScriptRequest
148 .sendRequest({
149 'action': 'geti18nMessage',
150 'msg': 'inject_profileindicator_loading'
151 })
152 .then(string => createPlainTooltip(numPostsContainer, string));
153
avm99963ad65e752020-09-01 00:13:59 +0200154 return numPostsContainer;
155}
156
avm9996313658b92020-12-02 00:02:53 +0100157// Set the badge text
158function setNumPostsBadge(badge, text) {
159 badge.classList.remove('num-posts-indicator--loading');
160 badge.querySelector('span').classList.remove(
161 'num-posts-indicator--num--loading');
162 badge.querySelector('span').textContent = text;
163}
164
avm99963ad65e752020-09-01 00:13:59 +0200165// Get options and then handle all the indicators
166function getOptionsAndHandleIndicators(sourceNode, isCC) {
167 contentScriptRequest.sendRequest({'action': 'getProfileIndicatorOptions'})
168 .then(options => handleIndicators(sourceNode, isCC, options));
169}
170
171// Handle the profile indicator dot
172function handleIndicators(sourceNode, isCC, options) {
avm99963e51444e2020-08-31 14:50:06 +0200173 var escapedUsername = escapeUsername(
Adrià Vilanova Martínez8cb54432021-09-19 23:05:13 +0200174 (isCC ? sourceNode.querySelector('.name-text').textContent :
175 sourceNode.querySelector('span').textContent));
avm99963e51444e2020-08-31 14:50:06 +0200176
177 if (isCC) {
178 var threadLink = document.location.href;
179 } else {
180 var CCLink = document.getElementById('onebar-community-console');
181 if (CCLink === null) {
182 console.error(
avm99963ad65e752020-09-01 00:13:59 +0200183 '[opindicator] The user is not a PE so the dot indicator cannot be shown in TW.');
avm99963e51444e2020-08-31 14:50:06 +0200184 return;
185 }
186 var threadLink = CCLink.href;
187 }
188
189 var forumUrlSplit = threadLink.split('/forum/');
190 if (forumUrlSplit.length < 2) {
avm99963ad65e752020-09-01 00:13:59 +0200191 console.error('[opindicator] Can\'t get forum id.');
avm99963e51444e2020-08-31 14:50:06 +0200192 return;
193 }
194
195 var forumId = forumUrlSplit[1].split('/')[0];
avm99963ad65e752020-09-01 00:13:59 +0200196
avm99963104bad32021-02-05 22:00:44 +0100197 /*
198 * TODO(avm99963): If the TW filters ever work again, set isCCLink to isCC.
199 * Otherwise, issue #29 should be resolved:
200 * https://github.com/avm99963/infinitegforums/issues/29
201 */
202 var isCCLink = true;
203
avm99963e51444e2020-08-31 14:50:06 +0200204 var query = '(replier:"' + escapedUsername + '" | creator:"' +
205 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
206 var encodedQuery =
avm99963104bad32021-02-05 22:00:44 +0100207 encodeURIComponent(query + (isCCLink ? ' forum:' + forumId : ''));
avm99963a2945b62020-11-27 00:32:02 +0100208 var authuserPart =
209 (authuser == '0' ?
210 '' :
avm99963104bad32021-02-05 22:00:44 +0100211 (isCCLink ? '?' : '&') + 'authuser=' + encodeURIComponent(authuser));
avm99963e51444e2020-08-31 14:50:06 +0200212 var searchURL =
avm99963104bad32021-02-05 22:00:44 +0100213 (isCCLink ? 'https://support.google.com/s/community/search/' +
avm99963a2945b62020-11-27 00:32:02 +0100214 encodeURIComponent('query=' + encodedQuery) + authuserPart :
avm99963104bad32021-02-05 22:00:44 +0100215 document.location.pathname.split('/thread')[0] +
avm99963a2945b62020-11-27 00:32:02 +0100216 '/threads?thread_filter=' + encodedQuery + authuserPart);
avm99963e51444e2020-08-31 14:50:06 +0200217
avm99963ad65e752020-09-01 00:13:59 +0200218 if (options.numPosts) {
219 var profileURL = new URL(sourceNode.href);
220 var userId =
221 profileURL.pathname.split(isCC ? 'user/' : 'profile/')[1].split('/')[0];
avm99963e51444e2020-08-31 14:50:06 +0200222
Adrià Vilanova Martíneze7770472021-10-17 00:02:37 +0200223 var numPostsContainer = createNumPostsBadge(sourceNode, searchURL, isCC);
avm99963e51444e2020-08-31 14:50:06 +0200224
avm99963ad65e752020-09-01 00:13:59 +0200225 getProfile(userId, forumId)
226 .then(res => {
227 if (!('1' in res) || !('2' in res[1])) {
228 throw new Error('Unexpected profile response.');
229 return;
230 }
avm99963e51444e2020-08-31 14:50:06 +0200231
avm99963ad65e752020-09-01 00:13:59 +0200232 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
233 .then(months => {
234 if (!options.indicatorDot)
235 contentScriptRequest
236 .sendRequest({
237 'action': 'geti18nMessage',
238 'msg': 'inject_profileindicatoralt_numposts',
239 'placeholders': [months]
240 })
241 .then(
242 string =>
avm999632485a3e2021-09-08 22:18:38 +0200243 createPlainTooltip(numPostsContainer, string));
avm99963e51444e2020-08-31 14:50:06 +0200244
avm99963ad65e752020-09-01 00:13:59 +0200245 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200246
avm99963ad65e752020-09-01 00:13:59 +0200247 for (const index of numPostsForumArraysToSum) {
248 if (!(index in res[1][2])) {
249 throw new Error('Unexpected profile response.');
250 return;
251 }
avm99963e51444e2020-08-31 14:50:06 +0200252
avm99963ad65e752020-09-01 00:13:59 +0200253 var i = 0;
254 for (const month of res[1][2][index].reverse()) {
255 if (i == months) break;
256 numPosts += month[3] || 0;
257 ++i;
258 }
259 }
avm99963e51444e2020-08-31 14:50:06 +0200260
avm9996313658b92020-12-02 00:02:53 +0100261 setNumPostsBadge(numPostsContainer, numPosts);
avm99963ad65e752020-09-01 00:13:59 +0200262 })
263 .catch(
264 err => console.error('[opindicator] Unexpected error.', err));
265 })
avm9996313658b92020-12-02 00:02:53 +0100266 .catch(err => {
267 console.error(
268 '[opindicator] Unexpected error. Couldn\'t load profile.', err);
269 setNumPostsBadge(numPostsContainer, '?');
270 });
avm99963ad65e752020-09-01 00:13:59 +0200271 }
272
273 if (options.indicatorDot) {
Adrià Vilanova Martíneze7770472021-10-17 00:02:37 +0200274 var dotContainer = createIndicatorDot(sourceNode, searchURL, options, isCC);
avm99963ad65e752020-09-01 00:13:59 +0200275
276 // Query threads in order to see what state the indicator should be in
277 getPosts(query, forumId)
278 .then(res => {
avm999639f586f42021-02-05 12:37:51 +0100279 // Throw an error when the replies array is not present in the reply.
avm99963ad65e752020-09-01 00:13:59 +0200280 if (!('1' in res) || !('2' in res['1'])) {
avm999639f586f42021-02-05 12:37:51 +0100281 // Throw a different error when the numThreads field exists and is
282 // equal to 0. This reply can be received, but is enexpected,
283 // because we know that the user has replied in at least 1 thread
284 // (the current one).
285 if (('1' in res) && ('4' in res['1']) && res['1']['4'] == 0)
286 throw new Error(
287 'Thread list is empty ' +
288 '(but the OP has participated in this thread, ' +
289 'so it shouldn\'t be empty).');
290
avm99963ad65e752020-09-01 00:13:59 +0200291 throw new Error('Unexpected thread list response.');
292 return;
293 }
294
295 // Current thread ID
296 var threadUrlSplit = threadLink.split('/thread/');
297 if (threadUrlSplit.length < 2)
298 throw new Error('Can\'t get thread id.');
299
300 var currId = threadUrlSplit[1].split('/')[0];
301
302 var OPStatus = OP_FIRST_POST;
303
304 for (const thread of res['1']['2']) {
305 var id = thread['2']['1']['1'] || undefined;
306 if (id === undefined || id == currId) continue;
307
308 var isRead = thread['6'] || false;
309 if (isRead)
310 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
311 else
312 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
313 }
314
315 var dotContainerPrefix =
316 (options.numPosts ? 'num-posts-indicator' : 'profile-indicator');
317
318 if (!options.numPosts)
319 dotContainer.classList.remove(dotContainerPrefix + '--loading');
320 dotContainer.classList.add(
321 dotContainerPrefix + '--' + OPClasses[OPStatus]);
322 contentScriptRequest
323 .sendRequest({
324 'action': 'geti18nMessage',
325 'msg': 'inject_profileindicator_' + OPi18n[OPStatus]
326 })
avm999632485a3e2021-09-08 22:18:38 +0200327 .then(string => createPlainTooltip(dotContainer, string));
avm99963ad65e752020-09-01 00:13:59 +0200328 })
329 .catch(
330 err => console.error(
331 '[opindicator] Unexpected error. Couldn\'t load recent posts.',
332 err));
333 }
avm99963e51444e2020-08-31 14:50:06 +0200334}
335
336if (CCRegex.test(location.href)) {
337 // We are in the Community Console
avm99963a2945b62020-11-27 00:32:02 +0100338 var startup =
339 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
340
341 authuser = startup[2][1] || '0';
342
avm9996389812882021-02-02 20:51:25 +0100343 // When the OP's username is found, call getOptionsAndHandleIndicators
avm99963e51444e2020-08-31 14:50:06 +0200344 function mutationCallback(mutationList, observer) {
345 mutationList.forEach((mutation) => {
346 if (mutation.type == 'childList') {
347 mutation.addedNodes.forEach(function(node) {
348 if (node.tagName == 'A' && ('href' in node) &&
349 CCProfileRegex.test(node.href) &&
avm999639f586f42021-02-05 12:37:51 +0100350 node.matches(
351 'ec-question ec-message-header .name-section ec-user-link a')) {
avm9996389812882021-02-02 20:51:25 +0100352 console.info('Handling profile indicator via mutation callback.');
avm99963ad65e752020-09-01 00:13:59 +0200353 getOptionsAndHandleIndicators(node, true);
avm99963e51444e2020-08-31 14:50:06 +0200354 }
355 });
356 }
357 });
358 };
359
360 var observerOptions = {
361 childList: true,
362 subtree: true,
363 }
364
avm9996389812882021-02-02 20:51:25 +0100365 // Before starting the mutation Observer, check if the OP's username link is
366 // already part of the page
367 var node = document.querySelector(
368 'ec-question ec-message-header .name-section ec-user-link a');
369 if (node !== null) {
370 console.info('Handling profile indicator via first check.');
371 getOptionsAndHandleIndicators(node, true);
372 }
373
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +0200374 var mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100375 mutationObserver.observe(document.body, observerOptions);
avm99963e51444e2020-08-31 14:50:06 +0200376} else {
377 // We are in TW
avm99963a2945b62020-11-27 00:32:02 +0100378 authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
379
avm99963ad65e752020-09-01 00:13:59 +0200380 var node =
381 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200382 if (node !== null)
avm99963ad65e752020-09-01 00:13:59 +0200383 getOptionsAndHandleIndicators(node, false);
avm99963e51444e2020-08-31 14:50:06 +0200384 else
avm99963ad65e752020-09-01 00:13:59 +0200385 console.error('[opindicator] Couldn\'t find username.');
avm99963e51444e2020-08-31 14:50:06 +0200386}