-
-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathbackground.js
More file actions
337 lines (290 loc) · 10.3 KB
/
background.js
File metadata and controls
337 lines (290 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import {
addRateLater,
addRateLaterBulk,
alertOnCurrentTab,
alertUseOnLinkToYoutube,
fetchTournesolApi,
getAccessToken,
getRandomSubarray,
getUserProof,
getRecommendationsLanguagesAuthenticated,
getSingleSetting,
} from './utils.js';
import { frontendHost } from './config.js';
const RECENT_VIDEOS_RATIO = 0.75;
const RECENT_VIDEOS_EXTRA_RATIO = 0.5;
const BUNDLE_OVERFETCH_FACTOR = 3;
/**
* Build the extension context menu.
*
* TODO: could be moved in its own `contextMenus` folder, imported and
* executed here. Investigate if it's possible.
*/
const createContextMenu = function createContextMenu() {
chrome.contextMenus.removeAll(function () {
chrome.contextMenus.create({
id: 'tournesol_add_rate_later',
title: 'Rate later on Tournesol',
contexts: ['link'],
});
});
chrome.contextMenus.onClicked.addListener(function (e, tab) {
var videoId = new URL(e.linkUrl).searchParams.get('v');
if (!videoId) {
alertUseOnLinkToYoutube(tab);
} else {
addRateLater(videoId).then((response) => {
if (!response.success) {
chrome.tabs.query(
{ active: true, currentWindow: true },
function (tabs) {
chrome.tabs.sendMessage(
tabs[0].id,
{ message: 'displayModal' },
function (response) {
if (!response.success) {
alertOnCurrentTab(
'Sorry, an error occured while opening the Tournesol login form.',
tab
);
}
}
);
}
);
}
});
}
});
};
createContextMenu();
function getDateThreeWeeksAgo() {
// format a string to properly display years months and day: 2011 -> 11, 5 -> 05, 12 -> 12
const threeWeeksAgo = new Date(Date.now() - 3 * 7 * 24 * 3600000);
// we truncate minutes, seconds and ms from the date in order to benefit
// from caching at the API level.
threeWeeksAgo.setMinutes(0, 0, 0);
return threeWeeksAgo.toISOString();
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// Returns a boolean indicating whether the user is logged in on Tournesol from the extension's perspective
if (request.message === 'isLoggedIn') {
getAccessToken().then((token) => sendResponse(!!token));
return true;
}
// Return the current access token in the chrome.storage.local.
if (request.message === 'extAccessTokenNeeded') {
getAccessToken().then((token) => sendResponse({ access_token: token }));
return true;
}
// Automatically hide the extension modal containing the login iframe after
// the access token has been refreshed.
if (request.message === 'accessTokenRefreshed') {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, { message: 'hideModal' });
});
return true;
}
// Forward the need to the proper content script.
if (request.message === 'displayModal') {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(
tabs[0].id,
{
message: 'displayModal',
modalOptions: request.modalOptions,
},
function (response) {
sendResponse(response);
}
);
});
return true;
}
if (request.message === 'openOptionsPage') {
chrome.runtime.openOptionsPage();
return true;
}
if (request.message == 'addRateLater') {
addRateLater(request.video_id).then(sendResponse);
return true;
}
if (request.message == 'addRateLaterBulk') {
addRateLaterBulk(request.videoIds).then(sendResponse);
return true;
}
if (request.message.startsWith('getProof:')) {
const keyword = request.message.split(':')[1];
if (keyword) {
getUserProof(keyword).then((response) => {
sendResponse(response);
});
return true;
}
}
if (request.message == 'getVideoStatistics') {
// getVideoStatistics(request.video_id).then(sendResponse);
return true;
}
if (request.message && request.message.startsWith('get:setting:')) {
let setting = request.message.split(':')[2];
if (!setting) {
sendResponse({ value: null });
return true;
}
getSingleSetting(setting, false).then((value) => {
sendResponse({ value: value });
});
return true;
} else if (
request.message == 'getTournesolRecommendations' ||
request.message == 'getTournesolSearchRecommendations'
) {
const poll_name = 'videos';
const request_recommendations = async (api_path, options) => {
const resp = await fetchTournesolApi(
`${api_path}${options ? '?' : ''}${options}`
);
if (resp && resp.ok) {
const json = await resp.json();
return json.results;
}
return [];
};
if (request.message === 'getTournesolRecommendations') {
const api_path = `polls/${poll_name}/recommendations/random/`;
const nbrPerRow = request.videosNumber;
const extraNbr = request.additionalVideosNumber;
const recentToLoadRow1 = Math.round(nbrPerRow * RECENT_VIDEOS_RATIO);
const oldToLoadRow1 = Math.round(nbrPerRow * (1 - RECENT_VIDEOS_RATIO));
const recentToLoadExtra = Math.round(
extraNbr * RECENT_VIDEOS_EXTRA_RATIO
);
const oldToLoadExtra = Math.round(
extraNbr * (1 - RECENT_VIDEOS_EXTRA_RATIO)
);
const process = async () => {
const threeWeeksAgo = getDateThreeWeeksAgo();
const recommendationsLangs =
await getRecommendationsLanguagesAuthenticated();
const recentParams = new URLSearchParams([
['date_gte', threeWeeksAgo],
[
'limit',
(recentToLoadRow1 + recentToLoadExtra) * BUNDLE_OVERFETCH_FACTOR,
],
['bundle', request.queryParamBundle],
]);
const oldParams = new URLSearchParams([
['date_lte', threeWeeksAgo],
['limit', (oldToLoadRow1 + oldToLoadExtra) * BUNDLE_OVERFETCH_FACTOR],
['bundle', request.queryParamBundle],
]);
recommendationsLangs.forEach((lang) => {
if (lang !== '') {
oldParams.append('metadata[language]', lang);
recentParams.append('metadata[language]', lang);
}
});
const [poolRecent, poolOld] = await Promise.all([
request_recommendations(api_path, recentParams),
request_recommendations(api_path, oldParams),
]);
const videosRecent = poolRecent.slice(0, recentToLoadRow1);
const videosRecentExtra = poolRecent.slice(recentToLoadRow1);
const videosOld = poolOld.slice(0, oldToLoadRow1);
const videosOldExtra = poolOld.slice(oldToLoadRow1);
// Compute the actual number of videos from each category that will appear in the feed.
// If there is not enough recent videos, use old ones of the same category instead.
let recentRow1Nbr = Math.round(nbrPerRow * RECENT_VIDEOS_RATIO);
if (recentRow1Nbr > videosRecent.length) {
recentRow1Nbr = videosRecent.length;
}
const oldRow1Nbr = nbrPerRow - recentRow1Nbr;
let recentExtraNbr = Math.round(extraNbr * RECENT_VIDEOS_EXTRA_RATIO);
if (recentExtraNbr > videosRecentExtra.length) {
recentExtraNbr = videosRecentExtra.length;
}
const oldExtraNbr = extraNbr - recentExtraNbr;
// Select randomly which videos are displayed, merge them, and shuffle them
// (separely for videos and extra videos).
const selectedRecentRow1 = getRandomSubarray(
videosRecent,
recentRow1Nbr
);
const selectedOldRow1 = getRandomSubarray(videosOld, oldRow1Nbr);
const row1 = getRandomSubarray(
[...selectedRecentRow1, ...selectedOldRow1],
nbrPerRow
);
const selectedRecentExtra = getRandomSubarray(
videosRecentExtra,
recentExtraNbr
);
const selectedOldExtra = getRandomSubarray(videosOldExtra, oldExtraNbr);
const extraRows = getRandomSubarray(
[...selectedRecentExtra, ...selectedOldExtra],
extraNbr
);
return {
data: [...row1, ...extraRows],
recommandationsLanguages: recommendationsLangs.join(','),
loadVideos: nbrPerRow > 0,
loadAdditionalVideos: extraNbr > 0,
};
};
process().then(sendResponse);
return true;
} else if (request.message === 'getTournesolSearchRecommendations') {
const process = async () => {
const api_path = `polls/${poll_name}/recommendations/`;
const videosNumber = request.videosNumber;
const recommendationsLangs =
await getRecommendationsLanguagesAuthenticated();
// Only one request for both videos and additional videos
const params = new URLSearchParams([
['limit', Math.max(20, videosNumber)],
['search', request.search],
['unsafe', false],
['score_mode', 'default'],
]);
recommendationsLangs.forEach((lang) => {
if (lang !== '') {
params.append('metadata[language]', lang);
}
});
const [videosList] = await Promise.all([
request_recommendations(api_path, params),
]);
return {
data: videosList.splice(0, videosNumber),
recommandationsLanguages: recommendationsLangs.join(','),
loadVideos: request.videosNumber > 0,
loadAdditionalVideos: request.additionalVideosNumber > 0,
};
};
process().then(sendResponse);
return true;
}
} else if (request.message === 'getBanners') {
const process = async () => {
const path = 'backoffice/banners/';
const response = await fetchTournesolApi(path, { authenticate: false });
const banners =
response && response.ok ? await response.json() : undefined;
sendResponse({ banners });
};
process();
return true;
}
});
// Send message to Tournesol tab on URL change, to sync access token
// during navigation (after login, logout, etc.)
chrome.webNavigation.onHistoryStateUpdated.addListener(
(event) => {
chrome.tabs.sendMessage(event.tabId, 'historyStateUpdated');
},
{
url: [{ hostEquals: frontendHost }],
}
);