blob: 1a0125ff1d09c3ba198f9c39fac4ae28d5fd2632 [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,
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;
93
avm99963ad65e752020-09-01 00:13:59 +020094 function sendRequest(data) {
avm99963e51444e2020-08-31 14:50:06 +020095 var id = requestId++;
96
97 return new Promise(function(resolve, reject) {
98 var listener = function(evt) {
avm99963ad65e752020-09-01 00:13:59 +020099 if (evt.source === window && evt.data && evt.data.prefix === 'TWPT' &&
100 evt.data.requestId == id) {
avm99963e51444e2020-08-31 14:50:06 +0200101 // Deregister self
avm99963ad65e752020-09-01 00:13:59 +0200102 window.removeEventListener('message', listener);
103 resolve(evt.data.data);
avm99963e51444e2020-08-31 14:50:06 +0200104 }
105 };
106
avm99963ad65e752020-09-01 00:13:59 +0200107 window.addEventListener('message', listener);
avm99963e51444e2020-08-31 14:50:06 +0200108
avm99963ad65e752020-09-01 00:13:59 +0200109 var payload = {data, id};
avm99963e51444e2020-08-31 14:50:06 +0200110
avm99963ad65e752020-09-01 00:13:59 +0200111 window.dispatchEvent(
112 new CustomEvent('TWPT_sendRequest', {detail: payload}));
avm99963e51444e2020-08-31 14:50:06 +0200113 });
114 }
115
avm99963ad65e752020-09-01 00:13:59 +0200116 return {sendRequest: sendRequest};
avm99963e51444e2020-08-31 14:50:06 +0200117})();
118
avm99963ad65e752020-09-01 00:13:59 +0200119// Create profile indicator dot with a loading state, or return the numPosts
120// badge if it is already created.
121function createIndicatorDot(sourceNode, searchURL, options) {
122 if (options.numPosts) return document.querySelector('.num-posts-indicator');
avm99963a1b23b62020-09-01 14:32:34 +0200123 var dotContainer = document.createElement('div');
avm99963ad65e752020-09-01 00:13:59 +0200124 dotContainer.classList.add('profile-indicator', 'profile-indicator--loading');
125 contentScriptRequest
126 .sendRequest({
127 'action': 'geti18nMessage',
128 'msg': 'inject_profileindicator_loading'
129 })
avm99963e51444e2020-08-31 14:50:06 +0200130 .then(string => dotContainer.setAttribute('title', string));
131
132 var dotLink = document.createElement('a');
133 dotLink.href = searchURL;
134 dotLink.innerText = '●';
135
136 dotContainer.appendChild(dotLink);
137 sourceNode.parentNode.appendChild(dotContainer);
138
139 return dotContainer;
140}
141
avm99963ad65e752020-09-01 00:13:59 +0200142// Create badge indicating the number of posts with a loading state
143function createNumPostsBadge(sourceNode, searchURL) {
144 var link = document.createElement('a');
145 link.href = searchURL;
146
147 var numPostsContainer = document.createElement('div');
148 numPostsContainer.classList.add(
149 'num-posts-indicator', 'num-posts-indicator--loading');
150 contentScriptRequest
151 .sendRequest({
152 'action': 'geti18nMessage',
153 'msg': 'inject_profileindicator_loading'
154 })
155 .then(string => numPostsContainer.setAttribute('title', string));
156
157 var numPostsSpan = document.createElement('span');
158 numPostsSpan.classList.add('num-posts-indicator--num');
159
160 numPostsContainer.appendChild(numPostsSpan);
161 link.appendChild(numPostsContainer);
162 sourceNode.parentNode.appendChild(link);
163 return numPostsContainer;
164}
165
avm9996313658b92020-12-02 00:02:53 +0100166// Set the badge text
167function setNumPostsBadge(badge, text) {
168 badge.classList.remove('num-posts-indicator--loading');
169 badge.querySelector('span').classList.remove(
170 'num-posts-indicator--num--loading');
171 badge.querySelector('span').textContent = text;
172}
173
avm99963ad65e752020-09-01 00:13:59 +0200174// Get options and then handle all the indicators
175function getOptionsAndHandleIndicators(sourceNode, isCC) {
176 contentScriptRequest.sendRequest({'action': 'getProfileIndicatorOptions'})
177 .then(options => handleIndicators(sourceNode, isCC, options));
178}
179
180// Handle the profile indicator dot
181function handleIndicators(sourceNode, isCC, options) {
avm99963e51444e2020-08-31 14:50:06 +0200182 var escapedUsername = escapeUsername(
183 (isCC ? sourceNode.innerHTML :
184 sourceNode.querySelector('span').innerHTML));
185
186 if (isCC) {
187 var threadLink = document.location.href;
188 } else {
189 var CCLink = document.getElementById('onebar-community-console');
190 if (CCLink === null) {
191 console.error(
avm99963ad65e752020-09-01 00:13:59 +0200192 '[opindicator] The user is not a PE so the dot indicator cannot be shown in TW.');
avm99963e51444e2020-08-31 14:50:06 +0200193 return;
194 }
195 var threadLink = CCLink.href;
196 }
197
198 var forumUrlSplit = threadLink.split('/forum/');
199 if (forumUrlSplit.length < 2) {
avm99963ad65e752020-09-01 00:13:59 +0200200 console.error('[opindicator] Can\'t get forum id.');
avm99963e51444e2020-08-31 14:50:06 +0200201 return;
202 }
203
204 var forumId = forumUrlSplit[1].split('/')[0];
avm99963ad65e752020-09-01 00:13:59 +0200205
avm99963e51444e2020-08-31 14:50:06 +0200206 var query = '(replier:"' + escapedUsername + '" | creator:"' +
207 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
208 var encodedQuery =
209 encodeURIComponent(query + (isCC ? ' forum:' + forumId : ''));
avm99963a2945b62020-11-27 00:32:02 +0100210 var authuserPart =
211 (authuser == '0' ?
212 '' :
213 (isCC ? '?' : '&') + 'authuser=' + encodeURIComponent(authuser));
avm99963e51444e2020-08-31 14:50:06 +0200214 var searchURL =
215 (isCC ? 'https://support.google.com/s/community/search/' +
avm99963a2945b62020-11-27 00:32:02 +0100216 encodeURIComponent('query=' + encodedQuery) + authuserPart :
avm99963e51444e2020-08-31 14:50:06 +0200217 document.location.pathname.split('/thread')[0] +
avm99963a2945b62020-11-27 00:32:02 +0100218 '/threads?thread_filter=' + encodedQuery + authuserPart);
avm99963e51444e2020-08-31 14:50:06 +0200219
avm99963ad65e752020-09-01 00:13:59 +0200220 if (options.numPosts) {
221 var profileURL = new URL(sourceNode.href);
222 var userId =
223 profileURL.pathname.split(isCC ? 'user/' : 'profile/')[1].split('/')[0];
avm99963e51444e2020-08-31 14:50:06 +0200224
avm99963ad65e752020-09-01 00:13:59 +0200225 var numPostsContainer = createNumPostsBadge(sourceNode, searchURL);
avm99963e51444e2020-08-31 14:50:06 +0200226
avm99963ad65e752020-09-01 00:13:59 +0200227 getProfile(userId, forumId)
228 .then(res => {
229 if (!('1' in res) || !('2' in res[1])) {
230 throw new Error('Unexpected profile response.');
231 return;
232 }
avm99963e51444e2020-08-31 14:50:06 +0200233
avm99963ad65e752020-09-01 00:13:59 +0200234 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
235 .then(months => {
236 if (!options.indicatorDot)
237 contentScriptRequest
238 .sendRequest({
239 'action': 'geti18nMessage',
240 'msg': 'inject_profileindicatoralt_numposts',
241 'placeholders': [months]
242 })
243 .then(
244 string =>
245 numPostsContainer.setAttribute('title', string));
avm99963e51444e2020-08-31 14:50:06 +0200246
avm99963ad65e752020-09-01 00:13:59 +0200247 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200248
avm99963ad65e752020-09-01 00:13:59 +0200249 for (const index of numPostsForumArraysToSum) {
250 if (!(index in res[1][2])) {
251 throw new Error('Unexpected profile response.');
252 return;
253 }
avm99963e51444e2020-08-31 14:50:06 +0200254
avm99963ad65e752020-09-01 00:13:59 +0200255 var i = 0;
256 for (const month of res[1][2][index].reverse()) {
257 if (i == months) break;
258 numPosts += month[3] || 0;
259 ++i;
260 }
261 }
avm99963e51444e2020-08-31 14:50:06 +0200262
avm9996313658b92020-12-02 00:02:53 +0100263 setNumPostsBadge(numPostsContainer, numPosts);
avm99963ad65e752020-09-01 00:13:59 +0200264 })
265 .catch(
266 err => console.error('[opindicator] Unexpected error.', err));
267 })
avm9996313658b92020-12-02 00:02:53 +0100268 .catch(err => {
269 console.error(
270 '[opindicator] Unexpected error. Couldn\'t load profile.', err);
271 setNumPostsBadge(numPostsContainer, '?');
272 });
avm99963ad65e752020-09-01 00:13:59 +0200273 }
274
275 if (options.indicatorDot) {
276 var dotContainer = createIndicatorDot(sourceNode, searchURL, options);
277
278 // Query threads in order to see what state the indicator should be in
279 getPosts(query, forumId)
280 .then(res => {
281 if (!('1' in res) || !('2' in res['1'])) {
282 throw new Error('Unexpected thread list response.');
283 return;
284 }
285
286 // Current thread ID
287 var threadUrlSplit = threadLink.split('/thread/');
288 if (threadUrlSplit.length < 2)
289 throw new Error('Can\'t get thread id.');
290
291 var currId = threadUrlSplit[1].split('/')[0];
292
293 var OPStatus = OP_FIRST_POST;
294
295 for (const thread of res['1']['2']) {
296 var id = thread['2']['1']['1'] || undefined;
297 if (id === undefined || id == currId) continue;
298
299 var isRead = thread['6'] || false;
300 if (isRead)
301 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
302 else
303 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
304 }
305
306 var dotContainerPrefix =
307 (options.numPosts ? 'num-posts-indicator' : 'profile-indicator');
308
309 if (!options.numPosts)
310 dotContainer.classList.remove(dotContainerPrefix + '--loading');
311 dotContainer.classList.add(
312 dotContainerPrefix + '--' + OPClasses[OPStatus]);
313 contentScriptRequest
314 .sendRequest({
315 'action': 'geti18nMessage',
316 'msg': 'inject_profileindicator_' + OPi18n[OPStatus]
317 })
318 .then(string => dotContainer.setAttribute('title', string));
319 })
320 .catch(
321 err => console.error(
322 '[opindicator] Unexpected error. Couldn\'t load recent posts.',
323 err));
324 }
avm99963e51444e2020-08-31 14:50:06 +0200325}
326
327if (CCRegex.test(location.href)) {
328 // We are in the Community Console
avm99963a2945b62020-11-27 00:32:02 +0100329 var startup =
330 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
331
332 authuser = startup[2][1] || '0';
333
avm99963e51444e2020-08-31 14:50:06 +0200334 function mutationCallback(mutationList, observer) {
335 mutationList.forEach((mutation) => {
336 if (mutation.type == 'childList') {
337 mutation.addedNodes.forEach(function(node) {
338 if (node.tagName == 'A' && ('href' in node) &&
339 CCProfileRegex.test(node.href) &&
340 isElementInside(node, 'EC-QUESTION') && ('children' in node) &&
341 node.children.length == 0) {
avm99963ad65e752020-09-01 00:13:59 +0200342 getOptionsAndHandleIndicators(node, true);
avm99963e51444e2020-08-31 14:50:06 +0200343 }
344 });
345 }
346 });
347 };
348
349 var observerOptions = {
350 childList: true,
351 subtree: true,
352 }
353
354 mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100355 mutationObserver.observe(document.body, observerOptions);
avm99963e51444e2020-08-31 14:50:06 +0200356} else {
357 // We are in TW
avm99963a2945b62020-11-27 00:32:02 +0100358 authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
359
avm99963ad65e752020-09-01 00:13:59 +0200360 var node =
361 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200362 if (node !== null)
avm99963ad65e752020-09-01 00:13:59 +0200363 getOptionsAndHandleIndicators(node, false);
avm99963e51444e2020-08-31 14:50:06 +0200364 else
avm99963ad65e752020-09-01 00:13:59 +0200365 console.error('[opindicator] Couldn\'t find username.');
avm99963e51444e2020-08-31 14:50:06 +0200366}