The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
fix(filesystem): 成品路径 stat 失败不再弹异常 #881
XiaoYouChRf8a7b479030c
diff --git a/app/platform/desktop.py b/app/platform/desktop.pyindex c45108f1..ce855206 100644--- a/app/platform/desktop.py+++ b/app/platform/desktop.py@@ -9,6 +9,8 @@ from PySide6.QtGui import QDesktopServices, QDragfrom PySide6.QtWidgets import QApplication, QWidgetfrom loguru import logger+from app.platform.filesystem import probe+def buildFontFamilies(locale: QLocale, defaultFamily: str) -> list[str]:locale = locale if locale.script() != QLocale.Script.AnyScript else QLocale.system()@@ -118,7 +120,7 @@ def openFolder(path: str | PathLike[str]) -> None:def revealInFolder(path: str | PathLike[str]) -> None:path = Path(path)- if path.exists():+ if probe(path):match sys.platform:case "win32":if not _revealInFolderShell(path):@@ -127,7 +129,7 @@ def revealInFolder(path: str | PathLike[str]) -> None:QProcess.startDetached("open", ["-R", str(path)])case _:QProcess.startDetached("xdg-open", [str(path.parent)])- elif path.parent.exists():+ elif probe(path.parent):openFolder(path.parent)diff --git a/app/platform/filesystem.py b/app/platform/filesystem.pyindex 0bf4e334..e274b36d 100644--- a/app/platform/filesystem.py+++ b/app/platform/filesystem.py@@ -4,7 +4,9 @@ import hashlibimport reimport shutilimport sys+from os import PathLikefrom pathlib import Path+from stat import S_ISDIRfrom urllib.parse import urlparsefrom urllib.request import url2pathname@@ -16,6 +18,21 @@ WINDOWS_RESERVED_FILENAMES = {}+def probe(path: str | PathLike[str]) -> bool:+ try:+ Path(path).stat()+ except (OSError, ValueError):+ return False+ return True+++def probeDirectory(path: str | PathLike[str]) -> bool:+ try:+ return S_ISDIR(Path(path).stat().st_mode)+ except (OSError, ValueError):+ return False++def toSafeFilename(name: str, fallback: str = "file", maxLength: int = 200) -> str:candidate = str(name or "")candidate = INVALID_FILENAME_PATTERN.sub("_", candidate).strip().rstrip(". ")diff --git a/app/services/browser_service.py b/app/services/browser_service.pyindex c547e3b3..6a19b50c 100644--- a/app/services/browser_service.py+++ b/app/services/browser_service.py@@ -18,6 +18,7 @@ from loguru import loggerfrom app.config.cfg import cfgfrom app.config.constants import LATEST_EXTENSION_VERSION, VERSIONfrom app.config.paths import APP_DATA_DIR+from app.platform.filesystem import probefrom app.signal import Signalfrom app.update import isNewer@@ -172,8 +173,8 @@ def toTaskSummary(task: Task) -> dict:"speed": speed,"createdAt": task.createdAt,"canPause": task.canPause,- "canOpenFile": outputPath.exists(),- "canOpenFolder": outputPath.parent.exists(),+ "canOpenFile": probe(outputPath),+ "canOpenFolder": probe(outputPath.parent),"fileExt": outputPath.suffix.lstrip(".").lower(),"packName": task.packId,}@@ -599,7 +600,7 @@ class BrowserService:elif action == TaskAction.OPEN_FILE:path = Path(task.outputPath)- if not path.exists():+ if not probe(path):self._sendResult(session, MessageType.TASK_ACTION_RESULT, requestId,ok=False, message="文件尚未生成")return@@ -607,7 +608,7 @@ class BrowserService:elif action == TaskAction.OPEN_FOLDER:path = Path(task.outputPath)- if not path.parent.exists():+ if not probe(path.parent):self._sendResult(session, MessageType.TASK_ACTION_RESULT, requestId,ok=False, message="目录不存在")returndiff --git a/app/services/task_service.py b/app/services/task_service.pyindex 2eb96887..ce9677da 100644--- a/app/services/task_service.py+++ b/app/services/task_service.py@@ -12,7 +12,7 @@ from loguru import loggerfrom app.config.cfg import cfgfrom app.config.paths import APP_DATA_DIR-from app.platform.filesystem import splitStemExt+from app.platform.filesystem import probe, splitStemExtfrom app.signal import Signalif TYPE_CHECKING:@@ -210,7 +210,7 @@ class TaskService:def isTaken() -> bool:op = task.outputPath- return op in storePaths or Path(op).exists() or Path(f"{op}.ghd").exists()+ return op in storePaths or probe(op) or probe(f"{op}.ghd")if not isTaken():return@@ -318,7 +318,7 @@ class TaskService:from app.models.task import TaskStatusfor task in self._store.loadSaved():self.taskAdded.emit(task)- if task.status == TaskStatus.COMPLETED and task.hasOutputFile and Path(task.outputPath).exists():+ if task.status == TaskStatus.COMPLETED and task.hasOutputFile and probe(task.outputPath):self._watchFile(task)elif task.status in {TaskStatus.WAITING, TaskStatus.RUNNING}:task.setStatus(TaskStatus.WAITING)@@ -440,7 +440,7 @@ class TaskService:self._fileWatcher.removePath(path)def _onWatchedFileChanged(self, path: str) -> None:- if Path(path).exists():+ if probe(path):returntaskId = self._watchedPaths.pop(path, None)if taskId is None:diff --git a/app/view/cards/task_cards.py b/app/view/cards/task_cards.pyindex 225a550b..8fc43179 100644--- a/app/view/cards/task_cards.py+++ b/app/view/cards/task_cards.py@@ -2,7 +2,6 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom datetime import datetime-from pathlib import Pathfrom collections.abc import Callablefrom typing import TYPE_CHECKING@@ -20,6 +19,7 @@ from app.config.cfg import cfgfrom app.format import toReadableSize, toReadableTimefrom app.models.task import TaskStatus, SpecialFileSizefrom app.platform.desktop import openFile, revealInFolder+from app.platform.filesystem import probe, probeDirectoryfrom app.view.components.labels import IconBodyLabel, IconStrongBodyLabelfrom app.view.components.category_settings import toCategoryNamefrom app.i18n import toLocalizedError@@ -90,12 +90,12 @@ VERIFY_HASH_BUTTON = ButtonSpec("verifyHash", FluentIcon.FINGERPRINT, N("TaskCardefault=BUTTON_HIDDEN,states={TaskStatus.COMPLETED: lambda t: ButtonState(- enabled=t.hasOutputFile and Path(t.outputPath).exists()),+ enabled=t.hasOutputFile and probe(t.outputPath)),})OPEN_FILE_BUTTON = ButtonSpec("openFile", FluentIcon.LINK, N("TaskCard", "打开文件"), states={TaskStatus.COMPLETED: lambda t: ButtonState(- enabled=not t.hasOutputFile or Path(t.outputPath).exists()),+ enabled=not t.hasOutputFile or probe(t.outputPath)),})OPEN_FOLDER_BUTTON = ButtonSpec("openFolder", FluentIcon.FOLDER, N("TaskCard", "打开文件夹"))@@ -255,7 +255,7 @@ class TaskCard(CardWidget):elif task.status == TaskStatus.COMPLETED:self.progressBar.pause()self.progressBar.hide()- self._isFileMissing = task.hasOutputFile and not Path(task.outputPath).exists()+ self._isFileMissing = task.hasOutputFile and not probe(task.outputPath)if self._isFileMissing:self._setStatus(self.tr("文件不存在"))self.statusLabel.setTextColor(QColor(200, 160, 80), QColor(200, 170, 100))@@ -336,7 +336,7 @@ class TaskCard(CardWidget):self._taskService.delete(self._task, deleteFiles.isChecked())def _onVerifyHashClicked(self) -> None:- if not Path(self._task.outputPath).is_file():+ if probeDirectory(self._task.outputPath) or not probe(self._task.outputPath):self._setStatus(self.tr("文件不存在,无法校验"))returnfrom app.view.dialogs.file_hash import FileHashDialog@@ -456,7 +456,7 @@ class TaskCard(CardWidget):def _canDrag(self) -> bool:return (self._task.status == TaskStatus.COMPLETEDand self._task.hasOutputFile- and Path(self._task.outputPath).exists())+ and probe(self._task.outputPath))def resizeEvent(self, e) -> None:self.progressBar.setGeometry(4, self.height() - 4, self.width() - 8, 4)diff --git a/app/view/pages/task_page.py b/app/view/pages/task_page.pyindex d4509347..0fdaea02 100644--- a/app/view/pages/task_page.py+++ b/app/view/pages/task_page.py@@ -20,6 +20,7 @@ from app.view.components.scroll_area import ScrollAreafrom app.config.cfg import cfgfrom app.format import toReadableSizefrom app.models.task import TaskStatus+from app.platform.filesystem import probefrom app.view.cards.task_cards import TaskCardfrom app.view.components.category_settings import toCategoryNamefrom app.view.components.labels import IconBodyLabel@@ -374,7 +375,7 @@ class TaskPage(QWidget):self._selectedIds.clear()for taskId in self._displayOrder:task = self._taskService.taskById(taskId)- if task and task.hasOutputFile and not Path(task.outputPath).exists():+ if task and task.hasOutputFile and not probe(task.outputPath):self._selectedIds.add(taskId)for taskId, card in self._liveCards.items():card.setChecked(taskId in self._selectedIds)@@ -748,7 +749,7 @@ class TaskPage(QWidget):if (task := self._taskService.taskById(tid))and task.status == TaskStatus.COMPLETEDand task.hasOutputFile- and Path(task.outputPath).exists()+ and probe(task.outputPath)]else:task = self._taskService.taskById(taskId)diff --git a/tests/test_filesystem_probe.py b/tests/test_filesystem_probe.pynew file mode 100644index 00000000..b8c02eb5--- /dev/null+++ b/tests/test_filesystem_probe.py@@ -0,0 +1,28 @@+from __future__ import annotations++from pathlib import Path++from app.platform.filesystem import probe, probeDirectory+++def test_probe_missing(tmp_path: Path):+ assert probe(tmp_path / "missing") is False+++def test_probe_present(tmp_path: Path):+ file = tmp_path / "file"+ file.write_text("x")+ assert probe(file) is True+ assert probeDirectory(file) is False+ assert probeDirectory(tmp_path) is True+++def test_probe_stat_failure(tmp_path: Path, monkeypatch):+ def fail(self, *, follow_symlinks=True):+ error = OSError(22, "参数错误")+ error.winerror = 87+ raise error++ monkeypatch.setattr(Path, "stat", fail)+ assert probe(tmp_path / "zh-cn_windows_11.iso") is False+ assert probeDirectory(tmp_path / "zh-cn_windows_11.iso") is False