mirror of
https://gitee.com/spark-store-project/spark-store
synced 2026-04-26 09:20:18 +08:00
feat(install): add metalink download support and progress tracking
close #12
This commit is contained in:
@@ -725,6 +725,7 @@ export const watchDownloadsChange = (callback: () => void) => {
|
||||
### Code Style
|
||||
|
||||
- **Use TypeScript strict mode** - no `any` types without `eslint-disable`
|
||||
- **Avoid used of eslint-disable directly** - use `undefined` instead if you really do not know its type.
|
||||
- **Prefer Composition API** - `<script setup lang="ts">`
|
||||
- **Use arrow functions** for methods in setup
|
||||
- **Destructure imports** - `import { ref } from 'vue'`
|
||||
@@ -744,7 +745,7 @@ fix(ui): correct dark mode toggle persistence
|
||||
refactor(ipc): simplify install manager event handling
|
||||
docs(readme): update build instructions
|
||||
```
|
||||
|
||||
Add sign off to the commit is recommended.
|
||||
---
|
||||
|
||||
## 🔗 Related Resources
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { ipcMain, WebContents } from "electron";
|
||||
import { spawn, ChildProcess, exec } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import pino from "pino";
|
||||
|
||||
import { ChannelPayload, InstalledAppInfo } from "../../typedefinition";
|
||||
import axios from "axios";
|
||||
|
||||
const logger = pino({ name: "install-manager" });
|
||||
|
||||
@@ -12,8 +15,12 @@ type InstallTask = {
|
||||
pkgname: string;
|
||||
execCommand: string;
|
||||
execParams: string[];
|
||||
process: ChildProcess | null;
|
||||
download_process: ChildProcess | null;
|
||||
install_process: ChildProcess | null;
|
||||
webContents: WebContents | null;
|
||||
downloadDir?: string;
|
||||
metalinkUrl?: string;
|
||||
filename?: string;
|
||||
};
|
||||
|
||||
const SHELL_CALLER_PATH = "/opt/apm-store/extras/shell-caller.sh";
|
||||
@@ -131,7 +138,7 @@ const parseUpgradableList = (output: string) => {
|
||||
// Listen for download requests from renderer process
|
||||
ipcMain.on("queue-install", async (event, download_json) => {
|
||||
const download = JSON.parse(download_json);
|
||||
const { id, pkgname } = download || {};
|
||||
const { id, pkgname, metalinkUrl, filename } = download || {};
|
||||
|
||||
if (!id || !pkgname) {
|
||||
logger.warn("passed arguments missing id or pkgname");
|
||||
@@ -163,98 +170,224 @@ ipcMain.on("queue-install", async (event, download_json) => {
|
||||
const superUserCmd = await checkSuperUserCommand();
|
||||
let execCommand = "";
|
||||
const execParams = [];
|
||||
const downloadDir = `/tmp/apm-store/download/${pkgname}`;
|
||||
|
||||
if (superUserCmd.length > 0) {
|
||||
execCommand = superUserCmd;
|
||||
execParams.push(SHELL_CALLER_PATH);
|
||||
} else {
|
||||
execCommand = SHELL_CALLER_PATH;
|
||||
}
|
||||
|
||||
if (metalinkUrl && filename) {
|
||||
execParams.push("apm", "ssaudit", `${downloadDir}/${filename}`);
|
||||
} else {
|
||||
execParams.push("apm", "install", "-y", pkgname);
|
||||
}
|
||||
|
||||
const task: InstallTask = {
|
||||
id,
|
||||
pkgname,
|
||||
execCommand,
|
||||
execParams,
|
||||
process: null,
|
||||
download_process: null,
|
||||
install_process: null,
|
||||
webContents,
|
||||
downloadDir,
|
||||
metalinkUrl,
|
||||
filename,
|
||||
};
|
||||
tasks.set(id, task);
|
||||
if (idle) processNextInQueue(0);
|
||||
if (idle) processNextInQueue();
|
||||
});
|
||||
|
||||
function processNextInQueue(index: number) {
|
||||
// Cancel Handler
|
||||
ipcMain.on("cancel-install", (event, id) => {
|
||||
if (tasks.has(id)) {
|
||||
const task = tasks.get(id);
|
||||
if (task) {
|
||||
task.download_process?.kill(); // Kill the download process
|
||||
task.install_process?.kill(); // Kill the install process
|
||||
logger.info(`已取消任务: ${id}`);
|
||||
}
|
||||
// Note: 'close' handler usually handles cleanup
|
||||
}
|
||||
});
|
||||
|
||||
async function processNextInQueue() {
|
||||
if (!idle) return;
|
||||
|
||||
// Always take the first task to ensure sequence
|
||||
const task = Array.from(tasks.values())[0];
|
||||
if (!task) {
|
||||
idle = true;
|
||||
return;
|
||||
}
|
||||
|
||||
idle = false;
|
||||
const task = Array.from(tasks.values())[index];
|
||||
const webContents = task.webContents;
|
||||
let stdoutData = "";
|
||||
let stderrData = "";
|
||||
const { webContents, id, downloadDir } = task;
|
||||
|
||||
webContents.send("install-status", {
|
||||
id: task.id,
|
||||
const sendLog = (msg: string) => {
|
||||
webContents?.send("install-log", { id, time: Date.now(), message: msg });
|
||||
};
|
||||
const sendStatus = (status: string) => {
|
||||
webContents?.send("install-status", {
|
||||
id,
|
||||
time: Date.now(),
|
||||
message: "installing",
|
||||
message: status,
|
||||
});
|
||||
webContents.send("install-log", {
|
||||
id: task.id,
|
||||
time: Date.now(),
|
||||
message: `开始执行: ${task.execCommand} ${task.execParams.join(" ")}`,
|
||||
});
|
||||
logger.info(`启动安装命令: ${task.execCommand} ${task.execParams.join(" ")}`);
|
||||
};
|
||||
|
||||
try {
|
||||
// 1. Metalink & Aria2c Phase
|
||||
if (task.metalinkUrl) {
|
||||
try {
|
||||
if (!fs.existsSync(downloadDir)) {
|
||||
fs.mkdirSync(downloadDir, { recursive: true });
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(`无法创建目录 ${downloadDir}: ${err}`);
|
||||
throw err;
|
||||
}
|
||||
|
||||
const metalinkPath = path.join(downloadDir, `${task.filename}.metalink`);
|
||||
|
||||
sendLog(`正在获取 Metalink 文件: ${task.metalinkUrl}`);
|
||||
|
||||
const response = await axios.get(task.metalinkUrl, {
|
||||
baseURL: "https://erotica.spark-app.store",
|
||||
responseType: "stream",
|
||||
});
|
||||
|
||||
const writer = fs.createWriteStream(metalinkPath);
|
||||
response.data.pipe(writer);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
writer.on("finish", resolve);
|
||||
writer.on("error", reject);
|
||||
});
|
||||
|
||||
sendLog("Metalink 文件下载完成");
|
||||
|
||||
// Aria2c
|
||||
const aria2Args = [
|
||||
`--dir=${downloadDir}`,
|
||||
"--allow-overwrite=true",
|
||||
"--summary-interval=1",
|
||||
"-M",
|
||||
metalinkPath,
|
||||
];
|
||||
|
||||
sendStatus("downloading");
|
||||
sendLog(`启动下载: aria2c ${aria2Args.join(" ")}`);
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const child = spawn("aria2c", aria2Args);
|
||||
task.download_process = child;
|
||||
|
||||
child.stdout.on("data", (data) => {
|
||||
const str = data.toString();
|
||||
// Match ( 12%) or (12%)
|
||||
const match = str.match(/[0-9]+(\.[0-9]+)?%/g);
|
||||
if (match) {
|
||||
const p = parseFloat(match.at(-1)) / 100;
|
||||
webContents?.send("install-progress", { id, progress: p });
|
||||
}
|
||||
});
|
||||
child.stderr.on("data", (d) => sendLog(`aria2c: ${d}`));
|
||||
|
||||
child.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
webContents?.send("install-progress", { id, progress: 1 });
|
||||
resolve();
|
||||
} else {
|
||||
reject(new Error(`Aria2c exited with code ${code}`));
|
||||
}
|
||||
});
|
||||
child.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Install Phase
|
||||
sendStatus("installing");
|
||||
|
||||
const cmdString = `${task.execCommand} ${task.execParams.join(" ")}`;
|
||||
sendLog(`执行安装: ${cmdString}`);
|
||||
logger.info(`启动安装: ${cmdString}`);
|
||||
|
||||
const result = await new Promise<{
|
||||
code: number;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}>((resolve, reject) => {
|
||||
const child = spawn(task.execCommand, task.execParams, {
|
||||
shell: true,
|
||||
env: process.env,
|
||||
});
|
||||
task.process = child;
|
||||
task.install_process = child;
|
||||
|
||||
// 监听 stdout
|
||||
child.stdout.on("data", (data) => {
|
||||
stdoutData += data.toString();
|
||||
webContents.send("install-log", {
|
||||
id: task.id,
|
||||
time: Date.now(),
|
||||
message: data.toString(),
|
||||
});
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
child.stdout.on("data", (d) => {
|
||||
const s = d.toString();
|
||||
stdout += s;
|
||||
sendLog(s);
|
||||
});
|
||||
|
||||
// 监听 stderr
|
||||
child.stderr.on("data", (data) => {
|
||||
stderrData += data.toString();
|
||||
webContents.send("install-log", {
|
||||
id: task.id,
|
||||
time: Date.now(),
|
||||
message: data.toString(),
|
||||
});
|
||||
child.stderr.on("data", (d) => {
|
||||
const s = d.toString();
|
||||
stderr += s;
|
||||
sendLog(s);
|
||||
});
|
||||
|
||||
child.on("close", (code) => {
|
||||
const success = code === 0;
|
||||
// 拼接json消息
|
||||
const messageJSONObj = {
|
||||
message: success ? "安装完成" : `安装失败,退出码 ${code}`,
|
||||
stdout: stdoutData,
|
||||
stderr: stderrData,
|
||||
resolve({ code: code ?? -1, stdout, stderr });
|
||||
});
|
||||
child.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
|
||||
// Completion
|
||||
const success = result.code === 0;
|
||||
const msgObj = {
|
||||
message: success ? "安装完成" : `安装失败,退出码 ${result.code}`,
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
};
|
||||
|
||||
if (success) {
|
||||
logger.info(messageJSONObj);
|
||||
} else {
|
||||
logger.error(messageJSONObj);
|
||||
}
|
||||
if (success) logger.info(msgObj);
|
||||
else logger.error(msgObj);
|
||||
|
||||
webContents.send("install-complete", {
|
||||
id: task.id,
|
||||
success: success,
|
||||
webContents?.send("install-complete", {
|
||||
id,
|
||||
success,
|
||||
time: Date.now(),
|
||||
exitCode: code,
|
||||
message: JSON.stringify(messageJSONObj),
|
||||
exitCode: result.code,
|
||||
message: JSON.stringify(msgObj),
|
||||
});
|
||||
tasks.delete(task.id);
|
||||
} catch (error) {
|
||||
logger.error(`Task ${id} failed: ${error}`);
|
||||
webContents?.send("install-complete", {
|
||||
id,
|
||||
success: false,
|
||||
time: Date.now(),
|
||||
exitCode: -1,
|
||||
message: JSON.stringify({
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
}),
|
||||
});
|
||||
} finally {
|
||||
tasks.delete(id);
|
||||
idle = true;
|
||||
if (tasks.size > 0) processNextInQueue(0);
|
||||
});
|
||||
// Trigger next
|
||||
if (tasks.size > 0) {
|
||||
processNextInQueue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ipcMain.handle("check-installed", async (_event, pkgname: string) => {
|
||||
|
||||
@@ -563,7 +563,9 @@ const cancelDownload = (id: DownloadItem) => {
|
||||
const index = downloads.value.findIndex((d) => d.id === id.id);
|
||||
if (index !== -1) {
|
||||
const download = downloads.value[index];
|
||||
// download.status = 'cancelled'; // 'cancelled' not in DownloadItem type union? Check type
|
||||
// 发送到主进程取消
|
||||
window.ipcRenderer.send("cancel-install", download.id);
|
||||
|
||||
download.status = "failed"; // Use 'failed' or add 'cancelled' to type if needed. User asked to keep type simple.
|
||||
download.logs.push({
|
||||
time: Date.now(),
|
||||
@@ -572,7 +574,10 @@ const cancelDownload = (id: DownloadItem) => {
|
||||
// 延迟删除,让用户看到取消状态
|
||||
setTimeout(() => {
|
||||
logger.info(`删除下载: ${download.pkgname}`);
|
||||
downloads.value.splice(index, 1);
|
||||
// Remove from list only if it's still failed (user didn't retry immediately)
|
||||
// Check index again
|
||||
const idx = downloads.value.findIndex((d) => d.id === id.id);
|
||||
if (idx !== -1) downloads.value.splice(idx, 1);
|
||||
}, 1000);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -203,6 +203,7 @@ import { computed, useAttrs } from "vue";
|
||||
import {
|
||||
useDownloadItemStatus,
|
||||
useInstallFeedback,
|
||||
downloads,
|
||||
} from "../global/downloadStatus";
|
||||
import { APM_STORE_BASE_URL } from "../global/storeConfig";
|
||||
import type { App } from "../global/typedefinition";
|
||||
@@ -225,6 +226,11 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const appPkgname = computed(() => props.app?.pkgname);
|
||||
|
||||
const activeDownload = computed(() => {
|
||||
return downloads.value.find((d) => d.pkgname === props.app?.pkgname);
|
||||
});
|
||||
|
||||
const { installFeedback } = useInstallFeedback(appPkgname);
|
||||
const { isCompleted } = useDownloadItemStatus(appPkgname);
|
||||
const installBtnText = computed(() => {
|
||||
@@ -232,7 +238,17 @@ const installBtnText = computed(() => {
|
||||
// TODO: 似乎有一个时间差,安装好了之后并不是立马就可以从已安装列表看见
|
||||
return "已安装";
|
||||
}
|
||||
return installFeedback.value ? "已加入队列" : "安装";
|
||||
if (installFeedback.value) {
|
||||
const status = activeDownload.value?.status;
|
||||
if (status === "downloading") {
|
||||
return `下载中 ${(activeDownload.value?.progress || 0) * 100}%`;
|
||||
}
|
||||
if (status === "installing") {
|
||||
return "安装中...";
|
||||
}
|
||||
return "已加入队列";
|
||||
}
|
||||
return "安装";
|
||||
});
|
||||
const iconPath = computed(() => {
|
||||
if (!props.app) return "";
|
||||
|
||||
@@ -83,13 +83,13 @@
|
||||
<div class="h-2 rounded-full bg-slate-100 dark:bg-slate-800">
|
||||
<div
|
||||
class="h-full rounded-full bg-brand"
|
||||
:style="{ width: download.progress + '%' }"
|
||||
:style="{ width: downloadProgress + '%' }"
|
||||
></div>
|
||||
</div>
|
||||
<div
|
||||
class="flex flex-wrap items-center justify-between text-sm text-slate-500 dark:text-slate-400"
|
||||
>
|
||||
<span>{{ download.progress }}%</span>
|
||||
<span>{{ downloadProgress }}%</span>
|
||||
<span v-if="download.downloadedSize && download.totalSize">
|
||||
{{ formatSize(download.downloadedSize) }} /
|
||||
{{ formatSize(download.totalSize) }}
|
||||
@@ -170,6 +170,19 @@
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap justify-end gap-3">
|
||||
<button
|
||||
v-if="
|
||||
download.status === 'downloading' ||
|
||||
download.status === 'queued' ||
|
||||
download.status === 'paused'
|
||||
"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-2xl border border-rose-200/60 px-4 py-2 text-sm font-semibold text-rose-500 transition hover:bg-rose-50 dark:border-rose-500/30 dark:text-rose-400 dark:hover:bg-rose-900/20"
|
||||
@click="cancel"
|
||||
>
|
||||
<i class="fas fa-times"></i>
|
||||
取消下载
|
||||
</button>
|
||||
<button
|
||||
v-if="download.status === 'failed'"
|
||||
type="button"
|
||||
@@ -196,6 +209,7 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import type { DownloadItem } from "../global/typedefinition";
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -220,6 +234,12 @@ const handleOverlayClick = () => {
|
||||
close();
|
||||
};
|
||||
|
||||
const cancel = () => {
|
||||
if (props.download) {
|
||||
emit("cancel", props.download);
|
||||
}
|
||||
};
|
||||
|
||||
const retry = () => {
|
||||
if (props.download) {
|
||||
emit("retry", props.download);
|
||||
@@ -286,4 +306,8 @@ const copyLogs = () => {
|
||||
prompt("请手动复制日志:", logsText);
|
||||
});
|
||||
};
|
||||
|
||||
const downloadProgress = computed(() => {
|
||||
return props.download ? Math.floor(props.download.progress * 100) : 0;
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -86,7 +86,7 @@
|
||||
</p>
|
||||
<p class="text-xs text-slate-500 dark:text-slate-400">
|
||||
<span v-if="download.status === 'downloading'"
|
||||
>下载中 {{ download.progress }}%</span
|
||||
>下载中 {{ Math.floor(download.progress * 100) }}%</span
|
||||
>
|
||||
<span v-else-if="download.status === 'installing'"
|
||||
>安装中...</span
|
||||
@@ -104,7 +104,7 @@
|
||||
>
|
||||
<div
|
||||
class="h-full rounded-full bg-brand"
|
||||
:style="{ width: `${download.progress}%` }"
|
||||
:style="{ width: `${download.progress * 100}%` }"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
export interface InstallLog {
|
||||
export interface InstallStatus {
|
||||
id: number;
|
||||
success: boolean;
|
||||
time: number;
|
||||
exitCode: number | null;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface DownloadResult extends InstallLog {
|
||||
export interface InstallLog extends InstallStatus {
|
||||
success: boolean;
|
||||
exitCode: number | null;
|
||||
}
|
||||
|
||||
export interface DownloadResult extends InstallStatus {
|
||||
success: boolean;
|
||||
exitCode: number | null;
|
||||
status: DownloadItemStatus | null;
|
||||
}
|
||||
|
||||
export type DownloadItemStatus =
|
||||
| "downloading"
|
||||
| "installing"
|
||||
@@ -26,7 +30,7 @@ export interface DownloadItem {
|
||||
version: string;
|
||||
icon: string;
|
||||
status: DownloadItemStatus;
|
||||
progress: number; // 0 ~ 100 的百分比,或 0 ~ 1 的小数(建议统一)
|
||||
progress: number; // 0 ~ 1 的小数
|
||||
downloadedSize: number; // 已下载字节数
|
||||
totalSize: number; // 总字节数(可能为 0 初始时)
|
||||
speed: number; // 当前下载速度,单位如 B/s
|
||||
@@ -41,6 +45,8 @@ export interface DownloadItem {
|
||||
retry: boolean; // 当前是否为重试下载
|
||||
upgradeOnly?: boolean; // 是否为仅升级任务
|
||||
error?: string;
|
||||
metalinkUrl?: string; // Metalink 下载链接
|
||||
filename?: string; // 文件名
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
@@ -44,6 +44,8 @@ export const handleInstall = () => {
|
||||
logs: [{ time: Date.now(), message: "开始下载..." }],
|
||||
source: "APM Store",
|
||||
retry: false,
|
||||
filename: currentApp.value.filename,
|
||||
metalinkUrl: `${window.apm_store.arch}/${currentApp.value.category}/${currentApp.value.pkgname}/${currentApp.value.filename}.metalink`,
|
||||
};
|
||||
|
||||
downloads.value.push(download);
|
||||
@@ -114,6 +116,17 @@ window.ipcRenderer.on("install-status", (_event, log: InstallLog) => {
|
||||
const downloadObj = downloads.value.find((d) => d.id === log.id);
|
||||
if (downloadObj) downloadObj.status = log.message as DownloadItemStatus;
|
||||
});
|
||||
|
||||
window.ipcRenderer.on(
|
||||
"install-progress",
|
||||
(_event, payload: { id: number; progress: number }) => {
|
||||
const downloadObj = downloads.value.find((d) => d.id === payload.id);
|
||||
if (downloadObj) {
|
||||
downloadObj.progress = payload.progress;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
window.ipcRenderer.on("install-log", (_event, log: InstallLog) => {
|
||||
const downloadObj = downloads.value.find((d) => d.id === log.id);
|
||||
if (downloadObj)
|
||||
|
||||
Reference in New Issue
Block a user