-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbackground.ts
More file actions
245 lines (220 loc) · 9.47 KB
/
background.ts
File metadata and controls
245 lines (220 loc) · 9.47 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
interface VersionData {
rsi: string;
concierge: string;
orgs: string;
addresses: string;
hangar: string;
uex: string;
dps: string;
[key: string]: string;
}
interface ReplaceWord {
word: string;
replacement: string;
}
let dataVersion: VersionData | null = null
chrome.runtime.onInstalled.addListener(function () {
console.log("SWTT init");
chrome.contextMenus.create({
id: "translate",
title: "切换翻译",
contexts: ["all"]
});
});
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action === "_loadLocalizationData") {
let domain = getURLDomain(request.url);
let switchKey = `_translate_switch_${domain}`;
getLocalData(switchKey).then(enableManual => {
console.log("GET domain ===", domain, "enableManual === ", enableManual);
_initLocalization(request.url, enableManual).then(data => {
sendResponse({result: data});
});
})
} else if (request.action === "_setTranslateSwitch") {
let domain = getURLDomain(request.url);
let switchKey = `_translate_switch_${domain}`;
setLocalData(switchKey, request.enableManual).then(() => {
console.log("SET translate switch ===", domain, "enableManual === ", request.enableManual);
sendResponse({result: true});
});
}
return true;
});
function getURLDomain(url: string): string {
const urlObj = new URL(url);
return urlObj.hostname;
}
async function _checkVersion(): Promise<void> {
dataVersion = await _getJsonData("versions.json") as VersionData;
console.log("Localization Version ===", dataVersion);
}
async function _initLocalization(url: string, enableManual: boolean): Promise<ReplaceWord[]> {
console.log("url ===" + url);
// Check if translation is disabled first, before fetching any resources
if (enableManual != null && !enableManual) return [];
// TODO check version
let data: Record<string, any> = {};
if (url.includes("robertsspaceindustries.com")) {
data["zh-CN"] = await _getJsonData("zh-CN-rsi.json", {cacheKey: "zh-CN", versionKey: "rsi"});
data["concierge"] = await _getJsonData("concierge.json", {cacheKey: "concierge", versionKey: "concierge"});
data["orgs"] = await _getJsonData("orgs.json", {cacheKey: "orgs", versionKey: "orgs"});
data["address"] = await _getJsonData("addresses.json", {cacheKey: "addresses", versionKey: "addresses"});
data["hangar"] = await _getJsonData("hangar.json", {cacheKey: "hangar", versionKey: "hangar"});
} else if (url.includes("uexcorp.space")) {
data["UEX"] = await _getJsonData("zh-CN-uex.json", {cacheKey: "uex", versionKey: "uex"});
} else if (url.includes("erkul.games")) {
data["DPS"] = await _getJsonData("zh-CN-dps.json", {cacheKey: "dps", versionKey: "dps"});
} else if (enableManual) {
data["zh-CN"] = await _getJsonData("zh-CN-rsi.json", {cacheKey: "zh-CN", versionKey: "rsi"});
data["concierge"] = await _getJsonData("concierge.json", {cacheKey: "concierge", versionKey: "concierge"});
data["orgs"] = await _getJsonData("orgs.json", {cacheKey: "orgs", versionKey: "orgs"});
data["address"] = await _getJsonData("addresses.json", {cacheKey: "address", versionKey: "addresses"});
data["hangar"] = await _getJsonData("hangar.json", {cacheKey: "hangar", versionKey: "hangar"});
data["UEX"] = await _getJsonData("zh-CN-uex.json", {cacheKey: "uex", versionKey: "uex"});
data["DPS"] = await _getJsonData("zh-CN-dps.json", {cacheKey: "dps", versionKey: "dps"});
}
// update data
let replaceWords: ReplaceWord[] = [];
function addLocalizationResource(key: string): void {
replaceWords.push(...getLocalizationResource(data, key));
}
if (url.includes("robertsspaceindustries.com")) {
const org = "https://robertsspaceindustries.com/orgs";
const citizens = "https://robertsspaceindustries.com/citizens";
const organization = "https://robertsspaceindustries.com/account/organization";
const concierge = "https://robertsspaceindustries.com/account/concierge";
const referral = "https://robertsspaceindustries.com/account/referral-program";
const address = "https://robertsspaceindustries.com/account/addresses";
const hangar = "https://robertsspaceindustries.com/account/pledges";
const spectrum = "https://robertsspaceindustries.com/spectrum/community/";
if (url.startsWith(spectrum)) {
return [];
}
addLocalizationResource("zh-CN");
if (url.startsWith(org) || url.startsWith(citizens) || url.startsWith(organization)) {
replaceWords.push({"word": 'members', "replacement": '名成员'});
addLocalizationResource("orgs");
}
if (url.startsWith(address)) {
addLocalizationResource("address");
}
if (url.startsWith(referral)) {
replaceWords.push(
{"word": 'Total recruits: ', "replacement": '总邀请数:'},
{"word": 'Prospects ', "replacement": '未完成的邀请'},
{"word": 'Recruits', "replacement": '已完成的邀请'}
);
}
if (url.startsWith(concierge)) {
replaceWords = [];
addLocalizationResource("concierge");
}
if (url.startsWith(hangar)) {
addLocalizationResource("hangar");
}
} else if (url.includes("uexcorp.space")) {
addLocalizationResource("UEX");
} else if (url.includes("erkul.games")) {
addLocalizationResource("DPS");
} else if (enableManual) {
addLocalizationResource("zh-CN");
replaceWords.push({"word": 'members', "replacement": '名成员'});
addLocalizationResource("orgs");
addLocalizationResource("address");
replaceWords.push(
{"word": 'Total recruits: ', "replacement": '总邀请数:'},
{"word": 'Prospects ', "replacement": '未完成的邀请'},
{"word": 'Recruits', "replacement": '已完成的邀请'}
);
addLocalizationResource("concierge");
addLocalizationResource("hangar");
addLocalizationResource("UEX");
addLocalizationResource("DPS");
}
return replaceWords;
}
function getLocalizationResource(localizationResource: Record<string, any>, key: string): ReplaceWord[] {
const localizations: ReplaceWord[] = [];
const dict = localizationResource[key];
if (typeof dict === "object") {
for (const [k, v] of Object.entries(dict)) {
const trimmedKey = k
.toString()
.trim()
.toLowerCase()
.replace(/\xa0/g, ' ')
.replace(/\s{2,}/g, ' ');
localizations.push({"word": trimmedKey, "replacement": String(v)});
}
}
return localizations;
}
interface JsonDataOptions {
cacheKey?: string;
versionKey?: string;
}
async function _getJsonData(fileName: string, options: JsonDataOptions = {}): Promise<any> {
const {cacheKey = "", versionKey = ""} = options;
const url = "https://ecdn.git.scbox.xkeyc.cn/SCToolBox/ScWeb_Chinese_Translate/raw/branch/main/json/locales/" + fileName;
// Get version from dataVersion by versionKey if needed
let version: string | null = null;
if (versionKey && versionKey !== "") {
if (dataVersion == null) {
await _checkVersion();
}
version = dataVersion?.[versionKey] ?? null;
}
if (cacheKey && cacheKey !== "") {
const localVersion = await getLocalData(`${cacheKey}_version`);
const data = await getLocalData(cacheKey);
if (data && typeof data === 'object' && Object.keys(data).length > 0 && localVersion === version) {
return data;
}
}
const startTime = new Date();
const response = await fetch(url, {method: 'GET', mode: 'cors'});
const endTime = new Date();
const data = await response.json();
if (cacheKey && cacheKey !== "") {
const timeDiff = endTime.getTime() - startTime.getTime();
console.log(`update ${cacheKey} v == ${version} time == ${timeDiff / 1000}s`);
await setLocalData(cacheKey, data);
await setLocalData(`${cacheKey}_version`, version);
}
return data;
}
function getLocalData(key: string): Promise<any> {
return new Promise((resolve) => {
chrome.storage.local.get([key], (result) => {
const data = result[key];
if (data === undefined ){
return resolve(null);
}
resolve(data);
});
});
}
function setLocalData(key: string, data: any): Promise<void> {
return new Promise<void>((resolve) => {
const newData: Record<string, any> = {};
newData[key] = data;
chrome.storage.local.set(newData, () => {
resolve();
});
});
}
chrome.contextMenus.onClicked.addListener((info, tab) => {
console.log("contextMenus", info, tab);
let passedUrl = "manual";
const supportedSites = ["robertsspaceindustries.com", "erkul.games", "uexcorp.space"];
if (tab && tab.url && supportedSites.find(site => tab.url!.includes(site))) {
passedUrl = tab.url;
}
_initLocalization(passedUrl, true).then(data => {
if (tab && tab.id !== undefined) {
chrome.tabs.sendMessage(tab.id, {action: "_toggleTranslation", data}).then((_) => {
});
}
});
});