diff --git a/src/app/service/service_worker/index.ts b/src/app/service/service_worker/index.ts index 7a5ec150c..d3b64952a 100644 --- a/src/app/service/service_worker/index.ts +++ b/src/app/service/service_worker/index.ts @@ -8,7 +8,6 @@ import { RuntimeService } from "./runtime"; import { type ServiceWorkerMessageSend } from "@Packages/message/window_message"; import { PopupService } from "./popup"; import { SystemConfig } from "@App/pkg/config/config"; -import { systemConfig } from "@App/pages/store/global"; import { SynchronizeService } from "./synchronize"; import { SubscribeService } from "./subscribe"; import { ScriptDAO } from "@App/app/repo/scripts"; @@ -18,6 +17,7 @@ import { localePath, t } from "@App/locales/locales"; import { getCurrentTab, InfoNotification } from "@App/pkg/utils/utils"; import { onTabRemoved, onUrlNavigated, setOnUserActionDomainChanged } from "./url_monitor"; import { LocalStorageDAO } from "@App/app/repo/localStorage"; +import { onRegularUpdateCheckAlarm } from "./regular_updatecheck"; // service worker的管理器 export default class ServiceWorkerManager { @@ -89,12 +89,28 @@ export default class ServiceWorkerManager { system.init(); const regularScriptUpdateCheck = async () => { - const res = await script.checkScriptUpdate({ checkType: "system" }); + const res = await onRegularUpdateCheckAlarm(systemConfig, script, subscribe); if (!res?.ok) return; targetSites = res.targetSites; pendingOpen = res.checktime; }; + const regularExtensionUpdateCheck = () => { + fetch(`${ExtServer}api/v1/system/version?version=${ExtVersion}`) + .then((resp) => resp.json()) + .then((resp: { data: { [key: string]: any; notice: string; version: string } }) => { + const data = resp.data; + systemConfig + .getCheckUpdate() + .then((items) => { + const isRead = items.notice !== data.notice ? false : items.isRead; + systemConfig.setCheckUpdate({ ...data, isRead: isRead }); + }) + .catch((e) => console.error("regularExtensionUpdateCheck: Check Error", e)); + }) + .catch((e) => console.error("regularExtensionUpdateCheck: Network Error", e)); + }; + this.mq.subscribe("msgUpdatePageOpened", () => { pendingOpen = 0; }); @@ -118,12 +134,9 @@ export default class ServiceWorkerManager { }); }); break; - case "checkSubscribeUpdate": - subscribe.checkSubscribeUpdate(); - break; case "checkUpdate": // 检查扩展更新 - this.checkUpdate(); + regularExtensionUpdateCheck(); break; } }); @@ -266,20 +279,4 @@ export default class ServiceWorkerManager { onTabRemoved(tabId); }); } - - checkUpdate() { - fetch(`${ExtServer}api/v1/system/version?version=${ExtVersion}`) - .then((resp) => resp.json()) - .then((resp: { data: { notice: string; version: string } }) => { - systemConfig - .getCheckUpdate() - .then((items) => { - const isRead = items.notice !== resp.data.notice ? false : items.isRead; - systemConfig.setCheckUpdate(Object.assign(resp.data, { isRead: isRead })); - }) - .catch((e) => { - console.error(e); - }); - }); - } } diff --git a/src/app/service/service_worker/regular_updatecheck.ts b/src/app/service/service_worker/regular_updatecheck.ts new file mode 100644 index 000000000..ea5bac7e0 --- /dev/null +++ b/src/app/service/service_worker/regular_updatecheck.ts @@ -0,0 +1,94 @@ +import { type SystemConfig } from "@App/pkg/config/config"; +import { type ScriptService } from "./script"; +import { type SubscribeService } from "./subscribe"; + +// 如果距离下次检查还有超过30秒,则使用计算的时间;否则使用默认延迟 +const MIN_REMAINING_TIME_MS = 30000; +// Service Worker 启动后的默认延迟时间,给予足够的初始化时间 +const DEFAULT_FIRST_CHECK_DELAY_MS = 6000; +// 允许在预定时间前最多65秒内触发检查(考虑 alarm 触发时间的不精确性) +const ALARM_TRIGGER_WINDOW_MS = 65000; +// Service Worker 启动后允许执行 alarm 的延迟时间 +const ALLOW_CHECK_DELAY_MS = 3000; + +export let allowRegularUpdateCheck = 0; // 避免SW启动时alarm触发 + +export const initRegularUpdateCheck = async (systemConfig: SystemConfig) => { + // regularScriptUpdateCheck + const [result, updateCycleSecond] = await Promise.all([ + chrome.storage.local.get(["checkupdate_script_lasttime"]), + systemConfig.getCheckScriptUpdateCycle(), // check_script_update_cycle + ]); + if (updateCycleSecond === 0) return; // no regular update check + const now = Date.now(); + let when = 0; + const checkupdate_script_lasttime: number = result.checkupdate_script_lasttime || 0; + // 有 checkupdate_script_lasttime 而且是单数值(上次的定时更新检查有完成) + if (checkupdate_script_lasttime && (checkupdate_script_lasttime & 1) === 1) { + const updateCycleMs = updateCycleSecond * 1000; + const next = checkupdate_script_lasttime + updateCycleMs; + if (next > now + MIN_REMAINING_TIME_MS) { + when = next; + } + } + when = when || now + DEFAULT_FIRST_CHECK_DELAY_MS; // 六秒后触发第一个alarm + let targetPeriodInMinutes = Math.ceil(updateCycleSecond / 60); // 分钟 + targetPeriodInMinutes = Math.ceil(targetPeriodInMinutes / 5) * 5; // 5的倍数 + if (targetPeriodInMinutes < 15) targetPeriodInMinutes = 15; // 至少15分钟 + chrome.alarms.create( + "checkScriptUpdate", + { + when, + periodInMinutes: targetPeriodInMinutes, + }, + () => { + const lastError = chrome.runtime.lastError; + if (lastError) { + console.error("chrome.runtime.lastError in chrome.alarms.create:", lastError); + // Starting in Chrome 117, the number of active alarms is limited to 500. Once this limit is reached, chrome.alarms.create() will fail. + console.error("Chrome alarm is unable to create. Please check whether limit is reached."); + } + } + ); + allowRegularUpdateCheck = now + ALLOW_CHECK_DELAY_MS; // 可以触发alarm的更新程序了 +}; + +const setCheckupdateScriptLasttime = async (t: number) => { + try { + // 试一下储存。储存不了也没所谓 + await chrome.storage.local.set({ checkupdate_script_lasttime: t }); + } catch (e: any) { + console.error(e); + } +}; + +export const onRegularUpdateCheckAlarm = async ( + systemConfig: SystemConfig, + script: ScriptService, + subscribe?: SubscribeService +) => { + const now = Date.now(); + if (!allowRegularUpdateCheck || now < allowRegularUpdateCheck) return null; // 避免SW启动时alarm触发 + const [result, updateCycleSecond] = await Promise.all([ + chrome.storage.local.get(["checkupdate_script_lasttime"]), + systemConfig.getCheckScriptUpdateCycle(), // check_script_update_cycle + ]); + if (updateCycleSecond === 0) return null; // no regular update check + const checkupdate_script_lasttime: number = result.checkupdate_script_lasttime || 0; + const targetWhen = checkupdate_script_lasttime + updateCycleSecond * 1000; + if (targetWhen - ALARM_TRIGGER_WINDOW_MS > now) return null; // 已检查过了(alarm触发了) + const storeTime = Math.floor(now / 2) * 2; // 双数 + await setCheckupdateScriptLasttime(storeTime); // 双数值:alarm触发了,但不知道有没有真的检查好(例如中途浏览器关了) + const res = await script.checkScriptUpdate({ checkType: "system" }); + try { + if (subscribe) { + // 不论 checkScriptUpdate 成功与否,执行 checkSubscribeUpdate + const checkDisableScript = await systemConfig.getUpdateDisableScript(); + await subscribe.checkSubscribeUpdate(updateCycleSecond, checkDisableScript); + } + } catch (e: any) { + console.error(e); + } + await setCheckupdateScriptLasttime(storeTime + 1); // 单数值:alarm触发了,而且真的检查好 + return res; +}; diff --git a/src/app/service/service_worker/script.ts b/src/app/service/service_worker/script.ts index fd669b14e..ade082aa9 100644 --- a/src/app/service/service_worker/script.ts +++ b/src/app/service/service_worker/script.ts @@ -51,6 +51,7 @@ import { import { getSimilarityScore, ScriptUpdateCheck } from "./script_update_check"; import { LocalStorageDAO } from "@App/app/repo/localStorage"; import { CompiledResourceDAO } from "@App/app/repo/resource"; +import { initRegularUpdateCheck } from "./regular_updatecheck"; // import { gzip as pakoGzip } from "pako"; const cIdKey = `(cid_${Math.random()})`; @@ -1306,21 +1307,6 @@ export class ScriptService { this.group.on("openBatchUpdatePage", this.openBatchUpdatePage.bind(this)); this.group.on("checkScriptUpdate", this.checkScriptUpdate.bind(this)); - // 定时检查更新, 首次执行为5分钟后,然后每30分钟检查一次 - chrome.alarms.create( - "checkScriptUpdate", - { - delayInMinutes: 5, - periodInMinutes: 30, - }, - () => { - const lastError = chrome.runtime.lastError; - if (lastError) { - console.error("chrome.runtime.lastError in chrome.alarms.create:", lastError); - // Starting in Chrome 117, the number of active alarms is limited to 500. Once this limit is reached, chrome.alarms.create() will fail. - console.error("Chrome alarm is unable to create. Please check whether limit is reached."); - } - } - ); + initRegularUpdateCheck(this.systemConfig); } } diff --git a/src/app/service/service_worker/subscribe.ts b/src/app/service/service_worker/subscribe.ts index 4eb397b02..f5350d336 100644 --- a/src/app/service/service_worker/subscribe.ts +++ b/src/app/service/service_worker/subscribe.ts @@ -267,13 +267,7 @@ export class SubscribeService { } } - async checkSubscribeUpdate() { - const checkCycle = await this.systemConfig.getCheckScriptUpdateCycle(); - if (!checkCycle) { - return; - } - this.logger.debug("start check update"); - const checkDisable = await this.systemConfig.getUpdateDisableScript(); + async checkSubscribeUpdate(checkCycle: number, checkDisable: boolean) { const list = await this.subscribeDAO.find((_, value) => { return value.checktime + checkCycle * 1000 < Date.now(); }); @@ -316,21 +310,6 @@ export class SubscribeService { this.upsertScript(message.subscribe.url); }); - // 定时检查更新, 首次執行為5分钟後,然後每30分钟检查一次 - chrome.alarms.create( - "checkSubscribeUpdate", - { - delayInMinutes: 5, - periodInMinutes: 30, - }, - () => { - const lastError = chrome.runtime.lastError; - if (lastError) { - console.error("chrome.runtime.lastError in chrome.alarms.create:", lastError); - // Starting in Chrome 117, the number of active alarms is limited to 500. Once this limit is reached, chrome.alarms.create() will fail. - console.error("Chrome alarm is unable to create. Please check whether limit is reached."); - } - } - ); + chrome.alarms.clear("checkSubscribeUpdate"); } } diff --git a/src/locales/ach-UG/translation.json b/src/locales/ach-UG/translation.json index 63083137c..ab94d2cf4 100644 --- a/src/locales/ach-UG/translation.json +++ b/src/locales/ach-UG/translation.json @@ -473,7 +473,7 @@ "display_right_click_menu_desc": "crwdns8918:0crwdne8918:0", "expand_count": "crwdns8896:0crwdne8896:0", "auto_collapse_when_exceeds": "crwdns8898:0crwdne8898:0", - "check_frequency": "crwdns8900:0crwdne8900:0", + "script_update_check_frequency": "crwdns8900:0crwdne8900:0", "script_auto_update_frequency": "crwdns8902:0crwdne8902:0", "update_options": "crwdns8904:0crwdne8904:0", "control_script_update_behavior": "crwdns8906:0crwdne8906:0", diff --git a/src/locales/de-DE/translation.json b/src/locales/de-DE/translation.json index cabb18df4..ee5bdafae 100644 --- a/src/locales/de-DE/translation.json +++ b/src/locales/de-DE/translation.json @@ -473,7 +473,7 @@ "display_right_click_menu_desc": "Skriptmenü im Rechtsklickmenü des Browsers anzeigen", "expand_count": "Erweiterte Anzahl", "auto_collapse_when_exceeds": "Automatisch einklappen, wenn diese Anzahl überschritten wird", - "check_frequency": "Prüffrequenz", + "script_update_check_frequency": "Häufigkeit der Skript-Aktualisierungsprüfung", "script_auto_update_frequency": "Frequenz der automatischen Skript-Update-Prüfung", "update_options": "Update-Optionen", "control_script_update_behavior": "Skript-Update-Verhalten kontrollieren", diff --git a/src/locales/en-US/translation.json b/src/locales/en-US/translation.json index efa5c867c..3ef06707e 100644 --- a/src/locales/en-US/translation.json +++ b/src/locales/en-US/translation.json @@ -473,7 +473,7 @@ "display_right_click_menu_desc": "Show script menu in browser right-click menu", "expand_count": "Expand Count", "auto_collapse_when_exceeds": "Auto collapse when exceeds this number", - "check_frequency": "Check Frequency", + "script_update_check_frequency": "Script Update Check Frequency", "script_auto_update_frequency": "Script automatic update check frequency", "update_options": "Update Options", "control_script_update_behavior": "Control script update behavior", diff --git a/src/locales/ja-JP/translation.json b/src/locales/ja-JP/translation.json index 0791b0bd1..9a44d68c2 100644 --- a/src/locales/ja-JP/translation.json +++ b/src/locales/ja-JP/translation.json @@ -473,8 +473,8 @@ "display_right_click_menu_desc": "ブラウザの右クリックメニューにスクリプトメニューを表示する", "expand_count": "展開数", "auto_collapse_when_exceeds": "この数を超えたときに自動的に折りたたむ", - "check_frequency": "チェック頻度", - "script_auto_update_frequency": "スクリプトの自動更新チェック頻度", + "script_update_check_frequency": "スクリプト更新の確認頻度", + "script_auto_update_frequency": "スクリプトの自動更新確認頻度", "update_options": "更新オプション", "control_script_update_behavior": "スクリプト更新の動作を制御", "blacklist_pages_desc": "指定されたページでスクリプトの実行を禁止、ワイルドカードをサポート", diff --git a/src/locales/ru-RU/translation.json b/src/locales/ru-RU/translation.json index 666c22b64..c05404454 100644 --- a/src/locales/ru-RU/translation.json +++ b/src/locales/ru-RU/translation.json @@ -473,7 +473,7 @@ "display_right_click_menu_desc": "Показать меню скрипта в контекстном меню браузера", "expand_count": "Количество развернутых", "auto_collapse_when_exceeds": "Автоматически сворачивать при превышении этого количества", - "check_frequency": "Частота проверки", + "script_update_check_frequency": "Частота проверки обновления скрипта", "script_auto_update_frequency": "Частота автоматической проверки обновлений скриптов", "update_options": "Параметры обновления", "control_script_update_behavior": "Управление поведением обновления скриптов", diff --git a/src/locales/vi-VN/translation.json b/src/locales/vi-VN/translation.json index a7fce17c9..773f4e257 100644 --- a/src/locales/vi-VN/translation.json +++ b/src/locales/vi-VN/translation.json @@ -473,7 +473,7 @@ "display_right_click_menu_desc": "Hiển thị menu script trong menu chuột phải của trình duyệt", "expand_count": "Số lượng mở rộng", "auto_collapse_when_exceeds": "Tự động thu gọn khi vượt quá số này", - "check_frequency": "Tần suất kiểm tra", + "script_update_check_frequency": "Tần suất kiểm tra cập nhật tập lệnh", "script_auto_update_frequency": "Tần suất kiểm tra cập nhật script tự động", "update_options": "Tùy chọn cập nhật", "control_script_update_behavior": "Kiểm soát hành vi cập nhật script", diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json index 9625441f9..21dee0156 100644 --- a/src/locales/zh-CN/translation.json +++ b/src/locales/zh-CN/translation.json @@ -473,7 +473,7 @@ "display_right_click_menu_desc": "在浏览器右键菜单中显示脚本菜单", "expand_count": "展开数量", "auto_collapse_when_exceeds": "超过此数量时自动折叠", - "check_frequency": "检查频率", + "script_update_check_frequency": "脚本更新检查频率", "script_auto_update_frequency": "脚本自动检查更新的频率", "update_options": "更新选项", "control_script_update_behavior": "控制脚本更新的行为", diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json index e7dac4edc..979aba5fe 100644 --- a/src/locales/zh-TW/translation.json +++ b/src/locales/zh-TW/translation.json @@ -473,7 +473,7 @@ "display_right_click_menu_desc": "在瀏覽器右鍵選單中顯示腳本選單", "expand_count": "展開數量", "auto_collapse_when_exceeds": "超過此數量時自動摺疊", - "check_frequency": "檢查頻率", + "script_update_check_frequency": "腳本更新檢查頻率", "script_auto_update_frequency": "腳本自動檢查更新的頻率", "update_options": "更新選項", "control_script_update_behavior": "控制腳本更新的行為", diff --git a/src/pages/options/routes/Setting.tsx b/src/pages/options/routes/Setting.tsx index bff54ce75..6aec60749 100644 --- a/src/pages/options/routes/Setting.tsx +++ b/src/pages/options/routes/Setting.tsx @@ -18,6 +18,7 @@ import { SystemConfigChange, type SystemConfigKey } from "@App/pkg/config/config import { type TKeyValue } from "@Packages/message/message_queue"; import { useEffect, useMemo } from "react"; import { systemConfig } from "@App/pages/store/global"; +import { initRegularUpdateCheck } from "@App/app/service/service_worker/regular_updatecheck"; function Setting() { const { subscribeMessage } = useAppContext(); @@ -308,13 +309,16 @@ function Setting() {
- {t("check_frequency")} + {t("script_update_check_frequency")}