77 lines
2.7 KiB
Python
77 lines
2.7 KiB
Python
"""
|
|
scripts/rpa/download_artifact_fallback.py
|
|
|
|
用途:在浏览器实际已落盘但 Playwright 未返回 Download 对象时,按下载目录中的新文件构造兼容适配器。
|
|
依赖:pathlib、shutil、time。
|
|
逻辑:由 DSV 导出链路在 `expect_download` 超时后调用;不改变站点交互,只补文件系统兜底。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import shutil
|
|
import time
|
|
from pathlib import Path
|
|
|
|
|
|
class FilesystemDownloadArtifact:
|
|
"""兼容 Playwright Download 的最小适配器,仅提供 `suggested_filename` 与 `save_as()`。"""
|
|
|
|
def __init__(self, path: Path) -> None:
|
|
self._path = Path(path)
|
|
self.suggested_filename = self._path.name
|
|
|
|
def save_as(self, dest: str) -> None:
|
|
target = Path(dest)
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
if self._path.resolve() == target.resolve():
|
|
return
|
|
shutil.move(str(self._path), str(target))
|
|
|
|
|
|
def wait_for_new_download_file(
|
|
*,
|
|
download_dir: str | Path,
|
|
baseline_names: set[str],
|
|
timeout_seconds: float = 12.0,
|
|
poll_seconds: float = 0.5,
|
|
) -> FilesystemDownloadArtifact | None:
|
|
"""
|
|
等待下载目录里出现本次新生成且大小稳定的文件。
|
|
|
|
核心逻辑:忽略 `.crdownload/.tmp` 等临时文件;优先接受 Excel/CSV 类产物,
|
|
同时兼容 Chromium 在 `downloads_path` 中落下的无扩展名原始文件;
|
|
连续两次观察到大小不变后,认为浏览器已完成落盘。
|
|
"""
|
|
root = Path(download_dir)
|
|
if not root.is_dir():
|
|
return None
|
|
|
|
deadline = time.monotonic() + max(1.0, timeout_seconds)
|
|
stable_sizes: dict[Path, int] = {}
|
|
allowed_suffixes = {".xlsx", ".xls", ".xlsm", ".xltx", ".xltm", ".csv", ""}
|
|
transient_suffixes = {".crdownload", ".tmp", ".part"}
|
|
|
|
while time.monotonic() < deadline:
|
|
candidates = []
|
|
for path in root.iterdir():
|
|
if not path.is_file():
|
|
continue
|
|
if path.name in baseline_names:
|
|
continue
|
|
suffix = path.suffix.lower()
|
|
if suffix in transient_suffixes or suffix not in allowed_suffixes:
|
|
continue
|
|
candidates.append(path)
|
|
candidates.sort(key=lambda item: item.stat().st_mtime, reverse=True)
|
|
for path in candidates:
|
|
try:
|
|
size = path.stat().st_size
|
|
except OSError:
|
|
continue
|
|
last_size = stable_sizes.get(path)
|
|
if last_size is not None and last_size == size and size > 0:
|
|
return FilesystemDownloadArtifact(path)
|
|
stable_sizes[path] = size
|
|
time.sleep(max(0.1, poll_seconds))
|
|
return None
|