Skip to content

Commit 760562f

Browse files
cyfung1031Copilot
andauthored
⚡️ 处理 check_script_update_cycle (#906)
* 处理 `check_script_update_cycle` * Update src/app/service/service_worker/regular_updatecheck.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * 定义为常量并添加注释说明其用途 --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent 67914d2 commit 760562f

File tree

13 files changed

+131
-71
lines changed

13 files changed

+131
-71
lines changed

src/app/service/service_worker/index.ts

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import { RuntimeService } from "./runtime";
88
import { type ServiceWorkerMessageSend } from "@Packages/message/window_message";
99
import { PopupService } from "./popup";
1010
import { SystemConfig } from "@App/pkg/config/config";
11-
import { systemConfig } from "@App/pages/store/global";
1211
import { SynchronizeService } from "./synchronize";
1312
import { SubscribeService } from "./subscribe";
1413
import { ScriptDAO } from "@App/app/repo/scripts";
@@ -18,6 +17,7 @@ import { initLocales, localePath, t } from "@App/locales/locales";
1817
import { getCurrentTab, InfoNotification } from "@App/pkg/utils/utils";
1918
import { onTabRemoved, onUrlNavigated, setOnUserActionDomainChanged } from "./url_monitor";
2019
import { LocalStorageDAO } from "@App/app/repo/localStorage";
20+
import { onRegularUpdateCheckAlarm } from "./regular_updatecheck";
2121

2222
// service worker的管理器
2323
export default class ServiceWorkerManager {
@@ -91,12 +91,28 @@ export default class ServiceWorkerManager {
9191
system.init();
9292

9393
const regularScriptUpdateCheck = async () => {
94-
const res = await script.checkScriptUpdate({ checkType: "system" });
94+
const res = await onRegularUpdateCheckAlarm(systemConfig, script, subscribe);
9595
if (!res?.ok) return;
9696
targetSites = res.targetSites;
9797
pendingOpen = res.checktime;
9898
};
9999

100+
const regularExtensionUpdateCheck = () => {
101+
fetch(`${ExtServer}api/v1/system/version?version=${ExtVersion}`)
102+
.then((resp) => resp.json())
103+
.then((resp: { data: { [key: string]: any; notice: string; version: string } }) => {
104+
const data = resp.data;
105+
systemConfig
106+
.getCheckUpdate()
107+
.then((items) => {
108+
const isRead = items.notice !== data.notice ? false : items.isRead;
109+
systemConfig.setCheckUpdate({ ...data, isRead: isRead });
110+
})
111+
.catch((e) => console.error("regularExtensionUpdateCheck: Check Error", e));
112+
})
113+
.catch((e) => console.error("regularExtensionUpdateCheck: Network Error", e));
114+
};
115+
100116
this.mq.subscribe<any>("msgUpdatePageOpened", () => {
101117
pendingOpen = 0;
102118
});
@@ -120,12 +136,9 @@ export default class ServiceWorkerManager {
120136
});
121137
});
122138
break;
123-
case "checkSubscribeUpdate":
124-
subscribe.checkSubscribeUpdate();
125-
break;
126139
case "checkUpdate":
127140
// 检查扩展更新
128-
this.checkUpdate();
141+
regularExtensionUpdateCheck();
129142
break;
130143
}
131144
});
@@ -268,20 +281,4 @@ export default class ServiceWorkerManager {
268281
onTabRemoved(tabId);
269282
});
270283
}
271-
272-
checkUpdate() {
273-
fetch(`${ExtServer}api/v1/system/version?version=${ExtVersion}`)
274-
.then((resp) => resp.json())
275-
.then((resp: { data: { notice: string; version: string } }) => {
276-
systemConfig
277-
.getCheckUpdate()
278-
.then((items) => {
279-
const isRead = items.notice !== resp.data.notice ? false : items.isRead;
280-
systemConfig.setCheckUpdate(Object.assign(resp.data, { isRead: isRead }));
281-
})
282-
.catch((e) => {
283-
console.error(e);
284-
});
285-
});
286-
}
287284
}
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import { type SystemConfig } from "@App/pkg/config/config";
2+
import { type ScriptService } from "./script";
3+
import { type SubscribeService } from "./subscribe";
4+
5+
// 如果距离下次检查还有超过30秒,则使用计算的时间;否则使用默认延迟
6+
const MIN_REMAINING_TIME_MS = 30000;
7+
// Service Worker 启动后的默认延迟时间,给予足够的初始化时间
8+
const DEFAULT_FIRST_CHECK_DELAY_MS = 6000;
9+
// 允许在预定时间前最多65秒内触发检查(考虑 alarm 触发时间的不精确性)
10+
const ALARM_TRIGGER_WINDOW_MS = 65000;
11+
// Service Worker 启动后允许执行 alarm 的延迟时间
12+
const ALLOW_CHECK_DELAY_MS = 3000;
13+
14+
export let allowRegularUpdateCheck = 0; // 避免SW启动时alarm触发
15+
16+
export const initRegularUpdateCheck = async (systemConfig: SystemConfig) => {
17+
// regularScriptUpdateCheck
18+
const [result, updateCycleSecond] = await Promise.all([
19+
chrome.storage.local.get(["checkupdate_script_lasttime"]),
20+
systemConfig.getCheckScriptUpdateCycle(), // check_script_update_cycle
21+
]);
22+
if (updateCycleSecond === 0) return; // no regular update check
23+
const now = Date.now();
24+
let when = 0;
25+
const checkupdate_script_lasttime: number = result.checkupdate_script_lasttime || 0;
26+
// 有 checkupdate_script_lasttime 而且是单数值(上次的定时更新检查有完成)
27+
if (checkupdate_script_lasttime && (checkupdate_script_lasttime & 1) === 1) {
28+
const updateCycleMs = updateCycleSecond * 1000;
29+
const next = checkupdate_script_lasttime + updateCycleMs;
30+
if (next > now + MIN_REMAINING_TIME_MS) {
31+
when = next;
32+
}
33+
}
34+
when = when || now + DEFAULT_FIRST_CHECK_DELAY_MS; // 六秒后触发第一个alarm
35+
let targetPeriodInMinutes = Math.ceil(updateCycleSecond / 60); // 分钟
36+
targetPeriodInMinutes = Math.ceil(targetPeriodInMinutes / 5) * 5; // 5的倍数
37+
if (targetPeriodInMinutes < 15) targetPeriodInMinutes = 15; // 至少15分钟
38+
chrome.alarms.create(
39+
"checkScriptUpdate",
40+
{
41+
when,
42+
periodInMinutes: targetPeriodInMinutes,
43+
},
44+
() => {
45+
const lastError = chrome.runtime.lastError;
46+
if (lastError) {
47+
console.error("chrome.runtime.lastError in chrome.alarms.create:", lastError);
48+
// Starting in Chrome 117, the number of active alarms is limited to 500. Once this limit is reached, chrome.alarms.create() will fail.
49+
console.error("Chrome alarm is unable to create. Please check whether limit is reached.");
50+
}
51+
}
52+
);
53+
allowRegularUpdateCheck = now + ALLOW_CHECK_DELAY_MS; // 可以触发alarm的更新程序了
54+
};
55+
56+
const setCheckupdateScriptLasttime = async (t: number) => {
57+
try {
58+
// 试一下储存。储存不了也没所谓
59+
await chrome.storage.local.set({ checkupdate_script_lasttime: t });
60+
} catch (e: any) {
61+
console.error(e);
62+
}
63+
};
64+
65+
export const onRegularUpdateCheckAlarm = async (
66+
systemConfig: SystemConfig,
67+
script: ScriptService,
68+
subscribe?: SubscribeService
69+
) => {
70+
const now = Date.now();
71+
if (!allowRegularUpdateCheck || now < allowRegularUpdateCheck) return null; // 避免SW启动时alarm触发
72+
const [result, updateCycleSecond] = await Promise.all([
73+
chrome.storage.local.get(["checkupdate_script_lasttime"]),
74+
systemConfig.getCheckScriptUpdateCycle(), // check_script_update_cycle
75+
]);
76+
if (updateCycleSecond === 0) return null; // no regular update check
77+
const checkupdate_script_lasttime: number = result.checkupdate_script_lasttime || 0;
78+
const targetWhen = checkupdate_script_lasttime + updateCycleSecond * 1000;
79+
if (targetWhen - ALARM_TRIGGER_WINDOW_MS > now) return null; // 已检查过了(alarm触发了)
80+
const storeTime = Math.floor(now / 2) * 2; // 双数
81+
await setCheckupdateScriptLasttime(storeTime); // 双数值:alarm触发了,但不知道有没有真的检查好(例如中途浏览器关了)
82+
const res = await script.checkScriptUpdate({ checkType: "system" });
83+
try {
84+
if (subscribe) {
85+
// 不论 checkScriptUpdate 成功与否,执行 checkSubscribeUpdate
86+
const checkDisableScript = await systemConfig.getUpdateDisableScript();
87+
await subscribe.checkSubscribeUpdate(updateCycleSecond, checkDisableScript);
88+
}
89+
} catch (e: any) {
90+
console.error(e);
91+
}
92+
await setCheckupdateScriptLasttime(storeTime + 1); // 单数值:alarm触发了,而且真的检查好
93+
return res;
94+
};

src/app/service/service_worker/script.ts

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import {
5151
import { getSimilarityScore, ScriptUpdateCheck } from "./script_update_check";
5252
import { LocalStorageDAO } from "@App/app/repo/localStorage";
5353
import { CompiledResourceDAO } from "@App/app/repo/resource";
54+
import { initRegularUpdateCheck } from "./regular_updatecheck";
5455
// import { gzip as pakoGzip } from "pako";
5556

5657
const cIdKey = `(cid_${Math.random()})`;
@@ -1404,21 +1405,6 @@ export class ScriptService {
14041405
this.group.on("openBatchUpdatePage", this.openBatchUpdatePage.bind(this));
14051406
this.group.on("checkScriptUpdate", this.checkScriptUpdate.bind(this));
14061407

1407-
// 定时检查更新, 首次执行为5分钟后,然后每30分钟检查一次
1408-
chrome.alarms.create(
1409-
"checkScriptUpdate",
1410-
{
1411-
delayInMinutes: 5,
1412-
periodInMinutes: 30,
1413-
},
1414-
() => {
1415-
const lastError = chrome.runtime.lastError;
1416-
if (lastError) {
1417-
console.error("chrome.runtime.lastError in chrome.alarms.create:", lastError);
1418-
// Starting in Chrome 117, the number of active alarms is limited to 500. Once this limit is reached, chrome.alarms.create() will fail.
1419-
console.error("Chrome alarm is unable to create. Please check whether limit is reached.");
1420-
}
1421-
}
1422-
);
1408+
initRegularUpdateCheck(this.systemConfig);
14231409
}
14241410
}

src/app/service/service_worker/subscribe.ts

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -267,13 +267,7 @@ export class SubscribeService {
267267
}
268268
}
269269

270-
async checkSubscribeUpdate() {
271-
const checkCycle = await this.systemConfig.getCheckScriptUpdateCycle();
272-
if (!checkCycle) {
273-
return;
274-
}
275-
this.logger.debug("start check update");
276-
const checkDisable = await this.systemConfig.getUpdateDisableScript();
270+
async checkSubscribeUpdate(checkCycle: number, checkDisable: boolean) {
277271
const list = await this.subscribeDAO.find((_, value) => {
278272
return value.checktime + checkCycle * 1000 < Date.now();
279273
});
@@ -316,21 +310,6 @@ export class SubscribeService {
316310
this.upsertScript(message.subscribe.url);
317311
});
318312

319-
// 定时检查更新, 首次執行為5分钟後,然後每30分钟检查一次
320-
chrome.alarms.create(
321-
"checkSubscribeUpdate",
322-
{
323-
delayInMinutes: 5,
324-
periodInMinutes: 30,
325-
},
326-
() => {
327-
const lastError = chrome.runtime.lastError;
328-
if (lastError) {
329-
console.error("chrome.runtime.lastError in chrome.alarms.create:", lastError);
330-
// Starting in Chrome 117, the number of active alarms is limited to 500. Once this limit is reached, chrome.alarms.create() will fail.
331-
console.error("Chrome alarm is unable to create. Please check whether limit is reached.");
332-
}
333-
}
334-
);
313+
chrome.alarms.clear("checkSubscribeUpdate");
335314
}
336315
}

src/locales/ach-UG/translation.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@
473473
"display_right_click_menu_desc": "crwdns8918:0crwdne8918:0",
474474
"expand_count": "crwdns8896:0crwdne8896:0",
475475
"auto_collapse_when_exceeds": "crwdns8898:0crwdne8898:0",
476-
"check_frequency": "crwdns8900:0crwdne8900:0",
476+
"script_update_check_frequency": "crwdns8900:0crwdne8900:0",
477477
"script_auto_update_frequency": "crwdns8902:0crwdne8902:0",
478478
"update_options": "crwdns8904:0crwdne8904:0",
479479
"control_script_update_behavior": "crwdns8906:0crwdne8906:0",

src/locales/de-DE/translation.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@
473473
"display_right_click_menu_desc": "Skriptmenü im Rechtsklickmenü des Browsers anzeigen",
474474
"expand_count": "Erweiterte Anzahl",
475475
"auto_collapse_when_exceeds": "Automatisch einklappen, wenn diese Anzahl überschritten wird",
476-
"check_frequency": "Prüffrequenz",
476+
"script_update_check_frequency": "Häufigkeit der Skript-Aktualisierungsprüfung",
477477
"script_auto_update_frequency": "Frequenz der automatischen Skript-Update-Prüfung",
478478
"update_options": "Update-Optionen",
479479
"control_script_update_behavior": "Skript-Update-Verhalten kontrollieren",

src/locales/en-US/translation.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@
473473
"display_right_click_menu_desc": "Show script menu in browser right-click menu",
474474
"expand_count": "Expand Count",
475475
"auto_collapse_when_exceeds": "Auto collapse when exceeds this number",
476-
"check_frequency": "Check Frequency",
476+
"script_update_check_frequency": "Script Update Check Frequency",
477477
"script_auto_update_frequency": "Script automatic update check frequency",
478478
"update_options": "Update Options",
479479
"control_script_update_behavior": "Control script update behavior",

src/locales/ja-JP/translation.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -473,8 +473,8 @@
473473
"display_right_click_menu_desc": "ブラウザの右クリックメニューにスクリプトメニューを表示する",
474474
"expand_count": "展開数",
475475
"auto_collapse_when_exceeds": "この数を超えたときに自動的に折りたたむ",
476-
"check_frequency": "チェック頻度",
477-
"script_auto_update_frequency": "スクリプトの自動更新チェック頻度",
476+
"script_update_check_frequency": "スクリプト更新の確認頻度",
477+
"script_auto_update_frequency": "スクリプトの自動更新確認頻度",
478478
"update_options": "更新オプション",
479479
"control_script_update_behavior": "スクリプト更新の動作を制御",
480480
"blacklist_pages_desc": "指定されたページでスクリプトの実行を禁止、ワイルドカードをサポート",

src/locales/ru-RU/translation.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@
473473
"display_right_click_menu_desc": "Показать меню скрипта в контекстном меню браузера",
474474
"expand_count": "Количество развернутых",
475475
"auto_collapse_when_exceeds": "Автоматически сворачивать при превышении этого количества",
476-
"check_frequency": "Частота проверки",
476+
"script_update_check_frequency": "Частота проверки обновления скрипта",
477477
"script_auto_update_frequency": "Частота автоматической проверки обновлений скриптов",
478478
"update_options": "Параметры обновления",
479479
"control_script_update_behavior": "Управление поведением обновления скриптов",

src/locales/vi-VN/translation.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@
473473
"display_right_click_menu_desc": "Hiển thị menu script trong menu chuột phải của trình duyệt",
474474
"expand_count": "Số lượng mở rộng",
475475
"auto_collapse_when_exceeds": "Tự động thu gọn khi vượt quá số này",
476-
"check_frequency": "Tần suất kiểm tra",
476+
"script_update_check_frequency": "Tần suất kiểm tra cập nhật tập lệnh",
477477
"script_auto_update_frequency": "Tần suất kiểm tra cập nhật script tự động",
478478
"update_options": "Tùy chọn cập nhật",
479479
"control_script_update_behavior": "Kiểm soát hành vi cập nhật script",

0 commit comments

Comments
 (0)