refactor: http download function

This commit is contained in:
linyuchen
2024-03-19 14:36:58 +08:00
parent fa5540da5c
commit 3a964af0b0
7 changed files with 65 additions and 64 deletions

View File

@@ -1,10 +1,10 @@
{ {
"manifest_version": 4, "manifest_version": 4,
"type": "extension", "type": "extension",
"name": "LLOneBot v3.16.1", "name": "LLOneBot v3.16.0",
"slug": "LLOneBot", "slug": "LLOneBot",
"description": "LiteLoaderQQNT的OneBotApi,不支持商店在线更新", "description": "LiteLoaderQQNT的OneBotApi,不支持商店在线更新",
"version": "3.16.1", "version": "3.16.0",
"icon": "./icon.jpg", "icon": "./icon.jpg",
"authors": [ "authors": [
{ {

13
package-lock.json generated
View File

@@ -14,7 +14,6 @@
"file-type": "^19.0.0", "file-type": "^19.0.0",
"fluent-ffmpeg": "^2.1.2", "fluent-ffmpeg": "^2.1.2",
"level": "^8.0.1", "level": "^8.0.1",
"node-stream-zip": "^1.15.0",
"silk-wasm": "^3.2.3", "silk-wasm": "^3.2.3",
"utf-8-validate": "^6.0.3", "utf-8-validate": "^6.0.3",
"uuid": "^9.0.1", "uuid": "^9.0.1",
@@ -5067,18 +5066,6 @@
"integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==",
"dev": true "dev": true
}, },
"node_modules/node-stream-zip": {
"version": "1.15.0",
"resolved": "https://registry.npmjs.org/node-stream-zip/-/node-stream-zip-1.15.0.tgz",
"integrity": "sha512-LN4fydt9TqhZhThkZIVQnF9cwjU3qmUH9h78Mx/K7d3VvfRqqwthLwJEUOEL0QPZ0XQmNN7be5Ggit5+4dq3Bw==",
"engines": {
"node": ">=0.12.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/antelle"
}
},
"node_modules/normalize-url": { "node_modules/normalize-url": {
"version": "6.1.0", "version": "6.1.0",
"resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz", "resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",

View File

@@ -9,6 +9,8 @@ import {DATA_DIR, log, TEMP_DIR} from "./index";
import {getConfigUtil} from "../config"; import {getConfigUtil} from "../config";
import {dbUtil} from "../db"; import {dbUtil} from "../db";
import * as fileType from "file-type"; import * as fileType from "file-type";
import {net} from "electron";
import ClientRequestConstructorOptions = Electron.ClientRequestConstructorOptions;
export function isGIF(path: string) { export function isGIF(path: string) {
const buffer = Buffer.alloc(4); const buffer = Buffer.alloc(4);
@@ -79,7 +81,7 @@ export function checkFfmpeg(newPath: string = null): Promise<boolean> {
resolve(true); resolve(true);
} }
}) })
}catch (e) { } catch (e) {
resolve(false); resolve(false);
} }
}); });
@@ -268,6 +270,26 @@ export function calculateFileMD5(filePath: string): Promise<string> {
}); });
} }
export function httpDownload(options: ClientRequestConstructorOptions | string): Promise<Buffer> {
let chunks: Buffer[] = [];
let netRequest = net.request(options)
return new Promise((resolve, reject) => {
netRequest.on("response", (response) => {
if (!(response.statusCode >= 200 && response.statusCode < 300)) {
return reject(new Error(`下载失败,状态码${response.statusCode}`))
}
response.on("data", (chunk) => {
chunks.push(chunk);
}).on("end", () => {
resolve(Buffer.concat(chunks));
})
}).on("error", (err) => {
reject(err);
})
netRequest.end()
})
}
type Uri2LocalRes = { type Uri2LocalRes = {
success: boolean, success: boolean,
errMsg: string, errMsg: string,

View File

@@ -6,7 +6,7 @@ export * from './helper'
export * from './log' export * from './log'
export * from './qqlevel' export * from './qqlevel'
export * from './qqpkg' export * from './qqpkg'
export * from './update' export * from './upgrade'
export const DATA_DIR = global.LiteLoader.plugins["LLOneBot"].path.data; export const DATA_DIR = global.LiteLoader.plugins["LLOneBot"].path.data;
export const TEMP_DIR = path.join(DATA_DIR, "temp"); export const TEMP_DIR = path.join(DATA_DIR, "temp");
export const PLUGIN_DIR = global.LiteLoader.plugins["LLOneBot"].path.plugin; export const PLUGIN_DIR = global.LiteLoader.plugins["LLOneBot"].path.plugin;

View File

@@ -1,46 +1,50 @@
import { version } from "../../version"; import {version} from "../../version";
import https from "node:https";
//import http from "node:http";
import * as path from "node:path"; import * as path from "node:path";
import * as fs from "node:fs"; import * as fs from "node:fs";
import { PLUGIN_DIR, TEMP_DIR } from "."; import {httpDownload, log, PLUGIN_DIR, TEMP_DIR} from ".";
import compressing from "compressing"; import compressing from "compressing";
const downloadMirrorHosts = ["https://mirror.ghproxy.com/"];
const checkVersionMirrorHosts = ["https://521github.com"];
export async function checkVersion() { export async function checkVersion() {
const latestVersionText = await getRemoteVersion(); const latestVersionText = await getRemoteVersion();
const latestVersion = latestVersionText.split("."); const latestVersion = latestVersionText.split(".");
log("llonebot last version", latestVersion);
const currentVersion = version.split("."); const currentVersion = version.split(".");
for (let k in [0, 1, 2]) { for (let k in [0, 1, 2]) {
if (latestVersion[k] > currentVersion[k]) { if (latestVersion[k] > currentVersion[k]) {
return { result: false, version: latestVersionText }; return {result: false, version: latestVersionText};
} }
} }
return { result: true, version: version }; return {result: true, version: version};
} }
export async function updateLLOneBot() {
let mirrorGithubList = ["https://mirror.ghproxy.com/"]; export async function upgradeLLOneBot() {
const latestVersion = await getRemoteVersion(); const latestVersion = await getRemoteVersion();
if (latestVersion && latestVersion != "") { if (latestVersion && latestVersion != "") {
const downloadUrl = "https://github.com/LLOneBot/LLOneBot/releases/download/v" + latestVersion + "/LLOneBot.zip"; const downloadUrl = "https://github.com/LLOneBot/LLOneBot/releases/download/v" + latestVersion + "/LLOneBot.zip";
const realUrl = mirrorGithubList[0] + downloadUrl; const mirrorUrl = downloadMirrorHosts[0] + downloadUrl;
const filePath = path.join(TEMP_DIR, "./update-" + latestVersion + ".zip"); const filePath = path.join(TEMP_DIR, "./update-" + latestVersion + ".zip");
const fileStream = fs.createWriteStream(filePath); const fileStream = fs.createWriteStream(filePath);
let downloadPromise = async function (filePath): Promise<boolean> { let downloadSuccess = false;
return new Promise((resolve, reject) => { // 多镜像下载
https.get(filePath, res => { for(const mirrorGithub of downloadMirrorHosts){
res.pipe(fileStream); try{
res.on('end', () => { const buffer = await httpDownload(mirrorGithub + downloadUrl);
resolve(true); fs.writeFileSync(filePath, buffer)
}); downloadSuccess = true;
}).on('error', err => { break;
resolve(false); }catch (e) {
}); log("llonebot upgrade error", e);
}); }
} }
if (!(await downloadPromise(realUrl))) { if (!downloadSuccess){
// 下载异常 log("llonebot upgrade error", "download failed");
return false; return false;
} }
let uncompressPromise = async function () { let uncompressedPromise = async function () {
return new Promise<boolean>((resolve, reject) => { return new Promise<boolean>((resolve, reject) => {
compressing.zip.uncompress(filePath, PLUGIN_DIR).then(() => { compressing.zip.uncompress(filePath, PLUGIN_DIR).then(() => {
resolve(true); resolve(true);
@@ -53,16 +57,16 @@ export async function updateLLOneBot() {
}); });
}); });
} }
const uncompressResult = await uncompressPromise(); const uncompressResult = await uncompressedPromise();
return uncompressResult; return uncompressResult;
} }
return false; return false;
} }
export async function getRemoteVersion() { export async function getRemoteVersion() {
let mirrorGithubList = ["https://521github.com"];
let Version = ""; let Version = "";
for (let i = 0; i < mirrorGithubList.length; i++) { for (let i = 0; i < checkVersionMirrorHosts.length; i++) {
let mirrorGithub = mirrorGithubList[i]; let mirrorGithub = checkVersionMirrorHosts[i];
let tVersion = await getRemoteVersionByMirror(mirrorGithub); let tVersion = await getRemoteVersionByMirror(mirrorGithub);
if (tVersion && tVersion != "") { if (tVersion && tVersion != "") {
Version = tVersion; Version = tVersion;
@@ -71,29 +75,17 @@ export async function getRemoteVersion() {
} }
return Version; return Version;
} }
export async function getRemoteVersionByMirror(mirrorGithub: string) { export async function getRemoteVersionByMirror(mirrorGithub: string) {
let releasePage = "error"; let releasePage = "error";
let reqPromise = async function (): Promise<string> {
return new Promise((resolve, reject) => {
https.get(mirrorGithub + "/LLOneBot/LLOneBot/releases", res => {
let list = [];
res.on('data', chunk => {
list.push(chunk);
});
res.on('end', () => {
resolve(Buffer.concat(list).toString());
});
}).on('error', err => {
reject();
});
});
}
try { try {
releasePage = await reqPromise(); releasePage = (await httpDownload(mirrorGithub + "/LLOneBot/LLOneBot/releases")).toString();
log("releasePage", releasePage);
if (releasePage === "error") return ""; if (releasePage === "error") return "";
return releasePage.match(new RegExp('(?<=(tag/v)).*?(?=("))'))[0]; return releasePage.match(new RegExp('(?<=(tag/v)).*?(?=("))'))[0];
} catch {
} }
catch { }
return ""; return "";
} }

View File

@@ -41,7 +41,7 @@ import {NTQQUserApi} from "../ntqqapi/api/user";
import {NTQQGroupApi} from "../ntqqapi/api/group"; import {NTQQGroupApi} from "../ntqqapi/api/group";
import {registerPokeHandler} from "../ntqqapi/external/ccpoke"; import {registerPokeHandler} from "../ntqqapi/external/ccpoke";
import {OB11FriendPokeEvent, OB11GroupPokeEvent} from "../onebot11/event/notice/OB11PokeEvent"; import {OB11FriendPokeEvent, OB11GroupPokeEvent} from "../onebot11/event/notice/OB11PokeEvent";
import {checkVersion, updateLLOneBot} from "../common/utils/update"; import {checkVersion, upgradeLLOneBot} from "../common/utils/upgrade";
import {checkFfmpeg} from "../common/utils/file"; import {checkFfmpeg} from "../common/utils/file";
import {log} from "../common/utils/log"; import {log} from "../common/utils/log";
import {getConfigUtil} from "../common/config"; import {getConfigUtil} from "../common/config";
@@ -57,7 +57,7 @@ function onLoad() {
return checkVersion(); return checkVersion();
}); });
ipcMain.handle(CHANNEL_UPDATE, async (event, arg) => { ipcMain.handle(CHANNEL_UPDATE, async (event, arg) => {
return updateLLOneBot(); return upgradeLLOneBot();
}); });
ipcMain.handle(CHANNEL_SELECT_FILE, async (event, arg) => { ipcMain.handle(CHANNEL_SELECT_FILE, async (event, arg) => {
const selectPath = new Promise<string>((resolve, reject) => { const selectPath = new Promise<string>((resolve, reject) => {

View File

@@ -1 +1 @@
export const version = "3.16.1" export const version = "3.16.0"