调整通信
Some checks failed
test / Run tests (push) Failing after 15s
build / Build (push) Failing after 19s
Some checks failed
test / Run tests (push) Failing after 15s
build / Build (push) Failing after 19s
This commit is contained in:
parent
131f1bda40
commit
57bef5a023
@ -6,5 +6,11 @@
|
|||||||
|
|
||||||
- 从脚本发起的GM请求,需要层层传递到service_worker/offscreen进行处理,有的GM只需要进行一次调用获取一次结果,有的需要进行
|
- 从脚本发起的GM请求,需要层层传递到service_worker/offscreen进行处理,有的GM只需要进行一次调用获取一次结果,有的需要进行
|
||||||
多次调用获取多次结果,使用connect的方式实现
|
多次调用获取多次结果,使用connect的方式实现
|
||||||
- 从service_woker/offscreen发起的请求,类似消息队列,其它页面进行监听,触发后广播给所有页面,使用connect方式实现
|
- 从service_worker/offscreen发起的请求,类似消息队列,其它页面进行监听,触发后广播给所有页面,使用sendMessage方式实现
|
||||||
- 从扩展页面发起的请求,需要传递到service_worker/offscreen进行处理,如果只是单次调用,获取一次结果,使用message方式实现
|
- 从扩展页面发起的请求,需要传递到service_worker/offscreen进行处理,如果只是单次调用,获取一次结果,使用sendMessage方式实现,如果需要
|
||||||
|
多次调用获取多次结果,使用connect方式实现
|
||||||
|
|
||||||
|
## 注意点
|
||||||
|
|
||||||
|
- service_worker和offscreen之间可以使用postMessage的方式进行通信,避免同时监听message与connect导致冲突的问题
|
||||||
|
- service_worker会变为不活动的状态,尽量避免与service_worker建立长连接
|
||||||
|
@ -35,6 +35,9 @@ export class ExtensionMessage extends ExtensionMessageSend implements Message {
|
|||||||
// 注意chrome.runtime.onMessage.addListener的回调函数需要返回true才能处理异步请求
|
// 注意chrome.runtime.onMessage.addListener的回调函数需要返回true才能处理异步请求
|
||||||
onMessage(callback: (data: any, sendResponse: (data: any) => void) => void) {
|
onMessage(callback: (data: any, sendResponse: (data: any) => void) => void) {
|
||||||
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
||||||
|
if (msg.action === "messageQueue") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
return callback(msg, sendResponse);
|
return callback(msg, sendResponse);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -1,98 +1,57 @@
|
|||||||
import EventEmitter from "eventemitter3";
|
import EventEmitter from "eventemitter3";
|
||||||
import { ApiFunction, MessageConnect, MessageSend, Server } from "./server";
|
|
||||||
import { sendMessage } from "./client";
|
|
||||||
import Logger from "@App/app/logger/logger";
|
import Logger from "@App/app/logger/logger";
|
||||||
import LoggerCore from "@App/app/logger/core";
|
import LoggerCore from "@App/app/logger/core";
|
||||||
|
|
||||||
export type SubscribeCallback = (message: any) => void;
|
export type SubscribeCallback = (message: any) => void;
|
||||||
|
// 释放订阅
|
||||||
export class Broker {
|
export type Unsubscribe = () => void;
|
||||||
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 class MessageQueue {
|
export class MessageQueue {
|
||||||
topicConMap: Map<string, { name: string; con: MessageConnect }[]> = new Map();
|
|
||||||
|
|
||||||
private EE: EventEmitter = new EventEmitter();
|
private EE: EventEmitter = new EventEmitter();
|
||||||
|
|
||||||
logger: Logger;
|
constructor() {
|
||||||
constructor(api: Server) {
|
chrome.runtime.onMessage.addListener((msg) => {
|
||||||
api.on("messageQueue", this.handler());
|
if (msg.action === "messageQueue") {
|
||||||
this.logger = LoggerCore.getInstance().logger({ service: "messageQueue" });
|
this.handler(msg.data);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
handler(): ApiFunction {
|
handler({ action, topic, message }: { action: string; topic: string; message: any }) {
|
||||||
return ({ action, topic, message }: { action: string; topic: string; message: any }, con) => {
|
LoggerCore.getInstance()
|
||||||
this.logger.trace("messageQueueHandler", { action, topic, message });
|
.logger({ service: "messageQueue" })
|
||||||
if (!con) {
|
.trace("messageQueueHandler", { action, topic, message });
|
||||||
throw new Error("con is required");
|
if (!topic) {
|
||||||
}
|
throw new Error("topic is required");
|
||||||
if (!topic) {
|
}
|
||||||
throw new Error("topic is required");
|
switch (action) {
|
||||||
}
|
case "message":
|
||||||
switch (action) {
|
this.EE.emit(topic, message);
|
||||||
case "subscribe":
|
break;
|
||||||
this.subscribe(topic, con as MessageConnect);
|
default:
|
||||||
break;
|
throw new Error("action not found");
|
||||||
case "publish":
|
}
|
||||||
this.publish(topic, message);
|
}
|
||||||
break;
|
|
||||||
default:
|
subscribe(topic: string, handler: SubscribeCallback): Unsubscribe {
|
||||||
throw new Error("action not found");
|
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) {
|
publish(topic: string, message: any) {
|
||||||
const list = this.topicConMap.get(topic);
|
chrome.runtime.sendMessage({
|
||||||
list?.forEach((item) => {
|
action: "messageQueue",
|
||||||
item.con.sendMessage({ action: "message", topic, message });
|
data: { action: "message", topic, message },
|
||||||
});
|
});
|
||||||
this.EE.emit(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) {
|
emit(topic: string, message: any) {
|
||||||
this.EE.emit(topic, message);
|
this.EE.emit(topic, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 同环境下使用addListener
|
|
||||||
addListener(topic: string, handler: (message: any) => void) {
|
|
||||||
this.EE.on(topic, handler);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -28,15 +28,21 @@ export class Server {
|
|||||||
|
|
||||||
private logger = LoggerCore.getInstance().logger({ service: "messageServer" });
|
private logger = LoggerCore.getInstance().logger({ service: "messageServer" });
|
||||||
|
|
||||||
constructor(message: Message) {
|
constructor(prefix: string, message: Message) {
|
||||||
message.onConnect((msg: any, con: MessageConnect) => {
|
message.onConnect((msg: any, con: MessageConnect) => {
|
||||||
this.logger.trace("server onConnect", { msg });
|
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) => {
|
message.onMessage((msg: { action: string; data: any }, sendResponse) => {
|
||||||
this.logger.trace("server onMessage", { msg });
|
this.logger.trace("server onMessage", { msg: msg as any });
|
||||||
return this.messageHandle(msg.action, msg.data, sendResponse);
|
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) => {
|
from.on(path, (params, fromCon) => {
|
||||||
|
console.log("forwardMessage", path, prefix, params);
|
||||||
if (fromCon) {
|
if (fromCon) {
|
||||||
to.connect({ action: path, data: params }).then((toCon) => {
|
to.connect({ action: prefix + "/" + path, data: params }).then((toCon) => {
|
||||||
fromCon.onMessage((data) => {
|
fromCon.onMessage((data) => {
|
||||||
toCon.sendMessage(data);
|
toCon.sendMessage(data);
|
||||||
});
|
});
|
||||||
@ -116,7 +123,7 @@ export function forwardMessage(path: string, from: Server, to: MessageSend) {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
return to.sendMessage({ action: path, data: params });
|
return to.sendMessage({ action: prefix + "/" + path, data: params });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -171,7 +171,6 @@ export class ServiceWorkerMessageSend implements MessageSend {
|
|||||||
const list = await self.clients.matchAll({ includeUncontrolled: true, type: "window" });
|
const list = await self.clients.matchAll({ includeUncontrolled: true, type: "window" });
|
||||||
this.target = list[0];
|
this.target = list[0];
|
||||||
self.addEventListener("message", (e) => {
|
self.addEventListener("message", (e) => {
|
||||||
console.log("serviceWorker", e);
|
|
||||||
this.messageHandle(e.data);
|
this.messageHandle(e.data);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -39,7 +39,7 @@ export default class LoggerCore {
|
|||||||
this.labels = config.labels || {};
|
this.labels = config.labels || {};
|
||||||
// 获取日志debug等级, 如果是开发环境, 则默认为trace
|
// 获取日志debug等级, 如果是开发环境, 则默认为trace
|
||||||
if (process.env.NODE_ENV === "development") {
|
if (process.env.NODE_ENV === "development") {
|
||||||
this.debug = "debug";
|
this.debug = "trace";
|
||||||
}
|
}
|
||||||
if (!LoggerCore.instance) {
|
if (!LoggerCore.instance) {
|
||||||
LoggerCore.instance = this;
|
LoggerCore.instance = this;
|
||||||
|
@ -50,7 +50,7 @@ export default class Logger {
|
|||||||
console.warn(msg);
|
console.warn(msg);
|
||||||
break;
|
break;
|
||||||
case "trace":
|
case "trace":
|
||||||
console.trace(msg);
|
console.info(msg);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
console.info(msg);
|
console.info(msg);
|
||||||
|
@ -1,19 +1,20 @@
|
|||||||
import { WindowMessage } from "@Packages/message/window_message";
|
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 { sendMessage } from "@Packages/message/client";
|
||||||
|
import { MessageSend } from "@Packages/message/server";
|
||||||
|
|
||||||
export function preparationSandbox(msg: WindowMessage) {
|
export function preparationSandbox(msg: WindowMessage) {
|
||||||
return sendMessage(msg, "preparationSandbox");
|
return sendMessage(msg, "offscreen/preparationSandbox");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 代理发送消息到ServiceWorker
|
// 代理发送消息到ServiceWorker
|
||||||
export function sendMessageToServiceWorker(msg: WindowMessage, action: string, data?: any) {
|
export function sendMessageToServiceWorker(msg: WindowMessage, action: string, data?: any) {
|
||||||
return sendMessage(msg, "sendMessageToServiceWorker", { action, data });
|
return sendMessage(msg, "offscreen/sendMessageToServiceWorker", { action, data });
|
||||||
}
|
}
|
||||||
|
|
||||||
// 代理连接ServiceWorker
|
// 代理连接ServiceWorker
|
||||||
export function connectServiceWorker(msg: WindowMessage) {
|
export function connectServiceWorker(msg: WindowMessage) {
|
||||||
return sendMessage(msg, "connectServiceWorker");
|
return sendMessage(msg, "offscreen/connectServiceWorker");
|
||||||
}
|
}
|
||||||
|
|
||||||
export function proxyUpdateRunStatus(
|
export function proxyUpdateRunStatus(
|
||||||
@ -22,3 +23,11 @@ export function proxyUpdateRunStatus(
|
|||||||
) {
|
) {
|
||||||
return sendMessageToServiceWorker(msg, "script/updateRunStatus", data);
|
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);
|
||||||
|
}
|
||||||
|
@ -1,12 +1,12 @@
|
|||||||
import { forwardMessage, MessageSend, Server } from "@Packages/message/server";
|
import { forwardMessage, MessageSend, Server } from "@Packages/message/server";
|
||||||
import { ScriptService } from "./script";
|
import { ScriptService } from "./script";
|
||||||
import { Broker } from "@Packages/message/message_queue";
|
|
||||||
import { Logger, LoggerDAO } from "@App/app/repo/logger";
|
import { Logger, LoggerDAO } from "@App/app/repo/logger";
|
||||||
import { WindowMessage } from "@Packages/message/window_message";
|
import { WindowMessage } from "@Packages/message/window_message";
|
||||||
import { ExtensionMessageSend } from "@Packages/message/extension_message";
|
import { ExtensionMessageSend } from "@Packages/message/extension_message";
|
||||||
import { ServiceWorkerClient } from "../service_worker/client";
|
import { ServiceWorkerClient } from "../service_worker/client";
|
||||||
import { sendMessage } from "@Packages/message/client";
|
import { sendMessage } from "@Packages/message/client";
|
||||||
import GMApi from "./gm_api";
|
import GMApi from "./gm_api";
|
||||||
|
import { MessageQueue } from "@Packages/message/message_queue";
|
||||||
|
|
||||||
// offscreen环境的管理器
|
// offscreen环境的管理器
|
||||||
export class OffscreenManager {
|
export class OffscreenManager {
|
||||||
@ -14,9 +14,9 @@ export class OffscreenManager {
|
|||||||
|
|
||||||
private windowMessage = new WindowMessage(window, sandbox, true);
|
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);
|
private serviceWorker = new ServiceWorkerClient(this.extensionMessage);
|
||||||
|
|
||||||
@ -31,7 +31,7 @@ export class OffscreenManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sendMessageToServiceWorker(data: { action: string; data: any }) {
|
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() {
|
async initManager() {
|
||||||
@ -39,10 +39,17 @@ export class OffscreenManager {
|
|||||||
this.windowApi.on("logger", this.logger.bind(this));
|
this.windowApi.on("logger", this.logger.bind(this));
|
||||||
this.windowApi.on("preparationSandbox", this.preparationSandbox.bind(this));
|
this.windowApi.on("preparationSandbox", this.preparationSandbox.bind(this));
|
||||||
this.windowApi.on("sendMessageToServiceWorker", this.sendMessageToServiceWorker.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();
|
script.init();
|
||||||
// 转发gm api请求
|
// 转发从sandbox来的gm api请求
|
||||||
forwardMessage("runtime/gmApi", this.windowApi, this.extensionMessage);
|
forwardMessage("serviceWorker", "runtime/gmApi", this.windowApi, this.extensionMessage);
|
||||||
|
// 转发message queue请求
|
||||||
|
|
||||||
const gmApi = new GMApi(this.windowApi.group("gmApi"));
|
const gmApi = new GMApi(this.windowApi.group("gmApi"));
|
||||||
gmApi.init();
|
gmApi.init();
|
||||||
|
|
||||||
|
@ -1,17 +1,12 @@
|
|||||||
import LoggerCore from "@App/app/logger/core";
|
import LoggerCore from "@App/app/logger/core";
|
||||||
import Logger from "@App/app/logger/logger";
|
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 { WindowMessage } from "@Packages/message/window_message";
|
||||||
import {
|
import { ResourceClient, ScriptClient, ValueClient } from "../service_worker/client";
|
||||||
ResourceClient,
|
import { SCRIPT_STATUS_ENABLE, SCRIPT_TYPE_NORMAL, ScriptRunResouce } from "@App/app/repo/scripts";
|
||||||
ScriptClient,
|
import { disableScript, enableScript, runScript, stopScript } from "../sandbox/client";
|
||||||
subscribeScriptEnable,
|
import { Group, MessageSend } from "@Packages/message/server";
|
||||||
subscribeScriptInstall,
|
import { subscribeScriptEnable, subscribeScriptInstall } from "../queue";
|
||||||
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";
|
|
||||||
|
|
||||||
export class ScriptService {
|
export class ScriptService {
|
||||||
logger: Logger;
|
logger: Logger;
|
||||||
@ -21,15 +16,25 @@ export class ScriptService {
|
|||||||
valueClient: ValueClient = new ValueClient(this.extensionMessage);
|
valueClient: ValueClient = new ValueClient(this.extensionMessage);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
|
private group: Group,
|
||||||
private extensionMessage: MessageSend,
|
private extensionMessage: MessageSend,
|
||||||
private windowMessage: WindowMessage,
|
private windowMessage: WindowMessage,
|
||||||
private broker: Broker
|
private messageQueue: MessageQueue
|
||||||
) {
|
) {
|
||||||
this.logger = LoggerCore.logger().with({ service: "script" });
|
this.logger = LoggerCore.logger().with({ service: "script" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
runScript(script: ScriptRunResouce) {
|
||||||
|
runScript(this.windowMessage, script);
|
||||||
|
}
|
||||||
|
|
||||||
|
stopScript(uuid: string) {
|
||||||
|
stopScript(this.windowMessage, uuid);
|
||||||
|
}
|
||||||
|
|
||||||
async init() {
|
async init() {
|
||||||
subscribeScriptEnable(this.broker, async (data) => {
|
subscribeScriptEnable(this.messageQueue, async (data) => {
|
||||||
|
console.log("subscribeScriptEnable", data);
|
||||||
const script = await this.scriptClient.info(data.uuid);
|
const script = await this.scriptClient.info(data.uuid);
|
||||||
if (script.type === SCRIPT_TYPE_NORMAL) {
|
if (script.type === SCRIPT_TYPE_NORMAL) {
|
||||||
return;
|
return;
|
||||||
@ -42,7 +47,8 @@ export class ScriptService {
|
|||||||
disableScript(this.windowMessage, script.uuid);
|
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) {
|
if (data.script.status === SCRIPT_STATUS_ENABLE) {
|
||||||
// 构造脚本运行资源,发送给沙盒运行
|
// 构造脚本运行资源,发送给沙盒运行
|
||||||
@ -52,5 +58,8 @@ export class ScriptService {
|
|||||||
disableScript(this.windowMessage, data.script.uuid);
|
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
29
src/app/service/queue.ts
Normal 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);
|
||||||
|
}
|
@ -3,9 +3,17 @@ import { sendMessage } from "@Packages/message/client";
|
|||||||
import { WindowMessage } from "@Packages/message/window_message";
|
import { WindowMessage } from "@Packages/message/window_message";
|
||||||
|
|
||||||
export function enableScript(msg: WindowMessage, data: ScriptRunResouce) {
|
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) {
|
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);
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,7 @@ import { Runtime } from "./runtime";
|
|||||||
|
|
||||||
// sandbox环境的管理器
|
// sandbox环境的管理器
|
||||||
export class SandboxManager {
|
export class SandboxManager {
|
||||||
api: Server = new Server(this.windowMessage);
|
api: Server = new Server("sandbox", this.windowMessage);
|
||||||
|
|
||||||
constructor(private windowMessage: WindowMessage) {}
|
constructor(private windowMessage: WindowMessage) {}
|
||||||
|
|
||||||
|
@ -269,18 +269,32 @@ export class Runtime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
stopScript(uuid: string) {
|
async stopScript(uuid: string) {
|
||||||
const exec = this.execScripts.get(uuid);
|
const exec = this.execScripts.get(uuid);
|
||||||
if (!exec) {
|
if (!exec) {
|
||||||
|
proxyUpdateRunStatus(this.windowMessage, { uuid: uuid, runStatus: SCRIPT_RUN_STATUS_COMPLETE });
|
||||||
return Promise.resolve(false);
|
return Promise.resolve(false);
|
||||||
}
|
}
|
||||||
exec.stop();
|
exec.stop();
|
||||||
this.execScripts.delete(uuid);
|
this.execScripts.delete(uuid);
|
||||||
|
proxyUpdateRunStatus(this.windowMessage, { uuid: uuid, runStatus: SCRIPT_RUN_STATUS_COMPLETE });
|
||||||
return Promise.resolve(true);
|
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() {
|
init() {
|
||||||
this.api.on("enableScript", this.enableScript.bind(this));
|
this.api.on("enableScript", this.enableScript.bind(this));
|
||||||
this.api.on("disableScript", this.disableScript.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));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,12 @@
|
|||||||
import { Script, ScriptCode, ScriptRunResouce } from "@App/app/repo/scripts";
|
import { Script, ScriptCode, ScriptRunResouce } from "@App/app/repo/scripts";
|
||||||
import { Client } from "@Packages/message/client";
|
import { Client } from "@Packages/message/client";
|
||||||
import { InstallSource } from ".";
|
import { InstallSource } from ".";
|
||||||
import { Broker } from "@Packages/message/message_queue";
|
|
||||||
import { Resource } from "@App/app/repo/resource";
|
import { Resource } from "@App/app/repo/resource";
|
||||||
import { MessageSend } from "@Packages/message/server";
|
import { MessageSend } from "@Packages/message/server";
|
||||||
|
|
||||||
export class ServiceWorkerClient extends Client {
|
export class ServiceWorkerClient extends Client {
|
||||||
constructor(msg: MessageSend) {
|
constructor(msg: MessageSend) {
|
||||||
super(msg);
|
super(msg, "serviceWorker");
|
||||||
}
|
}
|
||||||
|
|
||||||
preparationOffscreen() {
|
preparationOffscreen() {
|
||||||
@ -17,7 +16,7 @@ export class ServiceWorkerClient extends Client {
|
|||||||
|
|
||||||
export class ScriptClient extends Client {
|
export class ScriptClient extends Client {
|
||||||
constructor(msg: MessageSend) {
|
constructor(msg: MessageSend) {
|
||||||
super(msg, "script");
|
super(msg, "serviceWorker/script");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取安装信息
|
// 获取安装信息
|
||||||
@ -52,7 +51,7 @@ export class ScriptClient extends Client {
|
|||||||
|
|
||||||
export class ResourceClient extends Client {
|
export class ResourceClient extends Client {
|
||||||
constructor(msg: MessageSend) {
|
constructor(msg: MessageSend) {
|
||||||
super(msg, "resource");
|
super(msg, "serviceWorker/resource");
|
||||||
}
|
}
|
||||||
|
|
||||||
getScriptResources(script: Script): Promise<{ [key: string]: Resource }> {
|
getScriptResources(script: Script): Promise<{ [key: string]: Resource }> {
|
||||||
@ -62,7 +61,7 @@ export class ResourceClient extends Client {
|
|||||||
|
|
||||||
export class ValueClient extends Client {
|
export class ValueClient extends Client {
|
||||||
constructor(msg: MessageSend) {
|
constructor(msg: MessageSend) {
|
||||||
super(msg, "value");
|
super(msg, "serviceWorker/value");
|
||||||
}
|
}
|
||||||
|
|
||||||
getScriptValue(script: Script) {
|
getScriptValue(script: Script) {
|
||||||
@ -70,19 +69,16 @@ export class ValueClient extends Client {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function subscribeScriptInstall(
|
export class RuntimeClient extends Client {
|
||||||
border: Broker,
|
constructor(msg: MessageSend) {
|
||||||
callback: (message: { script: Script; update: boolean }) => void
|
super(msg, "serviceWorker/runtime");
|
||||||
) {
|
}
|
||||||
return border.subscribe("installScript", callback);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function subscribeScriptDelete(border: Broker, callback: (message: { uuid: string }) => void) {
|
runScript(uuid: string) {
|
||||||
return border.subscribe("deleteScript", callback);
|
return this.do("runScript", uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ScriptEnableCallbackValue = { uuid: string; enable: boolean };
|
stopScript(uuid: string) {
|
||||||
|
return this.do("stopScript", uuid);
|
||||||
export function subscribeScriptEnable(border: Broker, callback: (message: ScriptEnableCallbackValue) => void) {
|
}
|
||||||
return border.subscribe("enableScript", callback);
|
|
||||||
}
|
}
|
||||||
|
@ -44,7 +44,7 @@ export default class GMApi {
|
|||||||
this.logger.trace("GM API request", { api: data.api, uuid: data.uuid, param: data.params });
|
this.logger.trace("GM API request", { api: data.api, uuid: data.uuid, param: data.params });
|
||||||
const api = PermissionVerify.apis.get(data.api);
|
const api = PermissionVerify.apis.get(data.api);
|
||||||
if (!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 });
|
const req = await this.parseRequest(data, { tabId: 0 });
|
||||||
try {
|
try {
|
||||||
|
@ -25,11 +25,11 @@ export default class ServiceWorkerManager {
|
|||||||
|
|
||||||
const resource = new ResourceService(this.api.group("resource"), this.mq);
|
const resource = new ResourceService(this.api.group("resource"), this.mq);
|
||||||
resource.init();
|
resource.init();
|
||||||
const value = new ValueService(this.api.group("value"), this.mq);
|
const value = new ValueService(this.api.group("value"));
|
||||||
value.init();
|
value.init();
|
||||||
const script = new ScriptService(this.api.group("script"), this.mq, value, resource);
|
const script = new ScriptService(this.api.group("script"), this.mq, value, resource);
|
||||||
script.init();
|
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();
|
runtime.init();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,11 @@
|
|||||||
import { MessageQueue } from "@Packages/message/message_queue";
|
import { MessageQueue } from "@Packages/message/message_queue";
|
||||||
import { ScriptEnableCallbackValue } from "./client";
|
|
||||||
import { Group, MessageSend } from "@Packages/message/server";
|
import { Group, MessageSend } from "@Packages/message/server";
|
||||||
import { Script, SCRIPT_STATUS_ENABLE, SCRIPT_TYPE_NORMAL, ScriptAndCode, ScriptDAO } from "@App/app/repo/scripts";
|
import { Script, SCRIPT_STATUS_ENABLE, SCRIPT_TYPE_NORMAL, ScriptAndCode, ScriptDAO } from "@App/app/repo/scripts";
|
||||||
import { ValueService } from "./value";
|
import { ValueService } from "./value";
|
||||||
import GMApi from "./gm_api";
|
import GMApi from "./gm_api";
|
||||||
|
import { subscribeScriptEnable } from "../queue";
|
||||||
|
import { ScriptService } from "./script";
|
||||||
|
import { runScript, stopScript } from "../offscreen/client";
|
||||||
|
|
||||||
export class RuntimeService {
|
export class RuntimeService {
|
||||||
scriptDAO: ScriptDAO = new ScriptDAO();
|
scriptDAO: ScriptDAO = new ScriptDAO();
|
||||||
@ -12,12 +14,13 @@ export class RuntimeService {
|
|||||||
private group: Group,
|
private group: Group,
|
||||||
private sender: MessageSend,
|
private sender: MessageSend,
|
||||||
private mq: MessageQueue,
|
private mq: MessageQueue,
|
||||||
private value: ValueService
|
private value: ValueService,
|
||||||
|
private script: ScriptService
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async init() {
|
async init() {
|
||||||
// 监听脚本开启
|
// 监听脚本开启
|
||||||
this.mq.addListener("enableScript", async (data: ScriptEnableCallbackValue) => {
|
subscribeScriptEnable(this.mq, async (data) => {
|
||||||
const script = await this.scriptDAO.getAndCode(data.uuid);
|
const script = await this.scriptDAO.getAndCode(data.uuid);
|
||||||
if (!script) {
|
if (!script) {
|
||||||
return;
|
return;
|
||||||
@ -44,7 +47,7 @@ export class RuntimeService {
|
|||||||
this.mq.publish("enableScript", { uuid: script.uuid, enable: true });
|
this.mq.publish("enableScript", { uuid: script.uuid, enable: true });
|
||||||
});
|
});
|
||||||
// 监听offscreen环境初始化, 初始化完成后, 再将后台脚本运行起来
|
// 监听offscreen环境初始化, 初始化完成后, 再将后台脚本运行起来
|
||||||
this.mq.addListener("preparationOffscreen", () => {
|
this.mq.subscribe("preparationOffscreen", () => {
|
||||||
list.forEach((script) => {
|
list.forEach((script) => {
|
||||||
if (script.status !== SCRIPT_STATUS_ENABLE || script.type === SCRIPT_TYPE_NORMAL) {
|
if (script.status !== SCRIPT_STATUS_ENABLE || script.type === SCRIPT_TYPE_NORMAL) {
|
||||||
return;
|
return;
|
||||||
@ -56,6 +59,24 @@ export class RuntimeService {
|
|||||||
// 启动gm api
|
// 启动gm api
|
||||||
const gmApi = new GMApi(this.group, this.sender, this.value);
|
const gmApi = new GMApi(this.group, this.sender, this.value);
|
||||||
gmApi.start();
|
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) {
|
registryPageScript(script: ScriptAndCode) {
|
||||||
|
@ -235,7 +235,6 @@ export class ScriptService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async updateRunStatus(params: { uuid: string; runStatus: SCRIPT_RUN_STATUS; error?: string; nextruntime?: number }) {
|
async updateRunStatus(params: { uuid: string; runStatus: SCRIPT_RUN_STATUS; error?: string; nextruntime?: number }) {
|
||||||
this.mq.publish("updateRunStatus", params);
|
|
||||||
if (
|
if (
|
||||||
(await this.scriptDAO.update(params.uuid, {
|
(await this.scriptDAO.update(params.uuid, {
|
||||||
runStatus: params.runStatus,
|
runStatus: params.runStatus,
|
||||||
@ -246,6 +245,7 @@ export class ScriptService {
|
|||||||
) {
|
) {
|
||||||
return Promise.reject("update error");
|
return Promise.reject("update error");
|
||||||
}
|
}
|
||||||
|
this.mq.publish("scriptRunStatus", params);
|
||||||
return Promise.resolve(true);
|
return Promise.resolve(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,7 +3,6 @@ import Logger from "@App/app/logger/logger";
|
|||||||
import { Script, ScriptDAO } from "@App/app/repo/scripts";
|
import { Script, ScriptDAO } from "@App/app/repo/scripts";
|
||||||
import { ValueDAO } from "@App/app/repo/value";
|
import { ValueDAO } from "@App/app/repo/value";
|
||||||
import { storageKey } from "@App/runtime/utils";
|
import { storageKey } from "@App/runtime/utils";
|
||||||
import { MessageQueue } from "@Packages/message/message_queue";
|
|
||||||
import { Group } from "@Packages/message/server";
|
import { Group } from "@Packages/message/server";
|
||||||
|
|
||||||
export class ValueService {
|
export class ValueService {
|
||||||
@ -11,10 +10,7 @@ export class ValueService {
|
|||||||
scriptDAO: ScriptDAO = new ScriptDAO();
|
scriptDAO: ScriptDAO = new ScriptDAO();
|
||||||
valueDAO: ValueDAO = new ValueDAO();
|
valueDAO: ValueDAO = new ValueDAO();
|
||||||
|
|
||||||
constructor(
|
constructor(private group: Group) {
|
||||||
private group: Group,
|
|
||||||
private mq: MessageQueue
|
|
||||||
) {
|
|
||||||
this.logger = LoggerCore.logger().with({ service: "value" });
|
this.logger = LoggerCore.logger().with({ service: "value" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -13,6 +13,7 @@ import LoggerCore from "@App/app/logger/core.ts";
|
|||||||
import { LoggerDAO } from "@App/app/repo/logger.ts";
|
import { LoggerDAO } from "@App/app/repo/logger.ts";
|
||||||
import DBWriter from "@App/app/logger/db_writer.ts";
|
import DBWriter from "@App/app/logger/db_writer.ts";
|
||||||
import registerEditor from "@App/pkg/utils/monaco-editor.ts";
|
import registerEditor from "@App/pkg/utils/monaco-editor.ts";
|
||||||
|
import storeSubscribe from "../store/subscribe.ts";
|
||||||
|
|
||||||
// 初始化数据库
|
// 初始化数据库
|
||||||
migrate();
|
migrate();
|
||||||
@ -25,6 +26,8 @@ const loggerCore = new LoggerCore({
|
|||||||
|
|
||||||
loggerCore.logger().debug("page start");
|
loggerCore.logger().debug("page start");
|
||||||
|
|
||||||
|
storeSubscribe();
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<Provider store={store}>
|
<Provider store={store}>
|
||||||
|
@ -79,12 +79,14 @@ import {
|
|||||||
selectScripts,
|
selectScripts,
|
||||||
sortScript,
|
sortScript,
|
||||||
upsertScript,
|
upsertScript,
|
||||||
|
requestStopScript,
|
||||||
|
requestRunScript,
|
||||||
} from "@App/pages/store/features/script";
|
} from "@App/pages/store/features/script";
|
||||||
import { selectScriptListColumnWidth } from "@App/pages/store/features/setting";
|
import { selectScriptListColumnWidth } from "@App/pages/store/features/setting";
|
||||||
import { Broker } from "@Packages/message/message_queue";
|
import { MessageQueue, Unsubscribe } from "@Packages/message/message_queue";
|
||||||
import { subscribeScriptDelete, subscribeScriptInstall } from "@App/app/service/service_worker/client";
|
import { subscribeScriptDelete, subscribeScriptInstall, subscribeScriptRunStatus } from "@App/app/service/queue";
|
||||||
import { ExtensionMessageSend } from "@Packages/message/extension_message";
|
import { RuntimeClient } from "@App/app/service/service_worker/client";
|
||||||
import { MessageConnect } from "@Packages/message/server";
|
import { ExtensionMessage, ExtensionMessageSend } from "@Packages/message/extension_message";
|
||||||
|
|
||||||
type ListType = Script & { loading?: boolean };
|
type ListType = Script & { loading?: boolean };
|
||||||
|
|
||||||
@ -105,43 +107,10 @@ function ScriptList() {
|
|||||||
const [action, setAction] = useState("");
|
const [action, setAction] = useState("");
|
||||||
const [select, setSelect] = useState<Script[]>([]);
|
const [select, setSelect] = useState<Script[]>([]);
|
||||||
const [selectColumn, setSelectColumn] = useState(0);
|
const [selectColumn, setSelectColumn] = useState(0);
|
||||||
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
dispatch(fetchAndSortScriptList());
|
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]);
|
}, [dispatch]);
|
||||||
|
|
||||||
const columns: ColumnProps[] = [
|
const columns: ColumnProps[] = [
|
||||||
@ -314,7 +283,7 @@ function ScriptList() {
|
|||||||
if (item.type === SCRIPT_TYPE_BACKGROUND) {
|
if (item.type === SCRIPT_TYPE_BACKGROUND) {
|
||||||
tooltip = t("background_script_tooltip");
|
tooltip = t("background_script_tooltip");
|
||||||
} else {
|
} else {
|
||||||
tooltip = `${t("scheduled_script_tooltip")} ${nextTime(item.metadata.crontab[0])}`;
|
tooltip = `${t("scheduled_script_tooltip")} ${nextTime(item.metadata!.crontab![0])}`;
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<Tooltip content={tooltip}>
|
<Tooltip content={tooltip}>
|
||||||
@ -532,19 +501,28 @@ function ScriptList() {
|
|||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
if (item.runStatus === SCRIPT_RUN_STATUS_RUNNING) {
|
if (item.runStatus === SCRIPT_RUN_STATUS_RUNNING) {
|
||||||
// Stop script
|
// 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={{
|
style={{
|
||||||
color: "var(--color-text-2)",
|
color: "var(--color-text-2)",
|
||||||
|
@ -1,11 +1,18 @@
|
|||||||
import { createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
|
import { createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
|
||||||
import { createAppSlice } from "../hooks";
|
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 { 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";
|
import { message } from "../global";
|
||||||
|
|
||||||
export const scriptClient = new ScriptClient(message);
|
export const scriptClient = new ScriptClient(message);
|
||||||
|
export const runtimeClient = new RuntimeClient(message);
|
||||||
|
|
||||||
export const fetchAndSortScriptList = createAsyncThunk("script/fetchScriptList", async () => {
|
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) => {
|
export const requestDeleteScript = createAsyncThunk("script/deleteScript", async (uuid: string) => {
|
||||||
return scriptClient.delete(uuid);
|
return scriptClient.delete(uuid);
|
||||||
});
|
});
|
||||||
@ -70,12 +85,19 @@ export const scriptSlice = createAppSlice({
|
|||||||
}
|
}
|
||||||
state.scripts = newItems;
|
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) => {
|
extraReducers: (builder) => {
|
||||||
builder
|
builder
|
||||||
.addCase(fetchAndSortScriptList.fulfilled, (state, action) => {
|
.addCase(fetchAndSortScriptList.fulfilled, (state, action) => {
|
||||||
state.scripts = action.payload;
|
state.scripts = action.payload;
|
||||||
})
|
})
|
||||||
|
// 处理enableScript
|
||||||
.addCase(requestEnableScript.fulfilled, (state, action) => {
|
.addCase(requestEnableScript.fulfilled, (state, action) => {
|
||||||
updateScript(state.scripts, action.meta.arg.uuid, (script) => {
|
updateScript(state.scripts, action.meta.arg.uuid, (script) => {
|
||||||
script.enableLoading = false;
|
script.enableLoading = false;
|
||||||
@ -85,11 +107,25 @@ export const scriptSlice = createAppSlice({
|
|||||||
.addCase(requestEnableScript.pending, (state, action) =>
|
.addCase(requestEnableScript.pending, (state, action) =>
|
||||||
updateScript(state.scripts, action.meta.arg.uuid, (s) => (s.enableLoading = true))
|
updateScript(state.scripts, action.meta.arg.uuid, (s) => (s.enableLoading = true))
|
||||||
)
|
)
|
||||||
|
// 处理deleteScript
|
||||||
.addCase(requestDeleteScript.fulfilled, (state, action) => {
|
.addCase(requestDeleteScript.fulfilled, (state, action) => {
|
||||||
state.scripts = state.scripts.filter((s) => s.uuid !== action.meta.arg);
|
state.scripts = state.scripts.filter((s) => s.uuid !== action.meta.arg);
|
||||||
})
|
})
|
||||||
.addCase(requestDeleteScript.pending, (state, action) =>
|
.addCase(requestDeleteScript.pending, (state, action) =>
|
||||||
updateScript(state.scripts, action.meta.arg, (s) => (s.actionLoading = true))
|
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: {
|
selectors: {
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
import { ExtensionMessage } from "@Packages/message/extension_message";
|
import { ExtensionMessage } from "@Packages/message/extension_message";
|
||||||
|
import { MessageQueue } from "@Packages/message/message_queue";
|
||||||
|
|
||||||
export const message = new ExtensionMessage();
|
export const message = new ExtensionMessage();
|
||||||
|
export const messageQueue = new MessageQueue();
|
||||||
|
18
src/pages/store/subscribe.ts
Normal file
18
src/pages/store/subscribe.ts
Normal 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));
|
||||||
|
});
|
||||||
|
}
|
@ -55,8 +55,8 @@ async function main() {
|
|||||||
});
|
});
|
||||||
loggerCore.logger().debug("service worker start");
|
loggerCore.logger().debug("service worker start");
|
||||||
// 初始化管理器
|
// 初始化管理器
|
||||||
const server = new Server(new ExtensionMessage());
|
const server = new Server("serviceWorker", new ExtensionMessage());
|
||||||
const manager = new ServiceWorkerManager(server, new MessageQueue(server), new ServiceWorkerMessageSend());
|
const manager = new ServiceWorkerManager(server, new MessageQueue(), new ServiceWorkerMessageSend());
|
||||||
manager.initManager();
|
manager.initManager();
|
||||||
// 初始化沙盒环境
|
// 初始化沙盒环境
|
||||||
await setupOffscreenDocument();
|
await setupOffscreenDocument();
|
||||||
|
@ -5,7 +5,6 @@ import migrate from "@App/app/migrate";
|
|||||||
import { LoggerDAO } from "@App/app/repo/logger";
|
import { LoggerDAO } from "@App/app/repo/logger";
|
||||||
import { MockMessage } from "@Packages/message/mock_message";
|
import { MockMessage } from "@Packages/message/mock_message";
|
||||||
import { Message, Server } from "@Packages/message/server";
|
import { Message, Server } from "@Packages/message/server";
|
||||||
import { MessageQueue } from "@Packages/message/message_queue";
|
|
||||||
import { ValueService } from "@App/app/service/service_worker/value";
|
import { ValueService } from "@App/app/service/service_worker/value";
|
||||||
import GMApi from "@App/app/service/service_worker/gm_api";
|
import GMApi from "@App/app/service/service_worker/gm_api";
|
||||||
import OffscreenGMApi from "@App/app/service/offscreen/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 osMessage = new MockMessage(osEE);
|
||||||
|
|
||||||
const serviceWorkerServer = new Server(wsMessage);
|
const serviceWorkerServer = new Server(wsMessage);
|
||||||
const mq = new MessageQueue(serviceWorkerServer);
|
const valueService = new ValueService(serviceWorkerServer.group("value"));
|
||||||
const valueService = new ValueService(serviceWorkerServer.group("value"), mq);
|
|
||||||
const swGMApi = new GMApi(serviceWorkerServer.group("runtime"), osMessage, valueService);
|
const swGMApi = new GMApi(serviceWorkerServer.group("runtime"), osMessage, valueService);
|
||||||
|
|
||||||
valueService.init();
|
valueService.init();
|
||||||
|
Loading…
x
Reference in New Issue
Block a user