-
Notifications
You must be signed in to change notification settings - Fork 5
/
background.js
95 lines (90 loc) · 2.55 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
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
async function get_data(url, type) {
try {
let res = await fetch(url);
if (!res.ok) {
console.log(`NETWORK ERROR: ${res.status}`);
return { error: res.status };
}
return type == "json" ? await res.json() : await res.text();
} catch (e) {
console.log(`FETCH ERROR: ${e}`);
return { error: e };
}
}
const getLocalStorage = async (key) => {
return new Promise((resolve, reject) => {
chrome.storage.local.get([key], function (result) {
if (result[key] === undefined) {
resolve("");
} else {
resolve(result[key]);
}
});
});
};
const setLocalStorage = async (key, value) => {
return new Promise((resolve, reject) => {
chrome.storage.local.set({ [key]: value }, function () {
resolve();
});
});
};
var json_data = {};
const resource_list = ["nckuhub", "urschool"];
var json_data_proxy = new Proxy(json_data, {
set: function (target, key, value) {
target[key] = value;
if (Object.keys(target).length == resource_list.length) {
chrome.tabs.query(
{ active: true, currentWindow: true },
function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
method: "response_data",
json_data: json_data,
});
},
);
}
return true;
},
deleteProperty: function (target, prop) {
if (prop in target) {
delete target[prop];
}
}
});
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
switch (request.method) {
case "get_data":
resource_list.forEach(async (item) => {
delete json_data_proxy[item];
});
resource_list.forEach(async (item) => {
let latest_hash = await get_data(
`https://ncchen99.github.io/ncku-evaluation/data/${item}-sha256.txt`,
"text"
);
var sha = `${item}-sha256`;
let sha_res = await getLocalStorage(sha);
if (!latest_hash.error && sha_res != latest_hash) {
console.log("🥗");
await setLocalStorage(sha, latest_hash);
await setLocalStorage(
item,
await get_data(
`https://ncchen99.github.io/ncku-evaluation/data/${item}.json`,
"json"
),
);
}
json_data_proxy[item] = await getLocalStorage(item);
console.log("🥳");
});
sendResponse({ complete: "ok" });
break;
default:
sendResponse({});
break;
}
return true;
});