调整通信
Some checks failed
test / Run tests (push) Failing after 15s
build / Build (push) Failing after 19s

This commit is contained in:
王一之 2025-03-22 02:50:56 +08:00
parent 131f1bda40
commit 57bef5a023
27 changed files with 301 additions and 203 deletions

View File

@ -6,5 +6,11 @@
- 从脚本发起的GM请求需要层层传递到service_worker/offscreen进行处理有的GM只需要进行一次调用获取一次结果有的需要进行
多次调用获取多次结果使用connect的方式实现
- 从service_woker/offscreen发起的请求类似消息队列其它页面进行监听触发后广播给所有页面使用connect方式实现
- 从扩展页面发起的请求需要传递到service_worker/offscreen进行处理如果只是单次调用获取一次结果使用message方式实现
- 从service_worker/offscreen发起的请求类似消息队列其它页面进行监听触发后广播给所有页面使用sendMessage方式实现
- 从扩展页面发起的请求需要传递到service_worker/offscreen进行处理如果只是单次调用获取一次结果使用sendMessage方式实现如果需要
多次调用获取多次结果使用connect方式实现
## 注意点
- service_worker和offscreen之间可以使用postMessage的方式进行通信避免同时监听message与connect导致冲突的问题
- service_worker会变为不活动的状态尽量避免与service_worker建立长连接

View File

@ -35,6 +35,9 @@ export class ExtensionMessage extends ExtensionMessageSend implements Message {
// 注意chrome.runtime.onMessage.addListener的回调函数需要返回true才能处理异步请求
onMessage(callback: (data: any, sendResponse: (data: any) => void) => void) {
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.action === "messageQueue") {
return false;
}
return callback(msg, sendResponse);
});
}

View File

@ -1,98 +1,57 @@
import EventEmitter from "eventemitter3";
import { ApiFunction, MessageConnect, MessageSend, Server } from "./server";
import { sendMessage } from "./client";
import Logger from "@App/app/logger/logger";
import LoggerCore from "@App/app/logger/core";
export type SubscribeCallback = (message: any) => void;
export class Broker {
constructor(private msg: MessageSend) {}
// 订阅
async subscribe(topic: string, handler: SubscribeCallback): Promise<MessageConnect> {
LoggerCore.getInstance().logger({ service: "messageQueue" }).debug("subscribe", { topic });
const con = await this.msg.connect({ action: "messageQueue", data: { action: "subscribe", topic } });
con.onMessage((msg: { action: string; topic: string; message: any }) => {
if (msg.action === "message") {
handler(msg.message);
}
});
return con;
}
// 发布
publish(topic: string, message: any) {
sendMessage(this.msg, "messageQueue", { action: "publish", topic, message });
}
}
// 释放订阅
export type Unsubscribe = () => void;
// 消息队列
export class MessageQueue {
topicConMap: Map<string, { name: string; con: MessageConnect }[]> = new Map();
private EE: EventEmitter = new EventEmitter();
logger: Logger;
constructor(api: Server) {
api.on("messageQueue", this.handler());
this.logger = LoggerCore.getInstance().logger({ service: "messageQueue" });
constructor() {
chrome.runtime.onMessage.addListener((msg) => {
if (msg.action === "messageQueue") {
this.handler(msg.data);
}
});
}
handler(): ApiFunction {
return ({ action, topic, message }: { action: string; topic: string; message: any }, con) => {
this.logger.trace("messageQueueHandler", { action, topic, message });
if (!con) {
throw new Error("con is required");
}
if (!topic) {
throw new Error("topic is required");
}
switch (action) {
case "subscribe":
this.subscribe(topic, con as MessageConnect);
break;
case "publish":
this.publish(topic, message);
break;
default:
throw new Error("action not found");
}
handler({ action, topic, message }: { action: string; topic: string; message: any }) {
LoggerCore.getInstance()
.logger({ service: "messageQueue" })
.trace("messageQueueHandler", { action, topic, message });
if (!topic) {
throw new Error("topic is required");
}
switch (action) {
case "message":
this.EE.emit(topic, message);
break;
default:
throw new Error("action not found");
}
}
subscribe(topic: string, handler: SubscribeCallback): Unsubscribe {
this.EE.on(topic, handler);
return () => {
this.EE.off(topic, handler);
};
}
private subscribe(topic: string, con: MessageConnect) {
let list = this.topicConMap.get(topic);
if (!list) {
list = [];
this.topicConMap.set(topic, list);
}
list.push({ name: topic, con });
con.onDisconnect(() => {
let list = this.topicConMap.get(topic);
// 移除断开连接的con
list = list!.filter((item) => item.con !== con);
this.topicConMap.set(topic, list);
this.logger.debug("disconnect", { topic });
});
}
publish(topic: string, message: any) {
const list = this.topicConMap.get(topic);
list?.forEach((item) => {
item.con.sendMessage({ action: "message", topic, message });
chrome.runtime.sendMessage({
action: "messageQueue",
data: { action: "message", topic, message },
});
this.EE.emit(topic, message);
this.logger.trace("publish", { topic, message, list: list?.length });
LoggerCore.getInstance().logger({ service: "messageQueue" }).trace("publish", { topic, message });
}
// 只发布给当前环境
emit(topic: string, message: any) {
this.EE.emit(topic, message);
}
// 同环境下使用addListener
addListener(topic: string, handler: (message: any) => void) {
this.EE.on(topic, handler);
}
}

View File

@ -28,15 +28,21 @@ export class Server {
private logger = LoggerCore.getInstance().logger({ service: "messageServer" });
constructor(message: Message) {
constructor(prefix: string, message: Message) {
message.onConnect((msg: any, con: MessageConnect) => {
this.logger.trace("server onConnect", { msg });
this.connectHandle(msg.action, msg.data, con);
if (msg.action.startsWith(prefix)) {
return this.connectHandle(msg.action.slice(prefix.length + 1), msg.data, con);
}
return false;
});
message.onMessage((msg, sendResponse) => {
this.logger.trace("server onMessage", { msg });
return this.messageHandle(msg.action, msg.data, sendResponse);
message.onMessage((msg: { action: string; data: any }, sendResponse) => {
this.logger.trace("server onMessage", { msg: msg as any });
if (msg.action.startsWith(prefix)) {
return this.messageHandle(msg.action.slice(prefix.length + 1), msg.data, sendResponse);
}
return false;
});
}
@ -98,10 +104,11 @@ export class Group {
}
// 转发消息
export function forwardMessage(path: string, from: Server, to: MessageSend) {
export function forwardMessage(prefix: string, path: string, from: Server, to: MessageSend) {
from.on(path, (params, fromCon) => {
console.log("forwardMessage", path, prefix, params);
if (fromCon) {
to.connect({ action: path, data: params }).then((toCon) => {
to.connect({ action: prefix + "/" + path, data: params }).then((toCon) => {
fromCon.onMessage((data) => {
toCon.sendMessage(data);
});
@ -116,7 +123,7 @@ export function forwardMessage(path: string, from: Server, to: MessageSend) {
});
});
} else {
return to.sendMessage({ action: path, data: params });
return to.sendMessage({ action: prefix + "/" + path, data: params });
}
});
}

View File

@ -171,7 +171,6 @@ export class ServiceWorkerMessageSend implements MessageSend {
const list = await self.clients.matchAll({ includeUncontrolled: true, type: "window" });
this.target = list[0];
self.addEventListener("message", (e) => {
console.log("serviceWorker", e);
this.messageHandle(e.data);
});
}

View File

@ -39,7 +39,7 @@ export default class LoggerCore {
this.labels = config.labels || {};
// 获取日志debug等级, 如果是开发环境, 则默认为trace
if (process.env.NODE_ENV === "development") {
this.debug = "debug";
this.debug = "trace";
}
if (!LoggerCore.instance) {
LoggerCore.instance = this;

View File

@ -50,7 +50,7 @@ export default class Logger {
console.warn(msg);
break;
case "trace":
console.trace(msg);
console.info(msg);
break;
default:
console.info(msg);

View File

@ -1,19 +1,20 @@
import { WindowMessage } from "@Packages/message/window_message";
import { SCRIPT_RUN_STATUS } from "@App/app/repo/scripts";
import { SCRIPT_RUN_STATUS, ScriptRunResouce } from "@App/app/repo/scripts";
import { sendMessage } from "@Packages/message/client";
import { MessageSend } from "@Packages/message/server";
export function preparationSandbox(msg: WindowMessage) {
return sendMessage(msg, "preparationSandbox");
return sendMessage(msg, "offscreen/preparationSandbox");
}
// 代理发送消息到ServiceWorker
export function sendMessageToServiceWorker(msg: WindowMessage, action: string, data?: any) {
return sendMessage(msg, "sendMessageToServiceWorker", { action, data });
return sendMessage(msg, "offscreen/sendMessageToServiceWorker", { action, data });
}
// 代理连接ServiceWorker
export function connectServiceWorker(msg: WindowMessage) {
return sendMessage(msg, "connectServiceWorker");
return sendMessage(msg, "offscreen/connectServiceWorker");
}
export function proxyUpdateRunStatus(
@ -22,3 +23,11 @@ export function proxyUpdateRunStatus(
) {
return sendMessageToServiceWorker(msg, "script/updateRunStatus", data);
}
export function runScript(msg: MessageSend, data: ScriptRunResouce) {
return sendMessage(msg, "offscreen/script/runScript", data);
}
export function stopScript(msg: MessageSend, uuid: string) {
return sendMessage(msg, "offscreen/script/stopScript", uuid);
}

View File

@ -1,12 +1,12 @@
import { forwardMessage, MessageSend, Server } from "@Packages/message/server";
import { ScriptService } from "./script";
import { Broker } from "@Packages/message/message_queue";
import { Logger, LoggerDAO } from "@App/app/repo/logger";
import { WindowMessage } from "@Packages/message/window_message";
import { ExtensionMessageSend } from "@Packages/message/extension_message";
import { ServiceWorkerClient } from "../service_worker/client";
import { sendMessage } from "@Packages/message/client";
import GMApi from "./gm_api";
import { MessageQueue } from "@Packages/message/message_queue";
// offscreen环境的管理器
export class OffscreenManager {
@ -14,9 +14,9 @@ export class OffscreenManager {
private windowMessage = new WindowMessage(window, sandbox, true);
private windowApi: Server = new Server(this.windowMessage);
private windowApi: Server = new Server("offscreen", this.windowMessage);
private broker: Broker = new Broker(this.extensionMessage);
private messageQueue: MessageQueue = new MessageQueue();
private serviceWorker = new ServiceWorkerClient(this.extensionMessage);
@ -31,7 +31,7 @@ export class OffscreenManager {
}
sendMessageToServiceWorker(data: { action: string; data: any }) {
return sendMessage(this.extensionMessage, data.action, data.data);
return sendMessage(this.extensionMessage, "serviceWorker/" + data.action, data.data);
}
async initManager() {
@ -39,10 +39,17 @@ export class OffscreenManager {
this.windowApi.on("logger", this.logger.bind(this));
this.windowApi.on("preparationSandbox", this.preparationSandbox.bind(this));
this.windowApi.on("sendMessageToServiceWorker", this.sendMessageToServiceWorker.bind(this));
const script = new ScriptService(this.extensionMessage, this.windowMessage, this.broker);
const script = new ScriptService(
this.windowApi.group("script"),
this.extensionMessage,
this.windowMessage,
this.messageQueue
);
script.init();
// 转发gm api请求
forwardMessage("runtime/gmApi", this.windowApi, this.extensionMessage);
// 转发从sandbox来的gm api请求
forwardMessage("serviceWorker", "runtime/gmApi", this.windowApi, this.extensionMessage);
// 转发message queue请求
const gmApi = new GMApi(this.windowApi.group("gmApi"));
gmApi.init();

View File

@ -1,17 +1,12 @@
import LoggerCore from "@App/app/logger/core";
import Logger from "@App/app/logger/logger";
import { Broker } from "@Packages/message/message_queue";
import { MessageQueue } from "@Packages/message/message_queue";
import { WindowMessage } from "@Packages/message/window_message";
import {
ResourceClient,
ScriptClient,
subscribeScriptEnable,
subscribeScriptInstall,
ValueClient,
} from "../service_worker/client";
import { SCRIPT_STATUS_ENABLE, SCRIPT_TYPE_NORMAL } from "@App/app/repo/scripts";
import { disableScript, enableScript } from "../sandbox/client";
import { MessageSend } from "@Packages/message/server";
import { ResourceClient, ScriptClient, ValueClient } from "../service_worker/client";
import { SCRIPT_STATUS_ENABLE, SCRIPT_TYPE_NORMAL, ScriptRunResouce } from "@App/app/repo/scripts";
import { disableScript, enableScript, runScript, stopScript } from "../sandbox/client";
import { Group, MessageSend } from "@Packages/message/server";
import { subscribeScriptEnable, subscribeScriptInstall } from "../queue";
export class ScriptService {
logger: Logger;
@ -21,15 +16,25 @@ export class ScriptService {
valueClient: ValueClient = new ValueClient(this.extensionMessage);
constructor(
private group: Group,
private extensionMessage: MessageSend,
private windowMessage: WindowMessage,
private broker: Broker
private messageQueue: MessageQueue
) {
this.logger = LoggerCore.logger().with({ service: "script" });
}
runScript(script: ScriptRunResouce) {
runScript(this.windowMessage, script);
}
stopScript(uuid: string) {
stopScript(this.windowMessage, uuid);
}
async init() {
subscribeScriptEnable(this.broker, async (data) => {
subscribeScriptEnable(this.messageQueue, async (data) => {
console.log("subscribeScriptEnable", data);
const script = await this.scriptClient.info(data.uuid);
if (script.type === SCRIPT_TYPE_NORMAL) {
return;
@ -42,7 +47,8 @@ export class ScriptService {
disableScript(this.windowMessage, script.uuid);
}
});
subscribeScriptInstall(this.broker, async (data) => {
subscribeScriptInstall(this.messageQueue, async (data) => {
console.log("subscribeScriptInstall", data);
// 判断是开启还是关闭
if (data.script.status === SCRIPT_STATUS_ENABLE) {
// 构造脚本运行资源,发送给沙盒运行
@ -52,5 +58,8 @@ export class ScriptService {
disableScript(this.windowMessage, data.script.uuid);
}
});
this.group.on("runScript", this.runScript.bind(this));
this.group.on("stopScript", this.stopScript.bind(this));
}
}

29
src/app/service/queue.ts Normal file
View File

@ -0,0 +1,29 @@
import { MessageQueue } from "@Packages/message/message_queue";
import { Script, SCRIPT_RUN_STATUS } from "../repo/scripts";
export function subscribeScriptInstall(
messageQueue: MessageQueue,
callback: (message: { script: Script; update: boolean }) => void
) {
return messageQueue.subscribe("installScript", callback);
}
export function subscribeScriptDelete(messageQueue: MessageQueue, callback: (message: { uuid: string }) => void) {
return messageQueue.subscribe("deleteScript", callback);
}
export type ScriptEnableCallbackValue = { uuid: string; enable: boolean };
export function subscribeScriptEnable(
messageQueue: MessageQueue,
callback: (message: ScriptEnableCallbackValue) => void
) {
return messageQueue.subscribe("enableScript", callback);
}
export function subscribeScriptRunStatus(
messageQueue: MessageQueue,
callback: (message: { uuid: string; runStatus: SCRIPT_RUN_STATUS }) => void
) {
return messageQueue.subscribe("scriptRunStatus", callback);
}

View File

@ -3,9 +3,17 @@ import { sendMessage } from "@Packages/message/client";
import { WindowMessage } from "@Packages/message/window_message";
export function enableScript(msg: WindowMessage, data: ScriptRunResouce) {
return sendMessage(msg, "enableScript", data);
return sendMessage(msg, "sandbox/enableScript", data);
}
export function disableScript(msg: WindowMessage, uuid: string) {
return sendMessage(msg, "disableScript", uuid);
return sendMessage(msg, "sandbox/disableScript", uuid);
}
export function runScript(msg: WindowMessage, data: ScriptRunResouce) {
return sendMessage(msg, "sandbox/runScript", data);
}
export function stopScript(msg: WindowMessage, uuid: string) {
return sendMessage(msg, "sandbox/stopScript", uuid);
}

View File

@ -5,7 +5,7 @@ import { Runtime } from "./runtime";
// sandbox环境的管理器
export class SandboxManager {
api: Server = new Server(this.windowMessage);
api: Server = new Server("sandbox", this.windowMessage);
constructor(private windowMessage: WindowMessage) {}

View File

@ -269,18 +269,32 @@ export class Runtime {
}
}
stopScript(uuid: string) {
async stopScript(uuid: string) {
const exec = this.execScripts.get(uuid);
if (!exec) {
proxyUpdateRunStatus(this.windowMessage, { uuid: uuid, runStatus: SCRIPT_RUN_STATUS_COMPLETE });
return Promise.resolve(false);
}
exec.stop();
this.execScripts.delete(uuid);
proxyUpdateRunStatus(this.windowMessage, { uuid: uuid, runStatus: SCRIPT_RUN_STATUS_COMPLETE });
return Promise.resolve(true);
}
async runScript(script: ScriptRunResouce) {
console.log("runScript", script);
const exec = this.execScripts.get(script.uuid);
// 如果正在运行,先释放
if (exec) {
await this.stopScript(script.uuid);
}
return this.execScript(script, true);
}
init() {
this.api.on("enableScript", this.enableScript.bind(this));
this.api.on("disableScript", this.disableScript.bind(this));
this.api.on("runScript", this.runScript.bind(this));
this.api.on("stopScript", this.stopScript.bind(this));
}
}

View File

@ -1,13 +1,12 @@
import { Script, ScriptCode, ScriptRunResouce } from "@App/app/repo/scripts";
import { Client } from "@Packages/message/client";
import { InstallSource } from ".";
import { Broker } from "@Packages/message/message_queue";
import { Resource } from "@App/app/repo/resource";
import { MessageSend } from "@Packages/message/server";
export class ServiceWorkerClient extends Client {
constructor(msg: MessageSend) {
super(msg);
super(msg, "serviceWorker");
}
preparationOffscreen() {
@ -17,7 +16,7 @@ export class ServiceWorkerClient extends Client {
export class ScriptClient extends Client {
constructor(msg: MessageSend) {
super(msg, "script");
super(msg, "serviceWorker/script");
}
// 获取安装信息
@ -52,7 +51,7 @@ export class ScriptClient extends Client {
export class ResourceClient extends Client {
constructor(msg: MessageSend) {
super(msg, "resource");
super(msg, "serviceWorker/resource");
}
getScriptResources(script: Script): Promise<{ [key: string]: Resource }> {
@ -62,7 +61,7 @@ export class ResourceClient extends Client {
export class ValueClient extends Client {
constructor(msg: MessageSend) {
super(msg, "value");
super(msg, "serviceWorker/value");
}
getScriptValue(script: Script) {
@ -70,19 +69,16 @@ export class ValueClient extends Client {
}
}
export function subscribeScriptInstall(
border: Broker,
callback: (message: { script: Script; update: boolean }) => void
) {
return border.subscribe("installScript", callback);
}
export class RuntimeClient extends Client {
constructor(msg: MessageSend) {
super(msg, "serviceWorker/runtime");
}
export function subscribeScriptDelete(border: Broker, callback: (message: { uuid: string }) => void) {
return border.subscribe("deleteScript", callback);
}
runScript(uuid: string) {
return this.do("runScript", uuid);
}
export type ScriptEnableCallbackValue = { uuid: string; enable: boolean };
export function subscribeScriptEnable(border: Broker, callback: (message: ScriptEnableCallbackValue) => void) {
return border.subscribe("enableScript", callback);
stopScript(uuid: string) {
return this.do("stopScript", uuid);
}
}

View File

@ -44,7 +44,7 @@ export default class GMApi {
this.logger.trace("GM API request", { api: data.api, uuid: data.uuid, param: data.params });
const api = PermissionVerify.apis.get(data.api);
if (!api) {
return Promise.reject(new Error("api is not found"));
return Promise.reject(new Error("gm api is not found"));
}
const req = await this.parseRequest(data, { tabId: 0 });
try {

View File

@ -25,11 +25,11 @@ export default class ServiceWorkerManager {
const resource = new ResourceService(this.api.group("resource"), this.mq);
resource.init();
const value = new ValueService(this.api.group("value"), this.mq);
const value = new ValueService(this.api.group("value"));
value.init();
const script = new ScriptService(this.api.group("script"), this.mq, value, resource);
script.init();
const runtime = new RuntimeService(this.api.group("runtime"), this.sender, this.mq, value);
const runtime = new RuntimeService(this.api.group("runtime"), this.sender, this.mq, value, script);
runtime.init();
}
}

View File

@ -1,9 +1,11 @@
import { MessageQueue } from "@Packages/message/message_queue";
import { ScriptEnableCallbackValue } from "./client";
import { Group, MessageSend } from "@Packages/message/server";
import { Script, SCRIPT_STATUS_ENABLE, SCRIPT_TYPE_NORMAL, ScriptAndCode, ScriptDAO } from "@App/app/repo/scripts";
import { ValueService } from "./value";
import GMApi from "./gm_api";
import { subscribeScriptEnable } from "../queue";
import { ScriptService } from "./script";
import { runScript, stopScript } from "../offscreen/client";
export class RuntimeService {
scriptDAO: ScriptDAO = new ScriptDAO();
@ -12,12 +14,13 @@ export class RuntimeService {
private group: Group,
private sender: MessageSend,
private mq: MessageQueue,
private value: ValueService
private value: ValueService,
private script: ScriptService
) {}
async init() {
// 监听脚本开启
this.mq.addListener("enableScript", async (data: ScriptEnableCallbackValue) => {
subscribeScriptEnable(this.mq, async (data) => {
const script = await this.scriptDAO.getAndCode(data.uuid);
if (!script) {
return;
@ -44,7 +47,7 @@ export class RuntimeService {
this.mq.publish("enableScript", { uuid: script.uuid, enable: true });
});
// 监听offscreen环境初始化, 初始化完成后, 再将后台脚本运行起来
this.mq.addListener("preparationOffscreen", () => {
this.mq.subscribe("preparationOffscreen", () => {
list.forEach((script) => {
if (script.status !== SCRIPT_STATUS_ENABLE || script.type === SCRIPT_TYPE_NORMAL) {
return;
@ -56,6 +59,24 @@ export class RuntimeService {
// 启动gm api
const gmApi = new GMApi(this.group, this.sender, this.value);
gmApi.start();
this.group.on("stopScript", this.stopScript.bind(this));
this.group.on("runScript", this.runScript.bind(this));
}
// 停止脚本
stopScript(uuid: string) {
return stopScript(this.sender, uuid);
}
// 运行脚本
async runScript(uuid: string) {
const script = await this.scriptDAO.get(uuid);
if (!script) {
return;
}
const res = await this.script.buildScriptRunResource(script);
return runScript(this.sender, res);
}
registryPageScript(script: ScriptAndCode) {

View File

@ -235,7 +235,6 @@ export class ScriptService {
}
async updateRunStatus(params: { uuid: string; runStatus: SCRIPT_RUN_STATUS; error?: string; nextruntime?: number }) {
this.mq.publish("updateRunStatus", params);
if (
(await this.scriptDAO.update(params.uuid, {
runStatus: params.runStatus,
@ -246,6 +245,7 @@ export class ScriptService {
) {
return Promise.reject("update error");
}
this.mq.publish("scriptRunStatus", params);
return Promise.resolve(true);
}

View File

@ -3,7 +3,6 @@ import Logger from "@App/app/logger/logger";
import { Script, ScriptDAO } from "@App/app/repo/scripts";
import { ValueDAO } from "@App/app/repo/value";
import { storageKey } from "@App/runtime/utils";
import { MessageQueue } from "@Packages/message/message_queue";
import { Group } from "@Packages/message/server";
export class ValueService {
@ -11,10 +10,7 @@ export class ValueService {
scriptDAO: ScriptDAO = new ScriptDAO();
valueDAO: ValueDAO = new ValueDAO();
constructor(
private group: Group,
private mq: MessageQueue
) {
constructor(private group: Group) {
this.logger = LoggerCore.logger().with({ service: "value" });
}

View File

@ -13,6 +13,7 @@ import LoggerCore from "@App/app/logger/core.ts";
import { LoggerDAO } from "@App/app/repo/logger.ts";
import DBWriter from "@App/app/logger/db_writer.ts";
import registerEditor from "@App/pkg/utils/monaco-editor.ts";
import storeSubscribe from "../store/subscribe.ts";
// 初始化数据库
migrate();
@ -25,6 +26,8 @@ const loggerCore = new LoggerCore({
loggerCore.logger().debug("page start");
storeSubscribe();
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<Provider store={store}>

View File

@ -79,12 +79,14 @@ import {
selectScripts,
sortScript,
upsertScript,
requestStopScript,
requestRunScript,
} from "@App/pages/store/features/script";
import { selectScriptListColumnWidth } from "@App/pages/store/features/setting";
import { Broker } from "@Packages/message/message_queue";
import { subscribeScriptDelete, subscribeScriptInstall } from "@App/app/service/service_worker/client";
import { ExtensionMessageSend } from "@Packages/message/extension_message";
import { MessageConnect } from "@Packages/message/server";
import { MessageQueue, Unsubscribe } from "@Packages/message/message_queue";
import { subscribeScriptDelete, subscribeScriptInstall, subscribeScriptRunStatus } from "@App/app/service/queue";
import { RuntimeClient } from "@App/app/service/service_worker/client";
import { ExtensionMessage, ExtensionMessageSend } from "@Packages/message/extension_message";
type ListType = Script & { loading?: boolean };
@ -105,43 +107,10 @@ function ScriptList() {
const [action, setAction] = useState("");
const [select, setSelect] = useState<Script[]>([]);
const [selectColumn, setSelectColumn] = useState(0);
const { t } = useTranslation();
useEffect(() => {
dispatch(fetchAndSortScriptList());
// 监听脚本安装/运行
const msg = new ExtensionMessageSend();
const border = new Broker(msg);
const subCon: MessageConnect[] = [];
subscribeScriptInstall(border, (message) => {
dispatch(upsertScript(message.script));
}).then((con) => subCon.push(con));
subscribeScriptDelete(border, (message) => {
dispatch(deleteScript(message.uuid));
}).then((con) => subCon.push(con));
return () => {
subCon.forEach((con) => {
con.disconnect();
});
};
// const channel = runtimeCtrl.watchRunStatus();
// channel.setHandler(([id, status]: any) => {
// setScriptList((list) => {
// return list.map((item) => {
// if (item.id === id) {
// item.runStatus = status;
// }
// return item;
// });
// });
// });
// return () => {
// channel.disChannel();
// };
}, [dispatch]);
const columns: ColumnProps[] = [
@ -314,7 +283,7 @@ function ScriptList() {
if (item.type === SCRIPT_TYPE_BACKGROUND) {
tooltip = t("background_script_tooltip");
} else {
tooltip = `${t("scheduled_script_tooltip")} ${nextTime(item.metadata.crontab[0])}`;
tooltip = `${t("scheduled_script_tooltip")} ${nextTime(item.metadata!.crontab![0])}`;
}
return (
<Tooltip content={tooltip}>
@ -532,19 +501,28 @@ function ScriptList() {
onClick={async () => {
if (item.runStatus === SCRIPT_RUN_STATUS_RUNNING) {
// Stop script
Message.loading({
id: "script-stop",
content: t("stopping_script"),
});
await dispatch(requestStopScript(item.uuid));
Message.success({
id: "script-stop",
content: t("script_stopped"),
duration: 3000,
});
} else {
Message.loading({
id: "script-run",
content: t("starting_script"),
});
await dispatch(requestRunScript(item.uuid));
Message.success({
id: "script-run",
content: t("script_started"),
duration: 3000,
});
}
console.log(item.runStatus);
// Stop script
// Message.loading({
// id: "script-stop",
// content: t("stopping_script"),
// });
// await runtimeCtrl.stopScript(item.id);
// Message.success({
// id: "script-stop",
// content: t("script_stopped"),
// duration: 3000,
// });
}}
style={{
color: "var(--color-text-2)",

View File

@ -1,11 +1,18 @@
import { createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { createAppSlice } from "../hooks";
import { Script, SCRIPT_STATUS_DISABLE, SCRIPT_STATUS_ENABLE, ScriptDAO } from "@App/app/repo/scripts";
import {
Script,
SCRIPT_RUN_STATUS,
SCRIPT_STATUS_DISABLE,
SCRIPT_STATUS_ENABLE,
ScriptDAO,
} from "@App/app/repo/scripts";
import { arrayMove } from "@dnd-kit/sortable";
import { ScriptClient } from "@App/app/service/service_worker/client";
import { RuntimeClient, ScriptClient } from "@App/app/service/service_worker/client";
import { message } from "../global";
export const scriptClient = new ScriptClient(message);
export const runtimeClient = new RuntimeClient(message);
export const fetchAndSortScriptList = createAsyncThunk("script/fetchScriptList", async () => {
// 排序
@ -28,6 +35,14 @@ export const requestEnableScript = createAsyncThunk(
}
);
export const requestRunScript = createAsyncThunk("script/runScript", async (uuid: string) => {
return await runtimeClient.runScript(uuid);
});
export const requestStopScript = createAsyncThunk("script/stopScript", async (uuid: string) => {
return await runtimeClient.stopScript(uuid);
});
export const requestDeleteScript = createAsyncThunk("script/deleteScript", async (uuid: string) => {
return scriptClient.delete(uuid);
});
@ -70,12 +85,19 @@ export const scriptSlice = createAppSlice({
}
state.scripts = newItems;
},
updateRunStatus: (state, action: PayloadAction<{ uuid: string; runStatus: SCRIPT_RUN_STATUS }>) => {
const script = state.scripts.find((s) => s.uuid === action.payload.uuid);
if (script) {
script.runStatus = action.payload.runStatus;
}
},
},
extraReducers: (builder) => {
builder
.addCase(fetchAndSortScriptList.fulfilled, (state, action) => {
state.scripts = action.payload;
})
// 处理enableScript
.addCase(requestEnableScript.fulfilled, (state, action) => {
updateScript(state.scripts, action.meta.arg.uuid, (script) => {
script.enableLoading = false;
@ -85,11 +107,25 @@ export const scriptSlice = createAppSlice({
.addCase(requestEnableScript.pending, (state, action) =>
updateScript(state.scripts, action.meta.arg.uuid, (s) => (s.enableLoading = true))
)
// 处理deleteScript
.addCase(requestDeleteScript.fulfilled, (state, action) => {
state.scripts = state.scripts.filter((s) => s.uuid !== action.meta.arg);
})
.addCase(requestDeleteScript.pending, (state, action) =>
updateScript(state.scripts, action.meta.arg, (s) => (s.actionLoading = true))
)
// 处理runScript和stopScript
.addCase(requestRunScript.pending, (state, action) =>
updateScript(state.scripts, action.meta.arg, (s) => (s.actionLoading = true))
)
.addCase(requestRunScript.fulfilled, (state, action) =>
updateScript(state.scripts, action.meta.arg, (s) => (s.actionLoading = false))
)
.addCase(requestStopScript.pending, (state, action) =>
updateScript(state.scripts, action.meta.arg, (s) => (s.actionLoading = true))
)
.addCase(requestStopScript.fulfilled, (state, action) =>
updateScript(state.scripts, action.meta.arg, (s) => (s.actionLoading = false))
);
},
selectors: {

View File

@ -1,3 +1,5 @@
import { ExtensionMessage } from "@Packages/message/extension_message";
import { MessageQueue } from "@Packages/message/message_queue";
export const message = new ExtensionMessage();
export const messageQueue = new MessageQueue();

View File

@ -0,0 +1,18 @@
import { subscribeScriptDelete, subscribeScriptInstall, subscribeScriptRunStatus } from "@App/app/service/queue";
import { messageQueue } from "./global";
import { store } from "./store";
import { deleteScript, scriptSlice, upsertScript } from "./features/script";
export default function storeSubscribe() {
subscribeScriptRunStatus(messageQueue, (data) => {
console.log("subscribeScriptRunStatus", data);
store.dispatch(scriptSlice.actions.updateRunStatus(data));
});
subscribeScriptInstall(messageQueue, (message) => {
store.dispatch(upsertScript(message.script));
});
subscribeScriptDelete(messageQueue, (message) => {
store.dispatch(deleteScript(message.uuid));
});
}

View File

@ -55,8 +55,8 @@ async function main() {
});
loggerCore.logger().debug("service worker start");
// 初始化管理器
const server = new Server(new ExtensionMessage());
const manager = new ServiceWorkerManager(server, new MessageQueue(server), new ServiceWorkerMessageSend());
const server = new Server("serviceWorker", new ExtensionMessage());
const manager = new ServiceWorkerManager(server, new MessageQueue(), new ServiceWorkerMessageSend());
manager.initManager();
// 初始化沙盒环境
await setupOffscreenDocument();

View File

@ -5,7 +5,6 @@ import migrate from "@App/app/migrate";
import { LoggerDAO } from "@App/app/repo/logger";
import { MockMessage } from "@Packages/message/mock_message";
import { Message, Server } from "@Packages/message/server";
import { MessageQueue } from "@Packages/message/message_queue";
import { ValueService } from "@App/app/service/service_worker/value";
import GMApi from "@App/app/service/service_worker/gm_api";
import OffscreenGMApi from "@App/app/service/offscreen/gm_api";
@ -57,8 +56,7 @@ export function initTestGMApi(): Message {
const osMessage = new MockMessage(osEE);
const serviceWorkerServer = new Server(wsMessage);
const mq = new MessageQueue(serviceWorkerServer);
const valueService = new ValueService(serviceWorkerServer.group("value"), mq);
const valueService = new ValueService(serviceWorkerServer.group("value"));
const swGMApi = new GMApi(serviceWorkerServer.group("runtime"), osMessage, valueService);
valueService.init();