Peach: Local-first video metadata scraper and media manager.
fix(organize): 使用官方同盘移动并确认完整目录状态
longmeidaofe42428bf4bc
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 0cdf67608..c88f85fd7 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -213,7 +213,7 @@ 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`,不新增依赖。官方 `GetSubFiles(forceRefresh=True)` 从来源根逐层读取完整目录,校验每层成员来源、父目录、重名与体积;目录传输仍用固定 HTTPS,`MKCOL` 创建所需父目录,`MOVE` 使用 `Overwrite: F`。单次 HTTP 应答上限 2 MiB,遍历上限 10,000 条。移动后核对完整路径与体积,再刷新 CloudDrive 缓存并交回现有账本事务。应答不确定时保留意图回执并停止,不重复移动;成功状态码也必须取得完整成员变化证据。A 盘折叠目录使用不以点号开头的暂存名,保留同一套恢复回执;R 盘不进入该传输路径。+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`,不新增依赖。官方 `GetSubFiles(forceRefresh=True)` 从来源根逐层读取完整目录,校验每层成员来源、父目录、重名与体积。同父改名使用官方 `RenameFile`;同来源、保持原名的跨目录移动使用官方 `MoveFile`,冲突策略为 `Skip`,明确关闭跨云移动与递归合并。HTTPS `MKCOL` 创建所需父目录,其余 HTTPS `MOVE` 使用 `Overwrite: F`。单次 HTTP 应答上限 2 MiB,遍历上限 10,000 条。提交移动后只刷新涉及目录的缓存,沿完整祖先链取得路径与体积变化证据,再交回现有账本事务;最多四次只读确认,不重复提交移动。状态不确定时保留意图回执并停止,成功应答也必须取得完整成员变化证据。A 盘折叠目录使用不以点号开头的暂存名,保留同一套恢复回执;R 盘不进入该传输路径。A 盘同父目录改名复用 CloudDrive 官方 `RenameFile`;跨父且改名的操作拆为同父改名和保留名称的 HTTPS 移动,中间路径进入恢复回执并禁止覆盖。每步核对完整成员与体积;成功应答不替代路径核验。路径中的 `@` 保留为 URI 路径字符,其他字符使用 UTF-8 百分号编码。认证样本已移动时,最多另查两条馆藏内图片样本,仅提取既有认证,不读取媒体内容。diff --git a/src/peach/organize_clouddrive.py b/src/peach/organize_clouddrive.pyindex 022b88a71..6653289a3 100644--- a/src/peach/organize_clouddrive.py+++ b/src/peach/organize_clouddrive.py@@ -3,12 +3,14 @@ from __future__ import annotationsfrom contextlib import closing, contextmanagerfrom pathlib import PureWindowsPath+import timefrom urllib.parse import quote, unquote, urlsplitfrom xml.etree import ElementTree as ETimport httpximport grpcfrom google.protobuf import descriptor_pb2, descriptor_pool, message_factory+from google.protobuf.empty_pb2 import Emptyfrom . import organizefrom .downloads_clouddrive import CloudDriveClient, SERVICE, discover@@ -53,22 +55,38 @@ def _messages():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)+ move = proto.message_type.add(name='MoveRequest')+ move.field.add(name='theFilePaths', number=1, type=9, label=3)+ move.field.add(name='destPath', number=2, type=9, label=1)+ policy = move.enum_type.add(name='ConflictPolicy')+ for name, number in (('Overwrite', 0), ('Rename', 1), ('Skip', 2)):+ policy.value.add(name=name, number=number)+ move.field.add(name='conflictPolicy', number=3, type=14, label=1,+ type_name='.peach_organize_cloud.MoveRequest.ConflictPolicy')+ for name, number in (('moveAcrossClouds', 4), ('handleConflictRecursively', 5)):+ index = len(move.oneof_decl)+ move.oneof_decl.add(name='_' + name)+ move.field.add(name=name, number=number, type=8, label=1, proto3_optional=True, oneof_index=index)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'))+ for name in ('DownloadRequest', 'DownloadReply', 'ListRequest', 'ListReply', 'RenameRequest', 'MoveRequest'))-DownloadRequest, DownloadReply, ListRequest, ListReply, RenameRequest = _messages()+DownloadRequest, DownloadReply, ListRequest, ListReply, RenameRequest, MoveRequest = _messages()class PikPakDav:- def __init__(self, http: httpx.Client, root: str, refresh, rename=None, listing=None):+ def __init__(self, http: httpx.Client, root: str, refresh, rename=None, listing=None, move_remote=None, confirm_attempts=1):self.http, self.root, self.refresh = http, PureWindowsPath(root), refreshself.rename = renameself.listing = listing+ self.move_remote = move_remote+ if not 1 <= confirm_attempts <= 4:+ raise ValueError('移动确认次数越出预算')+ self.confirm_attempts = confirm_attemptsif self.root != PureWindowsPath('A:\\'):raise ValueError('HTTPS WebDAV 整理只支持已声明的 A 盘根目录')@@ -160,6 +178,8 @@ class PikPakDav: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+ if self.move_remote is not None and PureWindowsPath(source).name == PureWindowsPath(target).name:+ return self.move_remote(source, target)return self.request('MOVE', source, headers={'Destination': self.url(target), 'Overwrite': 'F'})[0]def move(self, source, target):@@ -178,6 +198,22 @@ class PikPakDav:response_status = self.submit_move(source, target)except OSError:response_status = None+ for attempt in range(self.confirm_attempts):+ try:+ if self.move_remote is not None:+ for parent in {old_parent, new_parent}:+ self.refresh(parent)+ self.confirm_move(source, target, found[0], before, response_status)+ return+ except FileNotFoundError:+ raise+ except (UnconfirmedMove, OSError, ValueError):+ if attempt + 1 == self.confirm_attempts:+ raise UnconfirmedMove('移动状态未确认,保留意图回执并停止;不重复操作、不写账本') from None+ time.sleep(2)++ def confirm_move(self, source, target, source_entry, before, response_status):+ old_parent, new_parent = str(PureWindowsPath(source).parent), str(PureWindowsPath(target).parent)try:after_parent = self.list(new_parent)old_listing = self.list(old_parent)@@ -187,14 +223,14 @@ class PikPakDav: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+ after = self.tree(target) if source_entry['directory'] else arrivedexpected = {(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}:+ if still_present or len(arrived) != 1 or arrived[0]['directory'] != source_entry['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']:+ if source_entry['directory']:self.refresh(target)except FileNotFoundError:raise@@ -243,6 +279,43 @@ def _fallback_samples():"AND path LIKE 'A:%' ORDER BY id LIMIT 2")]+def _move_remote(cloud, source, target):+ """官方同来源移动保持原名,显式跳过冲突并关闭跨云及递归合并。"""+ from . import downloads_clouddrive_pb2 as pb+ old, new = PureWindowsPath(source), PureWindowsPath(target)+ if (old.drive.casefold() != 'a:' or new.drive.casefold() != 'a:' or not old.is_absolute()+ or not new.is_absolute() or '..' in old.parts or '..' in new.parts+ or old.name != new.name or old.parent == new.parent):+ raise ValueError('官方移动来源、父目录或文件名不符')+ request = MoveRequest(theFilePaths=['/Pikpak/' + '/'.join(old.parts[1:])],+ destPath=('/Pikpak/' + '/'.join(new.parent.parts[1:])).rstrip('/'),+ conflictPolicy=2, moveAcrossClouds=False, handleConflictRecursively=False)+ stub = cloud.channel.unary_unary(SERVICE + 'MoveFile', request_serializer=MoveRequest.SerializeToString,+ response_deserializer=pb.FileOperationResult.FromString)+ try:+ reply = stub(request, timeout=15, metadata=(('authorization', 'Bearer ' + cloud.token),))+ return 200 if reply.success else 403+ except grpc.RpcError:+ return None+++def _refresh_listing(cloud, path):+ """限定 A 盘目录缓存过期后按完整祖先链读取实际成员。"""+ from . import downloads_clouddrive_pb2 as pb+ item = PureWindowsPath(path)+ if item.drive.casefold() != 'a:' or not item.is_absolute() or '..' in item.parts:+ raise ValueError('目录缓存范围越出 A 盘')+ stub = cloud.channel.unary_unary(SERVICE + 'ForceExpireDirCache',+ request_serializer=pb.FileRequest.SerializeToString, response_deserializer=Empty.FromString)+ try:+ stub(pb.FileRequest(path=('/Pikpak/' + '/'.join(item.parts[1:])).rstrip('/')),+ timeout=15, metadata=(('authorization', 'Bearer ' + cloud.token),))+ except grpc.RpcError as error:+ if error.code() != grpc.StatusCode.NOT_FOUND:+ raise OSError('目录缓存刷新未取得:' + error.code().name) from None+ return _cloud_listing(cloud, path)++def _download_headers(cloud, sample_path):paths = [sample_path]stub = cloud.channel.unary_unary(SERVICE + 'GetDownloadUrlPath',@@ -305,10 +378,12 @@ def pikpak_renames(sample_path: str, roots):return Falsedef refresh(path):- return _cloud_listing(cloud, path)+ return _refresh_listing(cloud, path)with httpx.Client(headers=headers, timeout=20, follow_redirects=False) as http:- dav, original = PikPakDav(http, 'A:\\', refresh, rename_remote, listing=refresh), organize._rename+ dav, original = PikPakDav(http, 'A:\\', refresh, rename_remote,+ listing=lambda path: _cloud_listing(cloud, path),+ move_remote=lambda source, target: _move_remote(cloud, source, target), confirm_attempts=4), organize._renamedef rename(source, target):if PureWindowsPath(source).drive.casefold() == 'a:':diff --git a/tests/test_downloads_clouddrive_organize.py b/tests/test_downloads_clouddrive_organize.pyindex 58c69bacf..10de54255 100644--- a/tests/test_downloads_clouddrive_organize.py+++ b/tests/test_downloads_clouddrive_organize.py@@ -158,6 +158,70 @@ class WebDavMoves(unittest.TestCase):self.assertEqual(self.entries['A:\\old\\film.mp4'], 20)self.dav.rename.assert_called_once()+ def test_official_move_preserves_name_and_checks_actual_size(self):+ def move(source,target):+ self.entries[target]=self.entries.pop(source)+ return 200+ self.dav.move_remote=Mock(side_effect=move)+ self.dav.move('A:\\old\\film.mp4','A:\\new\\film.mp4')+ self.assertEqual(self.entries['A:\\new\\film.mp4'],20)+ self.dav.move_remote.assert_called_once()+ self.assertFalse(any(row[0]=='MOVE' for row in self.requests))++ def test_delayed_listing_only_rechecks_the_single_submitted_move(self):+ self.dav.move_remote=Mock(return_value=200)+ self.dav.confirm_attempts=4+ reads=0+ def refresh(path):+ nonlocal reads+ reads+=1+ if reads==3:+ self.entries['A:\\new\\film.mp4']=self.entries.pop('A:\\old\\film.mp4')+ self.dav.refresh=refresh+ with patch.object(organize_clouddrive.time,'sleep'):+ self.dav.move('A:\\old\\film.mp4','A:\\new\\film.mp4')+ self.dav.move_remote.assert_called_once()+ self.assertEqual(self.entries['A:\\new\\film.mp4'],20)++ def test_cache_failure_after_submission_preserves_intent(self):+ self.dav.move_remote=Mock(return_value=200)+ self.dav.refresh=Mock(side_effect=OSError('未取得'))+ with self.assertRaises(UnconfirmedMove):+ self.dav.move('A:\\old\\film.mp4','A:\\new\\film.mp4')+ self.dav.move_remote.assert_called_once()+++class OfficialMoveProtocol(unittest.TestCase):+ def test_conflict_skip_and_false_optional_flags_are_encoded(self):+ cloud=Mock(token='test-token')+ cloud.channel.unary_unary.return_value.return_value=SimpleNamespace(success=True)+ self.assertEqual(organize_clouddrive._move_remote(cloud,'A:\\old\\film.mp4','A:\\new\\film.mp4'),200)+ request=cloud.channel.unary_unary.return_value.call_args.args[0]+ self.assertEqual(list(request.theFilePaths),['/Pikpak/old/film.mp4'])+ self.assertEqual(request.destPath,'/Pikpak/new')+ self.assertEqual(request.conflictPolicy,2)+ for flag in ('moveAcrossClouds','handleConflictRecursively'):+ self.assertTrue(request.HasField(flag))+ self.assertFalse(getattr(request,flag))++ def test_path_boundaries_stop_before_rpc(self):+ cloud=Mock(token='test-token')+ for target in ('R:\\film.mp4','A:\\new\\other.mp4','A:\\old\\film.mp4','A:\\new\\..\\film.mp4'):+ with self.subTest(target=target),self.assertRaises(ValueError):+ organize_clouddrive._move_remote(cloud,'A:\\old\\film.mp4',target)+ cloud.channel.unary_unary.assert_not_called()++ def test_rpc_timeout_has_no_automatic_resubmission(self):+ cloud=Mock(token='test-token')+ cloud.channel.unary_unary.return_value.side_effect=grpc.RpcError()+ self.assertIsNone(organize_clouddrive._move_remote(cloud,'A:\\old\\film.mp4','A:\\new\\film.mp4'))+ cloud.channel.unary_unary.return_value.assert_called_once()++ def test_cache_scope_rejects_another_drive(self):+ cloud=Mock(token='test-token')+ with self.assertRaises(ValueError):organize_clouddrive._refresh_listing(cloud,'B:\\MVP')+ cloud.channel.unary_unary.assert_not_called()+class OfficialDirectoryEvidence(unittest.TestCase):class Stream: