forked from PositiveSumNet/SocialAssistant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
64 lines (59 loc) · 1.89 KB
/
background.js
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
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// stackoverflow.com/a/73836810
let returnsData = false;
switch (request.actionType) {
case 'save':
returnsData = true;
break;
default:
break;
}
(async () => {
switch (request.actionType) {
case 'save':
const saveResponse = await processSave(request.payload);
sendResponse(saveResponse);
return returnsData;
case 'setBadge':
chrome.action.setBadgeText({text: request.badgeText});
return returnsData;
default:
return returnsData;
}
})();
return returnsData;
});
const processSave = async function(records) {
await injectImageBase64s(records);
saveToTempStorage(records);
return {saved: records, success: true};
}
// TODO: Parallel tasks like one of these
// bytelimes.com/batch-async-tasks-with-async-generators/
// stackoverflow.com/questions/35612428/call-async-await-functions-in-parallel
const injectImageBase64s = async function(records) {
for (let i = 0; i < records.length; i++) {
let item = records[i];
if (item.imgCdnUrl) {
item.img64Url = await getImageBase64(item.imgCdnUrl);
}
}
}
// caches what we'll want to persist to the sqlitedb when we get the chance
const saveToTempStorage = function(records) {
// the 'fordb-' prefix is how we find all such pending batches
const key = 'fordb-' + Date.now().toString();
chrome.storage.local.set({ [key]: records });
}
// stackoverflow.com/questions/57346889/how-to-return-base64-data-from-a-fetch-promise
const getImageBase64 = async function(url) {
const response = await fetch(url);
const blob = await response.blob();
const reader = new FileReader();
await new Promise((resolve, reject) => {
reader.onload = resolve;
reader.onerror = reject;
reader.readAsDataURL(blob);
});
return reader.result.replace(/^data:.+;base64,/, '')
}