blob: fa0415b7ed6c6a005b7d0061ece26a37267c2ab7 [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;
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(
184 (isCC ? sourceNode.innerHTML :
185 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
avm99963e51444e2020-08-31 14:50:06 +0200207 var query = '(replier:"' + escapedUsername + '" | creator:"' +
208 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
209 var encodedQuery =
210 encodeURIComponent(query + (isCC ? ' forum:' + forumId : ''));
avm99963a2945b62020-11-27 00:32:02 +0100211 var authuserPart =
212 (authuser == '0' ?
213 '' :
214 (isCC ? '?' : '&') + 'authuser=' + encodeURIComponent(authuser));
avm99963e51444e2020-08-31 14:50:06 +0200215 var searchURL =
216 (isCC ? 'https://support.google.com/s/community/search/' +
avm99963a2945b62020-11-27 00:32:02 +0100217 encodeURIComponent('query=' + encodedQuery) + authuserPart :
avm99963e51444e2020-08-31 14:50:06 +0200218 document.location.pathname.split('/thread')[0] +
avm99963a2945b62020-11-27 00:32:02 +0100219 '/threads?thread_filter=' + encodedQuery + authuserPart);
avm99963e51444e2020-08-31 14:50:06 +0200220
avm99963ad65e752020-09-01 00:13:59 +0200221 if (options.numPosts) {
222 var profileURL = new URL(sourceNode.href);
223 var userId =
224 profileURL.pathname.split(isCC ? 'user/' : 'profile/')[1].split('/')[0];
avm99963e51444e2020-08-31 14:50:06 +0200225
avm99963ad65e752020-09-01 00:13:59 +0200226 var numPostsContainer = createNumPostsBadge(sourceNode, searchURL);
avm99963e51444e2020-08-31 14:50:06 +0200227
avm99963ad65e752020-09-01 00:13:59 +0200228 getProfile(userId, forumId)
229 .then(res => {
230 if (!('1' in res) || !('2' in res[1])) {
231 throw new Error('Unexpected profile response.');
232 return;
233 }
avm99963e51444e2020-08-31 14:50:06 +0200234
avm99963ad65e752020-09-01 00:13:59 +0200235 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
236 .then(months => {
237 if (!options.indicatorDot)
238 contentScriptRequest
239 .sendRequest({
240 'action': 'geti18nMessage',
241 'msg': 'inject_profileindicatoralt_numposts',
242 'placeholders': [months]
243 })
244 .then(
245 string =>
246 numPostsContainer.setAttribute('title', string));
avm99963e51444e2020-08-31 14:50:06 +0200247
avm99963ad65e752020-09-01 00:13:59 +0200248 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200249
avm99963ad65e752020-09-01 00:13:59 +0200250 for (const index of numPostsForumArraysToSum) {
251 if (!(index in res[1][2])) {
252 throw new Error('Unexpected profile response.');
253 return;
254 }
avm99963e51444e2020-08-31 14:50:06 +0200255
avm99963ad65e752020-09-01 00:13:59 +0200256 var i = 0;
257 for (const month of res[1][2][index].reverse()) {
258 if (i == months) break;
259 numPosts += month[3] || 0;
260 ++i;
261 }
262 }
avm99963e51444e2020-08-31 14:50:06 +0200263
avm9996313658b92020-12-02 00:02:53 +0100264 setNumPostsBadge(numPostsContainer, numPosts);
avm99963ad65e752020-09-01 00:13:59 +0200265 })
266 .catch(
267 err => console.error('[opindicator] Unexpected error.', err));
268 })
avm9996313658b92020-12-02 00:02:53 +0100269 .catch(err => {
270 console.error(
271 '[opindicator] Unexpected error. Couldn\'t load profile.', err);
272 setNumPostsBadge(numPostsContainer, '?');
273 });
avm99963ad65e752020-09-01 00:13:59 +0200274 }
275
276 if (options.indicatorDot) {
277 var dotContainer = createIndicatorDot(sourceNode, searchURL, options);
278
279 // Query threads in order to see what state the indicator should be in
280 getPosts(query, forumId)
281 .then(res => {
282 if (!('1' in res) || !('2' in res['1'])) {
283 throw new Error('Unexpected thread list response.');
284 return;
285 }
286
287 // Current thread ID
288 var threadUrlSplit = threadLink.split('/thread/');
289 if (threadUrlSplit.length < 2)
290 throw new Error('Can\'t get thread id.');
291
292 var currId = threadUrlSplit[1].split('/')[0];
293
294 var OPStatus = OP_FIRST_POST;
295
296 for (const thread of res['1']['2']) {
297 var id = thread['2']['1']['1'] || undefined;
298 if (id === undefined || id == currId) continue;
299
300 var isRead = thread['6'] || false;
301 if (isRead)
302 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
303 else
304 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
305 }
306
307 var dotContainerPrefix =
308 (options.numPosts ? 'num-posts-indicator' : 'profile-indicator');
309
310 if (!options.numPosts)
311 dotContainer.classList.remove(dotContainerPrefix + '--loading');
312 dotContainer.classList.add(
313 dotContainerPrefix + '--' + OPClasses[OPStatus]);
314 contentScriptRequest
315 .sendRequest({
316 'action': 'geti18nMessage',
317 'msg': 'inject_profileindicator_' + OPi18n[OPStatus]
318 })
319 .then(string => dotContainer.setAttribute('title', string));
320 })
321 .catch(
322 err => console.error(
323 '[opindicator] Unexpected error. Couldn\'t load recent posts.',
324 err));
325 }
avm99963e51444e2020-08-31 14:50:06 +0200326}
327
328if (CCRegex.test(location.href)) {
329 // We are in the Community Console
avm99963a2945b62020-11-27 00:32:02 +0100330 var startup =
331 JSON.parse(document.querySelector('html').getAttribute('data-startup'));
332
333 authuser = startup[2][1] || '0';
334
avm99963e51444e2020-08-31 14:50:06 +0200335 function mutationCallback(mutationList, observer) {
336 mutationList.forEach((mutation) => {
337 if (mutation.type == 'childList') {
338 mutation.addedNodes.forEach(function(node) {
339 if (node.tagName == 'A' && ('href' in node) &&
340 CCProfileRegex.test(node.href) &&
341 isElementInside(node, 'EC-QUESTION') && ('children' in node) &&
342 node.children.length == 0) {
avm99963ad65e752020-09-01 00:13:59 +0200343 getOptionsAndHandleIndicators(node, true);
avm99963e51444e2020-08-31 14:50:06 +0200344 }
345 });
346 }
347 });
348 };
349
350 var observerOptions = {
351 childList: true,
352 subtree: true,
353 }
354
355 mutationObserver = new MutationObserver(mutationCallback);
avm99963e4cac402020-12-03 16:10:58 +0100356 mutationObserver.observe(document.body, observerOptions);
avm99963e51444e2020-08-31 14:50:06 +0200357} else {
358 // We are in TW
avm99963a2945b62020-11-27 00:32:02 +0100359 authuser = (new URL(location.href)).searchParams.get('authuser') || '0';
360
avm99963ad65e752020-09-01 00:13:59 +0200361 var node =
362 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200363 if (node !== null)
avm99963ad65e752020-09-01 00:13:59 +0200364 getOptionsAndHandleIndicators(node, false);
avm99963e51444e2020-08-31 14:50:06 +0200365 else
avm99963ad65e752020-09-01 00:13:59 +0200366 console.error('[opindicator] Couldn\'t find username.');
avm99963e51444e2020-08-31 14:50:06 +0200367}