blob: 352e3caec5b318fc1354c32f1f8b8be4552d2f8f [file] [log] [blame]
avm99963e51444e2020-08-31 14:50:06 +02001var CCProfileRegex =
2 /^(?:https:\/\/support\.google\.com)?\/s\/community\/forum\/[0-9]*\/user\/(?:[0-9]+)$/;
3var 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,
83 });
avm99963ad65e752020-09-01 00:13:59 +020084}
85
avm99963e51444e2020-08-31 14:50:06 +020086// Source:
87// https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response
avm99963ad65e752020-09-01 00:13:59 +020088var contentScriptRequest = (function() {
avm99963e51444e2020-08-31 14:50:06 +020089 var requestId = 0;
90
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) {
avm99963ad65e752020-09-01 00:13:59 +020096 if (evt.source === window && evt.data && evt.data.prefix === 'TWPT' &&
97 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
avm99963ad65e752020-09-01 00:13:59 +0200106 var payload = {data, id};
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
163// Get options and then handle all the indicators
164function getOptionsAndHandleIndicators(sourceNode, isCC) {
165 contentScriptRequest.sendRequest({'action': 'getProfileIndicatorOptions'})
166 .then(options => handleIndicators(sourceNode, isCC, options));
167}
168
169// Handle the profile indicator dot
170function handleIndicators(sourceNode, isCC, options) {
avm99963e51444e2020-08-31 14:50:06 +0200171 var escapedUsername = escapeUsername(
172 (isCC ? sourceNode.innerHTML :
173 sourceNode.querySelector('span').innerHTML));
174
175 if (isCC) {
176 var threadLink = document.location.href;
177 } else {
178 var CCLink = document.getElementById('onebar-community-console');
179 if (CCLink === null) {
180 console.error(
avm99963ad65e752020-09-01 00:13:59 +0200181 '[opindicator] The user is not a PE so the dot indicator cannot be shown in TW.');
avm99963e51444e2020-08-31 14:50:06 +0200182 return;
183 }
184 var threadLink = CCLink.href;
185 }
186
187 var forumUrlSplit = threadLink.split('/forum/');
188 if (forumUrlSplit.length < 2) {
avm99963ad65e752020-09-01 00:13:59 +0200189 console.error('[opindicator] Can\'t get forum id.');
avm99963e51444e2020-08-31 14:50:06 +0200190 return;
191 }
192
193 var forumId = forumUrlSplit[1].split('/')[0];
avm99963ad65e752020-09-01 00:13:59 +0200194
avm99963e51444e2020-08-31 14:50:06 +0200195 var query = '(replier:"' + escapedUsername + '" | creator:"' +
196 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
197 var encodedQuery =
198 encodeURIComponent(query + (isCC ? ' forum:' + forumId : ''));
avm99963a2945b62020-11-27 00:32:02 +0100199 var authuserPart =
200 (authuser == '0' ?
201 '' :
202 (isCC ? '?' : '&') + 'authuser=' + encodeURIComponent(authuser));
avm99963e51444e2020-08-31 14:50:06 +0200203 var searchURL =
204 (isCC ? 'https://support.google.com/s/community/search/' +
avm99963a2945b62020-11-27 00:32:02 +0100205 encodeURIComponent('query=' + encodedQuery) + authuserPart :
avm99963e51444e2020-08-31 14:50:06 +0200206 document.location.pathname.split('/thread')[0] +
avm99963a2945b62020-11-27 00:32:02 +0100207 '/threads?thread_filter=' + encodedQuery + authuserPart);
avm99963e51444e2020-08-31 14:50:06 +0200208
avm99963ad65e752020-09-01 00:13:59 +0200209 if (options.numPosts) {
210 var profileURL = new URL(sourceNode.href);
211 var userId =
212 profileURL.pathname.split(isCC ? 'user/' : 'profile/')[1].split('/')[0];
avm99963e51444e2020-08-31 14:50:06 +0200213
avm99963ad65e752020-09-01 00:13:59 +0200214 var numPostsContainer = createNumPostsBadge(sourceNode, searchURL);
avm99963e51444e2020-08-31 14:50:06 +0200215
avm99963ad65e752020-09-01 00:13:59 +0200216 getProfile(userId, forumId)
217 .then(res => {
218 if (!('1' in res) || !('2' in res[1])) {
219 throw new Error('Unexpected profile response.');
220 return;
221 }
avm99963e51444e2020-08-31 14:50:06 +0200222
avm99963ad65e752020-09-01 00:13:59 +0200223 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
224 .then(months => {
225 if (!options.indicatorDot)
226 contentScriptRequest
227 .sendRequest({
228 'action': 'geti18nMessage',
229 'msg': 'inject_profileindicatoralt_numposts',
230 'placeholders': [months]
231 })
232 .then(
233 string =>
234 numPostsContainer.setAttribute('title', string));
avm99963e51444e2020-08-31 14:50:06 +0200235
avm99963ad65e752020-09-01 00:13:59 +0200236 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200237
avm99963ad65e752020-09-01 00:13:59 +0200238 for (const index of numPostsForumArraysToSum) {
239 if (!(index in res[1][2])) {
240 throw new Error('Unexpected profile response.');
241 return;
242 }
avm99963e51444e2020-08-31 14:50:06 +0200243
avm99963ad65e752020-09-01 00:13:59 +0200244 var i = 0;
245 for (const month of res[1][2][index].reverse()) {
246 if (i == months) break;
247 numPosts += month[3] || 0;
248 ++i;
249 }
250 }
avm99963e51444e2020-08-31 14:50:06 +0200251
avm99963ad65e752020-09-01 00:13:59 +0200252 numPostsContainer.classList.remove(
253 'num-posts-indicator--loading');
254 numPostsContainer.querySelector('span').classList.remove(
255 'num-posts-indicator--num--loading');
256 numPostsContainer.querySelector('span').textContent = numPosts;
257 })
258 .catch(
259 err => console.error('[opindicator] Unexpected error.', err));
260 })
261 .catch(
262 err => console.error(
263 '[opindicator] Unexpected error. Couldn\'t load profile.',
264 err));
265 ;
266 }
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 => {
274 if (!('1' in res) || !('2' in res['1'])) {
275 throw new Error('Unexpected thread list response.');
276 return;
277 }
278
279 // Current thread ID
280 var threadUrlSplit = threadLink.split('/thread/');
281 if (threadUrlSplit.length < 2)
282 throw new Error('Can\'t get thread id.');
283
284 var currId = threadUrlSplit[1].split('/')[0];
285
286 var OPStatus = OP_FIRST_POST;
287
288 for (const thread of res['1']['2']) {
289 var id = thread['2']['1']['1'] || undefined;
290 if (id === undefined || id == currId) continue;
291
292 var isRead = thread['6'] || false;
293 if (isRead)
294 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
295 else
296 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
297 }
298
299 var dotContainerPrefix =
300 (options.numPosts ? 'num-posts-indicator' : 'profile-indicator');
301
302 if (!options.numPosts)
303 dotContainer.classList.remove(dotContainerPrefix + '--loading');
304 dotContainer.classList.add(
305 dotContainerPrefix + '--' + OPClasses[OPStatus]);
306 contentScriptRequest
307 .sendRequest({
308 'action': 'geti18nMessage',
309 'msg': 'inject_profileindicator_' + OPi18n[OPStatus]
310 })
311 .then(string => dotContainer.setAttribute('title', string));
312 })
313 .catch(
314 err => console.error(
315 '[opindicator] Unexpected error. Couldn\'t load recent posts.',
316 err));
317 }
avm99963e51444e2020-08-31 14:50:06 +0200318}
319
320if (CCRegex.test(location.href)) {
321 // We are in the Community Console
avm99963a2945b62020-11-27 00:32:02 +0100322 var startup =
323 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
324
325 authuser = startup[2][1] || '0';
326
avm99963e51444e2020-08-31 14:50:06 +0200327 function mutationCallback(mutationList, observer) {
328 mutationList.forEach((mutation) => {
329 if (mutation.type == 'childList') {
330 mutation.addedNodes.forEach(function(node) {
331 if (node.tagName == 'A' && ('href' in node) &&
332 CCProfileRegex.test(node.href) &&
333 isElementInside(node, 'EC-QUESTION') && ('children' in node) &&
334 node.children.length == 0) {
avm99963ad65e752020-09-01 00:13:59 +0200335 getOptionsAndHandleIndicators(node, true);
avm99963e51444e2020-08-31 14:50:06 +0200336 }
337 });
338 }
339 });
340 };
341
342 var observerOptions = {
343 childList: true,
344 subtree: true,
345 }
346
347 mutationObserver = new MutationObserver(mutationCallback);
348 mutationObserver.observe(
349 document.querySelector('.scrollable-content'), observerOptions);
350} else {
351 // We are in TW
avm99963a2945b62020-11-27 00:32:02 +0100352 authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
353
avm99963ad65e752020-09-01 00:13:59 +0200354 var node =
355 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200356 if (node !== null)
avm99963ad65e752020-09-01 00:13:59 +0200357 getOptionsAndHandleIndicators(node, false);
avm99963e51444e2020-08-31 14:50:06 +0200358 else
avm99963ad65e752020-09-01 00:13:59 +0200359 console.error('[opindicator] Couldn\'t find username.');
avm99963e51444e2020-08-31 14:50:06 +0200360}