Peach: Local-first video metadata scraper and media manager.
fix(organize): 核验 A 盘云端移动并拆分改名步骤
longmeidaof17b7a0b1766
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex d463e00f6..d3b01ca5a 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -211,6 +211,10 @@ JAV 默认封面(官方封面/预览图)与视频默认大小(大图/完整目录分类归位使用 `scripts/organize_library_dirs.py`,复用 `organize._rename`、目录折叠入口、番号解析器、实体分类与进程锁。默认冻结计划,`--apply --backup` 才执行;`--batch` 分开保存计划与回执,失败可恢复。`--stage flatten` 自行生成折叠复核 CSV。同目录已确认作品与缺厂牌配套图作为整包处理;混合目录只移动已知文件组及配对字幕,物理文件去重,未知视频、冲突身份和覆盖目标均保留。目录名的发行站、画质和分片标记复用 `release_code_from_filename`;一本道的日期式分隔符匹配复用其官网作品号解析,不跨片商合并日期编号。FC2 发行目录可使用 `FC-` 简写并附带标题;缺番号的 `@fc编号_分片` 同时核对父目录编号与厂牌,目录编号不补写账本。韩国 MIB 按厂牌归置。已有唯一创作者关系但细分类未确认时归入通用「创作者」目录,不提升身份候选。路径同步覆盖资产与已登记字幕,不补写真相字段。+PikPak WebDAV 同来源移动由 `organize_clouddrive.py` 提供,目录入口显式指定 `--pikpak-webdav --location pikpak --batch` 才启用。复用 CloudDrive 已存令牌与官方 `GetDownloadUrlPath` 的认证头;来源固定为 `https://dav.mypikpak.com`,认证不写入地址、日志或账本。协议依据 [PikPak WebDAV 官方说明](https://mypikpak.com/zh-TW/help-center/connected_apps/webdav/how_to) 与 [RFC 4918](https://www.rfc-editor.org/rfc/rfc4918),HTTP 客户端复用已声明的 `httpx`,消息编码复用已声明的 `protobuf`,不新增依赖。`PROPFIND` 核对目录成员,`MKCOL` 创建所需父目录,`MOVE` 使用 `Overwrite: F`;单次应答上限 2 MiB,遍历上限 10,000 条。移动后核对完整路径与体积,再刷新 CloudDrive 缓存并交回现有账本事务。应答不确定时保留意图回执并停止,不重复移动;成功状态码也必须取得完整成员变化证据。A 盘折叠目录使用不以点号开头的暂存名,保留同一套恢复回执;R 盘不进入该传输路径。++A 盘同父目录改名复用 CloudDrive 官方 `RenameFile`;跨父且改名的操作拆为同父改名和保留名称的 HTTPS 移动,中间路径进入恢复回执并禁止覆盖。每步核对完整成员与体积;成功应答不替代路径核验。路径中的 `@` 保留为 URI 路径字符,其他字符使用 UTF-8 百分号编码。认证样本已移动时,最多另查两条馆藏内图片样本,仅提取既有认证,不读取媒体内容。+推广网页资源目录中的横幅、标志和导航图片由 `web_batch._attachment_junk_reason` 进入复核队列。判据同时要求 `_files`、网址推广套话、域名、导航元素文件名和体积上限;继承的作品番号不豁免网页导航图片,作品图片、字幕、NFO 与普通 `_files` 目录保留。`1024核工厂.rar` 经嵌套目录清单核验仅含安装程序,精确名称且不超过 64 KiB 的附件进入复核,不泛化为所有压缩包。永久删除仍走 `trash_junk.py --purge --review-csv` 和 `purge_assets`。下载站的 DNS 导航步骤、hav.so 横幅、固定英文横幅和带下载套话的 HiHSP 地址卡片,按文件名与 2 MiB 上限进入复核;用户确认的「社區最新情報」精确名称 MP4 按 32 MiB 上限进入复核。普通作品图片和 `images.rar` 保留。CloudDrive WebDAV 的小文件删除复用原生 `Path.unlink`:同目录隔离改名报 WinError 50 时,最多 1 MiB 的文件先用标准库 `shutil.copyfile` 完整备份到 `generated/purge-staging/`,记录原路径、大小和 SHA256,再删除。数据库失败时恢复备份,提交后清退;大文件继续报告阻塞。该路径没有新增依赖,备份和恢复只由 `purge_assets` 管理。diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 6815551bc..21f14dcd9 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -1,6 +1,6 @@# Peach 运行核验记录-最后核验:2026-10-07+最后核验:2026-10-08状态查 `/healthz`;[待办](PRODUCT_BACKLOG.md)、[复用清单](REUSE.md)、[长期约定](HANDOFF.md)。@@ -22,7 +22,7 @@- 访问密码未开,局域网匿名可读;可选密码首启可跳过,配置页可改可关,登录可记住设备。- macOS 是 reader,代码与 `peach-data` 在内置盘;`peach.local` 经 8900/8443 和 pf 提供 80/443,GET 正常、写入回 409。- 两端各用本机 CA,私钥与凭据不跨机;代码走 Git、账本单写者复制、图片走 Syncthing;本机坐标见 `<数据根>/config.toml`。-- Windows ledger `0045`,资产 80,214 行;字幕 195 行(孤立 19),175 部带字幕轨;本轮删除确认广告 14 个。+- Windows ledger `0045`,资产 80,203 行;字幕 195 行(孤立 19),175 部带字幕轨;本轮删除确认广告 14 个。- Mac ledger 经授权从共享副本拉取,恢复 `in-sync`;`sources` 在内置盘,`archive`、`tools` 可指向外置盘。- Windows doctor、诊断页通过 CA 核验;本地目录缺失,115/PikPak 可读取;密码未开、历史失败为警告。- 本机 Python 3.14;`requires-python` 下限 3.12,CI 同测 3.12 与 3.14;Windows FFmpeg/ffprobe 在 `peach-data/tools/ffmpeg`,macOS 走 PATH。diff --git a/scripts/organize_library_dirs.py b/scripts/organize_library_dirs.pyindex 5cc12748d..13cd6bf62 100644--- a/scripts/organize_library_dirs.py+++ b/scripts/organize_library_dirs.py@@ -436,8 +436,19 @@ def expand(source, target, *, deadline, count=None):def restore(pairs):failures = []- for source, target in reversed(pairs):+ for index in range(len(pairs)-1, -1, -1):+ source, target = pairs[index]old, new = translate_ledger_path(source), translate_ledger_path(target)+ if not old.exists() and not new.exists():+ ancestor, present = source, False+ for earlier_source, earlier_target in reversed(pairs[:index]):+ if ancestor == earlier_target:+ ancestor = earlier_source+ if translate_ledger_path(ancestor).exists():+ present = True+ break+ if present:+ continueif old.exists() and not new.exists():continueif not old.exists() and new.exists():@@ -449,9 +460,14 @@ def restore(pairs):failures.append(dict(source=source, target=target, error='恢复路径状态冲突'))return failures+def staging_name(source):+ prefix = 'peach-organize-' if PureWindowsPath(source).drive.casefold() == 'a:' else '.peach-organize-'+ return prefix + hashlib.sha256(source.encode()).hexdigest()[:20]++def collapse_moves(source, target):parent = translate_ledger_path(target)- temporary = parent.with_name('.peach-organize-' + hashlib.sha256(source.encode()).hexdigest()[:20])+ temporary = parent.with_name(staging_name(source))if temporary.exists() or temporary.is_symlink():raise FileExistsError('临时目录已存在')child = temporary / translate_ledger_path(source).name@@ -592,7 +608,7 @@ def file_group_moves(op):return physical_pairs, emptydef shared_collapse_moves(local_source, local_target, root, source):- temporary = local_source.with_name('.peach-organize-' + hashlib.sha256(source.encode()).hexdigest()[:20])+ temporary = local_source.with_name(staging_name(source))if temporary.exists() or temporary.is_symlink() or not beneath(str(temporary), root):raise ValueError('暂存目录冲突或越出根目录')entries = list(local_source.iterdir())@@ -649,13 +665,34 @@ def cleanup_empty_paths(paths):except OSError:pass-def execute_operation(db, payload, op, stage, receipt, receipt_path, deadline, retry_failed):+def provider_moves(pairs, root, allow_intermediate=True):+ planned = {str(PureWindowsPath(path)).casefold() for pair in pairs for path in pair}+ result = []+ for old, new in pairs:+ source, target = PureWindowsPath(old), PureWindowsPath(new)+ if source.drive.casefold() == 'a:' and source.parent != target.parent and source.name != target.name:+ if not allow_intermediate:+ raise ValueError('目录折叠的改名中间路径需单独复核')+ intermediate = str(source.with_name(target.name))+ local = translate_ledger_path(intermediate)+ if not beneath(intermediate, root) or intermediate.casefold() in planned or local.exists() or local.is_symlink():+ raise FileExistsError('同父改名的中间路径冲突或越界')+ planned.add(intermediate.casefold())+ result.extend(((old, intermediate), (intermediate, new)))+ else:+ result.append((old, new))+ return result+++def execute_operation(db, payload, op, stage, receipt, receipt_path, deadline, retry_failed, pikpak_webdav=False):journal, committed = None, Falsetry:local_source,local_target,root,exclusive = operation_paths(op,payload['roots'])db.execute('BEGIN IMMEDIATE')verify_frozen_operation(db,op,stage)pairs,empty,collapse,shared_stage = prepare_moves(op,local_source,local_target,root,exclusive,deadline)+ if pikpak_webdav:+ pairs = provider_moves(pairs, root, allow_intermediate=not collapse and not shared_stage)journal = dict(key=op['key'],status='intent',source=op['source'],target=op['target'],moves=pairs,empty=empty,assets=len(op['rows']),collapse=collapse,shared_stage=shared_stage,retry_failed=retry_failed)receipt['entries'].append(journal)@@ -700,7 +737,7 @@ def verify_result(db, assets, subtitle_count, baseline):raise RuntimeError('目录执行后的账本计数或完整性核验失败')return result-def run_apply(stage, backup, limit, seconds, location=None, retry_failed=False, skip_collapses=False, batch=None):+def run_apply(stage, backup, limit, seconds, location=None, retry_failed=False, skip_collapses=False, batch=None, pikpak_webdav=False):if backup is None:raise ValueError('--apply 必须同时给 --backup')stem = stage + ('-' + batch if batch else '')@@ -729,7 +766,8 @@ def run_apply(stage, backup, limit, seconds, location=None, retry_failed=False,if owner in unavailable:continuechecked += 1- error = execute_operation(db,payload,op,stage,receipt,receipt_path,deadline,retry_failed)+ provider_options = {'pikpak_webdav': True} if pikpak_webdav else {}+ error = execute_operation(db,payload,op,stage,receipt,receipt_path,deadline,retry_failed,**provider_options)if isinstance(error,OfflineSource):unavailable.add(owner)if error is None:@@ -827,6 +865,7 @@ if __name__ == '__main__':parser.add_argument('--location', choices=('115','pikpak','local'))parser.add_argument('--retry-failed', action='store_true')parser.add_argument('--skip-collapses', action='store_true')+ parser.add_argument('--pikpak-webdav', action='store_true', help='冻结 A 盘批次使用既有 PikPak HTTPS WebDAV 移动')parser.add_argument('--batch', type=lambda value: value if re.fullmatch(r'[a-zA-Z0-9_-]+', value)else parser.error('批次编号只能包含字母、数字、下划线与连字号'))args = parser.parse_args()@@ -834,6 +873,18 @@ if __name__ == '__main__':if args.self_check:self_check()elif args.apply:- run_apply(args.stage, args.backup, args.limit, args.seconds, args.location, args.retry_failed, args.skip_collapses, args.batch)+ if args.pikpak_webdav:+ from peach.organize_clouddrive import pikpak_renames+ if args.location != 'pikpak' or not args.batch:+ parser.error('--pikpak-webdav 需要 --location pikpak 和明确冻结批次 --batch')+ stem = args.stage + '-' + args.batch+ payload = json.loads((OUT/f'{stem}-manifest.json').read_text(encoding='utf-8'))+ rows = [row for op in payload['operations'] for row in op['rows'] if row['path'].startswith('A:')]+ if not rows:+ parser.error('冻结批次没有 A 盘资源')+ with pikpak_renames(rows[0]['path'], payload['roots']):+ run_apply(args.stage, args.backup, args.limit, args.seconds, args.location, args.retry_failed, args.skip_collapses, args.batch, pikpak_webdav=True)+ else:+ run_apply(args.stage, args.backup, args.limit, args.seconds, args.location, args.retry_failed, args.skip_collapses, args.batch)else:build_plan(args.stage, args.batch)diff --git a/src/peach/organize_clouddrive.py b/src/peach/organize_clouddrive.pynew file mode 100644index 000000000..a942d06c6--- /dev/null+++ b/src/peach/organize_clouddrive.py@@ -0,0 +1,296 @@+"""PikPak WebDAV 的同来源 HTTPS 移动与有界核验。"""+from __future__ import annotations++from contextlib import closing, contextmanager+from pathlib import PureWindowsPath+from urllib.parse import quote, unquote, urlsplit+from xml.etree import ElementTree as ET++import httpx+import grpc+from google.protobuf import descriptor_pb2, descriptor_pool, message_factory++from . import organize+from .downloads_clouddrive import CloudDriveClient, SERVICE, discover+from .downloads import CLOUDDRIVE_CREDENTIAL, DownloadSettings+from .follow_secrets import CredentialStore+from .config import DATABASE_PATH, SECRETS_DIR, STATE_DIR+from .scripting import open_readonly++MAX_RESPONSE = 2 * 1024 * 1024+MAX_FILES = 10000+DAV_ORIGIN = 'https://dav.mypikpak.com'+++class UnconfirmedMove(SystemExit):+ """保留移动意图,停止当前进程供续跑核对。"""+++def _messages():+ """CloudDrive 官方 GetDownloadUrlPath/GetSubFiles 消息的所需字段。"""+ from . import downloads_clouddrive_pb2 as pb+ proto = descriptor_pb2.FileDescriptorProto(+ name='peach_organize_cloud.proto', package='peach_organize_cloud', syntax='proto3')+ proto.dependency.append(pb.DESCRIPTOR.name)+ request = proto.message_type.add(name='DownloadRequest')+ request.field.add(name='path', number=1, type=9, label=1)+ request.field.add(name='get_direct_url', number=4, type=8, label=1)+ reply = proto.message_type.add(name='DownloadReply')+ reply.field.add(name='directUrl', number=3, type=9, label=1)+ reply.field.add(name='userAgent', number=4, type=9, label=1)+ entry = reply.nested_type.add(name='HeadersEntry')+ entry.options.map_entry = True+ entry.field.add(name='key', number=1, type=9, label=1)+ entry.field.add(name='value', number=2, type=9, label=1)+ reply.field.add(name='additionalHeaders', number=5, type=11, label=3,+ type_name='.peach_organize_cloud.DownloadReply.HeadersEntry')+ listing = proto.message_type.add(name='ListRequest')+ listing.field.add(name='path', number=1, type=9, label=1)+ listing.field.add(name='forceRefresh', number=2, type=8, label=1)+ result = proto.message_type.add(name='ListReply')+ result.field.add(name='subFiles', number=1, type=11, label=3,+ type_name='.clouddrive.CloudDriveFile')+ rename = proto.message_type.add(name='RenameRequest')+ rename.field.add(name='path', number=1, type=9, label=1)+ rename.field.add(name='newName', number=2, type=9, label=1)+ pool = descriptor_pool.DescriptorPool()+ pool.AddSerializedFile(pb.DESCRIPTOR.dependencies[0].serialized_pb)+ pool.AddSerializedFile(pb.DESCRIPTOR.serialized_pb)+ pool.Add(proto)+ return tuple(message_factory.GetMessageClass(pool.FindMessageTypeByName('peach_organize_cloud.' + name))+ for name in ('DownloadRequest', 'DownloadReply', 'ListRequest', 'ListReply', 'RenameRequest'))+++DownloadRequest, DownloadReply, ListRequest, ListReply, RenameRequest = _messages()+++class PikPakDav:+ def __init__(self, http: httpx.Client, root: str, refresh, rename=None):+ self.http, self.root, self.refresh = http, PureWindowsPath(root), refresh+ self.rename = rename+ if self.root != PureWindowsPath('A:\\'):+ raise ValueError('HTTPS WebDAV 整理只支持已声明的 A 盘根目录')++ def url(self, path: str) -> str:+ item = PureWindowsPath(path)+ if item.drive.casefold() != self.root.drive.casefold() or '..' in item.parts or not item.is_absolute():+ raise ValueError('WebDAV 路径越出已声明来源')+ return DAV_ORIGIN + quote('/' + '/'.join(item.parts[1:]), safe='/@')++ def request(self, method, path, **kwargs):+ try:+ with self.http.stream(method, self.url(path), **kwargs) as response:+ chunks, size = [], 0+ for chunk in response.iter_bytes():+ size += len(chunk)+ if size > MAX_RESPONSE:+ raise ValueError('WebDAV 响应超过预算')+ chunks.append(chunk)+ return response.status_code, b''.join(chunks)+ except httpx.HTTPError:+ raise OSError('WebDAV 网络应答未取得') from None++ def list(self, path):+ status, body = self.request('PROPFIND', path, headers={'Depth': '1'})+ if status != 207:+ raise OSError('WebDAV 目录应答未取得:HTTP ' + str(status))+ result, seen = [], set()+ parent = PureWindowsPath(path)+ for node in ET.fromstring(body).findall('{DAV:}response'):+ href = urlsplit(node.findtext('{DAV:}href') or '')+ if href.netloc and (href.scheme + '://' + href.netloc) != DAV_ORIGIN:+ raise ValueError('WebDAV 成员来自其他来源')+ name = PureWindowsPath('A:' + unquote(href.path, errors='strict').replace('/', '\\'))+ if name != parent and name.parent != parent:+ raise ValueError('WebDAV 成员越出所列目录')+ if name in seen:+ raise ValueError('WebDAV 目录存在重复路径')+ seen.add(name)+ valid = [p for p in node.findall('{DAV:}propstat')+ if (p.findtext('{DAV:}status') or '').split()[1:2] == ['200']]+ if len(valid) != 1:+ raise ValueError('WebDAV 成员属性未完整取得')+ props = valid[0].find('{DAV:}prop')+ if props is None:+ raise ValueError('WebDAV 成员属性为空')+ if name != parent:+ result.append(dict(path=str(name), size=int(props.findtext('{DAV:}getcontentlength') or 0),+ directory=props.find('{DAV:}resourcetype/{DAV:}collection') is not None))+ if parent not in seen:+ raise ValueError('WebDAV 应答缺少目录自身')+ return result++ def tree(self, path):+ pending, files, visited = [path], [], set()+ while pending:+ parent = pending.pop()+ if parent in visited or len(visited) >= MAX_FILES:+ raise ValueError('WebDAV 目录遍历超过预算或循环')+ visited.add(parent)+ for entry in self.list(parent):+ if entry['directory']:+ pending.append(entry['path'])+ else:+ files.append(entry)+ if len(files) > MAX_FILES:+ raise ValueError('WebDAV 文件成员超过预算')+ return files++ def ensure_parent(self, path):+ parent = PureWindowsPath(path).parent+ if parent == self.root:+ return+ self.ensure_parent(str(parent))+ grandparent = str(parent.parent)+ listing = self.list(grandparent)+ matches = [r for r in listing if PureWindowsPath(r['path']) == parent]+ if matches:+ if not matches[0]['directory']:+ raise ValueError('目标父路径不是目录')+ return+ status, _ = self.request('MKCOL', str(parent))+ if status != 201:+ raise OSError('WebDAV 创建父目录失败:HTTP ' + str(status))+ self.refresh(grandparent)++ def submit_move(self, source, target):+ if PureWindowsPath(source).parent == PureWindowsPath(target).parent and self.rename is not None:+ return 200 if self.rename(source, target) else None+ return self.request('MOVE', source, headers={'Destination': self.url(target), 'Overwrite': 'F'})[0]++ def move(self, source, target):+ self.url(source)+ self.url(target)+ old_parent, new_parent = str(PureWindowsPath(source).parent), str(PureWindowsPath(target).parent)+ entries = self.list(old_parent)+ found = [r for r in entries if PureWindowsPath(r['path']) == PureWindowsPath(source)]+ if len(found) != 1:+ raise FileNotFoundError('WebDAV 来源未取得')+ before = self.tree(source) if found[0]['directory'] else found+ self.ensure_parent(target)+ if any(PureWindowsPath(r['path']) == PureWindowsPath(target) for r in self.list(new_parent)):+ raise FileExistsError('WebDAV 目标已存在')+ try:+ response_status = self.submit_move(source, target)+ except OSError:+ response_status = None+ try:+ after_parent = self.list(new_parent)+ old_listing = self.list(old_parent)+ arrived = [r for r in after_parent if PureWindowsPath(r['path']) == PureWindowsPath(target)]+ still_present = any(PureWindowsPath(r['path']) == PureWindowsPath(source) for r in old_listing)+ if still_present and not arrived:+ if response_status is None or response_status >= 500 or 200 <= response_status < 300:+ raise ValueError('WebDAV 请求仍可能在服务端处理')+ raise FileNotFoundError('WebDAV 移动未执行,原文件已确认保留')+ after = self.tree(target) if found[0]['directory'] else arrived+ expected = {(str(PureWindowsPath(target, *PureWindowsPath(r['path']).parts[len(PureWindowsPath(source).parts):])), r['size'])+ for r in before}+ if still_present or len(arrived) != 1 or arrived[0]['directory'] != found[0]['directory'] or expected != {(r['path'], r['size']) for r in after}:+ raise ValueError('WebDAV 移动状态或完整成员不符')+ for parent in {old_parent, new_parent}:+ self.refresh(parent)+ if found[0]['directory']:+ self.refresh(target)+ except FileNotFoundError:+ raise+ except Exception:+ raise UnconfirmedMove('WebDAV 移动状态未确认,保留意图回执并停止;不重复操作、不写账本') from None+++def _fallback_samples():+ with closing(open_readonly(DATABASE_PATH)) as db:+ return [row[0] for row in db.execute(+ "SELECT path FROM asset WHERE location='pikpak' AND disposal IS NULL AND medium='image' "+ "AND path LIKE 'A:%' ORDER BY id LIMIT 2")]+++def _download_headers(cloud, sample_path):+ paths = [sample_path]+ stub = cloud.channel.unary_unary(SERVICE + 'GetDownloadUrlPath',+ request_serializer=DownloadRequest.SerializeToString, response_deserializer=DownloadReply.FromString)+ for index in range(3):+ if index >= len(paths):+ break+ path = PureWindowsPath(paths[index])+ if path.drive.casefold() != 'a:' or not path.is_absolute() or '..' in path.parts:+ raise ValueError('认证样本越出 A 盘来源')+ relative = '/' + '/'.join(path.parts[1:])+ try:+ reply = stub(DownloadRequest(path='/Pikpak' + relative, get_direct_url=True), timeout=15,+ metadata=(('authorization', 'Bearer ' + cloud.token),))+ except grpc.RpcError as error:+ if error.code() != grpc.StatusCode.NOT_FOUND:+ raise ValueError('既有 CloudDrive 直链认证未取得') from None+ if index == 0:+ paths.extend(p for p in _fallback_samples() if p != sample_path)+ continue+ url = urlsplit(reply.directUrl)+ if url.hostname != 'dav.mypikpak.com' or url.scheme not in ('http', 'https') or url.username or url.query or unquote(url.path) != relative:+ raise ValueError('既有直链来源或路径不符')+ headers = dict(reply.additionalHeaders)+ if not any(k.casefold() == 'authorization' for k in headers):+ raise ValueError('既有 WebDAV 认证未取得')+ if reply.userAgent:+ headers['User-Agent'] = reply.userAgent+ return headers+ raise ValueError('既有 CloudDrive 认证样本未取得')+++@contextmanager+def pikpak_renames(sample_path: str, roots):+ """仅显式启用的目录批次复用既有 CloudDrive 认证。"""+ if tuple(roots.get('pikpak', ())) != ('A:\\',):+ raise ValueError('PikPak 来源根必须唯一声明为 A 盘')+ credential = CredentialStore(SECRETS_DIR).load(CLOUDDRIVE_CREDENTIAL)+ if not credential or not credential.values.get('token'):+ raise ValueError('既有 CloudDrive 令牌未取得')+ address = DownloadSettings(STATE_DIR).load().clouddrive_address or discover()+ with CloudDriveClient(address, credential.values['token'], timeout=15) as cloud:+ info = cloud.find('/Pikpak')+ if info is None or info.CloudAPI.name.casefold() != 'webdav':+ raise ValueError('既有 PikPak WebDAV 来源未取得')+ headers = _download_headers(cloud, sample_path)++ def rename_remote(source, target):+ from . import downloads_clouddrive_pb2 as pb+ if PureWindowsPath(source).parent != PureWindowsPath(target).parent:+ raise ValueError('官方改名只支持同父目录')+ stub = cloud.channel.unary_unary(SERVICE + 'RenameFile',+ request_serializer=RenameRequest.SerializeToString, response_deserializer=pb.FileOperationResult.FromString)+ try:+ reply = stub(RenameRequest(path='/Pikpak/' + '/'.join(PureWindowsPath(source).parts[1:]),+ newName=PureWindowsPath(target).name), timeout=15,+ metadata=(('authorization', 'Bearer ' + cloud.token),))+ return reply.success+ except grpc.RpcError:+ return False++ def refresh(path):+ request = ListRequest(path='/Pikpak' + '/' + '/'.join(PureWindowsPath(path).parts[1:]), forceRefresh=True)+ stream = cloud.channel.unary_stream(SERVICE + 'GetSubFiles',+ request_serializer=ListRequest.SerializeToString, response_deserializer=ListReply.FromString)+ replies = stream(request, timeout=15, metadata=(('authorization', 'Bearer ' + cloud.token),))+ try:+ count = 0+ for response in replies:+ count += len(response.subFiles)+ if count > MAX_FILES:+ raise ValueError('CloudDrive 刷新超过预算')+ finally:+ replies.cancel()++ with httpx.Client(headers=headers, timeout=20, follow_redirects=False) as http:+ dav, original = PikPakDav(http, 'A:\\', refresh, rename_remote), organize._rename++ def rename(source, target):+ if PureWindowsPath(source).drive.casefold() == 'a:':+ dav.move(source, target)+ else:+ original(source, target)++ organize._rename = rename+ try:+ yield dav+ finally:+ organize._rename = originaldiff --git a/tests/test_downloads_clouddrive_organize.py b/tests/test_downloads_clouddrive_organize.pynew file mode 100644index 000000000..5d2a6f6c0--- /dev/null+++ b/tests/test_downloads_clouddrive_organize.py@@ -0,0 +1,189 @@+"""CloudDrive HTTPS WebDAV 的冲突、成员核验、应答歧义与路径边界。"""+import unittest+from types import SimpleNamespace+from unittest.mock import Mock, patch+from urllib.parse import quote, unquote, urlsplit++import httpx+import grpc++from peach.organize_clouddrive import DAV_ORIGIN, PikPakDav, UnconfirmedMove+from peach import organize_clouddrive+++class WebDavMoves(unittest.TestCase):+ def setUp(self):+ self.entries = {'A:\\old': True, 'A:\\old\\film.mp4': 20, 'A:\\new': True}+ self.requests = []+ self.move_status = 201+ self.move_timeout = False+ self.omit_after_move = False+ self.refresh = Mock()+ self.http = httpx.Client(transport=httpx.MockTransport(self.handle), follow_redirects=False)+ self.addCleanup(self.http.close)+ self.dav = PikPakDav(self.http, 'A:\\', self.refresh)++ def handle(self, request):+ path = 'A:' + unquote(urlsplit(str(request.url)).path).replace('/', '\\').rstrip('\\')+ if path == 'A:':+ path += '\\'+ self.requests.append((request.method, path, request.headers))+ if request.method == 'MOVE':+ if self.move_timeout:+ raise httpx.ReadTimeout('模拟应答未取得', request=request)+ target = 'A:' + unquote(urlsplit(request.headers['Destination']).path).replace('/', '\\')+ if self.move_status == 201:+ items = list(self.entries.items())+ for name, value in items:+ if name == path or name.startswith(path + '\\'):+ self.entries[target + name[len(path):]] = value+ del self.entries[name]+ if self.omit_after_move:+ self.entries.pop(target + '\\film.mp4', None)+ return httpx.Response(self.move_status)+ if request.method == 'MKCOL':+ self.entries[path] = True+ return httpx.Response(201)+ if request.method != 'PROPFIND':+ return httpx.Response(405)+ if path != 'A:\\' and self.entries.get(path) is not True:+ return httpx.Response(404)+ names = [(path, True)] + [(name, value) for name, value in self.entries.items()+ if name != path and name.rsplit('\\', 1)[0].rstrip('\\') == path.rstrip('\\')]+ responses = []+ for name, value in names:+ href = quote('/' + name[3:].replace('\\', '/'), safe='/')+ kind = '<d:collection/>' if value is True else ''+ size = 0 if value is True else value+ responses.append(f'<d:response><d:href>{href}</d:href><d:propstat><d:prop>'+ f'<d:resourcetype>{kind}</d:resourcetype><d:getcontentlength>{size}</d:getcontentlength>'+ '</d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>')+ return httpx.Response(207, content=('<d:multistatus xmlns:d="DAV:">' + ''.join(responses) + '</d:multistatus>').encode())++ def test_file_move_preserves_size_and_refreshes_both_parents(self):+ self.dav.move('A:\\old\\film.mp4', 'A:\\new\\film.mp4')+ self.assertEqual(self.entries['A:\\new\\film.mp4'], 20)+ self.assertNotIn('A:\\old\\film.mp4', self.entries)+ self.assertEqual({c.args[0] for c in self.refresh.call_args_list}, {'A:\\old', 'A:\\new'})+ request = next(r for r in self.requests if r[0] == 'MOVE')+ self.assertEqual(request[2]['Overwrite'], 'F')+ self.assertTrue(request[2]['Destination'].startswith(DAV_ORIGIN))++ def test_target_collision_never_submits_move(self):+ self.entries['A:\\new\\film.mp4'] = 40+ with self.assertRaises(FileExistsError):+ self.dav.move('A:\\old\\film.mp4', 'A:\\new\\film.mp4')+ self.assertFalse(any(r[0] == 'MOVE' for r in self.requests))+ self.assertEqual(self.entries['A:\\new\\film.mp4'], 40)++ def test_failed_request_with_unchanged_source_is_recoverable(self):+ self.move_status = 403+ with self.assertRaises(FileNotFoundError):+ self.dav.move('A:\\old\\film.mp4', 'A:\\new\\film.mp4')+ self.assertEqual(self.entries['A:\\old\\film.mp4'], 20)++ def test_collection_move_checks_all_members(self):+ self.dav.move('A:\\old', 'A:\\new\\collection')+ self.assertEqual(self.entries['A:\\new\\collection\\film.mp4'], 20)+ self.assertNotIn('A:\\old', self.entries)++ def test_move_timeout_preserves_intent_when_source_is_still_present(self):+ self.move_timeout = True+ with self.assertRaises(UnconfirmedMove):+ self.dav.move('A:\\old\\film.mp4', 'A:\\new\\film.mp4')+ self.assertEqual(sum(r[0] == 'MOVE' for r in self.requests), 1)+ self.assertEqual(self.entries['A:\\old\\film.mp4'], 20)++ def test_incomplete_collection_stops_without_repeating_move(self):+ self.omit_after_move = True+ with self.assertRaises(UnconfirmedMove):+ self.dav.move('A:\\old', 'A:\\new\\collection')+ self.assertEqual(sum(r[0] == 'MOVE' for r in self.requests), 1)++ def test_success_acknowledgement_requires_namespace_change(self):+ for status in (200, 202, 204, 207):+ with self.subTest(status=status):+ self.requests.clear()+ self.move_status = status+ with self.assertRaises(UnconfirmedMove):+ self.dav.move('A:\\old\\film.mp4', 'A:\\new\\film.mp4')+ self.assertEqual(sum(r[0] == 'MOVE' for r in self.requests), 1)+ self.assertEqual(self.entries['A:\\old\\film.mp4'], 20)++ def test_empty_collection_requires_destination_entry(self):+ del self.entries['A:\\old\\film.mp4']+ self.dav.move('A:\\old', 'A:\\new\\empty')+ self.assertIs(self.entries['A:\\new\\empty'], True)++ def test_nested_parent_is_created_in_order(self):+ self.dav.move('A:\\old\\film.mp4', 'A:\\deep\\nested\\film.mp4')+ self.assertEqual([r[1] for r in self.requests if r[0] == 'MKCOL'], ['A:\\deep', 'A:\\deep\\nested'])++ def test_cross_drive_is_rejected_before_network(self):+ with self.assertRaises(ValueError):+ self.dav.move('A:\\old\\film.mp4', 'R:\\film.mp4')+ self.assertFalse(self.requests)++ def test_unicode_path_is_utf8_percent_encoded(self):+ self.assertEqual(self.dav.url('A:\\创作者\\a b.mp4'), DAV_ORIGIN + '/%E5%88%9B%E4%BD%9C%E8%80%85/a%20b.mp4')++ def test_creator_handle_uses_provider_literal_at_path(self):+ self.entries.update({'A:\\old\\creator@handle': True, 'A:\\old\\creator@handle\\film.mp4': 20})++ def provider(request):+ if b'%40' in request.url.raw_path or '%40' in request.headers.get('Destination', ''):+ return httpx.Response(404)+ return self.handle(request)++ with httpx.Client(transport=httpx.MockTransport(provider)) as http:+ dav = PikPakDav(http, 'A:\\', self.refresh)+ dav.move('A:\\old\\creator@handle', 'A:\\new\\creator@handle')+ self.assertEqual(self.entries['A:\\new\\creator@handle\\film.mp4'], 20)+ self.assertNotIn('A:\\old\\creator@handle', self.entries)++ def test_same_parent_rename_uses_verified_official_operation(self):+ def rename(source, target):+ self.entries[target] = self.entries.pop(source)+ return True+ self.dav.rename = Mock(side_effect=rename)+ self.dav.move('A:\\old\\film.mp4', 'A:\\old\\title.mp4')+ self.dav.rename.assert_called_once_with('A:\\old\\film.mp4', 'A:\\old\\title.mp4')+ self.assertEqual(self.entries['A:\\old\\title.mp4'], 20)+ self.assertFalse(any(r[0] == 'MOVE' for r in self.requests))++ def test_official_rename_ack_requires_actual_path_change(self):+ self.dav.rename = Mock(return_value=True)+ with self.assertRaises(UnconfirmedMove):+ self.dav.move('A:\\old\\film.mp4', 'A:\\old\\title.mp4')+ self.assertEqual(self.entries['A:\\old\\film.mp4'], 20)+ self.dav.rename.assert_called_once()+++class AuthenticationSamples(unittest.TestCase):+ class Missing(grpc.RpcError):+ def code(self):+ return grpc.StatusCode.NOT_FOUND++ def test_moved_sample_uses_existing_catalog_sample(self):+ cloud = Mock(token='test-token')+ reply = SimpleNamespace(directUrl=DAV_ORIGIN+'/available/image.jpg', userAgent='', additionalHeaders={'Authorization':'test-credential'})+ stub = cloud.channel.unary_unary.return_value+ stub.side_effect = [self.Missing(), reply]+ with patch.object(organize_clouddrive, '_fallback_samples', return_value=['A:\\available\\image.jpg']):+ headers = organize_clouddrive._download_headers(cloud, 'A:\\moved\\image.jpg')+ self.assertEqual(headers, {'Authorization':'test-credential'})+ self.assertEqual([c.args[0].path for c in stub.call_args_list], ['/Pikpak/moved/image.jpg','/Pikpak/available/image.jpg'])++ def test_missing_samples_stop_after_three_calls(self):+ cloud = Mock(token='test-token')+ stub = cloud.channel.unary_unary.return_value+ stub.side_effect = self.Missing()+ with patch.object(organize_clouddrive, '_fallback_samples', return_value=['A:\\first.jpg','A:\\second.jpg']), self.assertRaises(ValueError):+ organize_clouddrive._download_headers(cloud, 'A:\\moved.jpg')+ self.assertEqual(stub.call_count, 3)++ def test_foreign_download_source_is_rejected(self):+ cloud = Mock(token='test-token')+ cloud.channel.unary_unary.return_value.return_value = SimpleNamespace(directUrl='https://example.test/image.jpg', additionalHeaders={}, userAgent='')+ with self.assertRaises(ValueError):+ organize_clouddrive._download_headers(cloud, 'A:\\image.jpg')diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex ea5fc3254..367238b39 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -165,6 +165,51 @@ class LibraryDirectoryTests(unittest.TestCase):with redirect_stdout(io.StringIO()):self.script.self_check()+ def test_pikpak_collapse_staging_preserves_complete_recovery(self):+ script = self.script+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ source, target = r'A:\outer\outer', r'A:\outer'+ def translate(path):+ return root.joinpath(*PureWindowsPath(path).parts[1:]) if PureWindowsPath(path).drive.casefold() == 'a:' else Path(path)+ translate(source).mkdir(parents=True)+ media = translate(source) / 'film.mp4'+ media.write_bytes(b'media')+ with mock.patch.object(script, 'translate_ledger_path', side_effect=translate):+ for steps in (0, 1, 2):+ pairs, state = script.collapse_moves(source, target)+ self.assertTrue(Path(state['temporary']).name.startswith('peach-organize-'))+ entry = dict(moves=pairs, collapse=state)+ for old, new in pairs[:steps]:+ script.organize._rename(old, new)+ self.assertEqual(script.restore_entry(entry), [])+ self.assertEqual(media.read_bytes(), b'media')+ self.assertFalse(Path(state['temporary']).exists())++ def test_provider_move_separates_same_parent_rename_and_cross_parent_move(self):+ script = self.script+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ source, target = r'A:\old\account', r'A:\new\collection'+ def translate(path):+ return root.joinpath(*PureWindowsPath(path).parts[1:])+ translate(source).mkdir(parents=True)+ translate(target).parent.mkdir()+ media = translate(source) / 'film.mp4'+ media.write_bytes(b'media')+ with mock.patch.object(script, 'translate_ledger_path', side_effect=translate):+ pairs = script.provider_moves([(source,target)], 'A:\\')+ self.assertEqual(pairs, [(source,r'A:\old\collection'),(r'A:\old\collection',target)])+ for steps in (0, 1, 2):+ for old, new in pairs[:steps]:+ translate(old).rename(translate(new))+ with mock.patch.object(script.organize, '_rename', side_effect=lambda old,new:translate(old).rename(translate(new))):+ self.assertEqual(script.restore(pairs), [])+ self.assertEqual(media.read_bytes(), b'media')+ translate(r'A:\old\collection').mkdir()+ with self.assertRaises(FileExistsError):+ script.provider_moves([(source,target)], 'A:\\')+def test_fc_short_parts_require_matching_parent_and_publisher(self):row = dict(code=None, studio=None, name='@fc1780822_1.mp4',path=r'B:\MVP\FC2 collection\FC-1780822耐久黑田4K\@fc1780822_1.mp4')