Skip to content

Commit

Permalink
feat: 更新软件,加载时自动更新ocs脚本
Browse files Browse the repository at this point in the history
  • Loading branch information
enncy committed Mar 26, 2022
1 parent 2f68089 commit e16d954
Show file tree
Hide file tree
Showing 13 changed files with 96 additions and 75 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@
var resource = (url) => fetch(url).then((res) => res.text());
// 载入 OCS 并运行
(async () => {
const style = await resource("https://cdn.jsdelivr.net/npm/ocsjs@latest/dist/style/common.css");
const ocsjs = await resource("https://cdn.jsdelivr.net/npm/ocsjs@latest/dist/js/index.min.js");
const style = await resource("https://cdn.jsdelivr.net/npm/ocsjs/dist/style/common.css?t=" + Date.now());
const ocsjs = await resource("https://cdn.jsdelivr.net/npm/ocsjs/dist/js/index.min.js?t=" + Date.now());

// 加载 bootstrap icons 图标样式
const link = document.createElement("link");
Expand Down
3 changes: 3 additions & 0 deletions packages/app/.gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# customize

## 油猴拓展文件
extensions/Tampermonkey

*.local.test.js

pnpm-lock.yaml
Expand Down
4 changes: 1 addition & 3 deletions packages/app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ const { globalListenerRegister } = require("./src/tasks/global.listener");
const { task } = require("./src/utils");
const { handleError } = require("./src/tasks/error.handler");

const { fetchScriptFile } = require("./src/tasks/fetch.script.file");

/** @type {BrowserWindow | undefined} */
let window;

Expand All @@ -36,7 +34,7 @@ function bootstrap() {
window = createWindow();
task("初始化远程通信模块", () => remoteRegister(window));
task("注册app事件监听器", () => globalListenerRegister(window));
task("获取最新OCS脚本", () => fetchScriptFile());

if (app.isPackaged) {
await window.loadFile("public/index.html");
} else {
Expand Down
33 changes: 13 additions & 20 deletions packages/app/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
const ocs = require("@ocsjs/scripts");
const { loggerPrefix } = require("@ocsjs/scripts");
const { Instance: Chalk } = require("chalk");
const { readFileSync } = require("fs");
const { default: fetch } = require("node-fetch");
const path = require("path");
const { LoggerCore } = require("./src/logger.core");
const { bgRedBright, bgBlueBright, bgYellowBright, bgGray } = new Chalk({ level: 2 });

Expand All @@ -17,9 +18,7 @@ let page;

process.on("message", async (message) => {
// @ts-ignore
const { action, data, uid, logsPath, configPath } = JSON.parse(message);

const store = JSON.parse(readFileSync(configPath).toString());
const { action, data, uid, logsPath } = JSON.parse(message);

if (logger === undefined) {
logger = new LoggerCore(logsPath, false, "script", uid);
Expand All @@ -38,7 +37,7 @@ process.on("message", async (message) => {

/** @type {import("@ocsjs/scripts").LaunchScriptsOptions} */
const options = JSON.parse(data);
const { userDataDir, launchOptions, scripts } = options;
const { userDataDir, launchOptions, scripts, init } = options;
console.log("\n");
debug("任务启动", uid);
debug("隐身模式 ", launchOptions.headless === true ? bgBlueBright("开启") : bgRedBright("关闭"));
Expand All @@ -57,11 +56,20 @@ process.on("message", async (message) => {
},
};

/** 加载油猴 */
const pathToExtension = path.join(__dirname, "./extensions/Tampermonkey");

launchOptions.args = [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`,
];

const { browser: _browser, page: _page } = await ocs.launchScripts({
userDataDir,
launchOptions,
scripts,
sync: false,
init,
});

debug("启动成功");
Expand All @@ -71,13 +79,9 @@ process.on("message", async (message) => {
// @ts-ignore
page = _page;

page.on("load", () => executeScript(page, store.scriptFile));

page.context().on("page", (_page) => {
if (_page.url() === "about:blank") {
setTimeout(() => _page.close(), 500);
} else {
_page.on("load", () => executeScript(page, store.scriptFile));
}
});
} else {
Expand All @@ -103,14 +107,3 @@ process.on("message", async (message) => {
logger.info("任务发生未知错误!", e);
}
});

/**
* 执行 ocs 脚本
* @param {import("playwright").Page} page
* @param {string} script
*/
async function executeScript(page, script) {
await page.waitForFunction(() => window.document.readyState === "complete", "", { timeout: 0 });
console.log(bgGray(loggerPrefix("debug")), "执行脚本");
await page.evaluate(script);
}
30 changes: 0 additions & 30 deletions packages/app/src/tasks/fetch.script.file.js

This file was deleted.

35 changes: 33 additions & 2 deletions packages/scripts/src/nodejs/script.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import axios from "axios";
import { Browser, BrowserContext, chromium, LaunchOptions, Page } from "playwright";
import { CX, ZHS } from ".";
import { ScriptFunction, ScriptOptions } from "./types";
Expand All @@ -18,6 +19,8 @@ export interface LaunchScriptsOptions {
scripts: Script[];
/** 是否等待脚本执行,否:直接返回 browser 和 page 对象 */
sync?: boolean;
/** 是否初始化油猴脚本 */
init?: boolean;
}

export const scripts: Record<keyof ScriptOptions, ScriptFunction> = {
Expand All @@ -43,7 +46,7 @@ export const scriptNames = [
/**
* 运行脚本
*/
export async function launchScripts({ userDataDir, launchOptions, scripts, sync = true }: LaunchScriptsOptions) {
export async function launchScripts({ userDataDir, launchOptions, scripts, sync = true, init }: LaunchScriptsOptions) {
let browser: Browser | BrowserContext;

if (userDataDir && userDataDir !== "") {
Expand All @@ -53,7 +56,10 @@ export async function launchScripts({ userDataDir, launchOptions, scripts, sync
}
let page = await browser.newPage();


if (init) {
initScript(browser);
}

if (sync) {
for (const item of scripts) {
page = await script(item.name, item.options)(page);
Expand All @@ -67,6 +73,8 @@ export async function launchScripts({ userDataDir, launchOptions, scripts, sync
}
}

await page.bringToFront();

return {
browser,
page,
Expand All @@ -77,3 +85,26 @@ export function script<T extends keyof ScriptOptions>(name: T, options: ScriptOp
return scripts[name](page, options);
};
}

/**
* 安装 ocs 脚本
*
*/
async function initScript(browser: Browser | BrowserContext) {
/** 获取最新资源信息 */
const { data } = await axios.get("https://cdn.jsdelivr.net/npm/ocsjs/public/infos.json?t=" + Date.now());
const info = JSON.parse(data);

const page = await browser.newPage();
await page.goto(info.resource.tampermonkey);

const [installPage] = await Promise.all([
page.context().waitForEvent("page"),
// @ts-ignore
page.click(".install-link"),
]);

await installPage.click('[value="安装"],[value="重新安装"]');
await page.close();
await installPage.close();
}
2 changes: 1 addition & 1 deletion packages/web/src/components/CodeHighlight.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
</template>

<script setup lang="ts">
import { ref, toRefs, computed } from "vue";
import { ref, toRefs, computed, watch } from "vue";
import highlight from "highlight.js/lib/core";
import jsonLanguage from "highlight.js/lib/languages/json";
Expand Down
45 changes: 33 additions & 12 deletions packages/web/src/components/file/File.vue
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,16 @@
/>
</span>
</div>
<div class="form">
<label>自动更新OCS脚本</label>
<span class="w-100 text-start">
<a-switch
checked-children="开启"
un-checked-children="关闭"
v-model:checked="data.options.init"
/>
</span>
</div>
<div class="form">
<label>浏览器路径</label>
<a-input
Expand Down Expand Up @@ -229,6 +239,16 @@ interface FormCreateProps {
const props = withDefaults(defineProps<FormCreateProps>(), {});
const { file } = toRefs(props);

/** 解析文件内容 */
const result = validFileContent(fs.readFileSync(file.value.path).toString());
let options;
let error;
if (typeof result === "string") {
options = JSON.parse(result);
} else {
error = result.error;
}

const data = reactive<{
activeKey: "setting" | "terminal" | "content";
content: string;
Expand All @@ -243,26 +263,19 @@ const data = reactive<{
/** 文件内容 */
content: fs.readFileSync(file.value.path).toString(),
/** 解析内容 */
options: undefined,
options: options,
/** 是否错误 */
error: undefined,
error: error,

/** 开启无痕浏览 */
openIncognito: false,

/** 运行的子进程对象 */
process: new Process(file.value.uid, store["logs-path"], store["config-path"]),
process: new Process(file.value.uid, store["logs-path"]),
/** 终端对象 */
xterm: new ITerminal(file.value.uid),
});

const result = validFileContent(data.content);
if (typeof result === "string") {
data.options = JSON.parse(result);
} else {
data.error = result.error;
}

if (data.options && data.error === undefined) {
/** 更新用户浏览器缓存文件夹 */
setUserDataDir();
Expand All @@ -285,6 +298,7 @@ if (data.options && data.error === undefined) {
data.options,
debounce(() => {
const value = JSON.stringify(data.options, null, 4);
data.content = value;
fs.writeFileSync(file.value.path, value);
}, 500)
);
Expand Down Expand Up @@ -329,10 +343,17 @@ function run() {
file.value.stat.running = !file.value.stat.running;

if (file.value.stat.running) {
/** 如未初始化,则先初始化 */
/** 如未初始化控制台面板,则先初始化 */
if (data.process.shell === undefined) data.process.init(data.xterm);
/** 初始化文件 */

/** 运行 */
data.process.launch(data.options);
// @ts-ignore
if (data.options.init === undefined) {
// @ts-ignore 关闭初始化,下次将不再初始化脚本
data.options.init = false;
}
} else {
data.process.close();
}
Expand Down Expand Up @@ -449,7 +470,7 @@ onUnmounted(() => {
}

label {
width: 30%;
width: 40%;
text-align: left;

&::after {
Expand Down
3 changes: 1 addition & 2 deletions packages/web/src/components/terminal/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class Process {
launched: boolean = false;
options?: LaunchScriptsOptions;

constructor(public uid: string, public logsPath: string, public configPath: string) {}
constructor(public uid: string, public logsPath: string) {}

/**
* 使用 child_process 运行 ocs 命令
Expand Down Expand Up @@ -49,7 +49,6 @@ export class Process {
data: JSON.stringify(data),
uid: this.uid,
logsPath: this.logsPath,
configPath: this.configPath,
})
);
}
Expand Down
1 change: 1 addition & 0 deletions packages/web/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export const config = reactive({
options: {},
},
],
init: true,
} as LaunchScriptsOptions,
null,
4
Expand Down
1 change: 0 additions & 1 deletion packages/web/src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ export const store = reactive({
},
/** 列表展开的 key */
expandedKeys: s.get("expandedKeys") || [],
scriptFile: s.get("scriptFile") || "",
});

window.addEventListener("load", () => {
Expand Down
4 changes: 2 additions & 2 deletions public/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
var resource = (url) => fetch(url).then((res) => res.text());
// 载入 OCS 并运行
(async () => {
const style = await resource("https://cdn.jsdelivr.net/npm/ocsjs@latest/dist/style/common.css");
const ocsjs = await resource("https://cdn.jsdelivr.net/npm/ocsjs@latest/dist/js/index.min.js");
const style = await resource("https://cdn.jsdelivr.net/npm/ocsjs/dist/style/common.css?t=" + Date.now());
const ocsjs = await resource("https://cdn.jsdelivr.net/npm/ocsjs/dist/js/index.min.js?t=" + Date.now());

// 加载 bootstrap icons 图标样式
const link = document.createElement("link");
Expand Down
6 changes: 6 additions & 0 deletions public/infos.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"resource": {
"browser": "https://cdn.jsdelivr.net/npm/ocsjs@3.x/dist/js/index.min.js",
"tampermonkey": "https://greasyfork.org/zh-CN/scripts/442075-ocs-%E7%BD%91%E8%AF%BE%E5%8A%A9%E6%89%8B"
}
}

0 comments on commit e16d954

Please sign in to comment.