blob: ee897fe6e0c018a93204ca316341451a1af34916 [file] [log] [blame]
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +02001import {escapeUsername} from '../common/communityConsoleUtils.js';
2
avm99963e51444e2020-08-31 14:50:06 +02003var CCProfileRegex =
avm99963a945acd2021-02-06 19:23:14 +01004 /^(?:https:\/\/support\.google\.com)?\/s\/community(?:\/forum\/[0-9]*)?\/user\/(?:[0-9]+)$/;
avm99963e51444e2020-08-31 14:50:06 +02005var CCRegex = /^https:\/\/support\.google\.com\/s\/community/;
6
avm99963a2945b62020-11-27 00:32:02 +01007const BASE_URL = 'https://support.google.com/s/community/api/';
8
avm99963e51444e2020-08-31 14:50:06 +02009const OP_FIRST_POST = 0;
10const OP_OTHER_POSTS_READ = 1;
11const OP_OTHER_POSTS_UNREAD = 2;
12
13const OPClasses = {
avm99963ad65e752020-09-01 00:13:59 +020014 0: 'first-post',
15 1: 'other-posts-read',
16 2: 'other-posts-unread',
avm99963e51444e2020-08-31 14:50:06 +020017};
18
19const OPi18n = {
20 0: 'first_post',
21 1: 'other_posts_read',
22 2: 'other_posts_unread',
23};
24
avm99963ad65e752020-09-01 00:13:59 +020025const indicatorTypes = ['numPosts', 'indicatorDot'];
26
avm99963e51444e2020-08-31 14:50:06 +020027// Filter used as a workaround to speed up the ViewForum request.
28const FILTER_ALL_LANGUAGES =
29 '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)';
30
avm99963ad65e752020-09-01 00:13:59 +020031const numPostsForumArraysToSum = [3, 4];
32
avm99963a2945b62020-11-27 00:32:02 +010033var authuser = null;
34
avm99963e51444e2020-08-31 14:50:06 +020035function isElementInside(element, outerTag) {
36 while (element !== null && ('tagName' in element)) {
37 if (element.tagName == outerTag) return true;
38 element = element.parentNode;
39 }
40
41 return false;
42}
43
avm99963a2945b62020-11-27 00:32:02 +010044function APIRequest(action, body) {
45 var authuserPart =
46 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
47
48 return fetch(BASE_URL + action + authuserPart, {
avm99963e51444e2020-08-31 14:50:06 +020049 'credentials': 'include',
50 'headers': {'content-type': 'text/plain; charset=utf-8'},
avm99963a2945b62020-11-27 00:32:02 +010051 'body': JSON.stringify(body),
avm99963e51444e2020-08-31 14:50:06 +020052 'method': 'POST',
53 'mode': 'cors',
54 })
55 .then(res => res.json());
56}
57
avm99963a2945b62020-11-27 00:32:02 +010058function getPosts(query, forumId) {
59 return APIRequest('ViewForum', {
60 '1': forumId,
61 '2': {
62 '1': {
63 '2': 5,
64 },
65 '2': {
66 '1': 1,
67 '2': true,
68 },
69 '12': query,
70 },
71 });
72}
73
avm99963ad65e752020-09-01 00:13:59 +020074function getProfile(userId, forumId) {
avm99963a2945b62020-11-27 00:32:02 +010075 return APIRequest('ViewUser', {
76 '1': userId,
77 '2': 0,
78 '3': forumId,
avm999633a412b82020-12-01 23:22:31 +010079 '4': {
80 '20': true,
81 },
avm99963a2945b62020-11-27 00:32:02 +010082 });
avm99963ad65e752020-09-01 00:13:59 +020083}
84
avm99963e51444e2020-08-31 14:50:06 +020085// Source:
86// https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response
avm99963ad65e752020-09-01 00:13:59 +020087var contentScriptRequest = (function() {
avm99963e51444e2020-08-31 14:50:06 +020088 var requestId = 0;
avm999633e238882020-12-07 18:38:54 +010089 var prefix = 'TWPT-profileindicator';
avm99963e51444e2020-08-31 14:50:06 +020090
avm99963ad65e752020-09-01 00:13:59 +020091 function sendRequest(data) {
avm99963e51444e2020-08-31 14:50:06 +020092 var id = requestId++;
93
94 return new Promise(function(resolve, reject) {
95 var listener = function(evt) {
avm999633e238882020-12-07 18:38:54 +010096 if (evt.source === window && evt.data && evt.data.prefix === prefix &&
avm99963ad65e752020-09-01 00:13:59 +020097 evt.data.requestId == id) {
avm99963e51444e2020-08-31 14:50:06 +020098 // Deregister self
avm99963ad65e752020-09-01 00:13:59 +020099 window.removeEventListener('message', listener);
100 resolve(evt.data.data);
avm99963e51444e2020-08-31 14:50:06 +0200101 }
102 };
103
avm99963ad65e752020-09-01 00:13:59 +0200104 window.addEventListener('message', listener);
avm99963e51444e2020-08-31 14:50:06 +0200105
avm999633e238882020-12-07 18:38:54 +0100106 var payload = {data, id, prefix};
avm99963e51444e2020-08-31 14:50:06 +0200107
avm99963ad65e752020-09-01 00:13:59 +0200108 window.dispatchEvent(
109 new CustomEvent('TWPT_sendRequest', {detail: payload}));
avm99963e51444e2020-08-31 14:50:06 +0200110 });
111 }
112
avm99963ad65e752020-09-01 00:13:59 +0200113 return {sendRequest: sendRequest};
avm99963e51444e2020-08-31 14:50:06 +0200114})();
115
avm99963ad65e752020-09-01 00:13:59 +0200116// Create profile indicator dot with a loading state, or return the numPosts
117// badge if it is already created.
118function createIndicatorDot(sourceNode, searchURL, options) {
119 if (options.numPosts) return document.querySelector('.num-posts-indicator');
avm99963a1b23b62020-09-01 14:32:34 +0200120 var dotContainer = document.createElement('div');
avm99963ad65e752020-09-01 00:13:59 +0200121 dotContainer.classList.add('profile-indicator', 'profile-indicator--loading');
122 contentScriptRequest
123 .sendRequest({
124 'action': 'geti18nMessage',
125 'msg': 'inject_profileindicator_loading'
126 })
avm99963e51444e2020-08-31 14:50:06 +0200127 .then(string => dotContainer.setAttribute('title', string));
128
129 var dotLink = document.createElement('a');
130 dotLink.href = searchURL;
131 dotLink.innerText = '●';
132
133 dotContainer.appendChild(dotLink);
134 sourceNode.parentNode.appendChild(dotContainer);
135
136 return dotContainer;
137}
138
avm99963ad65e752020-09-01 00:13:59 +0200139// Create badge indicating the number of posts with a loading state
140function createNumPostsBadge(sourceNode, searchURL) {
141 var link = document.createElement('a');
142 link.href = searchURL;
143
144 var numPostsContainer = document.createElement('div');
145 numPostsContainer.classList.add(
146 'num-posts-indicator', 'num-posts-indicator--loading');
147 contentScriptRequest
148 .sendRequest({
149 'action': 'geti18nMessage',
150 'msg': 'inject_profileindicator_loading'
151 })
152 .then(string => numPostsContainer.setAttribute('title', string));
153
154 var numPostsSpan = document.createElement('span');
155 numPostsSpan.classList.add('num-posts-indicator--num');
156
157 numPostsContainer.appendChild(numPostsSpan);
158 link.appendChild(numPostsContainer);
159 sourceNode.parentNode.appendChild(link);
160 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
172function getOptionsAndHandleIndicators(sourceNode, isCC) {
173 contentScriptRequest.sendRequest({'action': 'getProfileIndicatorOptions'})
174 .then(options => handleIndicators(sourceNode, isCC, options));
175}
176
177// Handle the profile indicator dot
178function handleIndicators(sourceNode, isCC, options) {
avm99963e51444e2020-08-31 14:50:06 +0200179 var escapedUsername = escapeUsername(
avm999639f586f42021-02-05 12:37:51 +0100180 (isCC ? sourceNode.querySelector('.name-text').innerHTML :
avm99963e51444e2020-08-31 14:50:06 +0200181 sourceNode.querySelector('span').innerHTML));
182
183 if (isCC) {
184 var threadLink = document.location.href;
185 } else {
186 var CCLink = document.getElementById('onebar-community-console');
187 if (CCLink === null) {
188 console.error(
avm99963ad65e752020-09-01 00:13:59 +0200189 '[opindicator] The user is not a PE so the dot indicator cannot be shown in TW.');
avm99963e51444e2020-08-31 14:50:06 +0200190 return;
191 }
192 var threadLink = CCLink.href;
193 }
194
195 var forumUrlSplit = threadLink.split('/forum/');
196 if (forumUrlSplit.length < 2) {
avm99963ad65e752020-09-01 00:13:59 +0200197 console.error('[opindicator] Can\'t get forum id.');
avm99963e51444e2020-08-31 14:50:06 +0200198 return;
199 }
200
201 var forumId = forumUrlSplit[1].split('/')[0];
avm99963ad65e752020-09-01 00:13:59 +0200202
avm99963104bad32021-02-05 22:00:44 +0100203 /*
204 * TODO(avm99963): If the TW filters ever work again, set isCCLink to isCC.
205 * Otherwise, issue #29 should be resolved:
206 * https://github.com/avm99963/infinitegforums/issues/29
207 */
208 var isCCLink = true;
209
avm99963e51444e2020-08-31 14:50:06 +0200210 var query = '(replier:"' + escapedUsername + '" | creator:"' +
211 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
212 var encodedQuery =
avm99963104bad32021-02-05 22:00:44 +0100213 encodeURIComponent(query + (isCCLink ? ' forum:' + forumId : ''));
avm99963a2945b62020-11-27 00:32:02 +0100214 var authuserPart =
215 (authuser == '0' ?
216 '' :
avm99963104bad32021-02-05 22:00:44 +0100217 (isCCLink ? '?' : '&') + 'authuser=' + encodeURIComponent(authuser));
avm99963e51444e2020-08-31 14:50:06 +0200218 var searchURL =
avm99963104bad32021-02-05 22:00:44 +0100219 (isCCLink ? 'https://support.google.com/s/community/search/' +
avm99963a2945b62020-11-27 00:32:02 +0100220 encodeURIComponent('query=' + encodedQuery) + authuserPart :
avm99963104bad32021-02-05 22:00:44 +0100221 document.location.pathname.split('/thread')[0] +
avm99963a2945b62020-11-27 00:32:02 +0100222 '/threads?thread_filter=' + encodedQuery + authuserPart);
avm99963e51444e2020-08-31 14:50:06 +0200223
avm99963ad65e752020-09-01 00:13:59 +0200224 if (options.numPosts) {
225 var profileURL = new URL(sourceNode.href);
226 var userId =
227 profileURL.pathname.split(isCC ? 'user/' : 'profile/')[1].split('/')[0];
avm99963e51444e2020-08-31 14:50:06 +0200228
avm99963ad65e752020-09-01 00:13:59 +0200229 var numPostsContainer = createNumPostsBadge(sourceNode, searchURL);
avm99963e51444e2020-08-31 14:50:06 +0200230
avm99963ad65e752020-09-01 00:13:59 +0200231 getProfile(userId, forumId)
232 .then(res => {
233 if (!('1' in res) || !('2' in res[1])) {
234 throw new Error('Unexpected profile response.');
235 return;
236 }
avm99963e51444e2020-08-31 14:50:06 +0200237
avm99963ad65e752020-09-01 00:13:59 +0200238 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
239 .then(months => {
240 if (!options.indicatorDot)
241 contentScriptRequest
242 .sendRequest({
243 'action': 'geti18nMessage',
244 'msg': 'inject_profileindicatoralt_numposts',
245 'placeholders': [months]
246 })
247 .then(
248 string =>
249 numPostsContainer.setAttribute('title', string));
avm99963e51444e2020-08-31 14:50:06 +0200250
avm99963ad65e752020-09-01 00:13:59 +0200251 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200252
avm99963ad65e752020-09-01 00:13:59 +0200253 for (const index of numPostsForumArraysToSum) {
254 if (!(index in res[1][2])) {
255 throw new Error('Unexpected profile response.');
256 return;
257 }
avm99963e51444e2020-08-31 14:50:06 +0200258
avm99963ad65e752020-09-01 00:13:59 +0200259 var i = 0;
260 for (const month of res[1][2][index].reverse()) {
261 if (i == months) break;
262 numPosts += month[3] || 0;
263 ++i;
264 }
265 }
avm99963e51444e2020-08-31 14:50:06 +0200266
avm9996313658b92020-12-02 00:02:53 +0100267 setNumPostsBadge(numPostsContainer, numPosts);
avm99963ad65e752020-09-01 00:13:59 +0200268 })
269 .catch(
270 err => console.error('[opindicator] Unexpected error.', err));
271 })
avm9996313658b92020-12-02 00:02:53 +0100272 .catch(err => {
273 console.error(
274 '[opindicator] Unexpected error. Couldn\'t load profile.', err);
275 setNumPostsBadge(numPostsContainer, '?');
276 });
avm99963ad65e752020-09-01 00:13:59 +0200277 }
278
279 if (options.indicatorDot) {
280 var dotContainer = createIndicatorDot(sourceNode, searchURL, options);
281
282 // Query threads in order to see what state the indicator should be in
283 getPosts(query, forumId)
284 .then(res => {
avm999639f586f42021-02-05 12:37:51 +0100285 // Throw an error when the replies array is not present in the reply.
avm99963ad65e752020-09-01 00:13:59 +0200286 if (!('1' in res) || !('2' in res['1'])) {
avm999639f586f42021-02-05 12:37:51 +0100287 // Throw a different error when the numThreads field exists and is
288 // equal to 0. This reply can be received, but is enexpected,
289 // because we know that the user has replied in at least 1 thread
290 // (the current one).
291 if (('1' in res) && ('4' in res['1']) && res['1']['4'] == 0)
292 throw new Error(
293 'Thread list is empty ' +
294 '(but the OP has participated in this thread, ' +
295 'so it shouldn\'t be empty).');
296
avm99963ad65e752020-09-01 00:13:59 +0200297 throw new Error('Unexpected thread list response.');
298 return;
299 }
300
301 // Current thread ID
302 var threadUrlSplit = threadLink.split('/thread/');
303 if (threadUrlSplit.length < 2)
304 throw new Error('Can\'t get thread id.');
305
306 var currId = threadUrlSplit[1].split('/')[0];
307
308 var OPStatus = OP_FIRST_POST;
309
310 for (const thread of res['1']['2']) {
311 var id = thread['2']['1']['1'] || undefined;
312 if (id === undefined || id == currId) continue;
313
314 var isRead = thread['6'] || false;
315 if (isRead)
316 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
317 else
318 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
319 }
320
321 var dotContainerPrefix =
322 (options.numPosts ? 'num-posts-indicator' : 'profile-indicator');
323
324 if (!options.numPosts)
325 dotContainer.classList.remove(dotContainerPrefix + '--loading');
326 dotContainer.classList.add(
327 dotContainerPrefix + '--' + OPClasses[OPStatus]);
328 contentScriptRequest
329 .sendRequest({
330 'action': 'geti18nMessage',
331 'msg': 'inject_profileindicator_' + OPi18n[OPStatus]
332 })
333 .then(string => dotContainer.setAttribute('title', string));
334 })
335 .catch(
336 err => console.error(
337 '[opindicator] Unexpected error. Couldn\'t load recent posts.',
338 err));
339 }
avm99963e51444e2020-08-31 14:50:06 +0200340}
341
342if (CCRegex.test(location.href)) {
343 // We are in the Community Console
avm99963a2945b62020-11-27 00:32:02 +0100344 var startup =
345 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
346
347 authuser = startup[2][1] || '0';
348
avm9996389812882021-02-02 20:51:25 +0100349 // When the OP's username is found, call getOptionsAndHandleIndicators
avm99963e51444e2020-08-31 14:50:06 +0200350 function mutationCallback(mutationList, observer) {
351 mutationList.forEach((mutation) => {
352 if (mutation.type == 'childList') {
353 mutation.addedNodes.forEach(function(node) {
354 if (node.tagName == 'A' && ('href' in node) &&
355 CCProfileRegex.test(node.href) &&
avm999639f586f42021-02-05 12:37:51 +0100356 node.matches(
357 'ec-question ec-message-header .name-section ec-user-link a')) {
avm9996389812882021-02-02 20:51:25 +0100358 console.info('Handling profile indicator via mutation callback.');
avm99963ad65e752020-09-01 00:13:59 +0200359 getOptionsAndHandleIndicators(node, true);
avm99963e51444e2020-08-31 14:50:06 +0200360 }
361 });
362 }
363 });
364 };
365
366 var observerOptions = {
367 childList: true,
368 subtree: true,
369 }
370
avm9996389812882021-02-02 20:51:25 +0100371 // Before starting the mutation Observer, check if the OP's username link is
372 // already part of the page
373 var node = document.querySelector(
374 'ec-question ec-message-header .name-section ec-user-link a');
375 if (node !== null) {
376 console.info('Handling profile indicator via first check.');
377 getOptionsAndHandleIndicators(node, true);
378 }
379
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +0200380 var mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100381 mutationObserver.observe(document.body, observerOptions);
avm99963e51444e2020-08-31 14:50:06 +0200382} else {
383 // We are in TW
avm99963a2945b62020-11-27 00:32:02 +0100384 authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
385
avm99963ad65e752020-09-01 00:13:59 +0200386 var node =
387 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200388 if (node !== null)
avm99963ad65e752020-09-01 00:13:59 +0200389 getOptionsAndHandleIndicators(node, false);
avm99963e51444e2020-08-31 14:50:06 +0200390 else
avm99963ad65e752020-09-01 00:13:59 +0200391 console.error('[opindicator] Couldn\'t find username.');
avm99963e51444e2020-08-31 14:50:06 +0200392}