三个页面之间的交互
This commit is contained in:
parent
c4b47d117c
commit
c2e5c7600e
57
packages/message/extension_message.ts
Normal file
57
packages/message/extension_message.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import { Message, MessageConnect } from "./server";
|
||||
|
||||
export class ExtensionMessage implements Message {
|
||||
onConnect(callback: (data: any, con: MessageConnect) => void) {
|
||||
chrome.runtime.onConnect.addListener((port) => {
|
||||
const handler = (msg: any) => {
|
||||
port.onMessage.removeListener(handler);
|
||||
callback(msg, new ExtensionMessageConnect(port));
|
||||
};
|
||||
port.onMessage.addListener(handler);
|
||||
});
|
||||
}
|
||||
|
||||
connect(data: any): Promise<MessageConnect> {
|
||||
return new Promise((resolve) => {
|
||||
const con = chrome.runtime.connect();
|
||||
con.postMessage(data);
|
||||
resolve(new ExtensionMessageConnect(con));
|
||||
});
|
||||
}
|
||||
|
||||
// 注意chrome.runtime.onMessage.addListener的回调函数需要返回true才能处理异步请求
|
||||
onMessage(callback: (data: any, sendResponse: (data: any) => void) => void) {
|
||||
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
||||
return callback(msg, sendResponse);
|
||||
});
|
||||
}
|
||||
|
||||
// 发送消息 注意不进行回调的内存泄漏
|
||||
sendMessage(data: any): Promise<any> {
|
||||
return new Promise((resolve) => {
|
||||
chrome.runtime.sendMessage(data, (resp) => {
|
||||
resolve(resp);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class ExtensionMessageConnect implements MessageConnect {
|
||||
constructor(private con: chrome.runtime.Port) {}
|
||||
|
||||
sendMessage(data: any) {
|
||||
this.con.postMessage(data);
|
||||
}
|
||||
|
||||
onMessage(callback: (data: any) => void) {
|
||||
this.con.onMessage.addListener(callback);
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this.con.disconnect();
|
||||
}
|
||||
|
||||
onDisconnect(callback: () => void) {
|
||||
this.con.onDisconnect.addListener(callback);
|
||||
}
|
||||
}
|
@ -1,16 +1,15 @@
|
||||
import EventEmitter from "eventemitter3";
|
||||
import { connect } from "./client";
|
||||
import { ApiFunction, Server } from "./server";
|
||||
import { ApiFunction, Message, MessageConnect, Server } from "./server";
|
||||
|
||||
export type SubscribeCallback = (message: any) => void;
|
||||
|
||||
export class Broker {
|
||||
constructor() {}
|
||||
constructor(private msg: Message) {}
|
||||
|
||||
// 订阅
|
||||
async subscribe(topic: string, handler: SubscribeCallback): Promise<chrome.runtime.Port> {
|
||||
const con = await connect("messageQueue", { action: "subscribe", topic });
|
||||
con.onMessage.addListener((msg: { action: string; topic: string; message: any }) => {
|
||||
async subscribe(topic: string, handler: SubscribeCallback): Promise<MessageConnect> {
|
||||
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);
|
||||
}
|
||||
@ -26,7 +25,7 @@ export class Broker {
|
||||
|
||||
// 消息队列
|
||||
export class MessageQueue {
|
||||
topicConMap: Map<string, { name: string; con: chrome.runtime.Port }[]> = new Map();
|
||||
topicConMap: Map<string, { name: string; con: MessageConnect }[]> = new Map();
|
||||
|
||||
private EE: EventEmitter = new EventEmitter();
|
||||
|
||||
@ -44,7 +43,7 @@ export class MessageQueue {
|
||||
}
|
||||
switch (action) {
|
||||
case "subscribe":
|
||||
this.subscribe(topic, con as chrome.runtime.Port);
|
||||
this.subscribe(topic, con as MessageConnect);
|
||||
break;
|
||||
case "publish":
|
||||
this.publish(topic, message);
|
||||
@ -55,14 +54,14 @@ export class MessageQueue {
|
||||
};
|
||||
}
|
||||
|
||||
private subscribe(topic: string, con: chrome.runtime.Port) {
|
||||
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.addListener(() => {
|
||||
con.onDisconnect(() => {
|
||||
let list = this.topicConMap.get(topic);
|
||||
// 移除断开连接的con
|
||||
list = list!.filter((item) => item.con !== con);
|
||||
@ -73,7 +72,7 @@ export class MessageQueue {
|
||||
publish(topic: string, message: any) {
|
||||
const list = this.topicConMap.get(topic);
|
||||
list?.forEach((item) => {
|
||||
item.con.postMessage({ action: "message", topic, message });
|
||||
item.con.sendMessage({ action: "message", topic, message });
|
||||
});
|
||||
this.EE.emit(topic, message);
|
||||
}
|
||||
|
@ -1,19 +1,36 @@
|
||||
export type ApiFunction = (params: any, con: chrome.runtime.Port | chrome.runtime.MessageSender) => any;
|
||||
export interface Message {
|
||||
onConnect(callback: (data: any, con: MessageConnect) => void): void;
|
||||
onMessage(callback: (data: any, sendResponse: (data: any) => void) => void): void;
|
||||
connect(data: any): Promise<MessageConnect>;
|
||||
sendMessage(data: any): Promise<any>;
|
||||
}
|
||||
|
||||
export interface MessageConnect {
|
||||
onMessage(callback: (data: any) => void): void;
|
||||
sendMessage(data: any): void;
|
||||
disconnect(): void;
|
||||
onDisconnect(callback: () => void): void;
|
||||
}
|
||||
|
||||
export type MessageSender = {
|
||||
tabId: number;
|
||||
};
|
||||
|
||||
export type ApiFunction = (params: any, con: MessageConnect | null) => any;
|
||||
|
||||
export class Server {
|
||||
private apiFunctionMap: Map<string, ApiFunction> = new Map();
|
||||
|
||||
constructor(private env: string) {
|
||||
chrome.runtime.onConnect.addListener((port) => {
|
||||
const handler = (msg: { action: string; data: any }) => {
|
||||
port.onMessage.removeListener(handler);
|
||||
this.connectHandle(msg.action, msg.data, port);
|
||||
};
|
||||
port.onMessage.addListener(handler);
|
||||
constructor(
|
||||
private env: string,
|
||||
message: Message
|
||||
) {
|
||||
message.onConnect((msg: any, con: MessageConnect) => {
|
||||
this.connectHandle(msg.action, msg.data, con);
|
||||
});
|
||||
|
||||
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
||||
this.messageHandle(msg.action, msg.data, sender, sendResponse);
|
||||
message.onMessage((msg, sendResponse) => {
|
||||
return this.messageHandle(msg.action, msg.data, sendResponse);
|
||||
});
|
||||
}
|
||||
|
||||
@ -25,24 +42,26 @@ export class Server {
|
||||
this.apiFunctionMap.set(name, func);
|
||||
}
|
||||
|
||||
private connectHandle(msg: string, params: any, con: chrome.runtime.Port) {
|
||||
private connectHandle(msg: string, params: any, con: MessageConnect) {
|
||||
const func = this.apiFunctionMap.get(msg);
|
||||
if (func) {
|
||||
func(params, con);
|
||||
}
|
||||
}
|
||||
|
||||
private messageHandle(
|
||||
msg: string,
|
||||
params: any,
|
||||
sender: chrome.runtime.MessageSender,
|
||||
sendResponse: (response: any) => void
|
||||
) {
|
||||
private messageHandle(msg: string, params: any, sendResponse: (response: any) => void) {
|
||||
const func = this.apiFunctionMap.get(msg);
|
||||
if (func) {
|
||||
try {
|
||||
const ret = func(params, sender);
|
||||
const ret = func(params, null);
|
||||
if (ret instanceof Promise) {
|
||||
ret.then((data) => {
|
||||
sendResponse({ code: 0, data });
|
||||
});
|
||||
return true;
|
||||
} else {
|
||||
sendResponse({ code: 0, data: ret });
|
||||
}
|
||||
} catch (e: any) {
|
||||
sendResponse({ code: -1, message: e.message });
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { Message, MessageConnect } from "./server";
|
||||
|
||||
// 通过 window.postMessage/onmessage 实现通信
|
||||
|
||||
@ -7,11 +8,11 @@ import EventEmitter from "eventemitter3";
|
||||
// 消息体
|
||||
export type WindowMessageBody = {
|
||||
messageId: string; // 消息id
|
||||
type: "sendMessage" | "respMessage" | "connect"; // 消息类型
|
||||
type: "sendMessage" | "respMessage" | "connect" | "disconnect" | "connectMessage"; // 消息类型
|
||||
data: any; // 消息数据
|
||||
};
|
||||
|
||||
export class WindowMessage {
|
||||
export class WindowMessage implements Message {
|
||||
EE: EventEmitter = new EventEmitter();
|
||||
|
||||
// source: Window 消息来源
|
||||
@ -22,7 +23,7 @@ export class WindowMessage {
|
||||
) {
|
||||
// 监听消息
|
||||
this.source.addEventListener("message", (e) => {
|
||||
if (e.source === this.target) {
|
||||
if (e.source === this.target || e.source === this.source) {
|
||||
this.messageHandle(e.data);
|
||||
}
|
||||
});
|
||||
@ -47,22 +48,22 @@ export class WindowMessage {
|
||||
} else if (data.type === "connect") {
|
||||
this.EE.emit("connect", data.data, new WindowMessageConnect(data.messageId, this.EE, this.target));
|
||||
} else if (data.type === "disconnect") {
|
||||
this.EE.emit("disconnect", data.data, new WindowMessageConnect(data.messageId, this.EE, this.target));
|
||||
this.EE.emit("disconnect:" + data.messageId);
|
||||
} else if (data.type === "connectMessage") {
|
||||
this.EE.emit("connectMessage", data.data, new WindowMessageConnect(data.messageId, this.EE, this.target));
|
||||
this.EE.emit("connectMessage:" + data.messageId, data.data);
|
||||
}
|
||||
}
|
||||
|
||||
onConnect(callback: (data: any, con: WindowMessageConnect) => void) {
|
||||
onConnect(callback: (data: any, con: MessageConnect) => void) {
|
||||
this.EE.addListener("connect", callback);
|
||||
}
|
||||
|
||||
connect(action: string, data?: any): Promise<WindowMessageConnect> {
|
||||
connect(data: any): Promise<MessageConnect> {
|
||||
return new Promise((resolve) => {
|
||||
const body: WindowMessageBody = {
|
||||
messageId: uuidv4(),
|
||||
type: "connect",
|
||||
data: { action, data },
|
||||
data,
|
||||
};
|
||||
this.target.postMessage(body, "*");
|
||||
resolve(new WindowMessageConnect(body.messageId, this.EE, this.target));
|
||||
@ -73,12 +74,13 @@ export class WindowMessage {
|
||||
this.EE.addListener("message", callback);
|
||||
}
|
||||
|
||||
sendMessage(action: string, data?: any): Promise<any> {
|
||||
// 发送消息 注意不进行回调的内存泄漏
|
||||
sendMessage(data: any): Promise<any> {
|
||||
return new Promise((resolve) => {
|
||||
const body: WindowMessageBody = {
|
||||
messageId: uuidv4(),
|
||||
type: "sendMessage",
|
||||
data: { action, data },
|
||||
data,
|
||||
};
|
||||
const callback = (body: WindowMessageBody) => {
|
||||
this.EE.removeListener("response:" + body.messageId, callback);
|
||||
@ -90,10 +92,42 @@ export class WindowMessage {
|
||||
}
|
||||
}
|
||||
|
||||
export class WindowMessageConnect {
|
||||
export class WindowMessageConnect implements MessageConnect {
|
||||
constructor(
|
||||
private messageId: string,
|
||||
private EE: EventEmitter,
|
||||
private target: Window
|
||||
) {}
|
||||
) {
|
||||
this.onDisconnect(() => {
|
||||
// 移除所有监听
|
||||
this.EE.removeAllListeners("connectMessage:" + this.messageId);
|
||||
this.EE.removeAllListeners("disconnect:" + this.messageId);
|
||||
});
|
||||
}
|
||||
|
||||
sendMessage(data: any) {
|
||||
const body: WindowMessageBody = {
|
||||
messageId: this.messageId,
|
||||
type: "connectMessage",
|
||||
data,
|
||||
};
|
||||
this.target.postMessage(body, "*");
|
||||
}
|
||||
|
||||
onMessage(callback: (data: any) => void) {
|
||||
this.EE.addListener("connectMessage:" + this.messageId, callback);
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
const body: WindowMessageBody = {
|
||||
messageId: this.messageId,
|
||||
type: "disconnect",
|
||||
data: null,
|
||||
};
|
||||
this.target.postMessage(body);
|
||||
}
|
||||
|
||||
onDisconnect(callback: () => void) {
|
||||
this.EE.addListener("disconnect:" + this.messageId, callback);
|
||||
}
|
||||
}
|
||||
|
@ -1,29 +1,24 @@
|
||||
import MessageCenter from "../message/center";
|
||||
import { MessageManager } from "../message/message";
|
||||
import { Logger, LoggerDAO } from "../repo/logger";
|
||||
import { WindowMessage } from "@Packages/message/window_message";
|
||||
import { LogLabel, LogLevel, Writer } from "./core";
|
||||
|
||||
// 通过通讯机制写入日志
|
||||
export default class MessageWriter implements Writer {
|
||||
connect: MessageManager;
|
||||
connect: WindowMessage;
|
||||
|
||||
constructor(connect: MessageManager) {
|
||||
constructor(connect: WindowMessage) {
|
||||
this.connect = connect;
|
||||
}
|
||||
|
||||
write(level: LogLevel, message: string, label: LogLabel): void {
|
||||
this.connect.send("log", {
|
||||
this.connect.sendMessage({
|
||||
action: "logger",
|
||||
data: {
|
||||
id: 0,
|
||||
level,
|
||||
message,
|
||||
label,
|
||||
createtime: new Date().getTime(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function ListenerMessage(db: LoggerDAO, connect: MessageCenter) {
|
||||
connect.setHandler("log", (action, data: Logger) => {
|
||||
db.save(data);
|
||||
});
|
||||
}
|
||||
|
6
src/app/service/offscreen/client.ts
Normal file
6
src/app/service/offscreen/client.ts
Normal file
@ -0,0 +1,6 @@
|
||||
import { WindowMessage } from "@Packages/message/window_message";
|
||||
import { sendMessage } from "../utils";
|
||||
|
||||
export function preparationSandbox(msg: WindowMessage) {
|
||||
return sendMessage(msg, "preparationSandbox");
|
||||
}
|
@ -1,17 +1,42 @@
|
||||
import { Server } from "@Packages/message/server";
|
||||
import { ScriptService } from "./script";
|
||||
import { MessageQueue } from "@Packages/message/message_queue";
|
||||
import { Broker, MessageQueue } from "@Packages/message/message_queue";
|
||||
import { Logger, LoggerDAO } from "@App/app/repo/logger";
|
||||
import { WindowMessage } from "@Packages/message/window_message";
|
||||
import { ExtensionMessage } from "@Packages/message/extension_message";
|
||||
import { ServiceWorkerClient } from "../service_worker/client";
|
||||
|
||||
// offscreen环境的管理器
|
||||
export class OffscreenManager {
|
||||
private api: Server = new Server("offscreen");
|
||||
private extensionMessage = new ExtensionMessage();
|
||||
|
||||
private api: Server = new Server("offscreen", this.extensionMessage);
|
||||
|
||||
private windowMessage = new WindowMessage(window, sandbox);
|
||||
|
||||
private windowApi: Server = new Server("offscreen-window", this.windowMessage);
|
||||
|
||||
private mq: MessageQueue = new MessageQueue(this.api);
|
||||
|
||||
private broker: Broker = new Broker(this.extensionMessage);
|
||||
|
||||
logger(data: Logger) {
|
||||
const dao = new LoggerDAO();
|
||||
dao.save(data);
|
||||
}
|
||||
|
||||
preparationSandbox() {
|
||||
// 通知初始化好环境了
|
||||
const serviceWorker = new ServiceWorkerClient();
|
||||
serviceWorker.preparationOffscreen();
|
||||
}
|
||||
|
||||
initManager() {
|
||||
// 监听消息
|
||||
const group = this.api.group("serviceWorker");
|
||||
const script = new ScriptService(group.group("script"), this.mq);
|
||||
const group = this.api.group("offscreen");
|
||||
this.windowApi.on("logger", this.logger.bind(this));
|
||||
this.windowApi.on("preparationSandbox", this.preparationSandbox.bind(this));
|
||||
const script = new ScriptService(group.group("script"), this.mq, this.windowMessage, this.broker);
|
||||
script.init();
|
||||
}
|
||||
}
|
||||
|
@ -1,20 +1,37 @@
|
||||
import LoggerCore from "@App/app/logger/core";
|
||||
import Logger from "@App/app/logger/logger";
|
||||
import { MessageQueue } from "@Packages/message/message_queue";
|
||||
import { Broker, MessageQueue } from "@Packages/message/message_queue";
|
||||
import { Group } from "@Packages/message/server";
|
||||
import { WindowMessage } from "@Packages/message/window_message";
|
||||
import { ScriptClient, subscribeScriptEnable } from "../service_worker/client";
|
||||
import { SCRIPT_TYPE_NORMAL } from "@App/app/repo/scripts";
|
||||
import { disableScript, enableScript } from "../sandbox/client";
|
||||
|
||||
export class ScriptService {
|
||||
logger: Logger;
|
||||
|
||||
constructor(
|
||||
private group: Group,
|
||||
private mq: MessageQueue
|
||||
private mq: MessageQueue,
|
||||
private windowMessage: WindowMessage,
|
||||
private broker: Broker
|
||||
) {
|
||||
this.logger = LoggerCore.logger().with({ service: "script" });
|
||||
}
|
||||
|
||||
init() {
|
||||
// 初始化, 执行所有的后台脚本, 设置定时脚本计时器
|
||||
|
||||
async init() {
|
||||
subscribeScriptEnable(this.broker, async (data) => {
|
||||
const info = await new ScriptClient().info(data.uuid);
|
||||
if (info.type === SCRIPT_TYPE_NORMAL) {
|
||||
return;
|
||||
}
|
||||
if (data.enable) {
|
||||
// 发送给沙盒运行
|
||||
enableScript(this.windowMessage, info);
|
||||
} else {
|
||||
// 发送给沙盒停止
|
||||
disableScript(this.windowMessage, info);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
11
src/app/service/sandbox/client.ts
Normal file
11
src/app/service/sandbox/client.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { Script } from "@App/app/repo/scripts";
|
||||
import { WindowMessage } from "@Packages/message/window_message";
|
||||
import { sendMessage } from "../utils";
|
||||
|
||||
export function enableScript(msg: WindowMessage, data: Script) {
|
||||
return sendMessage(msg, "enableScript", data);
|
||||
}
|
||||
|
||||
export function disableScript(msg: WindowMessage, data: Script) {
|
||||
return sendMessage(msg, "disableScript", data);
|
||||
}
|
29
src/app/service/sandbox/index.ts
Normal file
29
src/app/service/sandbox/index.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { Server } from "@Packages/message/server";
|
||||
import { WindowMessage } from "@Packages/message/window_message";
|
||||
import { preparationSandbox } from "../offscreen/client";
|
||||
import { Script, SCRIPT_TYPE_BACKGROUND } from "@App/app/repo/scripts";
|
||||
|
||||
// sandbox环境的管理器
|
||||
export class SandboxManager {
|
||||
api: Server = new Server("sandbox", this.windowMessage);
|
||||
|
||||
constructor(private windowMessage: WindowMessage) {}
|
||||
|
||||
enableScript(data: Script) {
|
||||
// 开启脚本, 判断脚本是后台脚本还是定时脚本
|
||||
if(data.type === SCRIPT_TYPE_BACKGROUND) {
|
||||
// 后台脚本直接运行起来
|
||||
}else{
|
||||
// 定时脚本加入定时任务
|
||||
}
|
||||
eval("console.log('hello')");
|
||||
console.log("enableScript", data);
|
||||
}
|
||||
|
||||
initManager() {
|
||||
this.api.on("enableScript", this.enableScript.bind(this));
|
||||
|
||||
// 通知初始化好环境了
|
||||
preparationSandbox(this.windowMessage);
|
||||
}
|
||||
}
|
@ -3,6 +3,16 @@ import { Client } from "@Packages/message/client";
|
||||
import { InstallSource } from ".";
|
||||
import { Broker } from "@Packages/message/message_queue";
|
||||
|
||||
export class ServiceWorkerClient extends Client {
|
||||
constructor() {
|
||||
super("serviceWorker");
|
||||
}
|
||||
|
||||
preparationOffscreen() {
|
||||
return this.do("preparationOffscreen");
|
||||
}
|
||||
}
|
||||
|
||||
export class ScriptClient extends Client {
|
||||
constructor() {
|
||||
super("serviceWorker/script");
|
||||
@ -24,6 +34,10 @@ export class ScriptClient extends Client {
|
||||
enable(uuid: string, enable: boolean) {
|
||||
return this.do("enable", { uuid, enable });
|
||||
}
|
||||
|
||||
info(uuid: string): Promise<Script> {
|
||||
return this.do("fetchInfo", uuid);
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribeScriptInstall(
|
||||
@ -36,3 +50,9 @@ export function subscribeScriptInstall(
|
||||
export function subscribeScriptDelete(border: Broker, callback: (message: { uuid: string }) => void) {
|
||||
return border.subscribe("deleteScript", callback);
|
||||
}
|
||||
|
||||
export type ScriptEnableCallbackValue = { uuid: string; enable: boolean };
|
||||
|
||||
export function subscribeScriptEnable(border: Broker, callback: (message: ScriptEnableCallbackValue) => void) {
|
||||
return border.subscribe("enableScript", callback);
|
||||
}
|
||||
|
@ -1,6 +1,7 @@
|
||||
import { Server } from "@Packages/message/server";
|
||||
import { MessageQueue } from "@Packages/message/message_queue";
|
||||
import { ScriptService } from "./script";
|
||||
import { ExtensionMessage } from "@Packages/message/extension_message";
|
||||
|
||||
export type InstallSource = "user" | "system" | "sync" | "subscribe" | "vscode";
|
||||
|
||||
@ -8,12 +9,16 @@ export type InstallSource = "user" | "system" | "sync" | "subscribe" | "vscode";
|
||||
export default class ServiceWorkerManager {
|
||||
constructor() {}
|
||||
|
||||
private api: Server = new Server("service_worker");
|
||||
private api: Server = new Server("service_worker", new ExtensionMessage());
|
||||
|
||||
private mq: MessageQueue = new MessageQueue(this.api);
|
||||
|
||||
initManager() {
|
||||
const group = this.api.group("serviceWorker");
|
||||
group.on("preparationOffscreen", () => {
|
||||
// 准备好环境
|
||||
this.mq.emit("preparationOffscreen", {});
|
||||
});
|
||||
const script = new ScriptService(group.group("script"), this.mq);
|
||||
script.init();
|
||||
}
|
||||
|
@ -8,14 +8,14 @@ import CacheKey from "@App/app/cache_key";
|
||||
import { openInCurrentTab } from "@App/pkg/utils/utils";
|
||||
import {
|
||||
Script,
|
||||
SCRIPT_RUN_STATUS_COMPLETE,
|
||||
SCRIPT_RUN_STATUS_RUNNING,
|
||||
SCRIPT_STATUS_DISABLE,
|
||||
SCRIPT_STATUS_ENABLE,
|
||||
SCRIPT_TYPE_NORMAL,
|
||||
ScriptDAO,
|
||||
} from "@App/app/repo/scripts";
|
||||
import { MessageQueue } from "@Packages/message/message_queue";
|
||||
import { InstallSource } from ".";
|
||||
import { ScriptEnableCallbackValue } from "./client";
|
||||
|
||||
export class ScriptService {
|
||||
logger: Logger;
|
||||
@ -217,12 +217,67 @@ export class ScriptService {
|
||||
});
|
||||
}
|
||||
|
||||
init() {
|
||||
async fetchInfo(uuid: string) {
|
||||
const script = await new ScriptDAO().findByUUID(uuid);
|
||||
if (!script) {
|
||||
return null;
|
||||
}
|
||||
return script;
|
||||
}
|
||||
|
||||
async init() {
|
||||
this.listenerScriptInstall();
|
||||
|
||||
this.group.on("getInstallInfo", this.getInstallInfo);
|
||||
this.group.on("install", this.installScript.bind(this));
|
||||
this.group.on("delete", this.deleteScript.bind(this));
|
||||
this.group.on("enable", this.enableScript.bind(this));
|
||||
this.group.on("fetchInfo", this.fetchInfo.bind(this));
|
||||
|
||||
this.listenScript();
|
||||
}
|
||||
|
||||
// 监听脚本
|
||||
async listenScript() {
|
||||
// 监听脚本开启
|
||||
this.mq.addListener("enableScript", async (data: ScriptEnableCallbackValue) => {
|
||||
const script = await new ScriptDAO().findByUUID(data.uuid);
|
||||
if (!script) {
|
||||
return;
|
||||
}
|
||||
// 如果是普通脚本, 在service worker中进行注册
|
||||
// 如果是后台脚本, 在offscreen中进行处理
|
||||
if (script.type === SCRIPT_TYPE_NORMAL) {
|
||||
// 注册入页面脚本
|
||||
if (data.enable) {
|
||||
this.registryPageScript(script);
|
||||
} else {
|
||||
this.unregistryPageScript(script);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 将开启的脚本发送一次enable消息
|
||||
const scriptDao = new ScriptDAO();
|
||||
const list = await scriptDao.all();
|
||||
list.forEach((script) => {
|
||||
if (script.status !== SCRIPT_STATUS_ENABLE || script.type !== SCRIPT_TYPE_NORMAL) {
|
||||
return;
|
||||
}
|
||||
this.mq.publish("enableScript", { uuid: script.uuid, enable: true });
|
||||
});
|
||||
// 监听offscreen环境初始化, 初始化完成后, 再将后台脚本运行起来
|
||||
this.mq.addListener("preparationOffscreen", () => {
|
||||
list.forEach((script) => {
|
||||
if (script.status !== SCRIPT_STATUS_ENABLE || script.type === SCRIPT_TYPE_NORMAL) {
|
||||
return;
|
||||
}
|
||||
this.mq.publish("enableScript", { uuid: script.uuid, enable: true });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
registryPageScript(script: Script) {}
|
||||
|
||||
unregistryPageScript(script: Script) {}
|
||||
}
|
||||
|
8
src/app/service/utils.ts
Normal file
8
src/app/service/utils.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { WindowMessage } from "@Packages/message/window_message";
|
||||
|
||||
export function sendMessage(msg: WindowMessage, action: string, data?: any) {
|
||||
return msg.sendMessage({
|
||||
action,
|
||||
data,
|
||||
});
|
||||
}
|
@ -14,7 +14,6 @@ function main() {
|
||||
labels: { env: "offscreen" },
|
||||
});
|
||||
loggerCore.logger().debug("offscreen start");
|
||||
|
||||
// 初始化管理器
|
||||
const manager = new OffscreenManager();
|
||||
manager.initManager();
|
||||
|
@ -6,22 +6,25 @@ import {
|
||||
Input,
|
||||
Layout,
|
||||
Menu,
|
||||
Message,
|
||||
Modal,
|
||||
Space,
|
||||
Typography,
|
||||
} from "@arco-design/web-react";
|
||||
import { RefInputType } from "@arco-design/web-react/es/Input/interface";
|
||||
import { IconDesktop, IconMoonFill, IconSunFill } from "@arco-design/web-react/icon";
|
||||
import { IconDesktop, IconDown, IconLink, IconMoonFill, IconSunFill } from "@arco-design/web-react/icon";
|
||||
import React, { ReactNode, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import "./index.css";
|
||||
import { useAppDispatch, useAppSelector } from "@App/store/hooks";
|
||||
import { selectThemeMode, setDarkMode } from "@App/store/features/setting";
|
||||
import { RiFileCodeLine, RiImportLine, RiPlayListAddLine, RiTerminalBoxLine, RiTimerLine } from "react-icons/ri";
|
||||
|
||||
const MainLayout: React.FC<{
|
||||
children: ReactNode;
|
||||
className: string;
|
||||
}> = ({ children, className }) => {
|
||||
pageName?: string;
|
||||
}> = ({ children, className, pageName }) => {
|
||||
const lightMode = useAppSelector(selectThemeMode);
|
||||
const dispatch = useAppDispatch();
|
||||
const importRef = useRef<RefInputType>(null);
|
||||
@ -61,6 +64,86 @@ const MainLayout: React.FC<{
|
||||
</Typography.Title>
|
||||
</div>
|
||||
<Space size="small" className="action-tools">
|
||||
{pageName === "options" && (
|
||||
<Dropdown
|
||||
droplist={
|
||||
<Menu style={{ maxHeight: "100%", width: "calc(100% + 10px)" }}>
|
||||
<Menu.Item key="/script/editor">
|
||||
<a href="#/script/editor">
|
||||
<RiFileCodeLine /> {t("create_user_script")}
|
||||
</a>
|
||||
</Menu.Item>
|
||||
<Menu.Item key="background">
|
||||
<a href="#/script/editor?template=background">
|
||||
<RiTerminalBoxLine /> {t("create_background_script")}
|
||||
</a>
|
||||
</Menu.Item>
|
||||
<Menu.Item key="crontab">
|
||||
<a href="#/script/editor?template=crontab">
|
||||
<RiTimerLine /> {t("create_scheduled_script")}
|
||||
</a>
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
key="import_local"
|
||||
onClick={() => {
|
||||
const el = document.getElementById("import-local");
|
||||
el!.onchange = (e: Event) => {
|
||||
const scriptCtl = IoC.instance(ScriptController) as ScriptController;
|
||||
try {
|
||||
// 获取文件
|
||||
// @ts-ignore
|
||||
const file = e.target.files[0];
|
||||
// 实例化 FileReader对象
|
||||
const reader = new FileReader();
|
||||
reader.onload = async (processEvent) => {
|
||||
// 创建blob url
|
||||
const blob = new Blob(
|
||||
// @ts-ignore
|
||||
[processEvent.target!.result],
|
||||
{
|
||||
type: "application/javascript",
|
||||
}
|
||||
);
|
||||
const url = URL.createObjectURL(blob);
|
||||
await scriptCtl.importByUrl(url);
|
||||
Message.success(t("import_local_success"));
|
||||
};
|
||||
// 调用readerAsText方法读取文本
|
||||
reader.readAsText(file);
|
||||
} catch (error) {
|
||||
Message.error(`${t("import_local_failure")}: ${e}`);
|
||||
}
|
||||
};
|
||||
el!.click();
|
||||
}}
|
||||
>
|
||||
<input id="import-local" type="file" style={{ display: "none" }} accept=".js" />
|
||||
<RiImportLine /> {t("import_by_local")}
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
key="link"
|
||||
onClick={() => {
|
||||
setImportVisible(true);
|
||||
}}
|
||||
>
|
||||
<IconLink /> {t("import_link")}
|
||||
</Menu.Item>
|
||||
</Menu>
|
||||
}
|
||||
position="bl"
|
||||
>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
style={{
|
||||
color: "var(--color-text-1)",
|
||||
}}
|
||||
className="!text-size-sm"
|
||||
>
|
||||
<RiPlayListAddLine /> {t("create_script")} <IconDown />
|
||||
</Button>
|
||||
</Dropdown>
|
||||
)}
|
||||
<Dropdown
|
||||
droplist={
|
||||
<Menu
|
||||
|
@ -4,11 +4,6 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title><%= htmlRspackPlugin.options.title %></title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<iframe src="/src/sandbox.html" name="sandbox" sandbox="allow-scripts" style="display: none"></iframe>
|
||||
</body>
|
||||
<style>
|
||||
body {
|
||||
height: 100%;
|
||||
@ -17,6 +12,11 @@
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<iframe src="/src/sandbox.html" name="sandbox" sandbox="allow-scripts" style="display: none"></iframe>
|
||||
</body>
|
||||
<% if rspackConfig.mode=="script" { %>
|
||||
<script type="text/javascript" src="/_locales/i18n.js"></script>
|
||||
<script type="text/javascript" src="https://cdn.crowdin.com/jipt/jipt.js"></script>
|
||||
|
@ -1,27 +1,18 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import MainLayout from "../components/layout/MainLayout.tsx";
|
||||
import Sider from "../components/layout/Sider.tsx";
|
||||
import { Provider } from "react-redux";
|
||||
import { store } from "@App/store/store.ts";
|
||||
import "@arco-design/web-react/dist/css/arco.css";
|
||||
import "@App/locales/locales";
|
||||
import "@App/index.css";
|
||||
import "./index.css";
|
||||
import { Provider } from "react-redux";
|
||||
import { store } from "@App/store/store.ts";
|
||||
import { Broker } from "@Packages/message/message_queue.ts";
|
||||
import Sider from "../components/layout/Sider.tsx";
|
||||
|
||||
// // 测试监听广播
|
||||
|
||||
// const border = new Broker();
|
||||
|
||||
// border.subscribe("installScript", (message) => {
|
||||
// console.log(message);
|
||||
// });
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<Provider store={store}>
|
||||
<MainLayout className="!flex-row">
|
||||
<MainLayout className="!flex-row" pageName="options">
|
||||
<Sider />
|
||||
</MainLayout>
|
||||
</Provider>
|
||||
|
@ -83,6 +83,8 @@ import {
|
||||
import { selectScriptListColumnWidth } from "@App/store/features/setting";
|
||||
import { Broker } from "@Packages/message/message_queue";
|
||||
import { subscribeScriptDelete, subscribeScriptInstall } from "@App/app/service/service_worker/client";
|
||||
import { ExtensionMessage } from "@Packages/message/extension_message";
|
||||
import { MessageConnect } from "@Packages/message/server";
|
||||
|
||||
type ListType = Script & { loading?: boolean };
|
||||
|
||||
@ -109,8 +111,9 @@ function ScriptList() {
|
||||
useEffect(() => {
|
||||
dispatch(fetchAndSortScriptList());
|
||||
// 监听脚本安装/运行
|
||||
const border = new Broker();
|
||||
const subCon: chrome.runtime.Port[] = [];
|
||||
const msg = new ExtensionMessage();
|
||||
const border = new Broker(msg);
|
||||
const subCon: MessageConnect[] = [];
|
||||
|
||||
subscribeScriptInstall(border, (message) => {
|
||||
dispatch(upsertScript(message.script));
|
||||
|
@ -1,22 +1,22 @@
|
||||
import { WindowMessage } from "@Packages/message/window_message";
|
||||
import LoggerCore from "./app/logger/core";
|
||||
import DBWriter from "./app/logger/db_writer";
|
||||
import MessageWriter from "./app/logger/message_writer";
|
||||
import { LoggerDAO } from "./app/repo/logger";
|
||||
import { OffscreenManager } from "./app/service/offscreen";
|
||||
import { SandboxManager } from "./app/service/sandbox";
|
||||
|
||||
function main() {
|
||||
// 建立与offscreen页面的连接
|
||||
const msg = new WindowMessage(window, parent);
|
||||
|
||||
// 初始化日志组件
|
||||
const loggerCore = new LoggerCore({
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
writer: new MessageWriter(connectSandbox),
|
||||
writer: new MessageWriter(msg),
|
||||
labels: { env: "sandbox" },
|
||||
});
|
||||
loggerCore.logger().debug("offscreen start");
|
||||
|
||||
// 初始化管理器
|
||||
const manager = new OffscreenManager();
|
||||
const manager = new SandboxManager(msg);
|
||||
manager.initManager();
|
||||
}
|
||||
|
||||
|
@ -51,11 +51,11 @@ async function main() {
|
||||
labels: { env: "background" },
|
||||
});
|
||||
loggerCore.logger().debug("background start");
|
||||
// 初始化沙盒环境
|
||||
await setupOffscreenDocument();
|
||||
// 初始化管理器
|
||||
const manager = new ServiceWorkerManager();
|
||||
manager.initManager();
|
||||
// 初始化沙盒环境
|
||||
await setupOffscreenDocument();
|
||||
}
|
||||
|
||||
main();
|
||||
|
2
src/types/main.d.ts
vendored
2
src/types/main.d.ts
vendored
@ -2,3 +2,5 @@ declare module "@App/types/scriptcat.d.ts";
|
||||
declare module "*.tpl";
|
||||
declare module "*.json";
|
||||
declare module "*.yaml";
|
||||
|
||||
declare let sandbox: Window;
|
||||
|
Loading…
x
Reference in New Issue
Block a user