Files
NqiTools/desktop/src/features/download/DownloadManagerView.vue
T

538 lines
20 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { NButton, NCheckbox, NEmpty, NIcon, NInputNumber, NProgress, NTag, NTooltip, useDialog, useMessage } from "naive-ui";
import { ChevronBackOutline, FolderOpenOutline, HelpCircleOutline, PauseOutline, PlayOutline, TrashOutline } from "@vicons/ionicons5";
import { ApiError, revealLocal } from "../../shared/http";
import { deleteJob, loadDownloadSettings, loadJobs, pauseJob, resumeJob, saveDownloadSettings, updateConcurrency, type DownloadJob } from "./api";
const props = defineProps<{ focusId: string }>();
const message = useMessage();
const dialog = useDialog();
const jobs = ref<DownloadJob[]>([]);
const maxJobs = ref(2);
const tab = ref<"active" | "done">("active");
const openedId = ref("");
const selectedIds = ref<string[]>([]);
const speedBps = ref(0);
const batching = ref(false);
const samples = new Map<string, { bytes: number; at: number }>();
let pollTimer = 0;
let stopped = false;
let lastError = "";
const activeJobs = computed(() => jobs.value.filter((job) => job.status !== "done"));
const doneJobs = computed(() => jobs.value.filter((job) => job.status === "done"));
const visible = computed(() => (tab.value === "active" ? activeJobs.value : doneJobs.value));
const opened = computed(() => jobs.value.find((job) => job.id === openedId.value) ?? null);
const selectedVisible = computed(() => visible.value.filter((job) => selectedIds.value.includes(job.id)));
const pauseTargets = computed(() => selectedVisible.value.filter((job) => canPause(job)));
const resumeTargets = computed(() =>
selectedVisible.value.filter((job) => job.status !== "running" && job.status !== "done" && job.status !== "queued"),
);
const deleteTargets = computed(() => selectedVisible.value.filter((job) => job.status !== "running" && !job.stopping));
const allVisibleSelected = computed(
() => visible.value.length > 0 && visible.value.every((job) => selectedIds.value.includes(job.id)),
);
const statusText: Record<string, string> = {
queued: "等待中",
running: "下载中",
paused: "已暂停",
cancelled: "已停止",
error: "出错",
done_with_errors: "部分失败",
done: "已完成",
};
onMounted(() => {
stopped = false;
void poll();
void loadDownloadSettings()
.then((result) => {
maxJobs.value = result.maxConcurrentJobs;
})
.catch(() => undefined);
});
onUnmounted(() => {
stopped = true;
window.clearTimeout(pollTimer);
});
async function poll() {
await refresh();
if (stopped) return;
pollTimer = window.setTimeout(() => {
void poll();
}, 1000);
}
async function refresh() {
try {
const result = await loadJobs();
jobs.value = result.jobs;
const alive = new Set(result.jobs.map((job) => job.id));
selectedIds.value = selectedIds.value.filter((id) => alive.has(id));
updateSpeed(result.jobs);
lastError = "";
} catch (error) {
if (!(error instanceof ApiError) || error.status === 0 || error.status === 401) return;
if (error.message === lastError) return;
lastError = error.message;
message.error(error.message);
}
}
function statusLabel(job: DownloadJob) {
if (job.stopping) return "正在停止";
if (job.status === "cancelled" && (job.message === "已取消" || job.message === "已中断")) return job.message;
return statusText[job.status] || job.status;
}
function noteText(job: DownloadJob) {
let text = job.message.trim();
if (text === "下载失败,详情见日志") {
text = "保存编号进度时文件被拒绝访问,已下载的内容还在,点继续即可";
}
if (!text || text === statusLabel(job)) return "";
if (text === "正在读取并下载" || text === "准备中") return "";
if (/^已完成 \d+(,已读取 \d+)?(,失败 \d+)?$/.test(text)) return "";
if (/^已完成 \d+\/\d+,失败 \d+$/.test(text)) return "";
return text;
}
function cardFacts(job: DownloadJob) {
if (waitingToRead(job)) return [job.id, "等待读取编号", `已写入 ${job.writtenRows} 行`];
const progress = scanning(job)
? [`已下载 ${job.completed}`, `已读取 ${job.discovered || 0} 个栅格`]
: [`${job.completed}/${job.total} 个栅格`];
return [job.id, ...progress, `已写入 ${job.writtenRows} 行`];
}
function waitingToRead(job: DownloadJob) {
return Boolean(job.wholeCity) && job.status === "queued";
}
function formatCreatedAt(value?: string | null) {
if (!value) return "—";
return value.replace("T", " ");
}
function scanning(job: DownloadJob) {
return Boolean(job.wholeCity) && job.listingDone === false;
}
function hasProgress(job: DownloadJob) {
return !scanning(job) && job.total > 0;
}
function percent(job: DownloadJob) {
if (!hasProgress(job)) return 0;
return Math.min(100, Math.round((job.completed / job.total) * 100));
}
function updateSpeed(list: DownloadJob[]) {
const now = Date.now();
let total = 0;
const running = new Set<string>();
for (const job of list) {
if (job.status !== "running" || job.stopping) continue;
running.add(job.id);
const bytes = job.fileBytes || 0;
const previous = samples.get(job.id);
if (previous && now > previous.at) {
const gained = bytes - previous.bytes;
const seconds = (now - previous.at) / 1000;
if (gained > 0 && seconds > 0 && seconds < 10) total += gained / seconds;
}
samples.set(job.id, { bytes, at: now });
}
for (const id of samples.keys()) {
if (!running.has(id)) samples.delete(id);
}
speedBps.value = total;
}
function formatSpeed(bytesPerSecond: number) {
return `${formatSize(bytesPerSecond)}/s`;
}
function formatSize(bytes?: number) {
const size = bytes || 0;
if (size < 1024) return `${size} B`;
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
if (size < 1024 * 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`;
return `${(size / 1024 / 1024 / 1024).toFixed(2)} GB`;
}
function gridLabel(job: DownloadJob) {
return job.gridSize === "GRID50" ? "50米" : "20米";
}
function openDetail(job: DownloadJob) {
openedId.value = job.id;
}
function closeDetail() {
openedId.value = "";
}
function concurrencyLocked(job: DownloadJob) {
return job.status === "running" || job.status === "done";
}
async function changeConcurrency(job: DownloadJob, value: number | null) {
if (value == null || concurrencyLocked(job)) return;
const next = Math.min(32, Math.max(1, Math.round(value)));
if (next === job.concurrency) return;
try {
await updateConcurrency(job.id, next);
await refresh();
} catch (error) {
message.error(error instanceof ApiError ? error.message : "并发调整失败");
await refresh();
}
}
async function saveLimit(value: number | null) {
if (!value) return;
try {
const result = await saveDownloadSettings(value);
maxJobs.value = result.maxConcurrentJobs;
await refresh();
} catch (error) {
message.error(error instanceof ApiError ? error.message : "同时任务数保存失败");
}
}
async function pause(job: DownloadJob) {
try {
await pauseJob(job.id);
await refresh();
} catch (error) {
message.error(error instanceof ApiError ? error.message : "暂停失败");
}
}
async function resume(job: DownloadJob) {
try {
await resumeJob(job.id);
tab.value = "active";
await refresh();
} catch (error) {
message.error(error instanceof ApiError ? error.message : "继续失败");
}
}
async function openDir(job: DownloadJob) {
const revealed = await revealLocal(job.csvPath).catch(() => false);
if (!revealed) message.info(job.csvPath);
}
function inProgress(job: DownloadJob) {
return Boolean(job.stopping) || job.status === "running";
}
function canPause(job: DownloadJob) {
return !job.stopping && (job.status === "running" || job.status === "queued");
}
function confirmDelete(job: DownloadJob) {
dialog.warning({
title: "删除任务",
content: "是否同时删除这个任务的下载文件夹?",
positiveText: "同时删除",
negativeText: "只删除任务",
maskClosable: false,
onPositiveClick: () => removeJob(job, true),
onNegativeClick: () => removeJob(job, false),
});
}
function jobSelected(job: DownloadJob) {
return selectedIds.value.includes(job.id);
}
function setJobSelected(job: DownloadJob, checked: boolean) {
if (checked) {
if (!selectedIds.value.includes(job.id)) selectedIds.value = [...selectedIds.value, job.id];
return;
}
selectedIds.value = selectedIds.value.filter((id) => id !== job.id);
}
function setVisibleSelected(checked: boolean) {
const visibleIds = new Set(visible.value.map((job) => job.id));
if (checked) {
selectedIds.value = [...new Set([...selectedIds.value, ...visibleIds])];
return;
}
selectedIds.value = selectedIds.value.filter((id) => !visibleIds.has(id));
}
async function runBatch(targets: DownloadJob[], action: (job: DownloadJob) => Promise<unknown>, doneText: string) {
if (!targets.length || batching.value) {
if (!targets.length) message.info("所选任务里没有能这样操作的");
return;
}
batching.value = true;
try {
const results = await Promise.allSettled(targets.map((job) => action(job)));
const failed = results.filter((item) => item.status === "rejected").length;
await refresh();
if (failed) message.warning(`${doneText},${failed} 个没有成功`);
else message.success(doneText);
} finally {
batching.value = false;
}
}
function pauseSelected() {
return runBatch(pauseTargets.value, (job) => pauseJob(job.id), "已暂停");
}
function resumeSelected() {
return runBatch(resumeTargets.value, (job) => resumeJob(job.id), "已继续");
}
function confirmDeleteSelected() {
const targets = deleteTargets.value;
if (!targets.length) {
message.info("正在下载的任务要先暂停才能删除");
return;
}
dialog.warning({
title: "删除任务",
content: `删除选中的 ${targets.length} 个任务。是否同时删除下载文件夹?`,
positiveText: "同时删除",
negativeText: "只删除任务",
maskClosable: false,
onPositiveClick: () => removeSelected(targets, true),
onNegativeClick: () => removeSelected(targets, false),
});
}
async function removeSelected(targets: DownloadJob[], files: boolean) {
await runBatch(targets, async (job) => {
await deleteJob(job.id, files);
if (openedId.value === job.id) openedId.value = "";
}, "已删除任务");
selectedIds.value = selectedIds.value.filter((id) => !targets.some((job) => job.id === id));
}
async function removeJob(job: DownloadJob, files: boolean) {
try {
await deleteJob(job.id, files);
if (openedId.value === job.id) openedId.value = "";
message.success("已删除任务");
await refresh();
} catch (error) {
message.error(error instanceof ApiError ? error.message : "删除失败");
}
}
</script>
<template>
<section class="page">
<header class="page-head">
<div class="head-title">
<n-button v-if="opened" quaternary size="small" @click="closeDetail">
<template #icon><n-icon><ChevronBackOutline /></n-icon></template>
返回
</n-button>
<h2>{{ opened ? opened.name : "下载管理" }}</h2>
<span v-if="!opened" class="speed">总网速 {{ formatSpeed(speedBps) }}</span>
</div>
<div v-if="opened" class="head-actions">
<n-tag size="small" :type="opened.status === 'running' ? 'info' : opened.status === 'done' ? 'success' : opened.status === 'paused' ? 'warning' : 'default'">
{{ statusLabel(opened) }}
</n-tag>
<n-button v-if="canPause(opened)" size="small" @click="pause(opened)">
<template #icon><n-icon><PauseOutline /></n-icon></template>
暂停
</n-button>
<n-button v-else-if="opened.status !== 'done' && !inProgress(opened)" size="small" type="primary" secondary @click="resume(opened)">
<template #icon><n-icon><PlayOutline /></n-icon></template>
继续
</n-button>
<n-tooltip>
<template #trigger>
<n-button size="small" quaternary @click="openDir(opened)">
<template #icon><n-icon><FolderOpenOutline /></n-icon></template>
</n-button>
</template>
打开所在文件夹
</n-tooltip>
<n-button v-if="!inProgress(opened)" size="small" @click="confirmDelete(opened)">
<template #icon><n-icon><TrashOutline /></n-icon></template>
删除
</n-button>
</div>
<div v-else class="head-actions">
<n-button size="small" :disabled="!pauseTargets.length || batching" @click="pauseSelected">
<template #icon><n-icon><PauseOutline /></n-icon></template>
暂停
</n-button>
<n-button size="small" type="primary" secondary :disabled="!resumeTargets.length || batching" @click="resumeSelected">
<template #icon><n-icon><PlayOutline /></n-icon></template>
继续
</n-button>
<n-button size="small" :disabled="!deleteTargets.length || batching" @click="confirmDeleteSelected">
<template #icon><n-icon><TrashOutline /></n-icon></template>
删除
</n-button>
<span class="limit-label">同时任务</span>
<n-tooltip>
<template #trigger>
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
</template>
同时进行的下载任务数。每个任务仍按自己的并发数下载。
</n-tooltip>
<n-input-number
class="limit-control"
button-placement="both"
:value="maxJobs"
:min="1"
:max="8"
size="small"
@update:value="saveLimit"
/>
</div>
</header>
<div v-if="opened" class="task-list">
<div class="detail">
<n-progress
v-if="hasProgress(opened)"
:percentage="percent(opened)"
:processing="opened.status === 'running'"
/>
<div class="form-row"><label>任务号</label><span>{{ opened.id }}</span></div>
<div class="form-row"><label>状态</label><span>{{ statusLabel(opened) }}</span></div>
<div v-if="noteText(opened)" class="form-row"><label>说明</label><span>{{ noteText(opened) }}</span></div>
<div class="form-row"><label>网络</label><span>{{ opened.network === "NR" ? "5G" : "4G" }}</span></div>
<div class="form-row"><label>地市</label><span>{{ opened.cityName }}</span></div>
<div class="form-row"><label>月份</label><span>{{ opened.month }}</span></div>
<div class="form-row"><label>栅格</label><span>{{ gridLabel(opened) }}</span></div>
<div class="form-row"><label>范围</label><span>{{ opened.wholeCity ? "整个地市" : "区域表" }}</span></div>
<div class="form-row">
<label>
并发
<n-tooltip>
<template #trigger>
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
</template>
正在下载时不能改。暂停后修改,点继续时按新的数量下载。
</n-tooltip>
</label>
<n-input-number
button-placement="both"
:value="opened.concurrency || 1"
:min="1"
:max="32"
:disabled="concurrencyLocked(opened)"
@update:value="(value) => { if (opened) void changeConcurrency(opened, value); }"
/>
</div>
<div class="form-row">
<label>进度</label>
<span v-if="waitingToRead(opened)">等待读取</span>
<span v-else-if="scanning(opened)">已完成 {{ opened.completed }},已读取 {{ opened.discovered || 0 }}</span>
<span v-else>{{ opened.completed }}/{{ opened.total }}</span>
</div>
<div class="form-row"><label>失败</label><span>{{ opened.failed }}</span></div>
<div class="form-row"><label>已写入</label><span>{{ opened.writtenRows }} 行</span></div>
<div class="form-row"><label>文件大小</label><span>{{ formatSize(opened.fileBytes) }}</span></div>
<div class="form-row"><label>开始时间</label><span>{{ formatCreatedAt(opened.createdAt) }}</span></div>
<div v-if="opened.duplicateCount" class="form-row"><label>重复</label><span>已去掉 {{ opened.duplicateCount }} 个</span></div>
<div class="form-row form-top">
<label>保存位置</label>
<span class="path">{{ opened.csvPath }}</span>
</div>
<ul v-if="opened.failures?.length" class="fail-list">
<li v-for="item in opened.failures" :key="item.id">{{ item.id }}:{{ item.message }}</li>
</ul>
</div>
</div>
<div v-else class="tabs">
<n-checkbox
:checked="allVisibleSelected"
:disabled="visible.length === 0"
@update:checked="setVisibleSelected"
>
全选
</n-checkbox>
<button class="tab" :class="{ on: tab === 'active' }" type="button" @click="tab = 'active'">
未完成<em>{{ activeJobs.length }}</em>
</button>
<button class="tab" :class="{ on: tab === 'done' }" type="button" @click="tab = 'done'">
已完成<em>{{ doneJobs.length }}</em>
</button>
</div>
<div v-if="!opened" class="task-list">
<article
v-for="job in visible"
:key="job.id"
class="task clickable"
:class="{ focus: job.id === props.focusId, picked: jobSelected(job) }"
@click="openDetail(job)"
>
<div class="task-top">
<div class="task-main">
<span @click.stop>
<n-checkbox :checked="jobSelected(job)" @update:checked="(checked) => setJobSelected(job, checked)" />
</span>
<div>
<h3>{{ job.name }}</h3>
<div class="task-meta">
<span v-for="fact in cardFacts(job)" :key="fact">{{ fact }}</span>
</div>
</div>
</div>
<div class="task-actions" @click.stop>
<n-button v-if="canPause(job)" size="small" @click="pause(job)">
<template #icon><n-icon><PauseOutline /></n-icon></template>
暂停
</n-button>
<n-button v-else-if="job.status !== 'done' && !inProgress(job)" size="small" type="primary" secondary @click="resume(job)">
<template #icon><n-icon><PlayOutline /></n-icon></template>
继续
</n-button>
<n-tooltip>
<template #trigger>
<n-button size="small" quaternary @click="openDir(job)">
<template #icon><n-icon><FolderOpenOutline /></n-icon></template>
</n-button>
</template>
打开所在文件夹
</n-tooltip>
<n-button v-if="!inProgress(job)" size="small" @click="confirmDelete(job)">
<template #icon><n-icon><TrashOutline /></n-icon></template>
删除
</n-button>
</div>
</div>
<n-progress
v-if="hasProgress(job)"
style="margin-top: 10px"
:percentage="percent(job)"
:show-indicator="true"
:processing="job.status === 'running'"
/>
<div class="task-foot">
<span class="foot-status">
<n-tag size="small" :type="job.status === 'running' ? 'info' : job.status === 'done' ? 'success' : job.status === 'paused' ? 'warning' : 'default'">
{{ statusLabel(job) }}
</n-tag>
<span v-if="noteText(job)" class="task-notice">{{ noteText(job) }}</span>
</span>
<span class="task-size">失败 {{ job.failed }} · {{ formatSize(job.fileBytes) }}</span>
</div>
<ul v-if="job.failures?.length" class="fail-list">
<li v-for="item in job.failures.slice(0, 3)" :key="item.id">{{ item.id }}:{{ item.message }}</li>
</ul>
</article>
<n-empty v-if="visible.length === 0" class="empty" :description="tab === 'active' ? '没有未完成的任务' : '还没有完成的任务'" />
</div>
</section>
</template>