blob: e7935c83d0a5f8eb87774d6580647df1b5133ad3 [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
5const OP_FIRST_POST = 0;
6const OP_OTHER_POSTS_READ = 1;
7const OP_OTHER_POSTS_UNREAD = 2;
8
9const OPClasses = {
avm99963ad65e752020-09-01 00:13:59 +020010 0: 'first-post',
11 1: 'other-posts-read',
12 2: 'other-posts-unread',
avm99963e51444e2020-08-31 14:50:06 +020013};
14
15const OPi18n = {
16 0: 'first_post',
17 1: 'other_posts_read',
18 2: 'other_posts_unread',
19};
20
avm99963ad65e752020-09-01 00:13:59 +020021const indicatorTypes = ['numPosts', 'indicatorDot'];
22
avm99963e51444e2020-08-31 14:50:06 +020023// Filter used as a workaround to speed up the ViewForum request.
24const FILTER_ALL_LANGUAGES =
25 '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)';
26
avm99963ad65e752020-09-01 00:13:59 +020027const numPostsForumArraysToSum = [3, 4];
28
avm99963e51444e2020-08-31 14:50:06 +020029function isElementInside(element, outerTag) {
30 while (element !== null && ('tagName' in element)) {
31 if (element.tagName == outerTag) return true;
32 element = element.parentNode;
33 }
34
35 return false;
36}
37
38function escapeUsername(username) {
39 var quoteRegex = /"/g;
40 var commentRegex = /<!---->/g;
41 return username.replace(quoteRegex, '\\"').replace(commentRegex, '');
42}
43
44function getPosts(query, forumId) {
45 return fetch('https://support.google.com/s/community/api/ViewForum', {
46 'credentials': 'include',
47 'headers': {'content-type': 'text/plain; charset=utf-8'},
48 'body': JSON.stringify({
49 '1': forumId,
50 '2': {
51 '1': {
52 '2': 5,
53 },
54 '2': {
55 '1': 1,
56 '2': true,
57 },
58 '12': query,
59 },
60 }),
61 'method': 'POST',
62 'mode': 'cors',
63 })
64 .then(res => res.json());
65}
66
avm99963ad65e752020-09-01 00:13:59 +020067function getProfile(userId, forumId) {
68 return fetch('https://support.google.com/s/community/api/ViewUser', {
69 'credentials': 'include',
70 'headers': {'content-type': 'text/plain; charset=utf-8'},
71 'body': JSON.stringify({
72 '1': userId,
73 '2': 0,
74 '3': forumId,
75 }),
76 'method': 'POST',
77 'mode': 'cors',
78 })
79 .then(res => res.json());
80}
81
avm99963e51444e2020-08-31 14:50:06 +020082// Source:
83// https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response
avm99963ad65e752020-09-01 00:13:59 +020084var contentScriptRequest = (function() {
avm99963e51444e2020-08-31 14:50:06 +020085 var requestId = 0;
86
avm99963ad65e752020-09-01 00:13:59 +020087 function sendRequest(data) {
avm99963e51444e2020-08-31 14:50:06 +020088 var id = requestId++;
89
90 return new Promise(function(resolve, reject) {
91 var listener = function(evt) {
avm99963ad65e752020-09-01 00:13:59 +020092 if (evt.source === window && evt.data && evt.data.prefix === 'TWPT' &&
93 evt.data.requestId == id) {
avm99963e51444e2020-08-31 14:50:06 +020094 // Deregister self
avm99963ad65e752020-09-01 00:13:59 +020095 window.removeEventListener('message', listener);
96 resolve(evt.data.data);
avm99963e51444e2020-08-31 14:50:06 +020097 }
98 };
99
avm99963ad65e752020-09-01 00:13:59 +0200100 window.addEventListener('message', listener);
avm99963e51444e2020-08-31 14:50:06 +0200101
avm99963ad65e752020-09-01 00:13:59 +0200102 var payload = {data, id};
avm99963e51444e2020-08-31 14:50:06 +0200103
avm99963ad65e752020-09-01 00:13:59 +0200104 window.dispatchEvent(
105 new CustomEvent('TWPT_sendRequest', {detail: payload}));
avm99963e51444e2020-08-31 14:50:06 +0200106 });
107 }
108
avm99963ad65e752020-09-01 00:13:59 +0200109 return {sendRequest: sendRequest};
avm99963e51444e2020-08-31 14:50:06 +0200110})();
111
avm99963ad65e752020-09-01 00:13:59 +0200112// Create profile indicator dot with a loading state, or return the numPosts
113// badge if it is already created.
114function createIndicatorDot(sourceNode, searchURL, options) {
115 if (options.numPosts) return document.querySelector('.num-posts-indicator');
avm99963a1b23b62020-09-01 14:32:34 +0200116 var dotContainer = document.createElement('div');
avm99963ad65e752020-09-01 00:13:59 +0200117 dotContainer.classList.add('profile-indicator', 'profile-indicator--loading');
118 contentScriptRequest
119 .sendRequest({
120 'action': 'geti18nMessage',
121 'msg': 'inject_profileindicator_loading'
122 })
avm99963e51444e2020-08-31 14:50:06 +0200123 .then(string => dotContainer.setAttribute('title', string));
124
125 var dotLink = document.createElement('a');
126 dotLink.href = searchURL;
127 dotLink.innerText = '●';
128
129 dotContainer.appendChild(dotLink);
130 sourceNode.parentNode.appendChild(dotContainer);
131
132 return dotContainer;
133}
134
avm99963ad65e752020-09-01 00:13:59 +0200135// Create badge indicating the number of posts with a loading state
136function createNumPostsBadge(sourceNode, searchURL) {
137 var link = document.createElement('a');
138 link.href = searchURL;
139
140 var numPostsContainer = document.createElement('div');
141 numPostsContainer.classList.add(
142 'num-posts-indicator', 'num-posts-indicator--loading');
143 contentScriptRequest
144 .sendRequest({
145 'action': 'geti18nMessage',
146 'msg': 'inject_profileindicator_loading'
147 })
148 .then(string => numPostsContainer.setAttribute('title', string));
149
150 var numPostsSpan = document.createElement('span');
151 numPostsSpan.classList.add('num-posts-indicator--num');
152
153 numPostsContainer.appendChild(numPostsSpan);
154 link.appendChild(numPostsContainer);
155 sourceNode.parentNode.appendChild(link);
156 return numPostsContainer;
157}
158
159// Get options and then handle all the indicators
160function getOptionsAndHandleIndicators(sourceNode, isCC) {
161 contentScriptRequest.sendRequest({'action': 'getProfileIndicatorOptions'})
162 .then(options => handleIndicators(sourceNode, isCC, options));
163}
164
165// Handle the profile indicator dot
166function handleIndicators(sourceNode, isCC, options) {
avm99963e51444e2020-08-31 14:50:06 +0200167 var escapedUsername = escapeUsername(
168 (isCC ? sourceNode.innerHTML :
169 sourceNode.querySelector('span').innerHTML));
170
171 if (isCC) {
172 var threadLink = document.location.href;
173 } else {
174 var CCLink = document.getElementById('onebar-community-console');
175 if (CCLink === null) {
176 console.error(
avm99963ad65e752020-09-01 00:13:59 +0200177 '[opindicator] The user is not a PE so the dot indicator cannot be shown in TW.');
avm99963e51444e2020-08-31 14:50:06 +0200178 return;
179 }
180 var threadLink = CCLink.href;
181 }
182
183 var forumUrlSplit = threadLink.split('/forum/');
184 if (forumUrlSplit.length < 2) {
avm99963ad65e752020-09-01 00:13:59 +0200185 console.error('[opindicator] Can\'t get forum id.');
avm99963e51444e2020-08-31 14:50:06 +0200186 return;
187 }
188
189 var forumId = forumUrlSplit[1].split('/')[0];
avm99963ad65e752020-09-01 00:13:59 +0200190
avm99963e51444e2020-08-31 14:50:06 +0200191 var query = '(replier:"' + escapedUsername + '" | creator:"' +
192 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
193 var encodedQuery =
194 encodeURIComponent(query + (isCC ? ' forum:' + forumId : ''));
195 var searchURL =
196 (isCC ? 'https://support.google.com/s/community/search/' +
197 encodeURIComponent('query=' + encodedQuery) :
198 document.location.pathname.split('/thread')[0] +
avm99963ad65e752020-09-01 00:13:59 +0200199 '/threads?thread_filter=' + encodedQuery);
avm99963e51444e2020-08-31 14:50:06 +0200200
avm99963ad65e752020-09-01 00:13:59 +0200201 if (options.numPosts) {
202 var profileURL = new URL(sourceNode.href);
203 var userId =
204 profileURL.pathname.split(isCC ? 'user/' : 'profile/')[1].split('/')[0];
avm99963e51444e2020-08-31 14:50:06 +0200205
avm99963ad65e752020-09-01 00:13:59 +0200206 var numPostsContainer = createNumPostsBadge(sourceNode, searchURL);
avm99963e51444e2020-08-31 14:50:06 +0200207
avm99963ad65e752020-09-01 00:13:59 +0200208 getProfile(userId, forumId)
209 .then(res => {
210 if (!('1' in res) || !('2' in res[1])) {
211 throw new Error('Unexpected profile response.');
212 return;
213 }
avm99963e51444e2020-08-31 14:50:06 +0200214
avm99963ad65e752020-09-01 00:13:59 +0200215 contentScriptRequest.sendRequest({'action': 'getNumPostMonths'})
216 .then(months => {
217 if (!options.indicatorDot)
218 contentScriptRequest
219 .sendRequest({
220 'action': 'geti18nMessage',
221 'msg': 'inject_profileindicatoralt_numposts',
222 'placeholders': [months]
223 })
224 .then(
225 string =>
226 numPostsContainer.setAttribute('title', string));
avm99963e51444e2020-08-31 14:50:06 +0200227
avm99963ad65e752020-09-01 00:13:59 +0200228 var numPosts = 0;
avm99963e51444e2020-08-31 14:50:06 +0200229
avm99963ad65e752020-09-01 00:13:59 +0200230 for (const index of numPostsForumArraysToSum) {
231 if (!(index in res[1][2])) {
232 throw new Error('Unexpected profile response.');
233 return;
234 }
avm99963e51444e2020-08-31 14:50:06 +0200235
avm99963ad65e752020-09-01 00:13:59 +0200236 var i = 0;
237 for (const month of res[1][2][index].reverse()) {
238 if (i == months) break;
239 numPosts += month[3] || 0;
240 ++i;
241 }
242 }
avm99963e51444e2020-08-31 14:50:06 +0200243
avm99963ad65e752020-09-01 00:13:59 +0200244 numPostsContainer.classList.remove(
245 'num-posts-indicator--loading');
246 numPostsContainer.querySelector('span').classList.remove(
247 'num-posts-indicator--num--loading');
248 numPostsContainer.querySelector('span').textContent = numPosts;
249 })
250 .catch(
251 err => console.error('[opindicator] Unexpected error.', err));
252 })
253 .catch(
254 err => console.error(
255 '[opindicator] Unexpected error. Couldn\'t load profile.',
256 err));
257 ;
258 }
259
260 if (options.indicatorDot) {
261 var dotContainer = createIndicatorDot(sourceNode, searchURL, options);
262
263 // Query threads in order to see what state the indicator should be in
264 getPosts(query, forumId)
265 .then(res => {
266 if (!('1' in res) || !('2' in res['1'])) {
267 throw new Error('Unexpected thread list response.');
268 return;
269 }
270
271 // Current thread ID
272 var threadUrlSplit = threadLink.split('/thread/');
273 if (threadUrlSplit.length < 2)
274 throw new Error('Can\'t get thread id.');
275
276 var currId = threadUrlSplit[1].split('/')[0];
277
278 var OPStatus = OP_FIRST_POST;
279
280 for (const thread of res['1']['2']) {
281 var id = thread['2']['1']['1'] || undefined;
282 if (id === undefined || id == currId) continue;
283
284 var isRead = thread['6'] || false;
285 if (isRead)
286 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
287 else
288 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
289 }
290
291 var dotContainerPrefix =
292 (options.numPosts ? 'num-posts-indicator' : 'profile-indicator');
293
294 if (!options.numPosts)
295 dotContainer.classList.remove(dotContainerPrefix + '--loading');
296 dotContainer.classList.add(
297 dotContainerPrefix + '--' + OPClasses[OPStatus]);
298 contentScriptRequest
299 .sendRequest({
300 'action': 'geti18nMessage',
301 'msg': 'inject_profileindicator_' + OPi18n[OPStatus]
302 })
303 .then(string => dotContainer.setAttribute('title', string));
304 })
305 .catch(
306 err => console.error(
307 '[opindicator] Unexpected error. Couldn\'t load recent posts.',
308 err));
309 }
avm99963e51444e2020-08-31 14:50:06 +0200310}
311
312if (CCRegex.test(location.href)) {
313 // We are in the Community Console
314 function mutationCallback(mutationList, observer) {
315 mutationList.forEach((mutation) => {
316 if (mutation.type == 'childList') {
317 mutation.addedNodes.forEach(function(node) {
318 if (node.tagName == 'A' && ('href' in node) &&
319 CCProfileRegex.test(node.href) &&
320 isElementInside(node, 'EC-QUESTION') && ('children' in node) &&
321 node.children.length == 0) {
avm99963ad65e752020-09-01 00:13:59 +0200322 getOptionsAndHandleIndicators(node, true);
avm99963e51444e2020-08-31 14:50:06 +0200323 }
324 });
325 }
326 });
327 };
328
329 var observerOptions = {
330 childList: true,
331 subtree: true,
332 }
333
334 mutationObserver = new MutationObserver(mutationCallback);
335 mutationObserver.observe(
336 document.querySelector('.scrollable-content'), observerOptions);
337} else {
338 // We are in TW
avm99963ad65e752020-09-01 00:13:59 +0200339 var node =
340 document.querySelector('.thread-question a.user-info-display-name');
avm99963e51444e2020-08-31 14:50:06 +0200341 if (node !== null)
avm99963ad65e752020-09-01 00:13:59 +0200342 getOptionsAndHandleIndicators(node, false);
avm99963e51444e2020-08-31 14:50:06 +0200343 else
avm99963ad65e752020-09-01 00:13:59 +0200344 console.error('[opindicator] Couldn\'t find username.');
avm99963e51444e2020-08-31 14:50:06 +0200345}