Skip to content

Commit

Permalink
fix: 修复软件1.2.0自动更新BUG
Browse files Browse the repository at this point in the history
  • Loading branch information
enncy committed Apr 3, 2022
1 parent 0831102 commit 512b61c
Show file tree
Hide file tree
Showing 14 changed files with 104 additions and 53 deletions.
3 changes: 1 addition & 2 deletions packages/app/electron.builder.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
"asar": false,
"copyright": "Copyright © 2021 ${author}",
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true
"oneClick": true
},
"win": {
"icon": "public/favicon.ico",
Expand Down
5 changes: 3 additions & 2 deletions packages/app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,16 @@ function bootstrap() {
task("注册app事件监听器", () => globalListenerRegister(window));

if (app.isPackaged) {
task("软件更新", () => updater(window));
await window.loadFile("public/index.html");
} else {
await window.loadURL("http://localhost:3000");
}

window.show();

window.webContents.openDevTools();
if (app.isPackaged) {
task("软件更新", () => updater(window));
}
}),
])
);
Expand Down
2 changes: 1 addition & 1 deletion packages/app/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ocsjs/app",
"version": "1.2.0",
"version": "1.2.1",
"description": "app package of ocs",
"main": "index.js",
"scripts": {
Expand Down
25 changes: 13 additions & 12 deletions packages/app/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const { bgRedBright, bgBlueBright, bgYellowBright, bgGray } = new Chalk({ level:
/** @type { LoggerCore} */
let logger;

/** @type {import("playwright").BrowserContext | import("playwright").Browser} */
/** @type {import("playwright").BrowserContext } */
let browser;
/** @type {import("playwright").Page} */
let page;
Expand All @@ -28,6 +28,11 @@ process.on("message", async (message) => {
logger.info("未处理的错误!", e);
});

process.on("uncaughtException", (e) => {
console.log(bgRedBright(loggerPrefix("error")), "未处理的错误 : ", e);
logger.info("未处理的错误!", e);
});

try {
if (action === "launch") {
if (browser === undefined) {
Expand All @@ -36,14 +41,9 @@ process.on("message", async (message) => {
/** @type {import("@ocsjs/scripts").LaunchScriptsOptions} */
const options = JSON.parse(data);
const { userDataDir, launchOptions, scripts, init, localStorage: ocsLocalStorage } = options;
console.log("\n");
debug("任务启动", uid);
debug("隐身模式 ", launchOptions.headless === true ? bgBlueBright("开启") : bgRedBright("关闭"));
debug("无痕浏览 ", userDataDir === "" ? bgBlueBright("开启") : bgRedBright("关闭"));
const debug = (...msg) => console.log(bgGray(loggerPrefix("debug")), ...msg);

function debug(...msg) {
console.log(bgGray(loggerPrefix("debug")), ...msg);
}
debug("任务启动", uid);

launchOptions.logger = {
isEnabled: () => true,
Expand Down Expand Up @@ -80,8 +80,6 @@ process.on("message", async (message) => {
page.on("load", () => injectLocalStorage(page));

page.context().on("page", (_page) => {
debug("新开页面");

if (_page.url() === "about:blank") {
setTimeout(() => _page.close(), 500);
} else {
Expand All @@ -97,12 +95,15 @@ process.on("message", async (message) => {
let opts;
try {
opts = JSON.parse(window.localStorage.OCS);
if (opts.setting === undefined) {
opts = { setting: {} };
}
} catch {
opts = { setting: {} };
}
console.log("options", opts);

if (str && opts.setting) {
opts.setting.answererWrappers = JSON.parse(str)?.setting?.answererWrappers;
opts.setting.answererWrappers = JSON.parse(str)?.setting?.answererWrappers || [];
window.localStorage.OCS = JSON.stringify(opts);
// @ts-ignore
if (window.OCS) {
Expand Down
22 changes: 18 additions & 4 deletions packages/app/src/tasks/updater.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
const { app, dialog, clipboard } = require("electron");
const semver = require("semver");
const { Logger } = require("../logger");

const AdmZip = require("adm-zip");
const path = require("path");
const { downloadFile } = require("../utils");
const { OCSApi } = require("@ocsjs/common");
const { writeFileSync, rmSync } = require("fs");

exports.updater = async function (win) {
const logger = Logger("updater");
Expand Down Expand Up @@ -36,19 +37,32 @@ exports.updater = async function (win) {
});

if (response === 1) {
const dest = path.join(app.getAppPath(), `../app-${tag}.zip`);
const appPath = app.getAppPath();
/** 日志路径 */
const logPath = path.join(appPath, `../update-${tag}.log`);
/** 安装路径 */
const dest = path.join(appPath, `../app-${tag}.zip`);
/** 解压路径 */
const unzipDest = path.join(appPath, "./");

/** 删除app */
rmSync(unzipDest, { recursive: true, force: true });
/** 添加日志 */
writeFileSync(logPath, JSON.stringify(Object.assign(newVersion, { dest, unzipDest }), null, 4));

logger.info("更新文件 : " + dest);
logger.info("解压路径 : " + unzipDest);
try {
/** 下载最新版本 */
await downloadFile(url, dest, (rate, totalLength, chunkLength) => {
win?.webContents?.send("update", tag, rate, totalLength, chunkLength);
});

/** 解压缩 */
const AdmZip = require("adm-zip");
const zip = new AdmZip(dest);

new Promise((resolve, reject) => {
zip.extractAllTo(path.join(app.getAppPath(), "../"), true);
zip.extractAllTo(unzipDest, true);
resolve();
})
.then(() => {
Expand Down
6 changes: 4 additions & 2 deletions packages/app/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ exports.task = async function (name, func) {
*/
exports.downloadFile = async function (fileURL, outputURL, rateHandler) {
logger.info("downloadFile", fileURL, outputURL);
const writer = createWriteStream(outputURL);

return new Promise(async (resolve, reject) => {
const { data, headers } = await axios.get(fileURL, {
responseType: "stream",
Expand All @@ -39,7 +39,9 @@ exports.downloadFile = async function (fileURL, outputURL, rateHandler) {
rateHandler(rate, totalLength, chunkLength);
});

const writer = createWriteStream(outputURL);
data.pipe(writer);
resolve(finished(writer));
await finished(writer);
resolve();
});
};
5 changes: 5 additions & 0 deletions packages/app/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const { rmSync, writeFileSync } = require("fs");

writeFileSync("C:\\Program Files\\ocs\\resources\\update.log", "....");

// rmSync("C:\\Program Files\\ocs\\resources\\app", { recursive: true, force: true });
22 changes: 17 additions & 5 deletions packages/scripts/src/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,28 @@ export const scriptNames = [
["zhs-login-school", "智慧树学校登录"],
];

process.on("unhandledRejection", (e) => {
console.error("未知错误", e);
});

process.on("uncaughtException", (e) => {
console.error("未知错误", e);
});

/**
* 运行脚本
*/
export async function launchScripts({ userDataDir, launchOptions, scripts, sync = true, init }: LaunchScriptsOptions) {
let browser: Browser | BrowserContext;

if (userDataDir && userDataDir !== "") {
browser = await chromium.launchPersistentContext(userDataDir, launchOptions);
let browser: BrowserContext;

if (userDataDir) {
browser = await chromium.launchPersistentContext(userDataDir, {
viewport: null,
ignoreHTTPSErrors: true,
...launchOptions,
});
} else {
browser = await chromium.launch(launchOptions);
throw "传入的数据文件夹为空";
}
let page = await browser.newPage();

Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { notify } from "./utils/notify";
import { fetchRemoteNotify } from "./utils";
/** 获取最新远程通知 */
fetchRemoteNotify();
fetchRemoteNotify(false);
/** 如果正在更新的话,获取更新进度 */
const { ipcRenderer } = require("electron");
Expand Down
11 changes: 8 additions & 3 deletions packages/web/src/components/Title.vue
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
<a-menu-item @click="relaunch">重新启动</a-menu-item>
<a-menu-divider />

<a-menu-item @click="remote.win.call('setAlwaysOnTop')"
<a-menu-item @click="remote.win.call('setAlwaysOnTop', true)"
>窗口置顶</a-menu-item
>

Expand Down Expand Up @@ -62,6 +62,7 @@
url="https://github.com/enncy/online-course-script#readme"
/>
<a-menu-item @click="about">关于</a-menu-item>
<a-menu-item @click="allNotify">全部通知</a-menu-item>

<TitleLink
title="版本更新"
Expand Down Expand Up @@ -94,7 +95,7 @@ import { config } from "../config";
import { router, routes } from "../route";
import { remote } from "../utils/remote";
import TitleLink from "./TitleLink.vue";
import { formatDate } from "../utils";
import { fetchRemoteNotify, formatDate } from "../utils";
import { path } from "./file/File";
import { h, ref, watch } from "vue";
import favicon from "root/public/favicon.ico";
Expand Down Expand Up @@ -126,13 +127,17 @@ function openLog() {
shell.openPath(path.join(remote.app.call("getPath", "logs"), formatDate()));
}

function allNotify() {
fetchRemoteNotify(true);
}

function about() {
Modal.info({
title: "关于",
closable: true,
maskClosable: true,
content: h("ul", [
h("li", "版本 : " + store.version),
h("li", "软件版本 : " + remote.app.call("getVersion")),
h("li", [
h("span", "版本详情 : "),
h(
Expand Down
11 changes: 8 additions & 3 deletions packages/web/src/components/file/File.vue
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ import Icon from "../Icon.vue";
import { Process } from "../terminal/process";
import { ITerminal } from "../terminal";
import { Project } from "../project";
import { message } from "ant-design-vue";
const { scriptNames } = require("@ocsjs/scripts");
const childProcess = require("child_process") as typeof import("child_process");

Expand Down Expand Up @@ -263,10 +264,14 @@ function onScriptChange() {

/** 验证表单 */
function submitData() {
if (dataForm.value.checkValidity()) {
run();
if (!store.script.launchOptions.executablePath) {
message.error("请前往 设置 -> 指定浏览器 , 设置您的默认浏览器。");
} else {
dataForm.value.reportValidity();
if (dataForm.value.checkValidity()) {
run();
} else {
dataForm.value.reportValidity();
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/web/src/components/terminal/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class Process {

const shell = child_process.fork(target, { stdio: ["ipc"] });
shell.stdout?.on("data", (data: any) => xterm.write(data));
shell.stderr?.on("data", (data: any) => xterm.write(chalk.redBright(data)));
shell.stderr?.on("data", (data: any) => remote.logger.call("error", String(data)));
this.shell = shell;
}

Expand Down
31 changes: 19 additions & 12 deletions packages/web/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,24 +55,29 @@ export function formatDate() {
].join("-");
}

/** 获取远程通知 */
export async function fetchRemoteNotify() {
/**
* 获取远程通知
* @param readAll 是否阅读全部
*/
export async function fetchRemoteNotify(readAll: boolean) {
try {
const infos = await OCSApi.getInfos();

const remoteNotify = infos.notify;
let remoteNotify = infos.notify;
const storeNotify: typeof infos.notify = store.notify;
/** 寻找未阅读的通知 */
const unread = remoteNotify.filter(
(item) => storeNotify.findIndex((localeItem) => item?.id === localeItem?.id) === -1
);
if (!readAll) {
remoteNotify = remoteNotify.filter(
(item) => storeNotify.findIndex((localeItem) => item?.id === localeItem?.id) === -1
);
}

console.log("notify", { infos, exits: storeNotify, unread });
if (unread.length) {
console.log("notify", { infos, exits: storeNotify, remoteNotify });
if (remoteNotify.length) {
Modal.info({
title: () => "🎉最新公告🎉",
okText: "朕已阅读",
cancelText: "下次一定",
okText: readAll ? "确定" : "朕已阅读",
cancelText: readAll ? "取消" : "下次一定",
okCancel: true,
style: { top: "20px" },
content: () =>
Expand All @@ -84,7 +89,7 @@ export async function fetchRemoteNotify() {
overflow: "auto",
},
},
unread.map((item) =>
remoteNotify.map((item) =>
h("div", [
h(
"div",
Expand All @@ -104,7 +109,9 @@ export async function fetchRemoteNotify() {
)
),
onOk() {
store.notify = [...store.notify].concat(unread);
if (!readAll) {
store.notify = [...store.notify].concat(remoteNotify);
}
},
onCancel() {},
});
Expand Down
10 changes: 5 additions & 5 deletions scripts/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@ const del = require("del");
const zip = require("gulp-zip");
const { exec } = require("child_process");

function cleanOutput() {
return del(["../packages/app/dist"], { force: true });
}

function buildWeb() {
return exec("pnpm build", { cwd: "../packages/web" });
}
Expand All @@ -15,8 +11,12 @@ function buildApp() {
return exec("pnpm dist", { cwd: "../packages/app" });
}

function cleanOutput() {
return del(["../packages/app/dist/app.zip"], { force: true });
}

function packResource() {
return src("../packages/app/dist/win-unpacked/resources/app/*")
return src("../packages/app/dist/win-unpacked/resources/app/**/*")
.pipe(zip("app.zip"))
.pipe(dest("../packages/app/dist"));
}
Expand Down

0 comments on commit 512b61c

Please sign in to comment.