Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 19 additions & 22 deletions src/app/service/service_worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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 {
Expand Down Expand Up @@ -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<any>("msgUpdatePageOpened", () => {
pendingOpen = 0;
});
Expand All @@ -118,12 +134,9 @@ export default class ServiceWorkerManager {
});
});
break;
case "checkSubscribeUpdate":
subscribe.checkSubscribeUpdate();
break;
case "checkUpdate":
// 检查扩展更新
this.checkUpdate();
regularExtensionUpdateCheck();
break;
}
});
Expand Down Expand Up @@ -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);
});
});
}
}
94 changes: 94 additions & 0 deletions src/app/service/service_worker/regular_updatecheck.ts
Original file line number Diff line number Diff line change
@@ -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;
};
18 changes: 2 additions & 16 deletions src/app/service/service_worker/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()})`;
Expand Down Expand Up @@ -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);
}
}
25 changes: 2 additions & 23 deletions src/app/service/service_worker/subscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down Expand Up @@ -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");
}
}
2 changes: 1 addition & 1 deletion src/locales/ach-UG/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion src/locales/de-DE/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion src/locales/en-US/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions src/locales/ja-JP/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "指定されたページでスクリプトの実行を禁止、ワイルドカードをサポート",
Expand Down
2 changes: 1 addition & 1 deletion src/locales/ru-RU/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "Управление поведением обновления скриптов",
Expand Down
2 changes: 1 addition & 1 deletion src/locales/vi-VN/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion src/locales/zh-CN/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "控制脚本更新的行为",
Expand Down
2 changes: 1 addition & 1 deletion src/locales/zh-TW/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": "控制腳本更新的行為",
Expand Down
6 changes: 5 additions & 1 deletion src/pages/options/routes/Setting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -308,13 +309,16 @@ function Setting() {
<Space direction="vertical" size={20} className="w-full">
<div className="flex items-center justify-between min-h-9">
<div className="flex items-center gap-4 flex-1">
<span className="min-w-20 font-medium">{t("check_frequency")}</span>
<span className="min-w-20 font-medium">{t("script_update_check_frequency")}</span>
<Select
value={checkScriptUpdateCycle.toString()}
className="w-35 max-w-45"
onChange={(value) => {
const num = parseInt(value, 10);
submitCheckScriptUpdateCycle(num);
Promise.resolve().then(() => {
initRegularUpdateCheck(systemConfig);
});
}}
>
<Select.Option value="0">{t("never")}</Select.Option>
Expand Down
Loading