blob: ce9187b56fa440b30e3bdbc344100212c81e0232 [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 = {
10 0: 'profile-indicator--first-post',
11 1: 'profile-indicator--other-posts-read',
12 2: 'profile-indicator--other-posts-unread',
13};
14
15const OPi18n = {
16 0: 'first_post',
17 1: 'other_posts_read',
18 2: 'other_posts_unread',
19};
20
21// Filter used as a workaround to speed up the ViewForum request.
22const FILTER_ALL_LANGUAGES =
23 '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)';
24
25function isElementInside(element, outerTag) {
26 while (element !== null && ('tagName' in element)) {
27 if (element.tagName == outerTag) return true;
28 element = element.parentNode;
29 }
30
31 return false;
32}
33
34function escapeUsername(username) {
35 var quoteRegex = /"/g;
36 var commentRegex = /<!---->/g;
37 return username.replace(quoteRegex, '\\"').replace(commentRegex, '');
38}
39
40function getPosts(query, forumId) {
41 return fetch('https://support.google.com/s/community/api/ViewForum', {
42 'credentials': 'include',
43 'headers': {'content-type': 'text/plain; charset=utf-8'},
44 'body': JSON.stringify({
45 '1': forumId,
46 '2': {
47 '1': {
48 '2': 5,
49 },
50 '2': {
51 '1': 1,
52 '2': true,
53 },
54 '12': query,
55 },
56 }),
57 'method': 'POST',
58 'mode': 'cors',
59 })
60 .then(res => res.json());
61}
62
63// Source:
64// https://stackoverflow.com/questions/33063774/communication-from-an-injected-script-to-the-content-script-with-a-response
65var i18nRequest = (function() {
66 var requestId = 0;
67
68 function getMessage(msg) {
69 var id = requestId++;
70
71 return new Promise(function(resolve, reject) {
72 var listener = function(evt) {
73 if (evt.detail.requestId == id) {
74 // Deregister self
75 window.removeEventListener('sendChromeData', listener);
76 resolve(evt.detail.string);
77 }
78 };
79
80 window.addEventListener('sendi18nString', listener);
81
82 var payload = {msg: msg, id: id};
83
84 window.dispatchEvent(new CustomEvent('geti18nString', {detail: payload}));
85 });
86 }
87
88 return {getMessage: getMessage};
89})();
90
91// Create profile indicator dot with a loading state
92function createIndicatorDot(sourceNode, searchURL) {
93 var dotContainer = document.createElement('span');
94 dotContainer.classList.add('profile-indicator');
95 dotContainer.classList.add('profile-indicator--loading');
96 i18nRequest.getMessage('inject_profileindicator_loading')
97 .then(string => dotContainer.setAttribute('title', string));
98
99 var dotLink = document.createElement('a');
100 dotLink.href = searchURL;
101 dotLink.innerText = '●';
102
103 dotContainer.appendChild(dotLink);
104 sourceNode.parentNode.appendChild(dotContainer);
105
106 return dotContainer;
107}
108
109// Handle the profile indicator
110function handleIndicatorDot(sourceNode, isCC) {
111 var escapedUsername = escapeUsername(
112 (isCC ? sourceNode.innerHTML :
113 sourceNode.querySelector('span').innerHTML));
114
115 if (isCC) {
116 var threadLink = document.location.href;
117 } else {
118 var CCLink = document.getElementById('onebar-community-console');
119 if (CCLink === null) {
120 console.error(
121 '[dotindicator] The user is not a PE so the dot indicator cannot be shown in TW.');
122 return;
123 }
124 var threadLink = CCLink.href;
125 }
126
127 var forumUrlSplit = threadLink.split('/forum/');
128 if (forumUrlSplit.length < 2) {
129 console.error('[dotindicator] Can\'t get forum id.');
130 return;
131 }
132
133 var forumId = forumUrlSplit[1].split('/')[0];
134 var query = '(replier:"' + escapedUsername + '" | creator:"' +
135 escapedUsername + '") ' + FILTER_ALL_LANGUAGES;
136 var encodedQuery =
137 encodeURIComponent(query + (isCC ? ' forum:' + forumId : ''));
138 var searchURL =
139 (isCC ? 'https://support.google.com/s/community/search/' +
140 encodeURIComponent('query=' + encodedQuery) :
141 document.location.pathname.split('/thread')[0] +
142 '/threads?thread_filter=' + encodedQuery)
143
144 var dotContainer = createIndicatorDot(sourceNode, searchURL);
145
146 // Query threads in order to see what state the indicator should be in
147 getPosts(query, forumId)
148 .then(res => {
149 if (!('1' in res) || !('2' in res['1'])) {
150 throw new Error('Unexpected response.');
151 return;
152 }
153
154 // Current thread ID
155 var threadUrlSplit = threadLink.split('/thread/');
156 if (threadUrlSplit.length < 2) throw new Error('Can\'t get thread id.');
157
158 var currId = threadUrlSplit[1].split('/')[0];
159
160 var OPStatus = OP_FIRST_POST;
161
162 for (const thread of res['1']['2']) {
163 var id = thread['2']['1']['1'] || undefined;
164 if (id === undefined || id == currId) continue;
165
166 var isRead = thread['6'] || false;
167 if (isRead)
168 OPStatus = Math.max(OP_OTHER_POSTS_READ, OPStatus);
169 else
170 OPStatus = Math.max(OP_OTHER_POSTS_UNREAD, OPStatus);
171 }
172
173 dotContainer.classList.remove('profile-indicator--loading');
174 dotContainer.classList.add(OPClasses[OPStatus]);
175 i18nRequest.getMessage('inject_profileindicator_' + OPi18n[OPStatus])
176 .then(string => dotContainer.setAttribute('title', string));
177 })
178 .catch(
179 err => console.error(
180 '[dotindicator] Unexpected error. Couldn\'t load recent posts.',
181 err));
182}
183
184if (CCRegex.test(location.href)) {
185 // We are in the Community Console
186 function mutationCallback(mutationList, observer) {
187 mutationList.forEach((mutation) => {
188 if (mutation.type == 'childList') {
189 mutation.addedNodes.forEach(function(node) {
190 if (node.tagName == 'A' && ('href' in node) &&
191 CCProfileRegex.test(node.href) &&
192 isElementInside(node, 'EC-QUESTION') && ('children' in node) &&
193 node.children.length == 0) {
194 handleIndicatorDot(node, true);
195 }
196 });
197 }
198 });
199 };
200
201 var observerOptions = {
202 childList: true,
203 subtree: true,
204 }
205
206 mutationObserver = new MutationObserver(mutationCallback);
207 mutationObserver.observe(
208 document.querySelector('.scrollable-content'), observerOptions);
209} else {
210 // We are in TW
211 var node = document.querySelector('.thread-question .user-info-display-name');
212 if (node !== null)
213 handleIndicatorDot(node, false);
214 else
215 console.error('[dotindicator] Couldn\'t find username.');
216}