blob: b3bbdc6529a2896bde0d5162ac35aafa6c4ef892 [file] [log] [blame]
avm99963e51444e2020-08-31 14:50:06 +02001var CCProfileRegex =
avm99963a945acd2021-02-06 19:23:14 +01002 /^(?:https:\/\/support\.google\.com)?\/s\/community(?:\/forum\/[0-9]*)?\/user\/(?:[0-9]+)$/;
avm99963e51444e2020-08-31 14:50:06 +02003var CCRegex = /^https:\/\/support\.google\.com\/s\/community/;
4
avm99963a2945b62020-11-27 00:32:02 +01005const BASE_URL = 'https://support.google.com/s/community/api/';
6
avm99963e51444e2020-08-31 14:50:06 +02007const OP_FIRST_POST = 0;
8const OP_OTHER_POSTS_READ = 1;
9const OP_OTHER_POSTS_UNREAD = 2;
10
11const OPClasses = {
avm99963ad65e752020-09-01 00:13:59 +020012 0: 'first-post',
13 1: 'other-posts-read',
14 2: 'other-posts-unread',
avm99963e51444e2020-08-31 14:50:06 +020015};
16
17const OPi18n = {
18 0: 'first_post',
19 1: 'other_posts_read',
20 2: 'other_posts_unread',
21};
22
avm99963ad65e752020-09-01 00:13:59 +020023const indicatorTypes = ['numPosts', 'indicatorDot'];
24
avm99963e51444e2020-08-31 14:50:06 +020025// Filter used as a workaround to speed up the ViewForum request.
26const FILTER_ALL_LANGUAGES =
27 '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)';
28
avm99963ad65e752020-09-01 00:13:59 +020029const numPostsForumArraysToSum = [3, 4];
30
avm99963a2945b62020-11-27 00:32:02 +010031var authuser = null;
32
avm99963e51444e2020-08-31 14:50:06 +020033function isElementInside(element, outerTag) {
34 while (element !== null && ('tagName' in element)) {
35 if (element.tagName == outerTag) return true;
36 element = element.parentNode;
37 }
38
39 return false;
40}
41
42function escapeUsername(username) {
43 var quoteRegex = /"/g;
44 var commentRegex = /<!---->/g;
45 return username.replace(quoteRegex, '\\"').replace(commentRegex, '');
46}
47
avm99963a2945b62020-11-27 00:32:02 +010048function APIRequest(action, body) {
49 var authuserPart =
50 (authuser == '0' ? '' : '?authuser=' + encodeURIComponent(authuser));
51
52 return fetch(BASE_URL + action + authuserPart, {
avm99963e51444e2020-08-31 14:50:06 +020053 'credentials': 'include',
54 'headers': {'content-type': 'text/plain; charset=utf-8'},
avm99963a2945b62020-11-27 00:32:02 +010055 'body': JSON.stringify(body),
avm99963e51444e2020-08-31 14:50:06 +020056 'method': 'POST',
57 'mode': 'cors',
58 })
59 .then(res => res.json());
60}
61
avm99963a2945b62020-11-27 00:32:02 +010062function getPosts(query, forumId) {
63 return APIRequest('ViewForum', {
64 '1': forumId,
65 '2': {
66 '1': {
67 '2': 5,
68 },
69 '2': {
70 '1': 1,
71 '2': true,
72 },
73 '12': query,
74 },
75 });
76}
77
avm99963ad65e752020-09-01 00:13:59 +020078function getProfile(userId, forumId) {
avm99963a2945b62020-11-27 00:32:02 +010079 return APIRequest('ViewUser', {
80 '1': userId,
81 '2': 0,
82 '3': forumId,
avm999633a412b82020-12-01 23:22:31 +010083 '4': {
84 '20': true,
85 },
avm99963a2945b62020-11-27 00:32:02 +010086 });
avm99963ad65e752020-09-01 00:13:59 +020087}
88
avm99963e51444e2020-08-31 14:50:06 +020089// Source:
90// https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response
avm99963ad65e752020-09-01 00:13:59 +020091var contentScriptRequest = (function() {
avm99963e51444e2020-08-31 14:50:06 +020092 var requestId = 0;
avm999633e238882020-12-07 18:38:54 +010093 var prefix = 'TWPT-profileindicator';
avm99963e51444e2020-08-31 14:50:06 +020094
avm99963ad65e752020-09-01 00:13:59 +020095 function sendRequest(data) {
avm99963e51444e2020-08-31 14:50:06 +020096 var id = requestId++;
97
98 return new Promise(function(resolve, reject) {
99 var listener = function(evt) {
avm999633e238882020-12-07 18:38:54 +0100100 if (evt.source === window && evt.data && evt.data.prefix === prefix &&
avm99963ad65e752020-09-01 00:13:59 +0200101 evt.data.requestId == id) {
avm99963e51444e2020-08-31 14:50:06 +0200102 // Deregister self
avm99963ad65e752020-09-01 00:13:59 +0200103 window.removeEventListener('message', listener);
104 resolve(evt.data.data);
avm99963e51444e2020-08-31 14:50:06 +0200105 }
106 };
107
avm99963ad65e752020-09-01 00:13:59 +0200108 window.addEventListener('message', listener);
avm99963e51444e2020-08-31 14:50:06 +0200109
avm999633e238882020-12-07 18:38:54 +0100110 var payload = {data, id, prefix};
avm99963e51444e2020-08-31 14:50:06 +0200111
avm99963ad65e752020-09-01 00:13:59 +0200112 window.dispatchEvent(
113 new CustomEvent('TWPT_sendRequest', {detail: payload}));
avm99963e51444e2020-08-31 14:50:06 +0200114 });
115 }
116
avm99963ad65e752020-09-01 00:13:59 +0200117 return {sendRequest: sendRequest};
avm99963e51444e2020-08-31 14:50:06 +0200118})();
119
avm99963ad65e752020-09-01 00:13:59 +0200120// Create profile indicator dot with a loading state, or return the numPosts
121// badge if it is already created.
122function createIndicatorDot(sourceNode, searchURL, options) {
123 if (options.numPosts) return document.querySelector('.num-posts-indicator');
avm99963a1b23b62020-09-01 14:32:34 +0200124 var dotContainer = document.createElement('div');
avm99963ad65e752020-09-01 00:13:59 +0200125 dotContainer.classList.add('profile-indicator', 'profile-indicator--loading');
126 contentScriptRequest
127 .sendRequest({
128 'action': 'geti18nMessage',
129 'msg': 'inject_profileindicator_loading'
130 })
avm99963e51444e2020-08-31 14:50:06 +0200131 .then(string => dotContainer.setAttribute('title', string));
132
133 var dotLink = document.createElement('a');
134 dotLink.href = searchURL;
135 dotLink.innerText = '●';
136
137 dotContainer.appendChild(dotLink);
138 sourceNode.parentNode.appendChild(dotContainer);
139
140 return dotContainer;
141}
142
avm99963ad65e752020-09-01 00:13:59 +0200143// Create badge indicating the number of posts with a loading state
144function createNumPostsBadge(sourceNode, searchURL) {
145 var link = document.createElement('a');
146 link.href = searchURL;
147
148 var numPostsContainer = document.createElement('div');
149 numPostsContainer.classList.add(
150 'num-posts-indicator', 'num-posts-indicator--loading');
151 contentScriptRequest
152 .sendRequest({
153 'action': 'geti18nMessage',
154 'msg': 'inject_profileindicator_loading'
155 })
156 .then(string => numPostsContainer.setAttribute('title', string));
157
158 var numPostsSpan = document.createElement('span');
159 numPostsSpan.classList.add('num-posts-indicator--num');
160
161 numPostsContainer.appendChild(numPostsSpan);
162 link.appendChild(numPostsContainer);
163 sourceNode.parentNode.appendChild(link);
164 return numPostsContainer;
165}
166
avm9996313658b92020-12-02 00:02:53 +0100167// Set the badge text
168function setNumPostsBadge(badge, text) {
169 badge.classList.remove('num-posts-indicator--loading');
170 badge.querySelector('span').classList.remove(
171 'num-posts-indicator--num--loading');
172 badge.querySelector('span').textContent = text;
173}
174
avm99963ad65e752020-09-01 00:13:59 +0200175// Get options and then handle all the indicators
176function getOptionsAndHandleIndicators(sourceNode, isCC) {
177 contentScriptRequest.sendRequest({'action': 'getProfileIndicatorOptions'})
178 .then(options => handleIndicators(sourceNode, isCC, options));
179}
180
181// Handle the profile indicator dot
182function handleIndicators(sourceNode, isCC, options) {
avm99963e51444e2020-08-31 14:50:06 +0200183 var escapedUsername = escapeUsername(
avm999639f586f42021-02-05 12:37:51 +0100184 (isCC ? sourceNode.querySelector('.name-text').innerHTML :
avm99963e51444e2020-08-31 14:50:06 +0200185 sourceNode.querySelector('span').innerHTML));
186
187 if (isCC) {
188 var threadLink = document.location.href;
189 } else {
190 var CCLink = document.getElementById('onebar-community-console');
191 if (CCLink === null) {
192 console.error(
avm99963ad65e752020-09-01 00:13:59 +0200193 '[opindicator] The user is not a PE so the dot indicator cannot be shown in TW.');
avm99963e51444e2020-08-31 14:50:06 +0200194 return;
195 }
196 var threadLink = CCLink.href;
197 }
198
199 var forumUrlSplit = threadLink.split('/forum/');
200 if (forumUrlSplit.length < 2) {
avm99963ad65e752020-09-01 00:13:59 +0200201 console.error('[opindicator] Can\'t get forum id.');
avm99963e51444e2020-08-31 14:50:06 +0200202 return;
203 }
204
205 var forumId = forumUrlSplit[1].split('/')[0];
avm99963ad65e752020-09-01 00:13:59 +0200206
avm99963104bad32021-02-05 22:00:44 +0100207 /*
208 * TODO(avm99963): If the TW filters ever work again, set isCCLink to isCC.
209 * Otherwise, issue #29 should be resolved:
210 * https://github.com/avm99963/infinitegforums/issues/29
211 */
212 var isCCLink = true;
213
avm99963e51444e2020-08-31 14:50:06 +0200214 var query = '(replier:"' + escapedUsername + '" | creator:"' +
215 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
216 var encodedQuery =
avm99963104bad32021-02-05 22:00:44 +0100217 encodeURIComponent(query + (isCCLink ? ' forum:' + forumId : ''));
avm99963a2945b62020-11-27 00:32:02 +0100218 var authuserPart =
219 (authuser == '0' ?
220 '' :
avm99963104bad32021-02-05 22:00:44 +0100221 (isCCLink ? '?' : '&') + 'authuser=' + encodeURIComponent(authuser));
avm99963e51444e2020-08-31 14:50:06 +0200222 var searchURL =
avm99963104bad32021-02-05 22:00:44 +0100223 (isCCLink ? 'https://support.google.com/s/community/search/' +
avm99963a2945b62020-11-27 00:32:02 +0100224 encodeURIComponent('query=' + encodedQuery) + authuserPart :
avm99963104bad32021-02-05 22:00:44 +0100225 document.location.pathname.split('/thread')[0] +
avm99963a2945b62020-11-27 00:32:02 +0100226 '/threads?thread_filter=' + encodedQuery + authuserPart);
avm99963e51444e2020-08-31 14:50:06 +0200227
avm99963ad65e752020-09-01 00:13:59 +0200228 if (options.numPosts) {
229 var profileURL = new URL(sourceNode.href);
230 var userId =
231 profileURL.pathname.split(isCC ? 'user/' : 'profile/')[1].split('/')[0];
avm99963e51444e2020-08-31 14:50:06 +0200232
avm99963ad65e752020-09-01 00:13:59 +0200233 var numPostsContainer = createNumPostsBadge(sourceNode, searchURL);
avm99963e51444e2020-08-31 14:50:06 +0200234
avm99963ad65e752020-09-01 00:13:59 +0200235 getProfile(userId, forumId)
236 .then(res => {
237 if (!('1' in res) || !('2' in res[1])) {
238 throw new Error('Unexpected profile response.');
239 return;
240 }
avm99963e51444e2020-08-31 14:50:06 +0200241
avm99963ad65e752020-09-01 00:13:59 +0200242 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
243 .then(months => {
244 if (!options.indicatorDot)
245 contentScriptRequest
246 .sendRequest({
247 'action': 'geti18nMessage',
248 'msg': 'inject_profileindicatoralt_numposts',
249 'placeholders': [months]
250 })
251 .then(
252 string =>
253 numPostsContainer.setAttribute('title', string));
avm99963e51444e2020-08-31 14:50:06 +0200254
avm99963ad65e752020-09-01 00:13:59 +0200255 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200256
avm99963ad65e752020-09-01 00:13:59 +0200257 for (const index of numPostsForumArraysToSum) {
258 if (!(index in res[1][2])) {
259 throw new Error('Unexpected profile response.');
260 return;
261 }
avm99963e51444e2020-08-31 14:50:06 +0200262
avm99963ad65e752020-09-01 00:13:59 +0200263 var i = 0;
264 for (const month of res[1][2][index].reverse()) {
265 if (i == months) break;
266 numPosts += month[3] || 0;
267 ++i;
268 }
269 }
avm99963e51444e2020-08-31 14:50:06 +0200270
avm9996313658b92020-12-02 00:02:53 +0100271 setNumPostsBadge(numPostsContainer, numPosts);
avm99963ad65e752020-09-01 00:13:59 +0200272 })
273 .catch(
274 err => console.error('[opindicator] Unexpected error.', err));
275 })
avm9996313658b92020-12-02 00:02:53 +0100276 .catch(err => {
277 console.error(
278 '[opindicator] Unexpected error. Couldn\'t load profile.', err);
279 setNumPostsBadge(numPostsContainer, '?');
280 });
avm99963ad65e752020-09-01 00:13:59 +0200281 }
282
283 if (options.indicatorDot) {
284 var dotContainer = createIndicatorDot(sourceNode, searchURL, options);
285
286 // Query threads in order to see what state the indicator should be in
287 getPosts(query, forumId)
288 .then(res => {
avm999639f586f42021-02-05 12:37:51 +0100289 // Throw an error when the replies array is not present in the reply.
avm99963ad65e752020-09-01 00:13:59 +0200290 if (!('1' in res) || !('2' in res['1'])) {
avm999639f586f42021-02-05 12:37:51 +0100291 // Throw a different error when the numThreads field exists and is
292 // equal to 0. This reply can be received, but is enexpected,
293 // because we know that the user has replied in at least 1 thread
294 // (the current one).
295 if (('1' in res) && ('4' in res['1']) && res['1']['4'] == 0)
296 throw new Error(
297 'Thread list is empty ' +
298 '(but the OP has participated in this thread, ' +
299 'so it shouldn\'t be empty).');
300
avm99963ad65e752020-09-01 00:13:59 +0200301 throw new Error('Unexpected thread list response.');
302 return;
303 }
304
305 // Current thread ID
306 var threadUrlSplit = threadLink.split('/thread/');
307 if (threadUrlSplit.length < 2)
308 throw new Error('Can\'t get thread id.');
309
310 var currId = threadUrlSplit[1].split('/')[0];
311
312 var OPStatus = OP_FIRST_POST;
313
314 for (const thread of res['1']['2']) {
315 var id = thread['2']['1']['1'] || undefined;
316 if (id === undefined || id == currId) continue;
317
318 var isRead = thread['6'] || false;
319 if (isRead)
320 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
321 else
322 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
323 }
324
325 var dotContainerPrefix =
326 (options.numPosts ? 'num-posts-indicator' : 'profile-indicator');
327
328 if (!options.numPosts)
329 dotContainer.classList.remove(dotContainerPrefix + '--loading');
330 dotContainer.classList.add(
331 dotContainerPrefix + '--' + OPClasses[OPStatus]);
332 contentScriptRequest
333 .sendRequest({
334 'action': 'geti18nMessage',
335 'msg': 'inject_profileindicator_' + OPi18n[OPStatus]
336 })
337 .then(string => dotContainer.setAttribute('title', string));
338 })
339 .catch(
340 err => console.error(
341 '[opindicator] Unexpected error. Couldn\'t load recent posts.',
342 err));
343 }
avm99963e51444e2020-08-31 14:50:06 +0200344}
345
346if (CCRegex.test(location.href)) {
347 // We are in the Community Console
avm99963a2945b62020-11-27 00:32:02 +0100348 var startup =
349 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
350
351 authuser = startup[2][1] || '0';
352
avm9996389812882021-02-02 20:51:25 +0100353 // When the OP's username is found, call getOptionsAndHandleIndicators
avm99963e51444e2020-08-31 14:50:06 +0200354 function mutationCallback(mutationList, observer) {
355 mutationList.forEach((mutation) => {
356 if (mutation.type == 'childList') {
357 mutation.addedNodes.forEach(function(node) {
358 if (node.tagName == 'A' && ('href' in node) &&
359 CCProfileRegex.test(node.href) &&
avm999639f586f42021-02-05 12:37:51 +0100360 node.matches(
361 'ec-question ec-message-header .name-section ec-user-link a')) {
avm9996389812882021-02-02 20:51:25 +0100362 console.info('Handling profile indicator via mutation callback.');
avm99963ad65e752020-09-01 00:13:59 +0200363 getOptionsAndHandleIndicators(node, true);
avm99963e51444e2020-08-31 14:50:06 +0200364 }
365 });
366 }
367 });
368 };
369
370 var observerOptions = {
371 childList: true,
372 subtree: true,
373 }
374
avm9996389812882021-02-02 20:51:25 +0100375 // Before starting the mutation Observer, check if the OP's username link is
376 // already part of the page
377 var node = document.querySelector(
378 'ec-question ec-message-header .name-section ec-user-link a');
379 if (node !== null) {
380 console.info('Handling profile indicator via first check.');
381 getOptionsAndHandleIndicators(node, true);
382 }
383
avm99963e51444e2020-08-31 14:50:06 +0200384 mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100385 mutationObserver.observe(document.body, observerOptions);
avm99963e51444e2020-08-31 14:50:06 +0200386} else {
387 // We are in TW
avm99963a2945b62020-11-27 00:32:02 +0100388 authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
389
avm99963ad65e752020-09-01 00:13:59 +0200390 var node =
391 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200392 if (node !== null)
avm99963ad65e752020-09-01 00:13:59 +0200393 getOptionsAndHandleIndicators(node, false);
avm99963e51444e2020-08-31 14:50:06 +0200394 else
avm99963ad65e752020-09-01 00:13:59 +0200395 console.error('[opindicator] Couldn\'t find username.');
avm99963e51444e2020-08-31 14:50:06 +0200396}