feat: 完成后清理进度文件,并支持迁移数据目录
This commit is contained in:
@@ -5,6 +5,7 @@ Temp/
|
|||||||
|
|
||||||
# 运行数据与会话
|
# 运行数据与会话
|
||||||
data/
|
data/
|
||||||
|
.nqi-data-root
|
||||||
aidocs/
|
aidocs/
|
||||||
|
|
||||||
# Python
|
# Python
|
||||||
|
|||||||
@@ -22,6 +22,8 @@
|
|||||||
- 单个栅格下载失败会跳过并计入失败数。整轮遇到网络超时、连不上或平台暂时不可用时,任务会等几秒自动重试。
|
- 单个栅格下载失败会跳过并计入失败数。整轮遇到网络超时、连不上或平台暂时不可用时,任务会等几秒自动重试。
|
||||||
- 下载文件被占用、磁盘满或被拒绝访问时,任务会暂停并说明原因,处理好后点继续,已下载的内容不受影响。
|
- 下载文件被占用、磁盘满或被拒绝访问时,任务会暂停并说明原因,处理好后点继续,已下载的内容不受影响。
|
||||||
- 每个任务的下载文件和进度只由它自己的写入线程读写;界面只读内存里的状态,不会和下载抢同一个文件。
|
- 每个任务的下载文件和进度只由它自己的写入线程读写;界面只读内存里的状态,不会和下载抢同一个文件。
|
||||||
|
- 任务全部下完后会删掉进度文件和编号暂存。没下完的会保留,继续时接着用。
|
||||||
|
- 设置里可以把数据目录迁到别的磁盘。正在下载和排队的任务会先停下,迁完后自动继续;之前暂停的不会自动开始。下载好的表格仍在原来的保存位置。
|
||||||
|
|
||||||
## 运行
|
## 运行
|
||||||
|
|
||||||
|
|||||||
@@ -678,10 +678,16 @@ class JobManager:
|
|||||||
try:
|
try:
|
||||||
status = str(data.get("status") or "queued")
|
status = str(data.get("status") or "queued")
|
||||||
message = str(data.get("message") or "")
|
message = str(data.get("message") or "")
|
||||||
interrupted = status in _INTERRUPTED_STATUSES
|
paused_by = str(data.get("pausedBy") or "")
|
||||||
|
# 迁移前主动收起来的任务要保持暂停,重启后按记录继续,不要当成意外中断。
|
||||||
|
held_for_move = paused_by == "move"
|
||||||
|
interrupted = status in _INTERRUPTED_STATUSES and not held_for_move
|
||||||
if interrupted:
|
if interrupted:
|
||||||
status = "cancelled"
|
status = "cancelled"
|
||||||
message = "已中断"
|
message = "已中断"
|
||||||
|
elif held_for_move:
|
||||||
|
status = "paused"
|
||||||
|
message = "已暂停"
|
||||||
whole = bool(data.get("wholeCity"))
|
whole = bool(data.get("wholeCity"))
|
||||||
legacy_ids = [str(item) for item in data.get("gridIds") or []]
|
legacy_ids = [str(item) for item in data.get("gridIds") or []]
|
||||||
if data.get("gridCount") is None:
|
if data.get("gridCount") is None:
|
||||||
@@ -717,17 +723,51 @@ class JobManager:
|
|||||||
written_rows=int(data.get("writtenRows") or 0),
|
written_rows=int(data.get("writtenRows") or 0),
|
||||||
duplicate_count=int(data.get("duplicateCount") or 0),
|
duplicate_count=int(data.get("duplicateCount") or 0),
|
||||||
failures=list(data.get("failures") or []),
|
failures=list(data.get("failures") or []),
|
||||||
paused_by=str(data.get("pausedBy") or ""),
|
paused_by=paused_by,
|
||||||
stopping=bool(data.get("stopping") or False) and not interrupted,
|
stopping=bool(data.get("stopping") or False) and not interrupted,
|
||||||
failed_tiles=_combine_failed(data.get("failedTiles"), _spool_failed_tiles(path.parent)),
|
failed_tiles=_combine_failed(data.get("failedTiles"), _spool_failed_tiles(path.parent)),
|
||||||
)
|
)
|
||||||
except (KeyError, TypeError, ValueError) as exc:
|
except (KeyError, TypeError, ValueError) as exc:
|
||||||
raise NqiError("任务记录损坏") from exc
|
raise NqiError("任务记录损坏") from exc
|
||||||
_clear_temp_files(path.parent)
|
_clear_temp_files(path.parent)
|
||||||
|
if status == "done":
|
||||||
|
release_finished_work(path.parent)
|
||||||
if interrupted:
|
if interrupted:
|
||||||
job.save()
|
job.save()
|
||||||
return job
|
return job
|
||||||
|
|
||||||
|
async def shelve_for_move(self) -> list[str]:
|
||||||
|
"""停掉还开着文件的任务。正在下载和排队的记下来,迁移完成后继续。"""
|
||||||
|
self._discover()
|
||||||
|
jobs = [job for job in self.jobs.values() if not job.deleting]
|
||||||
|
for job in jobs:
|
||||||
|
if job.building or job.deleting:
|
||||||
|
raise NqiError("有任务还在创建或删除,请稍后再迁移")
|
||||||
|
resume: list[str] = []
|
||||||
|
for job in jobs:
|
||||||
|
should_resume = job.status in {"running", "queued"} or job.paused_by == "move"
|
||||||
|
if should_resume:
|
||||||
|
resume.append(job.id)
|
||||||
|
busy = job.is_active() or (job.files_closed is not None and not job.files_closed.done())
|
||||||
|
if busy:
|
||||||
|
try:
|
||||||
|
await _stop_and_wait(job)
|
||||||
|
except NqiError as exc:
|
||||||
|
if str(exc) == "任务还在收尾,请稍后再删":
|
||||||
|
raise NqiError("任务还在收尾,请稍后再迁移") from exc
|
||||||
|
raise
|
||||||
|
if not should_resume:
|
||||||
|
continue
|
||||||
|
job.status = "paused"
|
||||||
|
job.paused_by = "move"
|
||||||
|
job.message = "已暂停"
|
||||||
|
job.stopping = False
|
||||||
|
job.cancel_event = asyncio.Event()
|
||||||
|
job.save()
|
||||||
|
await job.flush_record()
|
||||||
|
await asyncio.wrap_future(RECORDS.barrier())
|
||||||
|
return resume
|
||||||
|
|
||||||
|
|
||||||
def _clear_temp_files(directory: Path) -> None:
|
def _clear_temp_files(directory: Path) -> None:
|
||||||
"""进程被强行结束时可能留下替换前的临时文件。只在任务没在运行时清。"""
|
"""进程被强行结束时可能留下替换前的临时文件。只在任务没在运行时清。"""
|
||||||
@@ -742,6 +782,21 @@ def _clear_temp_files(directory: Path) -> None:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
_FINISHED_WORK = ("progress.jsonl", "ids.spool", "ids.spool.meta")
|
||||||
|
|
||||||
|
|
||||||
|
def release_finished_work(directory: Path) -> None:
|
||||||
|
"""任务已经全部下完。进度和编号暂存只为继续下载服务,删掉以免一直占空间。"""
|
||||||
|
for name in _FINISHED_WORK:
|
||||||
|
path = directory / name
|
||||||
|
try:
|
||||||
|
path.unlink()
|
||||||
|
except FileNotFoundError:
|
||||||
|
continue
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning("完成后的进度文件暂时删不掉 %s: %s", path, exc)
|
||||||
|
|
||||||
|
|
||||||
async def _stop_and_wait(job: DownloadJob) -> None:
|
async def _stop_and_wait(job: DownloadJob) -> None:
|
||||||
"""强制结束任务协程,并等它关完文件。"""
|
"""强制结束任务协程,并等它关完文件。"""
|
||||||
task = job.task
|
task = job.task
|
||||||
@@ -1119,6 +1174,8 @@ async def _close_files(job: DownloadJob, io: JobIO, journal: CsvJournal, spool:
|
|||||||
await io.close()
|
await io.close()
|
||||||
if job.io is io:
|
if job.io is io:
|
||||||
job.io = None
|
job.io = None
|
||||||
|
if job.status == "done":
|
||||||
|
await asyncio.to_thread(release_finished_work, job.directory)
|
||||||
await job.flush_record()
|
await job.flush_record()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""把数据目录迁到用户选的位置。真正搬文件夹由桌面壳在停掉后台之后做。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from app.features.download import jobs as job_module
|
||||||
|
from app.features.download.journal import explain_os_error
|
||||||
|
from app.platform.client import NqiError
|
||||||
|
from app.shared.files import write_atomic
|
||||||
|
from app.shared.state import state
|
||||||
|
|
||||||
|
RESUME_NAME = "resume-after-move.json"
|
||||||
|
|
||||||
|
|
||||||
|
def data_root() -> Path:
|
||||||
|
return job_module.DATA_DIR.parent
|
||||||
|
|
||||||
|
|
||||||
|
def resume_path() -> Path:
|
||||||
|
return data_root() / RESUME_NAME
|
||||||
|
|
||||||
|
|
||||||
|
def current_dir() -> dict:
|
||||||
|
return {"path": str(data_root())}
|
||||||
|
|
||||||
|
|
||||||
|
def _same(left: Path, right: Path) -> bool:
|
||||||
|
if left.exists() and right.exists():
|
||||||
|
try:
|
||||||
|
return left.samefile(right)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return os.path.normcase(os.path.abspath(left)) == os.path.normcase(os.path.abspath(right))
|
||||||
|
|
||||||
|
|
||||||
|
def _within(child: Path, parent: Path) -> bool:
|
||||||
|
if _same(child, parent):
|
||||||
|
return False
|
||||||
|
child_text = os.path.normcase(os.path.abspath(child))
|
||||||
|
parent_text = os.path.normcase(os.path.abspath(parent)).rstrip("\\/")
|
||||||
|
return child_text.startswith(parent_text + os.sep)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_target(raw: str) -> Path:
|
||||||
|
text = (raw or "").strip()
|
||||||
|
if not text:
|
||||||
|
raise NqiError("请选择数据目录")
|
||||||
|
target = Path(text)
|
||||||
|
if not target.is_absolute():
|
||||||
|
raise NqiError("数据目录必须是绝对路径")
|
||||||
|
current = data_root().resolve()
|
||||||
|
chosen = target.resolve()
|
||||||
|
if _same(chosen, current):
|
||||||
|
raise NqiError("已经是当前数据目录")
|
||||||
|
if _within(chosen, current) or _within(current, chosen):
|
||||||
|
raise NqiError("不能选在当前数据目录里面,也不能选它的上级")
|
||||||
|
if target.exists() and not target.is_dir():
|
||||||
|
raise NqiError("请选择文件夹")
|
||||||
|
if target.exists() and any(target.iterdir()):
|
||||||
|
raise NqiError("请选择一个空文件夹")
|
||||||
|
job_module.ensure_output_dir(target)
|
||||||
|
return target.resolve()
|
||||||
|
|
||||||
|
|
||||||
|
async def prepare(raw: str) -> dict:
|
||||||
|
target = validate_target(raw)
|
||||||
|
ids = await state.jobs.shelve_for_move()
|
||||||
|
payload = json.dumps({"ids": ids}, ensure_ascii=False).encode("utf-8")
|
||||||
|
try:
|
||||||
|
write_atomic(resume_path(), payload)
|
||||||
|
except OSError as exc:
|
||||||
|
message = explain_os_error(exc) or "迁移记录写不进去"
|
||||||
|
raise NqiError(message) from exc
|
||||||
|
return {"path": str(data_root()), "target": str(target), "resumeIds": ids}
|
||||||
|
|
||||||
|
|
||||||
|
async def resume_moved() -> dict:
|
||||||
|
path = resume_path()
|
||||||
|
try:
|
||||||
|
data = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
except FileNotFoundError:
|
||||||
|
return {"resumed": []}
|
||||||
|
except (OSError, json.JSONDecodeError, UnicodeError, TypeError, ValueError) as exc:
|
||||||
|
raise NqiError("迁移记录读不出来") from exc
|
||||||
|
try:
|
||||||
|
path.unlink()
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
except OSError as exc:
|
||||||
|
message = explain_os_error(exc) or "迁移记录暂时删不掉"
|
||||||
|
raise NqiError(message) from exc
|
||||||
|
raw_ids = data.get("ids") if isinstance(data, dict) else []
|
||||||
|
if not isinstance(raw_ids, list):
|
||||||
|
raw_ids = []
|
||||||
|
resumed: list[str] = []
|
||||||
|
for job_id in raw_ids:
|
||||||
|
text = str(job_id)
|
||||||
|
try:
|
||||||
|
job = state.jobs.get(text)
|
||||||
|
except NqiError:
|
||||||
|
continue
|
||||||
|
if job.status == "done":
|
||||||
|
continue
|
||||||
|
job.paused_by = ""
|
||||||
|
if job.status != "queued":
|
||||||
|
job.status = "queued"
|
||||||
|
job.message = "等待中"
|
||||||
|
job.save()
|
||||||
|
resumed.append(text)
|
||||||
|
from app.features.download.router import fill_slots
|
||||||
|
|
||||||
|
fill_slots()
|
||||||
|
return {"resumed": resumed}
|
||||||
@@ -15,6 +15,7 @@ from fastapi import APIRouter, Body, File, Form, HTTPException, UploadFile
|
|||||||
from app.features.download.fields import IDENTITY, NETWORKS, cell_columns, columns_for, grid_spec, meta_groups
|
from app.features.download.fields import IDENTITY, NETWORKS, cell_columns, columns_for, grid_spec, meta_groups
|
||||||
from app.features.download.ids import parse_upload
|
from app.features.download.ids import parse_upload
|
||||||
from app.features.download.jobs import _write_ids, app_settings, ensure_output_dir, run_download, store_app_settings
|
from app.features.download.jobs import _write_ids, app_settings, ensure_output_dir, run_download, store_app_settings
|
||||||
|
from app.features.download.relocate import current_dir, prepare, resume_moved
|
||||||
from app.features.download.journal import explain_os_error
|
from app.features.download.journal import explain_os_error
|
||||||
from app.platform.client import NqiError
|
from app.platform.client import NqiError
|
||||||
from app.platform.constants import CITIES
|
from app.platform.constants import CITIES
|
||||||
@@ -62,6 +63,32 @@ def fill_slots() -> None:
|
|||||||
_spawn(waiting[0])
|
_spawn(waiting[0])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/data-dir")
|
||||||
|
async def read_data_dir() -> dict:
|
||||||
|
state.require_client()
|
||||||
|
return current_dir()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/data-dir/prepare")
|
||||||
|
async def prepare_data_dir(body: Any = Body(default=None)) -> dict:
|
||||||
|
state.require_client()
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
raise _bad("参数格式不正确")
|
||||||
|
try:
|
||||||
|
return await prepare(str(body.get("path") or ""))
|
||||||
|
except NqiError as exc:
|
||||||
|
raise _bad(str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/data-dir/resume")
|
||||||
|
async def resume_data_dir() -> dict:
|
||||||
|
state.require_client()
|
||||||
|
try:
|
||||||
|
return await resume_moved()
|
||||||
|
except NqiError as exc:
|
||||||
|
raise _bad(str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
@router.get("/settings/app")
|
@router.get("/settings/app")
|
||||||
async def read_app_settings() -> dict:
|
async def read_app_settings() -> dict:
|
||||||
return app_settings()
|
return app_settings()
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.features.download import jobs as job_module
|
||||||
|
from app.features.download import relocate
|
||||||
|
from app.features.download.jobs import JobManager
|
||||||
|
from app.platform.client import NqiError
|
||||||
|
from app.shared.state import state
|
||||||
|
|
||||||
|
|
||||||
|
def _use_data(monkeypatch, root: Path) -> Path:
|
||||||
|
jobs = root / "jobs"
|
||||||
|
monkeypatch.setattr(job_module, "DATA_DIR", jobs)
|
||||||
|
monkeypatch.setattr(job_module, "DOWNLOAD_ROOT", root / "downloads")
|
||||||
|
return jobs
|
||||||
|
|
||||||
|
|
||||||
|
def _record(directory: Path, **overrides) -> None:
|
||||||
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
|
payload = {
|
||||||
|
"id": directory.name,
|
||||||
|
"network": "NR",
|
||||||
|
"cityCode": "JM",
|
||||||
|
"cityName": "江门",
|
||||||
|
"month": "2026-09",
|
||||||
|
"groups": ["rsrp"],
|
||||||
|
"concurrency": 2,
|
||||||
|
"gridCount": 1,
|
||||||
|
"wholeCity": False,
|
||||||
|
"discovered": 1,
|
||||||
|
"listingDone": True,
|
||||||
|
"csvPath": str(directory / "out.csv"),
|
||||||
|
"createdAt": "2026-10-26T09:00:00",
|
||||||
|
"status": "done",
|
||||||
|
"message": "已完成",
|
||||||
|
"completed": 1,
|
||||||
|
"failed": 0,
|
||||||
|
"writtenRows": 1,
|
||||||
|
"duplicateCount": 0,
|
||||||
|
"failures": [],
|
||||||
|
"pausedBy": "",
|
||||||
|
"stopping": False,
|
||||||
|
"failedTiles": [],
|
||||||
|
}
|
||||||
|
payload.update(overrides)
|
||||||
|
(directory / "job.json").write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def test_finished_job_drops_progress_and_keeps_the_id_list(tmp_path: Path, monkeypatch):
|
||||||
|
jobs = _use_data(monkeypatch, tmp_path / "data")
|
||||||
|
done = jobs / "20261026090001"
|
||||||
|
partial = jobs / "20261026090002"
|
||||||
|
_record(done, status="done")
|
||||||
|
_record(partial, status="done_with_errors", message="1 个失败")
|
||||||
|
for directory in (done, partial):
|
||||||
|
(directory / "progress.jsonl").write_text('{"id": 1, "offset": 2, "rows": 1}\n', encoding="utf-8")
|
||||||
|
(directory / "ids.spool").write_text("1\n", encoding="utf-8")
|
||||||
|
(directory / "ids.spool.meta").write_text("{}", encoding="utf-8")
|
||||||
|
(directory / "ids.txt").write_text("1\n", encoding="utf-8")
|
||||||
|
loaded = JobManager()._load(done.name)
|
||||||
|
assert loaded.status == "done"
|
||||||
|
assert not (done / "progress.jsonl").exists()
|
||||||
|
assert not (done / "ids.spool").exists()
|
||||||
|
assert not (done / "ids.spool.meta").exists()
|
||||||
|
assert (done / "ids.txt").read_text(encoding="utf-8") == "1\n"
|
||||||
|
kept = JobManager()._load(partial.name)
|
||||||
|
assert kept.status == "done_with_errors"
|
||||||
|
assert (partial / "progress.jsonl").exists()
|
||||||
|
assert (partial / "ids.spool").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_move_hold_stays_paused(tmp_path: Path, monkeypatch):
|
||||||
|
jobs = _use_data(monkeypatch, tmp_path / "data")
|
||||||
|
directory = jobs / "20261026090003"
|
||||||
|
_record(directory, status="running", message="下载中", pausedBy="move")
|
||||||
|
loaded = JobManager()._load(directory.name)
|
||||||
|
assert loaded.status == "paused"
|
||||||
|
assert loaded.message == "已暂停"
|
||||||
|
assert loaded.paused_by == "move"
|
||||||
|
|
||||||
|
|
||||||
|
def test_prepare_shelves_active_jobs_and_resume_starts_them(tmp_path: Path, monkeypatch):
|
||||||
|
asyncio.run(_prepare_and_resume(tmp_path, monkeypatch))
|
||||||
|
|
||||||
|
|
||||||
|
async def _prepare_and_resume(tmp_path: Path, monkeypatch) -> None:
|
||||||
|
root = tmp_path / "data"
|
||||||
|
_use_data(monkeypatch, root)
|
||||||
|
manager = JobManager()
|
||||||
|
running = _make(manager, "running")
|
||||||
|
queued = _make(manager, "queued")
|
||||||
|
paused = _make(manager, "paused")
|
||||||
|
old_jobs = state.jobs
|
||||||
|
old_client = state.client
|
||||||
|
old_user = state.user
|
||||||
|
old_expired = state.expired
|
||||||
|
state.jobs = manager
|
||||||
|
|
||||||
|
async def _quiet(_job):
|
||||||
|
return None
|
||||||
|
|
||||||
|
monkeypatch.setattr("app.features.download.router.run_download", _quiet)
|
||||||
|
try:
|
||||||
|
with pytest.raises(NqiError, match="请选择一个空文件夹"):
|
||||||
|
busy = tmp_path / "busy"
|
||||||
|
busy.mkdir()
|
||||||
|
(busy / "keep.txt").write_text("x", encoding="utf-8")
|
||||||
|
await relocate.prepare(str(busy))
|
||||||
|
with pytest.raises(NqiError, match="已经是当前数据目录"):
|
||||||
|
await relocate.prepare(str(root))
|
||||||
|
target = tmp_path / "next"
|
||||||
|
prepared = await relocate.prepare(str(target))
|
||||||
|
assert prepared["resumeIds"] == [running.id, queued.id]
|
||||||
|
assert running.status == "paused" and running.paused_by == "move"
|
||||||
|
assert queued.paused_by == "move"
|
||||||
|
assert paused.status == "paused" and paused.paused_by == ""
|
||||||
|
stored = json.loads((root / "resume-after-move.json").read_text(encoding="utf-8"))
|
||||||
|
assert stored["ids"] == [running.id, queued.id]
|
||||||
|
assert target.is_dir()
|
||||||
|
state.client = object()
|
||||||
|
state.user = {"loginId": "u"}
|
||||||
|
state.expired = False
|
||||||
|
resumed = await relocate.resume_moved()
|
||||||
|
assert resumed["resumed"] == [running.id, queued.id]
|
||||||
|
assert not (root / "resume-after-move.json").exists()
|
||||||
|
assert running.status == "running"
|
||||||
|
assert queued.status == "running"
|
||||||
|
assert paused.status == "paused"
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
finally:
|
||||||
|
state.jobs = old_jobs
|
||||||
|
state.client = old_client
|
||||||
|
state.user = old_user
|
||||||
|
state.expired = old_expired
|
||||||
|
|
||||||
|
|
||||||
|
def _make(manager: JobManager, status: str):
|
||||||
|
job = manager.create(
|
||||||
|
network="NR",
|
||||||
|
city_code="JM",
|
||||||
|
city_name="江门",
|
||||||
|
month="2026-09",
|
||||||
|
groups=["rsrp"],
|
||||||
|
concurrency=1,
|
||||||
|
grid_ids=["1"],
|
||||||
|
csv_path=None,
|
||||||
|
grid_size="GRID20",
|
||||||
|
whole_city=False,
|
||||||
|
)
|
||||||
|
job.status = status
|
||||||
|
job.paused_by = ""
|
||||||
|
job.message = "下载中" if status == "running" else "已暂停" if status == "paused" else "等待中"
|
||||||
|
job.save()
|
||||||
|
return job
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
use std::fs;
|
||||||
|
use std::io;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
const RETRY_WAITS_MS: [u64; 5] = [0, 100, 300, 800, 1500];
|
||||||
|
|
||||||
|
pub fn check_target(source: &Path, target: &Path) -> Result<(), String> {
|
||||||
|
if !target.is_absolute() {
|
||||||
|
return Err("数据目录必须是绝对路径".into());
|
||||||
|
}
|
||||||
|
if same_path(source, target) {
|
||||||
|
return Err("已经是当前数据目录".into());
|
||||||
|
}
|
||||||
|
if !source.is_dir() {
|
||||||
|
return Err("当前数据目录不存在".into());
|
||||||
|
}
|
||||||
|
if within(target, source) || within(source, target) {
|
||||||
|
return Err("不能选在当前数据目录里面,也不能选它的上级".into());
|
||||||
|
}
|
||||||
|
if target.exists() && !target.is_dir() {
|
||||||
|
return Err("请选择文件夹".into());
|
||||||
|
}
|
||||||
|
if target.exists() && !is_empty_dir(target)? {
|
||||||
|
return Err("请选择一个空文件夹".into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn relocate_children(source: &Path, target: &Path, pointer: &Path) -> Result<(), String> {
|
||||||
|
check_target(source, target)?;
|
||||||
|
fs::create_dir_all(target).map_err(|error| format!("无法创建数据目录:{error}"))?;
|
||||||
|
if !is_empty_dir(target)? {
|
||||||
|
return Err("请选择一个空文件夹".into());
|
||||||
|
}
|
||||||
|
let entries = list_entries(source, pointer)?;
|
||||||
|
if same_volume(source, target) {
|
||||||
|
match rename_all(&entries, target) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(MoveError::CrossDevice) => copy_then_remove(&entries, target),
|
||||||
|
Err(MoveError::Message(message)) => Err(message),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
copy_then_remove(&entries, target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list_entries(source: &Path, pointer: &Path) -> Result<Vec<PathBuf>, String> {
|
||||||
|
let read = fs::read_dir(source).map_err(|error| format!("无法读取数据目录:{error}"))?;
|
||||||
|
let mut entries = Vec::new();
|
||||||
|
for item in read {
|
||||||
|
let item = item.map_err(|error| format!("无法读取数据目录:{error}"))?;
|
||||||
|
let path = item.path();
|
||||||
|
if same_path(&path, pointer) || skip_name(&item.file_name()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
entries.push(path);
|
||||||
|
}
|
||||||
|
entries.sort();
|
||||||
|
Ok(entries)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn skip_name(name: &std::ffi::OsStr) -> bool {
|
||||||
|
name == "backend.lock" || name == "data-root.txt" || name == ".nqi-data-root"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rename_all(entries: &[PathBuf], target: &Path) -> Result<(), MoveError> {
|
||||||
|
let mut moved = Vec::new();
|
||||||
|
for source in entries {
|
||||||
|
let dest = target.join(name_of(source).map_err(MoveError::Message)?);
|
||||||
|
if let Err(error) = rename_retry(source, &dest) {
|
||||||
|
undo_renames(&moved);
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
moved.push((dest, source.clone()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn undo_renames(moved: &[(PathBuf, PathBuf)]) {
|
||||||
|
for (dest, source) in moved.iter().rev() {
|
||||||
|
let _ = rename_retry(dest, source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_then_remove(entries: &[PathBuf], target: &Path) -> Result<(), String> {
|
||||||
|
let mut copied: Vec<PathBuf> = Vec::new();
|
||||||
|
for source in entries {
|
||||||
|
let dest = target.join(name_of(source)?);
|
||||||
|
if let Err(error) = copy_path(source, &dest) {
|
||||||
|
for path in copied.iter().rev() {
|
||||||
|
let _ = remove_path(path);
|
||||||
|
}
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
copied.push(dest);
|
||||||
|
}
|
||||||
|
for source in entries {
|
||||||
|
if let Err(error) = remove_path(source) {
|
||||||
|
restore_sources(entries, target);
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn restore_sources(entries: &[PathBuf], target: &Path) {
|
||||||
|
for source in entries {
|
||||||
|
let Ok(name) = name_of(source) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let dest = target.join(name);
|
||||||
|
if source.exists() {
|
||||||
|
let _ = remove_path(&dest);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if dest.exists() {
|
||||||
|
let _ = transfer_back(&dest, source);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transfer_back(from: &Path, to: &Path) -> Result<(), String> {
|
||||||
|
match rename_retry(from, to) {
|
||||||
|
Ok(()) => Ok(()),
|
||||||
|
Err(MoveError::CrossDevice) => copy_path(from, to).and_then(|_| remove_path(from)),
|
||||||
|
Err(MoveError::Message(message)) => Err(message),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_path(from: &Path, to: &Path) -> Result<(), String> {
|
||||||
|
let meta = fs::symlink_metadata(from).map_err(|error| format!("无法读取 {from}: {error}", from = from.display()))?;
|
||||||
|
if meta.file_type().is_symlink() {
|
||||||
|
return Err(format!("数据目录里有链接,无法迁移:{}", from.display()));
|
||||||
|
}
|
||||||
|
if meta.is_dir() {
|
||||||
|
fs::create_dir_all(to).map_err(|error| format!("无法创建 {to}: {error}", to = to.display()))?;
|
||||||
|
let read = fs::read_dir(from).map_err(|error| format!("无法读取 {from}: {error}", from = from.display()))?;
|
||||||
|
for item in read {
|
||||||
|
let item = item.map_err(|error| format!("无法读取 {from}: {error}", from = from.display()))?;
|
||||||
|
copy_path(&item.path(), &to.join(item.file_name()))?;
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if let Some(parent) = to.parent() {
|
||||||
|
fs::create_dir_all(parent).map_err(|error| format!("无法创建 {parent}: {error}", parent = parent.display()))?;
|
||||||
|
}
|
||||||
|
let copied = fs::copy(from, to).map_err(|error| format!("无法复制 {from}: {error}", from = from.display()))?;
|
||||||
|
if copied != meta.len() {
|
||||||
|
let _ = fs::remove_file(to);
|
||||||
|
return Err(format!("复制不完整:{}", from.display()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rename_retry(from: &Path, to: &Path) -> Result<(), MoveError> {
|
||||||
|
let mut last = String::new();
|
||||||
|
for wait_ms in RETRY_WAITS_MS {
|
||||||
|
if wait_ms > 0 {
|
||||||
|
thread::sleep(Duration::from_millis(wait_ms));
|
||||||
|
}
|
||||||
|
match fs::rename(from, to) {
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(error) if is_cross_device(&error) => return Err(MoveError::CrossDevice),
|
||||||
|
Err(error) if denied(&error) => last = error.to_string(),
|
||||||
|
Err(error) => return Err(MoveError::Message(format!("无法移动 {from}: {error}", from = from.display()))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(MoveError::Message(format!("文件被占用,无法移动 {from}:{last}", from = from.display())))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_path(path: &Path) -> Result<(), String> {
|
||||||
|
let mut last = String::new();
|
||||||
|
for wait_ms in RETRY_WAITS_MS {
|
||||||
|
if wait_ms > 0 {
|
||||||
|
thread::sleep(Duration::from_millis(wait_ms));
|
||||||
|
}
|
||||||
|
let result = if path.is_dir() {
|
||||||
|
fs::remove_dir_all(path)
|
||||||
|
} else {
|
||||||
|
fs::remove_file(path)
|
||||||
|
};
|
||||||
|
match result {
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||||
|
Err(error) if denied(&error) => last = error.to_string(),
|
||||||
|
Err(error) => return Err(format!("无法删除 {path}: {error}", path = path.display())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(format!("文件被占用,无法删除 {path}:{last}", path = path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name_of(path: &Path) -> Result<&std::ffi::OsStr, String> {
|
||||||
|
path.file_name()
|
||||||
|
.ok_or_else(|| format!("无法识别 {}", path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_empty_dir(path: &Path) -> Result<bool, String> {
|
||||||
|
let read = fs::read_dir(path).map_err(|error| format!("无法读取目标文件夹:{error}"))?;
|
||||||
|
for item in read {
|
||||||
|
let item = item.map_err(|error| format!("无法读取目标文件夹:{error}"))?;
|
||||||
|
if skip_name(&item.file_name()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn same_volume(left: &Path, right: &Path) -> bool {
|
||||||
|
volume_key(left) == volume_key(right)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn volume_key(path: &Path) -> Option<String> {
|
||||||
|
path.components()
|
||||||
|
.next()
|
||||||
|
.map(|part| part.as_os_str().to_string_lossy().to_lowercase())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn same_path(left: &Path, right: &Path) -> bool {
|
||||||
|
norm(left) == norm(right)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn within(child: &Path, parent: &Path) -> bool {
|
||||||
|
if same_path(child, parent) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let child_text = norm(child);
|
||||||
|
let parent_text = norm(parent).trim_end_matches(['\\', '/']).to_string();
|
||||||
|
child_text.starts_with(&format!("{parent_text}\\")) || child_text.starts_with(&format!("{parent_text}/"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn norm(path: &Path) -> String {
|
||||||
|
path.to_string_lossy().replace('/', "\\").trim_end_matches('\\').to_lowercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn denied(error: &io::Error) -> bool {
|
||||||
|
matches!(error.raw_os_error(), Some(5 | 32 | 33)) || error.kind() == io::ErrorKind::PermissionDenied
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_cross_device(error: &io::Error) -> bool {
|
||||||
|
matches!(error.raw_os_error(), Some(17 | 18))
|
||||||
|
}
|
||||||
|
|
||||||
|
enum MoveError {
|
||||||
|
CrossDevice,
|
||||||
|
Message(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn scratch(name: &str) -> PathBuf {
|
||||||
|
let path = std::env::temp_dir().join(format!("nqi-move-{}-{name}", std::process::id()));
|
||||||
|
let _ = fs::remove_dir_all(&path);
|
||||||
|
fs::create_dir_all(&path).unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn moves_children_and_leaves_the_pointer() {
|
||||||
|
let root = scratch("move");
|
||||||
|
let source = root.join("data");
|
||||||
|
let target = root.join("next");
|
||||||
|
fs::create_dir_all(source.join("jobs").join("1")).unwrap();
|
||||||
|
fs::write(source.join("jobs").join("1").join("job.json"), b"{}").unwrap();
|
||||||
|
fs::write(source.join("settings.json"), b"{\"showTray\":true}").unwrap();
|
||||||
|
let pointer = source.join("data-root.txt");
|
||||||
|
fs::write(&pointer, b"old\n").unwrap();
|
||||||
|
fs::create_dir_all(&target).unwrap();
|
||||||
|
relocate_children(&source, &target, &pointer).unwrap();
|
||||||
|
assert!(target.join("jobs").join("1").join("job.json").is_file());
|
||||||
|
assert!(target.join("settings.json").is_file());
|
||||||
|
assert!(!target.join("data-root.txt").exists());
|
||||||
|
assert!(pointer.is_file());
|
||||||
|
assert!(!source.join("jobs").exists());
|
||||||
|
let _ = fs::remove_dir_all(&root);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_a_folder_that_already_has_files() {
|
||||||
|
let root = scratch("busy");
|
||||||
|
let source = root.join("data");
|
||||||
|
let target = root.join("next");
|
||||||
|
fs::create_dir_all(&source).unwrap();
|
||||||
|
fs::write(source.join("settings.json"), b"{}").unwrap();
|
||||||
|
fs::create_dir_all(&target).unwrap();
|
||||||
|
fs::write(target.join("keep.txt"), b"x").unwrap();
|
||||||
|
let error = relocate_children(&source, &target, &root.join("pointer.txt")).unwrap_err();
|
||||||
|
assert_eq!(error, "请选择一个空文件夹");
|
||||||
|
assert!(source.join("settings.json").is_file());
|
||||||
|
let _ = fs::remove_dir_all(&root);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use std::net::TcpListener;
|
use std::net::{TcpListener, TcpStream};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::{Child, Command, Stdio};
|
use std::process::{Child, Command, Stdio};
|
||||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||||
@@ -7,6 +7,7 @@ use std::time::{Duration, Instant};
|
|||||||
|
|
||||||
use tauri::{Emitter, Manager};
|
use tauri::{Emitter, Manager};
|
||||||
|
|
||||||
|
mod datadir;
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
mod job;
|
mod job;
|
||||||
mod tray;
|
mod tray;
|
||||||
@@ -74,6 +75,59 @@ fn backend_info() -> BackendInfo {
|
|||||||
snapshot(&mut state)
|
snapshot(&mut state)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn wait_ready(port: u16) {
|
||||||
|
for _ in 0..50 {
|
||||||
|
if TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn migrate_data_dir(app: tauri::AppHandle, target: String) -> BackendInfo {
|
||||||
|
let _guard = lock_launch();
|
||||||
|
let chosen = PathBuf::from(target.trim());
|
||||||
|
let source = resolve_data_dir(&app);
|
||||||
|
if let Err(message) = datadir::check_target(&source, &chosen) {
|
||||||
|
let mut state = lock_backend();
|
||||||
|
let mut info = snapshot(&mut state);
|
||||||
|
info.error = Some(message);
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
let mut state = lock_backend();
|
||||||
|
stop_child(&mut state);
|
||||||
|
prepare(&app, &mut state);
|
||||||
|
let port = state.port;
|
||||||
|
drop(state);
|
||||||
|
let moved = datadir::relocate_children(&source, &chosen, &pointer_path(&app));
|
||||||
|
if let Err(message) = moved {
|
||||||
|
let mut state = lock_backend();
|
||||||
|
spawn_child(&app, &mut state);
|
||||||
|
wait_ready(port);
|
||||||
|
let mut info = snapshot(&mut state);
|
||||||
|
if info.error.is_none() {
|
||||||
|
info.error = Some(message);
|
||||||
|
}
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
if let Err(message) = write_pointer(&pointer_path(&app), &chosen) {
|
||||||
|
let _ = datadir::relocate_children(&chosen, &source, &pointer_path(&app));
|
||||||
|
let mut state = lock_backend();
|
||||||
|
spawn_child(&app, &mut state);
|
||||||
|
wait_ready(port);
|
||||||
|
let mut info = snapshot(&mut state);
|
||||||
|
if info.error.is_none() {
|
||||||
|
info.error = Some(message);
|
||||||
|
}
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
let mut state = lock_backend();
|
||||||
|
spawn_child(&app, &mut state);
|
||||||
|
wait_ready(port);
|
||||||
|
snapshot(&mut state)
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn restart_backend(app: tauri::AppHandle) -> BackendInfo {
|
fn restart_backend(app: tauri::AppHandle) -> BackendInfo {
|
||||||
let _guard = lock_launch();
|
let _guard = lock_launch();
|
||||||
@@ -188,6 +242,48 @@ fn bundled_backend(app: &tauri::AppHandle) -> Option<PathBuf> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn pointer_path(app: &tauri::AppHandle) -> PathBuf {
|
||||||
|
if cfg!(debug_assertions) {
|
||||||
|
if let Some(root) = repo_root() {
|
||||||
|
return root.join(".nqi-data-root");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
installed_data_dir(app).join("data-root.txt")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_data_dir(app: &tauri::AppHandle) -> PathBuf {
|
||||||
|
if cfg!(debug_assertions) {
|
||||||
|
if let Some(root) = repo_root() {
|
||||||
|
return root.join("data");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
installed_data_dir(app)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_pointer(path: &Path) -> Option<PathBuf> {
|
||||||
|
let text = std::fs::read_to_string(path).ok()?;
|
||||||
|
let chosen = PathBuf::from(text.trim());
|
||||||
|
if chosen.is_absolute() && chosen.is_dir() {
|
||||||
|
Some(chosen)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_pointer(path: &Path, target: &Path) -> Result<(), String> {
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
std::fs::create_dir_all(parent).map_err(|error| format!("无法记住数据目录:{error}"))?;
|
||||||
|
}
|
||||||
|
std::fs::write(path, format!("{}\n", target.display())).map_err(|error| format!("无法记住数据目录:{error}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_data_dir(app: &tauri::AppHandle) -> PathBuf {
|
||||||
|
if let Some(path) = read_pointer(&pointer_path(app)) {
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
default_data_dir(app)
|
||||||
|
}
|
||||||
|
|
||||||
fn installed_data_dir(app: &tauri::AppHandle) -> PathBuf {
|
fn installed_data_dir(app: &tauri::AppHandle) -> PathBuf {
|
||||||
let folder = app.config().identifier.clone();
|
let folder = app.config().identifier.clone();
|
||||||
if let Ok(appdata) = std::env::var("APPDATA") {
|
if let Ok(appdata) = std::env::var("APPDATA") {
|
||||||
@@ -216,7 +312,7 @@ fn launch_plan(app: &tauri::AppHandle, port: u16) -> Option<Launch> {
|
|||||||
program,
|
program,
|
||||||
args: Vec::new(),
|
args: Vec::new(),
|
||||||
cwd,
|
cwd,
|
||||||
data_dir: installed_data_dir(app),
|
data_dir: resolve_data_dir(app),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -242,7 +338,7 @@ fn launch_plan(app: &tauri::AppHandle, port: u16) -> Option<Launch> {
|
|||||||
"--no-access-log".into(),
|
"--no-access-log".into(),
|
||||||
],
|
],
|
||||||
cwd: repo.join("backend"),
|
cwd: repo.join("backend"),
|
||||||
data_dir: repo.join("data"),
|
data_dir: resolve_data_dir(app),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,6 +537,7 @@ pub fn run() {
|
|||||||
backend_port,
|
backend_port,
|
||||||
backend_info,
|
backend_info,
|
||||||
restart_backend,
|
restart_backend,
|
||||||
|
migrate_data_dir,
|
||||||
set_close_guard,
|
set_close_guard,
|
||||||
close_app,
|
close_app,
|
||||||
write_sample_csv,
|
write_sample_csv,
|
||||||
|
|||||||
@@ -98,6 +98,21 @@ export function saveAppSettings(settings: AppSettings) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function loadDataDir() {
|
||||||
|
return api<{ path: string }>("/api/download/data-dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function prepareDataMove(path: string) {
|
||||||
|
return api<{ path: string; target: string; resumeIds: string[] }>("/api/download/data-dir/prepare", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ path }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resumeMovedJobs() {
|
||||||
|
return api<{ resumed: string[] }>("/api/download/data-dir/resume", { method: "POST" });
|
||||||
|
}
|
||||||
|
|
||||||
export function loadDownloadSettings() {
|
export function loadDownloadSettings() {
|
||||||
return api<{ maxConcurrentJobs: number }>("/api/download/settings");
|
return api<{ maxConcurrentJobs: number }>("/api/download/settings");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,18 +2,21 @@
|
|||||||
import { onMounted, ref } from "vue";
|
import { onMounted, ref } from "vue";
|
||||||
import { NButton, NCheckbox, NEmpty, NIcon, NTooltip, useDialog, useMessage } from "naive-ui";
|
import { NButton, NCheckbox, NEmpty, NIcon, NTooltip, useDialog, useMessage } from "naive-ui";
|
||||||
import { HelpCircleOutline } from "@vicons/ionicons5";
|
import { HelpCircleOutline } from "@vicons/ionicons5";
|
||||||
import { clearAccounts, loadAccounts, removeAccount, type UserInfo } from "../auth/api";
|
import { clearAccounts, loadAccounts, removeAccount, resumeSaved, type UserInfo } from "../auth/api";
|
||||||
import { loadAppSettings, saveAppSettings } from "../download/api";
|
import { loadAppSettings, loadDataDir, prepareDataMove, resumeMovedJobs, saveAppSettings } from "../download/api";
|
||||||
import { ApiError } from "../../shared/http";
|
import { ApiError, chooseDirectory, migrateDataDir } from "../../shared/http";
|
||||||
import { applyShellMode } from "../../shared/shellMode";
|
import { applyShellMode } from "../../shared/shellMode";
|
||||||
|
|
||||||
|
const props = defineProps<{ loginId: string }>();
|
||||||
const message = useMessage();
|
const message = useMessage();
|
||||||
const dialog = useDialog();
|
const dialog = useDialog();
|
||||||
const accounts = ref<UserInfo[]>([]);
|
const accounts = ref<UserInfo[]>([]);
|
||||||
const showTray = ref(true);
|
const showTray = ref(true);
|
||||||
const closeToTray = ref(true);
|
const closeToTray = ref(true);
|
||||||
|
const dataDir = ref("");
|
||||||
const saving = ref(false);
|
const saving = ref(false);
|
||||||
const clearing = ref(false);
|
const clearing = ref(false);
|
||||||
|
const moving = ref(false);
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
void refresh();
|
void refresh();
|
||||||
@@ -21,10 +24,11 @@ onMounted(() => {
|
|||||||
|
|
||||||
async function refresh() {
|
async function refresh() {
|
||||||
try {
|
try {
|
||||||
const [settings, saved] = await Promise.all([loadAppSettings(), loadAccounts()]);
|
const [settings, saved, dir] = await Promise.all([loadAppSettings(), loadAccounts(), loadDataDir()]);
|
||||||
showTray.value = settings.showTray;
|
showTray.value = settings.showTray;
|
||||||
closeToTray.value = settings.closeToTray;
|
closeToTray.value = settings.closeToTray;
|
||||||
accounts.value = saved.accounts;
|
accounts.value = saved.accounts;
|
||||||
|
dataDir.value = dir.path;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
message.error(error instanceof ApiError ? error.message : "设置读取失败");
|
message.error(error instanceof ApiError ? error.message : "设置读取失败");
|
||||||
}
|
}
|
||||||
@@ -84,6 +88,44 @@ function confirmClear() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function confirmMove() {
|
||||||
|
void pickAndMove();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pickAndMove() {
|
||||||
|
if (moving.value) return;
|
||||||
|
const selected = await chooseDirectory();
|
||||||
|
if (!selected) return;
|
||||||
|
dialog.warning({
|
||||||
|
title: "迁移数据目录",
|
||||||
|
content: `会把任务进度、登录记录和设置迁到 ${selected}。正在下载和排队的任务会先停下来,迁完后自动继续。之前暂停的任务不会自动开始。已经下载的表格仍留在原来的保存位置。`,
|
||||||
|
positiveText: "迁移",
|
||||||
|
negativeText: "取消",
|
||||||
|
maskClosable: false,
|
||||||
|
onPositiveClick: () => {
|
||||||
|
void runMove(selected);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runMove(target: string) {
|
||||||
|
moving.value = true;
|
||||||
|
try {
|
||||||
|
await prepareDataMove(target);
|
||||||
|
await migrateDataDir(target);
|
||||||
|
const resumed = await resumeSaved(props.loginId);
|
||||||
|
if (!resumed.user) throw new ApiError(0, "迁移后没能恢复登录");
|
||||||
|
const result = await resumeMovedJobs();
|
||||||
|
dataDir.value = target;
|
||||||
|
message.success(result.resumed.length ? `数据目录已迁移,${result.resumed.length} 个任务已继续` : "数据目录已迁移");
|
||||||
|
} catch (error) {
|
||||||
|
message.error(error instanceof ApiError ? error.message : "迁移失败");
|
||||||
|
await refresh().catch(() => undefined);
|
||||||
|
} finally {
|
||||||
|
moving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function clearAll() {
|
async function clearAll() {
|
||||||
clearing.value = true;
|
clearing.value = true;
|
||||||
try {
|
try {
|
||||||
@@ -127,6 +169,25 @@ async function clearAll() {
|
|||||||
</n-checkbox>
|
</n-checkbox>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="settings-block">
|
||||||
|
<h3>数据目录</h3>
|
||||||
|
<div class="form-row">
|
||||||
|
<label>
|
||||||
|
保存位置
|
||||||
|
<n-tooltip>
|
||||||
|
<template #trigger>
|
||||||
|
<n-icon class="hint" :size="15"><HelpCircleOutline /></n-icon>
|
||||||
|
</template>
|
||||||
|
这里保存任务进度、登录记录和设置。下载好的表格仍在原来的保存位置。
|
||||||
|
</n-tooltip>
|
||||||
|
</label>
|
||||||
|
<div class="captcha-line">
|
||||||
|
<div class="path-text" :title="dataDir">{{ dataDir || "正在读取" }}</div>
|
||||||
|
<n-button :loading="moving" :disabled="moving" @click="confirmMove">迁移</n-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="settings-note">任务全部完成后,进度文件会自动删掉。没下完的会留着,方便继续。</p>
|
||||||
|
</div>
|
||||||
<div class="settings-block">
|
<div class="settings-block">
|
||||||
<div class="settings-head">
|
<div class="settings-head">
|
||||||
<h3>已登录账号</h3>
|
<h3>已登录账号</h3>
|
||||||
|
|||||||
@@ -200,6 +200,21 @@ export async function chooseDirectory() {
|
|||||||
return typeof selected === "string" ? selected : null;
|
return typeof selected === "string" ? selected : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function migrateDataDir(target: string) {
|
||||||
|
if (!isTauri()) throw new ApiError(0, "只能在桌面程序里迁移数据目录");
|
||||||
|
const { invoke } = await import("@tauri-apps/api/core");
|
||||||
|
const info = await invoke<BackendInfo>("migrate_data_dir", { target });
|
||||||
|
if (!applyBackend(info)) {
|
||||||
|
throw new ApiError(0, info.error || "后台没有重新启动");
|
||||||
|
}
|
||||||
|
if (info.error) throw new ApiError(0, info.error);
|
||||||
|
for (let attempt = 0; attempt < 80; attempt += 1) {
|
||||||
|
if (await pingHealth()) return;
|
||||||
|
await new Promise((resolve) => window.setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
throw new ApiError(0, "后台服务没有启动");
|
||||||
|
}
|
||||||
|
|
||||||
export async function restartBackend() {
|
export async function restartBackend() {
|
||||||
if (!isTauri()) return "missing" as const;
|
if (!isTauri()) return "missing" as const;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -133,7 +133,7 @@ async function signOut() {
|
|||||||
<n-layout class="content">
|
<n-layout class="content">
|
||||||
<GridDownloadView v-if="page === 'grid'" :city-name="props.user.cityName" @started="onStarted" />
|
<GridDownloadView v-if="page === 'grid'" :city-name="props.user.cityName" @started="onStarted" />
|
||||||
<DownloadManagerView v-else-if="page === 'tasks'" :focus-id="focusId" />
|
<DownloadManagerView v-else-if="page === 'tasks'" :focus-id="focusId" />
|
||||||
<SettingsView v-else />
|
<SettingsView v-else :login-id="props.user.loginId" />
|
||||||
</n-layout>
|
</n-layout>
|
||||||
</n-layout>
|
</n-layout>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -506,6 +506,12 @@ select {
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.settings-note {
|
||||||
|
margin: 12px 0 0;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
.account-list {
|
.account-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
|||||||
Reference in New Issue
Block a user