blob: b0c11702bb03d532cef6af2ab8590704940cd8e3 [file] [log] [blame]
avm99963e6166ed2021-08-26 10:45:17 +02001import {CCApi} from '../common/api.js';
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +02002import {escapeUsername} from '../common/communityConsoleUtils.js';
3
avm99963e51444e2020-08-31 14:50:06 +02004var CCProfileRegex =
avm99963a945acd2021-02-06 19:23:14 +01005 /^(?:https:\/\/support\.google\.com)?\/s\/community(?:\/forum\/[0-9]*)?\/user\/(?:[0-9]+)$/;
avm99963e51444e2020-08-31 14:50:06 +02006var CCRegex = /^https:\/\/support\.google\.com\/s\/community/;
7
8const OP_FIRST_POST = 0;
9const OP_OTHER_POSTS_READ = 1;
10const OP_OTHER_POSTS_UNREAD = 2;
11
12const OPClasses = {
avm99963ad65e752020-09-01 00:13:59 +020013 0: 'first-post',
14 1: 'other-posts-read',
15 2: 'other-posts-unread',
avm99963e51444e2020-08-31 14:50:06 +020016};
17
18const OPi18n = {
19 0: 'first_post',
20 1: 'other_posts_read',
21 2: 'other_posts_unread',
22};
23
avm99963ad65e752020-09-01 00:13:59 +020024const indicatorTypes = ['numPosts', 'indicatorDot'];
25
avm99963e51444e2020-08-31 14:50:06 +020026// Filter used as a workaround to speed up the ViewForum request.
27const FILTER_ALL_LANGUAGES =
28 '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)';
29
avm99963ad65e752020-09-01 00:13:59 +020030const numPostsForumArraysToSum = [3, 4];
31
avm99963a2945b62020-11-27 00:32:02 +010032var authuser = null;
33
avm99963e51444e2020-08-31 14:50:06 +020034function isElementInside(element, outerTag) {
35 while (element !== null && ('tagName' in element)) {
36 if (element.tagName == outerTag) return true;
37 element = element.parentNode;
38 }
39
40 return false;
41}
42
avm99963a2945b62020-11-27 00:32:02 +010043function getPosts(query, forumId) {
avm99963e6166ed2021-08-26 10:45:17 +020044 return CCApi(
45 'ViewForum', {
46 '1': forumId,
47 '2': {
48 '1': {
49 '2': 5,
50 },
51 '2': {
52 '1': 1,
53 '2': true,
54 },
55 '12': query,
56 },
avm99963a2945b62020-11-27 00:32:02 +010057 },
avm99963e6166ed2021-08-26 10:45:17 +020058 /* authenticated = */ true, authuser);
avm99963a2945b62020-11-27 00:32:02 +010059}
60
avm99963ad65e752020-09-01 00:13:59 +020061function getProfile(userId, forumId) {
avm99963e6166ed2021-08-26 10:45:17 +020062 return CCApi(
63 'ViewUser', {
64 '1': userId,
65 '2': 0,
66 '3': forumId,
67 '4': {
68 '20': true,
69 },
70 },
71 /* authenticated = */ true, authuser);
avm99963ad65e752020-09-01 00:13:59 +020072}
73
avm99963e51444e2020-08-31 14:50:06 +020074// Source:
75// https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response
avm99963ad65e752020-09-01 00:13:59 +020076var contentScriptRequest = (function() {
avm99963e51444e2020-08-31 14:50:06 +020077 var requestId = 0;
avm999633e238882020-12-07 18:38:54 +010078 var prefix = 'TWPT-profileindicator';
avm99963e51444e2020-08-31 14:50:06 +020079
avm99963ad65e752020-09-01 00:13:59 +020080 function sendRequest(data) {
avm99963e51444e2020-08-31 14:50:06 +020081 var id = requestId++;
82
83 return new Promise(function(resolve, reject) {
84 var listener = function(evt) {
avm999633e238882020-12-07 18:38:54 +010085 if (evt.source === window && evt.data && evt.data.prefix === prefix &&
avm99963ad65e752020-09-01 00:13:59 +020086 evt.data.requestId == id) {
avm99963e51444e2020-08-31 14:50:06 +020087 // Deregister self
avm99963ad65e752020-09-01 00:13:59 +020088 window.removeEventListener('message', listener);
89 resolve(evt.data.data);
avm99963e51444e2020-08-31 14:50:06 +020090 }
91 };
92
avm99963ad65e752020-09-01 00:13:59 +020093 window.addEventListener('message', listener);
avm99963e51444e2020-08-31 14:50:06 +020094
avm999633e238882020-12-07 18:38:54 +010095 var payload = {data, id, prefix};
avm99963e51444e2020-08-31 14:50:06 +020096
avm99963ad65e752020-09-01 00:13:59 +020097 window.dispatchEvent(
98 new CustomEvent('TWPT_sendRequest', {detail: payload}));
avm99963e51444e2020-08-31 14:50:06 +020099 });
100 }
101
avm99963ad65e752020-09-01 00:13:59 +0200102 return {sendRequest: sendRequest};
avm99963e51444e2020-08-31 14:50:06 +0200103})();
104
avm99963ad65e752020-09-01 00:13:59 +0200105// Create profile indicator dot with a loading state, or return the numPosts
106// badge if it is already created.
107function createIndicatorDot(sourceNode, searchURL, options) {
108 if (options.numPosts) return document.querySelector('.num-posts-indicator');
avm99963a1b23b62020-09-01 14:32:34 +0200109 var dotContainer = document.createElement('div');
avm99963ad65e752020-09-01 00:13:59 +0200110 dotContainer.classList.add('profile-indicator', 'profile-indicator--loading');
111 contentScriptRequest
112 .sendRequest({
113 'action': 'geti18nMessage',
114 'msg': 'inject_profileindicator_loading'
115 })
avm99963e51444e2020-08-31 14:50:06 +0200116 .then(string => dotContainer.setAttribute('title', string));
117
118 var dotLink = document.createElement('a');
119 dotLink.href = searchURL;
120 dotLink.innerText = '●';
121
122 dotContainer.appendChild(dotLink);
123 sourceNode.parentNode.appendChild(dotContainer);
124
125 return dotContainer;
126}
127
avm99963ad65e752020-09-01 00:13:59 +0200128// Create badge indicating the number of posts with a loading state
129function createNumPostsBadge(sourceNode, searchURL) {
130 var link = document.createElement('a');
131 link.href = searchURL;
132
133 var numPostsContainer = document.createElement('div');
134 numPostsContainer.classList.add(
135 'num-posts-indicator', 'num-posts-indicator--loading');
136 contentScriptRequest
137 .sendRequest({
138 'action': 'geti18nMessage',
139 'msg': 'inject_profileindicator_loading'
140 })
141 .then(string => numPostsContainer.setAttribute('title', string));
142
143 var numPostsSpan = document.createElement('span');
144 numPostsSpan.classList.add('num-posts-indicator--num');
145
146 numPostsContainer.appendChild(numPostsSpan);
147 link.appendChild(numPostsContainer);
148 sourceNode.parentNode.appendChild(link);
149 return numPostsContainer;
150}
151
avm9996313658b92020-12-02 00:02:53 +0100152// Set the badge text
153function setNumPostsBadge(badge, text) {
154 badge.classList.remove('num-posts-indicator--loading');
155 badge.querySelector('span').classList.remove(
156 'num-posts-indicator--num--loading');
157 badge.querySelector('span').textContent = text;
158}
159
avm99963ad65e752020-09-01 00:13:59 +0200160// Get options and then handle all the indicators
161function getOptionsAndHandleIndicators(sourceNode, isCC) {
162 contentScriptRequest.sendRequest({'action': 'getProfileIndicatorOptions'})
163 .then(options => handleIndicators(sourceNode, isCC, options));
164}
165
166// Handle the profile indicator dot
167function handleIndicators(sourceNode, isCC, options) {
avm99963e51444e2020-08-31 14:50:06 +0200168 var escapedUsername = escapeUsername(
avm999639f586f42021-02-05 12:37:51 +0100169 (isCC ? sourceNode.querySelector('.name-text').innerHTML :
avm99963e51444e2020-08-31 14:50:06 +0200170 sourceNode.querySelector('span').innerHTML));
171
172 if (isCC) {
173 var threadLink = document.location.href;
174 } else {
175 var CCLink = document.getElementById('onebar-community-console');
176 if (CCLink === null) {
177 console.error(
avm99963ad65e752020-09-01 00:13:59 +0200178 '[opindicator] The user is not a PE so the dot indicator cannot be shown in TW.');
avm99963e51444e2020-08-31 14:50:06 +0200179 return;
180 }
181 var threadLink = CCLink.href;
182 }
183
184 var forumUrlSplit = threadLink.split('/forum/');
185 if (forumUrlSplit.length < 2) {
avm99963ad65e752020-09-01 00:13:59 +0200186 console.error('[opindicator] Can\'t get forum id.');
avm99963e51444e2020-08-31 14:50:06 +0200187 return;
188 }
189
190 var forumId = forumUrlSplit[1].split('/')[0];
avm99963ad65e752020-09-01 00:13:59 +0200191
avm99963104bad32021-02-05 22:00:44 +0100192 /*
193 * TODO(avm99963): If the TW filters ever work again, set isCCLink to isCC.
194 * Otherwise, issue #29 should be resolved:
195 * https://github.com/avm99963/infinitegforums/issues/29
196 */
197 var isCCLink = true;
198
avm99963e51444e2020-08-31 14:50:06 +0200199 var query = '(replier:"' + escapedUsername + '" | creator:"' +
200 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
201 var encodedQuery =
avm99963104bad32021-02-05 22:00:44 +0100202 encodeURIComponent(query + (isCCLink ? ' forum:' + forumId : ''));
avm99963a2945b62020-11-27 00:32:02 +0100203 var authuserPart =
204 (authuser == '0' ?
205 '' :
avm99963104bad32021-02-05 22:00:44 +0100206 (isCCLink ? '?' : '&') + 'authuser=' + encodeURIComponent(authuser));
avm99963e51444e2020-08-31 14:50:06 +0200207 var searchURL =
avm99963104bad32021-02-05 22:00:44 +0100208 (isCCLink ? 'https://support.google.com/s/community/search/' +
avm99963a2945b62020-11-27 00:32:02 +0100209 encodeURIComponent('query=' + encodedQuery) + authuserPart :
avm99963104bad32021-02-05 22:00:44 +0100210 document.location.pathname.split('/thread')[0] +
avm99963a2945b62020-11-27 00:32:02 +0100211 '/threads?thread_filter=' + encodedQuery + authuserPart);
avm99963e51444e2020-08-31 14:50:06 +0200212
avm99963ad65e752020-09-01 00:13:59 +0200213 if (options.numPosts) {
214 var profileURL = new URL(sourceNode.href);
215 var userId =
216 profileURL.pathname.split(isCC ? 'user/' : 'profile/')[1].split('/')[0];
avm99963e51444e2020-08-31 14:50:06 +0200217
avm99963ad65e752020-09-01 00:13:59 +0200218 var numPostsContainer = createNumPostsBadge(sourceNode, searchURL);
avm99963e51444e2020-08-31 14:50:06 +0200219
avm99963ad65e752020-09-01 00:13:59 +0200220 getProfile(userId, forumId)
221 .then(res => {
222 if (!('1' in res) || !('2' in res[1])) {
223 throw new Error('Unexpected profile response.');
224 return;
225 }
avm99963e51444e2020-08-31 14:50:06 +0200226
avm99963ad65e752020-09-01 00:13:59 +0200227 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
228 .then(months => {
229 if (!options.indicatorDot)
230 contentScriptRequest
231 .sendRequest({
232 'action': 'geti18nMessage',
233 'msg': 'inject_profileindicatoralt_numposts',
234 'placeholders': [months]
235 })
236 .then(
237 string =>
238 numPostsContainer.setAttribute('title', string));
avm99963e51444e2020-08-31 14:50:06 +0200239
avm99963ad65e752020-09-01 00:13:59 +0200240 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200241
avm99963ad65e752020-09-01 00:13:59 +0200242 for (const index of numPostsForumArraysToSum) {
243 if (!(index in res[1][2])) {
244 throw new Error('Unexpected profile response.');
245 return;
246 }
avm99963e51444e2020-08-31 14:50:06 +0200247
avm99963ad65e752020-09-01 00:13:59 +0200248 var i = 0;
249 for (const month of res[1][2][index].reverse()) {
250 if (i == months) break;
251 numPosts += month[3] || 0;
252 ++i;
253 }
254 }
avm99963e51444e2020-08-31 14:50:06 +0200255
avm9996313658b92020-12-02 00:02:53 +0100256 setNumPostsBadge(numPostsContainer, numPosts);
avm99963ad65e752020-09-01 00:13:59 +0200257 })
258 .catch(
259 err => console.error('[opindicator] Unexpected error.', err));
260 })
avm9996313658b92020-12-02 00:02:53 +0100261 .catch(err => {
262 console.error(
263 '[opindicator] Unexpected error. Couldn\'t load profile.', err);
264 setNumPostsBadge(numPostsContainer, '?');
265 });
avm99963ad65e752020-09-01 00:13:59 +0200266 }
267
268 if (options.indicatorDot) {
269 var dotContainer = createIndicatorDot(sourceNode, searchURL, options);
270
271 // Query threads in order to see what state the indicator should be in
272 getPosts(query, forumId)
273 .then(res => {
avm999639f586f42021-02-05 12:37:51 +0100274 // Throw an error when the replies array is not present in the reply.
avm99963ad65e752020-09-01 00:13:59 +0200275 if (!('1' in res) || !('2' in res['1'])) {
avm999639f586f42021-02-05 12:37:51 +0100276 // Throw a different error when the numThreads field exists and is
277 // equal to 0. This reply can be received, but is enexpected,
278 // because we know that the user has replied in at least 1 thread
279 // (the current one).
280 if (('1' in res) && ('4' in res['1']) && res['1']['4'] == 0)
281 throw new Error(
282 'Thread list is empty ' +
283 '(but the OP has participated in this thread, ' +
284 'so it shouldn\'t be empty).');
285
avm99963ad65e752020-09-01 00:13:59 +0200286 throw new Error('Unexpected thread list response.');
287 return;
288 }
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
295 var currId = threadUrlSplit[1].split('/')[0];
296
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 })
322 .then(string => dotContainer.setAttribute('title', string));
323 })
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
avm99963e51444e2020-08-31 14:50:06 +0200339 function mutationCallback(mutationList, observer) {
340 mutationList.forEach((mutation) => {
341 if (mutation.type == 'childList') {
342 mutation.addedNodes.forEach(function(node) {
343 if (node.tagName == 'A' && ('href' in node) &&
344 CCProfileRegex.test(node.href) &&
avm999639f586f42021-02-05 12:37:51 +0100345 node.matches(
346 'ec-question ec-message-header .name-section ec-user-link a')) {
avm9996389812882021-02-02 20:51:25 +0100347 console.info('Handling profile indicator via mutation callback.');
avm99963ad65e752020-09-01 00:13:59 +0200348 getOptionsAndHandleIndicators(node, true);
avm99963e51444e2020-08-31 14:50:06 +0200349 }
350 });
351 }
352 });
353 };
354
355 var observerOptions = {
356 childList: true,
357 subtree: true,
358 }
359
avm9996389812882021-02-02 20:51:25 +0100360 // Before starting the mutation Observer, check if the OP's username link is
361 // already part of the page
362 var node = document.querySelector(
363 'ec-question ec-message-header .name-section ec-user-link a');
364 if (node !== null) {
365 console.info('Handling profile indicator via first check.');
366 getOptionsAndHandleIndicators(node, true);
367 }
368
Adrià Vilanova Martínez3465e772021-07-11 19:18:41 +0200369 var mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100370 mutationObserver.observe(document.body, observerOptions);
avm99963e51444e2020-08-31 14:50:06 +0200371} else {
372 // We are in TW
avm99963a2945b62020-11-27 00:32:02 +0100373 authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
374
avm99963ad65e752020-09-01 00:13:59 +0200375 var node =
376 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200377 if (node !== null)
avm99963ad65e752020-09-01 00:13:59 +0200378 getOptionsAndHandleIndicators(node, false);
avm99963e51444e2020-08-31 14:50:06 +0200379 else
avm99963ad65e752020-09-01 00:13:59 +0200380 console.error('[opindicator] Couldn\'t find username.');
avm99963e51444e2020-08-31 14:50:06 +0200381}