From ff5d22a6e7944d68d3ea7c23e637b0361e81bf9e Mon Sep 17 00:00:00 2001 From: chialecode <315431287+chialecode@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:01:30 +0800 Subject: [PATCH] feat(library,ui): add multi-select batch delete/export and author storage usage view Implements Issue #112 (DEC-083): - Extend Store.Statistics() with per-author itemCount and totalBytes preserving via collab/forward attribution (zero schema bump, fast at 5,000 items). - Show per-subscription and unsubscribed author storage usage with an offline sort-by-size toggle in the Library sidebar and narrow-window author filter. - Add Library multi-select mode with batch action bar, itemKey-synced tile selection, hidden card menus, and Esc/navigation auto-reset. - Add PlanDeleteBatch/DeleteBatch evaluating item_refs across the whole selected batch while preserving non-TRACE files, shared videos, and rejecting active recordings. - Add FeedFilter.ItemKeys with safe 400-key chunking and selected-items batch export scope. - Update docs (DEC-083, FR-LIB-001/003/005, ui.md), tests, and uishots scenes. Signed-off-by: chialecode <315431287+chialecode@users.noreply.github.com> --- docs/decisions.md | 1 + docs/requirements.md | 6 +- docs/ui.md | 9 +- internal/library/batch_storage_test.go | 436 +++++++++++++++++++++ internal/library/delete.go | 178 ++++++--- internal/library/feed.go | 34 ++ internal/library/schema.go | 6 +- internal/library/statistics.go | 6 +- internal/service/interfaces.go | 2 + internal/service/library_service.go | 22 ++ internal/service/transfer_jobs.go | 54 ++- internal/service/transfer_jobs_test.go | 117 ++++++ internal/ui/app.go | 61 ++- internal/ui/library_batch_storage_test.go | 454 ++++++++++++++++++++++ internal/ui/library_view.go | 393 +++++++++++++++---- internal/ui/navigation.go | 5 + internal/ui/overlays.go | 54 ++- internal/ui/shell.go | 194 ++++++++- internal/ui/transfer_view.go | 53 ++- internal/ui/views.go | 13 +- tools/uishots/scenes.go | 97 +++++ 21 files changed, 2020 insertions(+), 175 deletions(-) create mode 100644 internal/library/batch_storage_test.go create mode 100644 internal/ui/library_batch_storage_test.go diff --git a/docs/decisions.md b/docs/decisions.md index 85608f0..b3820f7 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -89,3 +89,4 @@ | DEC-075 | **失效公开图片尝试公共 CDN 缓存/网页归档回退,且绝不用失效或占位响应覆盖已有有效图片**:① 四站点作品图片与封面、直播封面、最近解析缩略图 `thumbs/` 与本地头像 `avatars/` 统一先写临时文件并校验二进制魔数与非失效占位图后再原子落盘;目标位置已存在归属本条目的有效非占位图片时,重缓存、刷新或原帖被删均保留本地有效文件与清单记录,绝不删除或覆盖;② 直连源站(含微博边缘轮换与下载期最多 1 次详情重取)返回 HTTP `403`/`404`/`410` 或已知失效占位图时,仅对无签名公开静态图片 URL(`*.sinaimg.cn` 排除 `*.us.sinaimg.cn`、`pbs.twimg.com` 仅含 `format`/`name`、`*.hdslb.com` 静态图)按顺序无凭证查询 Jetpack Photon(`i0.wp.com`)→ `wsrv.nl`(`n=-1`)→ Internet Archive Wayback(`/web/0id_/`),严禁在 `429`/风控时触发,严禁向第三方发送任何 Cookie、凭证头或带签名/令牌参数的地址 | 用户,2026-11-25(“失效图片尝试第三方CDN缓存的获取方式,以及避免失效图覆盖有效图片”;[#61](https://github.com/chialecode/trace/issues/61)) | 遵循用户系统代理与 `GuardedMediaDialer` 私网拦截,返回字节须通过严格图片魔数与非占位校验;自动化测试仅连 `127.0.0.1` 合成提供方。[数据与缓存设计 §1、§2.4、§2.5](design/data-and-cache.md#cache)、[公共 CDN 回退研究](research/2026-11-25-expired-image-cdn.md) | | DEC-076 | **全部缓存检查已缓存资源更新与任务页内容冲突保护(归档优先、零数据丢失)**:① 全部缓存(手动与 7 天定期 `fullCache`)顺带检查已缓存条目能否同源无损升级或补齐;抖音/微博/X 与 B 站动态直接复用列表页数据做零额外请求对比,B 站投稿采用三道门限(列表级标题/简介/时长比对、`cacheStandardVersion` 与规格上限跳过、7 天 `recheckedAt` 冷却 + `cache-queue` 40~150s 节奏)并将 `source="queue"` 纳入自动请求每小时额度记账,`trace-server` 远程版保持不执行;② 遇到远端已删除/不可用/试看或付费未购/地域受限/失效灰图占位 GIF/画质降级时,严禁覆盖本地有效缓存(即便选择“用新版替换”在执行期遇到失效降级也硬拦截 `ErrRemoteDegradedRefused`);③ 同源升级单调保护已有已校验弹幕快照(`Pxx.danmaku.xml`)、字幕、Hi-Res/杜比独立音轨、有效转发原帖 `Origin` 与完整 `LongText`;④ 遇到 V1/V2 资源不一致(换源改 `cid`、删减重排分 P、替换增删媒体、实质编辑正文,含手动重缓存/补全/升级/重试全入口冲突绊线)一律不静默覆盖,记入 `/cache-conflicts.json`(v1,零 URL/查询串/Cookie,含 `ignoredRevisions` 避免“保留本地”后每 7 天重复提示);⑤ 任务页新增“内容冲突(N)”(左栏全局任务角标仍只统计排队与进行中下载任务),批量默认采用无损的 **保留两版(推荐)**(先在 `.trace-stage-*` 完整下载校验 V2,通过后将 V1 归档为独立条目 `__v1-` 标 `archivedOf`、独立删除且不重复计入作品数,混合编辑时复用本地已校验未改动附件;覆盖替换先移入 `.trace-prev-*` 支持 Windows 文件锁失败立即回滚与启动自愈) | 用户,2026-11-25(“全部缓存时也检查已缓存条目是否有更新……不一致的在任务页面专门处理,防失效或 V2 覆盖 V1”“用更安全不易丢失数据的方式”;[#58](https://github.com/chialecode/trace/issues/58)) | 更新 [DEC-061](#dec-061) ①、[DEC-063](#dec-063) ③ 中已完整缓存条目一律跳过的规则。新增独立文件 `cache-conflicts.json`(`version: 1`),`item.json` 保持 v1 不升结构版本。正本:[需求 FR-CACHE-010、NFR-DATA-005](requirements.md#cache-scope)、[路线与验收 AC-89、90](delivery/roadmap.md#acceptance)、[订阅 §4](design/subscriptions.md#full-cache)、[数据与缓存 §1、§2.10](design/data-and-cache.md#cache-conflicts)、[界面规范 §3.6](ui.md#library) | | DEC-078 | **微博图片改为双份保存(官方原图 + 无水印最大版伴侣文件)及看图层切换**:基于 [ACT-023](https://github.com/chialecode/trace/issues/19) V-07 与单帖对照实测证实微博 `/oslarge/` 会将原图降采样至 690px 宽(虽无平台水印,并非无损原分辨率),撤回以 `/oslarge/` 替换主图的做法,改为双份保存:① 静态图与实况静帧的主图 `images/NN.`(`role: "image"`)恒定保存官方最高清原图 `largest`(`/large/` 或 `/mw2000/`),绝不降分辨率;② 「设置 › 缓存与下载」保留 `weiboRemoveWatermark` 键(默认开启,文案「微博同时保存无水印版」),开启时额外拉取无水印最大版 `/oslarge/` 保存为伴侣文件 `images/NN_nowm.`(`role: "image_nowm"`,`notePages[].noWatermark` 指向它;GIF 跳过;与主图 SHA-256 相同时去重不重复落盘;`/oslarge/` 失效、404/403 或占位图时静默跳过,不拖垮主图也不记缺失黄点;对已缓存旧条目再次缓存/补全时复用有效主图并顺带补齐伴侣文件);③ 媒体库与信息流仅展示主图卡片不重复展示伴侣文件,删除/归档/导入合并/刷新完整同步伴侣文件;④ 看图层打开含无水印伴侣图的已缓存图片时默认显示原图,并在顶部悬浮栏提供「原图 / 无水印」一键切换胶囊 | 用户,2026-11-26(基于 ACT-023 与单帖对照实测拍板;[#103](https://github.com/chialecode/trace/issues/103)) | `settings.json`(v1)、`item.json`(v1)与 `library.db`(v2)均保持结构版本不变,新增字段向后兼容。正本:[需求 FR-WB-006](requirements.md#weibo-scope)、[数据与缓存 §2.1~2.3](design/data-and-cache.md#cache)、[微博协议 §4.4、§13.1](research/weibo.md#a-review-choices)、[界面规范 §3.5、§3.7](ui.md#viewer) | +| DEC-083 | **媒体库多选、批量安全删除、批量导出与作者占用空间视图**:① 媒体库上下文侧栏与窄窗作者筛选在纯离线零网络请求下展示每个订阅(按当前站点筛选汇总关联账号)与未订阅作者的条目数与占用空间,并提供「按占用空间」降序排序切换,一键定位高占用来源并点击筛选;② 媒体库顶部栏增加「多选」开关(遵循每区域最多一个强调主按钮原则),进入后在网格上方展示批量操作栏(已选条数与总大小、全选已加载/取消全选、批量导出、红框批量删除、退出多选),点卡片切换选中并按 `itemKey` 同步多图卡片,隐藏单卡「⋯」菜单,无弹窗时按 `Esc` 或离开媒体库自动退出并清空选择;③ 批量删除经 `PlanDeleteBatch` / `DeleteBatch` 按整批集合评估 `item_refs`(仅被所选多条动态共同独占引用的未单独缓存视频纳入删除,仍被未选动态引用或单独缓存的视频保留),继续严守清单白名单逐文件 `os.Remove`、绝不 `os.RemoveAll`、保留非 TRACE 文件与空目录清理、拒绝录制中条目;④ 批量导出通过 `FeedFilter.ItemKeys` 安全分片查询复用既有导出管线,在导出弹窗新增「已选 N 项」范围 | 用户,2026-11-26(媒体库批量管理与存储清理体验改进;[#112](https://github.com/chialecode/trace/issues/112)) | `library.db`(v2)与 `item.json`(v1)均保持结构版本不变;零网络请求。正本:[需求 FR-LIB-001、FR-LIB-003、FR-LIB-005](requirements.md#library-scope)、[界面规范 §1、§3.6](ui.md#library) | diff --git a/docs/requirements.md b/docs/requirements.md index 4d9aca9..56d49a6 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -67,11 +67,11 @@ TRACE 是 Windows 桌面应用,以“订阅”(被追踪的人)为入口 | 编号 | 需求 | 状态 | | --- | --- | --- | | FR-FEED-001 | 主页信息流(DEC-023、DEC-037):把所有已缓存的动态、微博、X 帖子和直接缓存的视频按发布时间从新到旧汇总成一条信息流,不分作者,最上面是最新的;顶部栏提供纯图标离线刷新按钮(后台无锁增量检查本机媒体库并重读信息流与侧栏订阅/未读圆点,保留当前筛选或单订阅视图,不阻塞界面、零网络请求、不弹窗);主页侧栏列出订阅(DEC-053 ②,不加分节标题):正在直播的在最前(头像直播圈),然后是有没点开看过的新缓存内容的(头像右下角蓝色圆点),再是已读的,各组按当前站点筛选下最新已缓存内容的发布时间从新到旧;顺序在进入主页时定下,停留期间点开只消圆点不挪位置;点开单独浏览该订阅的已缓存内容(按订阅记录已看最新时间,不按单条记已读,第一次使用不显示圆点);窄窗时是时间线上方的横向头像条;每条像一条帖子(作者、时间、正文、图片、视频卡片,不放底部文字按钮,点图片看原图、点视频卡片在应用内播放、点头像进用户页);图片按原比例尽量完整显示,视频封面在左、标题与简介在右,不显示也不缓存播放数、评论数等会变的数字(DEC-040);再次打开时回到上次阅读的位置(DEC-053 ①):“全部 / B 站 / 抖音 / 微博 / X”分别记可见区最上面那条与偏移,每次启动后第一次显示某个筛选时停在那里,往上滑载入之后缓存的内容且当前条目不跳动,那条被删时停在不晚于它的最近一条;单个订阅的信息流不记位置;往上翻过的不再当成未读,不提示“N 条更新的内容”(DEC-040);滚动流畅,重绘时不逐帧读媒体库、不在界面线程解码原图;只读本机数据,不发网络请求 | 已实现 | -| FR-LIB-001 | 媒体库(DEC-037、DEC-039、DEC-049 ③):图标栏“媒体库”进入独立的纯离线浏览,网格显示已缓存的图片、视频和直播录像;可以按类型(全部、图片、视频、直播录像、转发;“图片”“视频”只列作者自己的内容,DEC-056)、站点与订阅/UP 主筛选,固定按发布时间从新到旧排序(直播录像按开播时间,不提供缓存时间排序);每格只显示 16:9 缩略图(不显示状态圆点,视频右下角时长)、最多两行标题、一行元信息和右下角“⋯”菜单(详情、在资源管理器中显示、删除),点缩略图或标题原地打开播放层或看图层;“⋯ → 详情”在媒体库自己的本机详情路由(`/library/item`)打开(图标栏保持高亮“媒体库”、保留媒体库侧栏,返回回到原筛选与滚动位置,只读本机数据、不发任何站点请求,仅在详情“⋯”保留“在解析页打开”作为明确联网入口) ;媒体库“刷新”(DEC-055)重新检查保存位置里的文件,在资源管理器里删掉的文件夹从媒体库移除、删掉文件的条目标为缺文件,并弹窗列出这次发现的变化(只读本机文件,不发站点请求)| 已实现 | +| FR-LIB-001 | 媒体库(DEC-037、DEC-039、DEC-049 ③、[DEC-083](decisions.md#dec-083)):图标栏“媒体库”进入独立的纯离线浏览,网格显示已缓存的图片、视频和直播录像;可以按类型(全部、图片、视频、直播录像、转发;“图片”“视频”只列作者自己的内容,DEC-056)、站点与订阅/UP 主筛选,固定按发布时间从新到旧排序(直播录像按开播时间,不提供缓存时间排序);每格只显示 16:9 缩略图(不显示状态圆点,视频右下角时长)、最多两行标题、一行元信息和右下角“⋯”菜单(详情、在资源管理器中显示、删除),点缩略图或标题原地打开播放层或看图层;“⋯ → 详情”在媒体库自己的本机详情路由(`/library/item`)打开(图标栏保持高亮“媒体库”、保留媒体库侧栏,返回回到原筛选与滚动位置,只读本机数据、不发任何站点请求,仅在详情“⋯”保留“在解析页打开”作为明确联网入口);顶部栏提供“多选”模式切换,进入后网格上方出现批量操作栏(显示已选条数与占用大小,提供全选已加载/取消全选、批量导出“已选 N 项”、批量删除与退出多选),点卡片切换勾选并按条目键同步多图卡片,无弹窗时按 Esc 或离开媒体库自动退出并清空选择;媒体库“刷新”(DEC-055)重新检查保存位置里的文件,在资源管理器里删掉的文件夹从媒体库移除、删掉文件的条目标为缺文件,并弹窗列出这次发现的变化(只读本机文件,不发站点请求)| 已实现 | | FR-LIB-002 | 媒体查看:图片用看图层(FR-IMG-001);视频在应用内播放(可拖动进度、有声音);都可以“在文件夹中显示” | 已实现 | | FR-LIB-004 | 播放器弹幕、字幕与章节跳转(DEC-027):应用内播放已缓存的视频时,可以开关弹幕(滚动、顶部、底部三种,随暂停、拖动同步),调整弹幕透明度和密度;有字幕时可以选择字幕语言或关闭;有章节看点(`chapters`)时在播放层展示章节栏并支持点击直跳到对应秒数。设置记住上次的选择 | 已实现 | -| FR-LIB-005 | 媒体库与订阅(DEC-026):媒体库的作者筛选先列订阅(一个订阅包含它关联的全部账号的内容),再列不属于订阅的 UP 主;类型标签增加“直播录像” | 已实现 | -| FR-LIB-003 | 媒体删除:可以删除单个缓存条目(动态或视频),只删除 TRACE 登记过的文件和清单,然后只删除已经变空的文件夹(条目文件夹,以及删掉一个作者的最后一条后变空的类型文件夹与作者文件夹,站点文件夹与保存位置本身保留,2026-11-15 反馈);文件夹里有用户自己放的文件时保留并告知。被其他动态共用的视频要提示并保留,直到最后一个引用被删除 | 已实现 | +| FR-LIB-005 | 媒体库与订阅(DEC-026、[DEC-083](decisions.md#dec-083)):媒体库的作者筛选先列订阅(一个订阅包含它关联的全部账号的内容),再列不属于订阅的 UP 主,并纯离线展示每个订阅与未订阅作者在当前站点筛选下的条目数与占用空间,支持切换“按占用空间”降序排序以快速定位并筛选高占用来源;类型标签增加“直播录像” | 已实现 | +| FR-LIB-003 | 媒体删除([DEC-083](decisions.md#dec-083)):支持单个或批量安全删除缓存条目(动态或视频;拒绝录制中条目),只删除 TRACE 登记过的文件和清单,然后只删除已经变空的文件夹(条目文件夹,以及删掉一个作者的最后一条后变空的类型文件夹与作者文件夹,站点文件夹与保存位置本身保留,2026-11-15 反馈);文件夹里有用户自己放的文件时保留并告知。批量删除按整批集合计算引用关系:仅被所选动态共同独占引用的未单独缓存视频随批删除,仍被未选动态引用或单独缓存的视频提示并保留,直到最后一个引用被删除 | 已实现 | | FR-SET-001 | 设置页(DEC-019、DEC-037、DEC-051 ①、DEC-070):图标栏底部的设置按钮进入单独页面,页面有分类栏:账号(当前账号、登录方式、重新登录、退出登录)、缓存与下载(保存位置、同时下载数)、画质与音质(视频清晰度、编码偏好、音质、多 P、打开视频时检查画质更新)、缓存标签、订阅与直播、存储(安装/数据/缓存位置、媒体库占用空间、打开文件夹、重建索引)、常规、网络、日志(后台状态,例如加载、重建索引、检查与录制的进行情况,以及运行日志;DEC-033)、更新(在“关于”之前:当前版本与通道、通道更新方式、上次与下次检查时间及结果、检查记录与更新记录;DEC-051 ①)、关于(版本、诊断概览与开源许可,版本与更新指向“更新”) | 已实现 | | FR-SET-003 | 网络与代理(DEC-046 ⑤):“设置 › 网络”的代理:跟随系统(默认,Windows 的代理设置与 `HTTP(S)_PROXY`)/ 不用代理 / 自定义(`http://`、`https://`、`socks5://` 地址,不接受账号密码,因为设置文件是明文);站点接口、缓存下载与直播录制都用它,改动立即生效;自定义地址检查通过才保存 | 已实现 | | FR-SET-002 | 新设置项(DEC-027、DEC-051 ③):账号分类显示续期状态(FR-AUTH-003);缓存与下载分类增加“缓存弹幕”“缓存字幕”“包括 AI 字幕”(默认都开);新增“订阅与直播”分类:定时检查更新(开关,默认关;间隔 30 分钟、1 小时、2 小时、6 小时,默认 1 小时)、开播检查间隔(默认 3 分钟,只在有订阅开启开播自动录制时运行;不设同时录制数上限,DEC-051 ③);存储分类显示安装、数据、缓存三个位置与“添加已有的缓存文件夹”(FR-STORE-001、FR-LIB-006);新增“常规”分类:关闭窗口时(最小化到托盘(默认)/ 退出)(FR-RUN-001) | 已实现 | diff --git a/docs/ui.md b/docs/ui.md index b18b689..3f81170 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -16,7 +16,7 @@ - **上下文侧栏**(`#f7f7f7` 底,细分隔线):当前页面里“看什么”的选择,像素材库的文件夹或聊天应用的会话列表。顶部是页面名(18px,600),下面是条目(图标或头像 + 名称,选中项浅强调色底、强调色文字),分组标题用 12px 灰字: - **主页**:“全部动态”、站点筛选,然后直接是订阅列表(DEC-053 ②,不加分节标题、不写状态文字):正在直播的在最前(头像橙色直播圈),然后未读(头像右下角蓝色圆点),再是已读;点一行只看这个订阅的时间线,选中项高亮([§3.1](#home))。 - **订阅**:“全部订阅”(头像网格)、“全部账号”(按站点列出全部订阅的账号,DEC-057 ⑥)和全部订阅的列表(虚拟滚动,直播中的头像带橙色圆环),点一项打开订阅详情。 - - **媒体库**(含媒体库本机详情 `/library/item`):类型(全部 / 视频 / 图片 / 直播录像 / 转发;“图片”“视频”只列作者自己的内容,转发的动态与它带的图片、视频在“转发”里,DEC-056);“来源”(全部来源、各订阅、不属于订阅的 UP 主);底部一行“N 项 · 占用大小”。 + - **媒体库**(含媒体库本机详情 `/library/item`):类型(全部 / 视频 / 图片 / 直播录像 / 转发;“图片”“视频”只列作者自己的内容,转发的动态与它带的图片、视频在“转发”里,DEC-056);“来源”(全部来源、各订阅、不属于订阅的 UP 主;每行纯离线显示当前站点筛选下的条目数与占用空间,标题右侧提供“按占用空间”降序排序切换,[DEC-083](decisions.md#dec-083));底部一行“N 项 · 占用大小”。 - **解析页、视频页与用户页**:“最近解析”,在解析过的对象之间切换,当前对象高亮(DEC-049 ②)。 - **我的**:按站点折叠的四组功能(哔哩哔哩、抖音、微博、X),默认折叠,见[第 3.11 节](#mine)。 - **任务**:“下载任务(N)”、“缓存队列(N)”(N 为未结束的队列数,DEC-057 ②)、“内容冲突(N)”(N 为待处理的缓存内容冲突数,为 0 时不带数字,[DEC-076](decisions.md#dec-076) ⑤)、“直播录制(N)”、“录制异常(N)”(N 为最近 7 天有异常的录制场数,为 0 时不带数字;DEC-050 ②、DEC-051 ③)、“检查计划”(DEC-059 ①)、“导入导出(N)”(N 为进行中与等待确认的导入导出数,为 0 时不带数字,DEC-062),见[第 3.6 节](#library)。 @@ -131,12 +131,13 @@ ### 3.6 媒体库与任务 -- **媒体库**(图标栏“媒体库”,DEC-037、DEC-039、DEC-049 ③):独立的离线浏览页面。顶部栏标题“媒体库”(“重建索引”在设置“存储”);搜索框右侧一个“刷新”按钮(DEC-055):在后台重新检查保存位置里的文件(只看文件在不在、大小对不对,不算哈希、不联网,进行中显示“正在刷新…”),完成后弹窗列出这次发现的变化——“文件夹已删除,已从媒体库移除(N)”(标题与文件夹路径)和“缺少文件(N)”(标题与缺少的文件名,最多列 6 个),没有变化时写“检查了 N 个条目,没有发现被删除的文件。”,底部“知道了”;类型与来源在上下文侧栏(窄窗时退回为页面里的标签“全部 / 图片 / 视频 / 直播录像 / 转发”和“作者筛选”);页面里一行搜索框,**固定按发布时间从新到旧排序**(直播录像按开播时间;不再提供“发布时间 / 缓存时间”切换,已保存的旧缓存时间排序偏好静默忽略)。来源分组里加站点筛选“全部 / B 站 / 抖音 / 微博 / X”(720 宽无横向溢出),与类型、作者筛选叠加(FR-SITE-002)。顶部栏右侧一个“⋯”(菜单“导入…”“导出…”,DEC-062)。 +- **媒体库**(图标栏“媒体库”,DEC-037、DEC-039、DEC-049 ③、[DEC-083](decisions.md#dec-083)):独立的离线浏览页面。顶部栏标题“媒体库”(“重建索引”在设置“存储”),右侧提供次要描边按钮“多选”与一个“⋯”(菜单“导入…”“导出…”,DEC-062);搜索框右侧一个“刷新”按钮(DEC-055):在后台重新检查保存位置里的文件(只看文件在不在、大小对不对,不算哈希、不联网,进行中显示“正在刷新…”),完成后弹窗列出这次发现的变化——“文件夹已删除,已从媒体库移除(N)”(标题与文件夹路径)和“缺少文件(N)”(标题与缺少的文件名,最多列 6 个),没有变化时写“检查了 N 个条目,没有发现被删除的文件。”,底部“知道了”;类型与来源在上下文侧栏(窄窗时退回为页面里的标签“全部 / 图片 / 视频 / 直播录像 / 转发”和“作者筛选”,同样展示各订阅/作者的条目数、占用空间与“按占用空间”降序排序切换);页面里一行搜索框,**固定按发布时间从新到旧排序**(直播录像按开播时间;不再提供“发布时间 / 缓存时间”切换,已保存的旧缓存时间排序偏好静默忽略)。来源分组里加站点筛选“全部 / B 站 / 抖音 / 微博 / X”(720 宽无横向溢出),与类型、作者筛选叠加(FR-SITE-002);来源行纯离线不发远程头像请求。 + - **多选与批量操作**([DEC-083](decisions.md#dec-083)):点顶部栏“多选”进入多选模式后,网格上方出现批量操作栏(720/1000/1280 宽均无横向溢出),显示“已选 N 项 · 占用大小”,以及“全选已加载 / 取消全选”、强调色“批量导出”、红框“批量删除”和“退出多选”(保持页面区域最多一个强调色主按钮)。多选模式下点击卡片缩略图或标题切换该条目的勾选状态(不再打开播放层或看图层),卡片左上角显示复选角标且选中项带强调色描边,多图条目按 `itemKey` 同步全部卡片的勾选状态,同时隐藏单卡右下角“⋯”菜单避免误触;无弹窗打开时按 `Esc`、点“退出多选”或离开媒体库均自动退出并清空选择。 - **导入页**(“⋯ → 导入…”,[远程 §6.3](design/remote.md#import)):在媒体库里打开,标题“导入”,左上角返回箭头回到媒体库,上下文侧栏仍是媒体库侧栏,内容宽度最多约 760px。上方“选择要导入的文件夹”、一行说明(网盘下载的文件夹、另一台 TRACE 的缓存或导出文件夹都可以;先只读扫描,确认后才写入)、路径输入框与强调色“扫描”(扫描中“正在扫描…”,下面一行“正在扫描:已检查 N 个条目”与“取消”)。扫描完成后:一行摘要“扫描到 N 个条目:M 个会导入(约 X),K 个冲突等你决定”;一排可点的分类胶囊“全部 N · 新条目 · 可补充 · 相同 · 冲突 · 未传完 · 无法识别”(各带条数,点了只看这一类);有冲突时一行“全部冲突都:[暂不处理 / 保留本地 / 用导入的 / 合并]”与小字“逐条选的优先”;下面每个条目一张细边框卡片:分类小标签、标题,冲突条目右侧一个同样的下拉框,一行小字(作者、“来自 <节点名>”、要复制的文件数与大小、缺失或不一致的文件数、内容不同的文件名、“本地在另一个作者文件夹”、无法识别的原因),一行来源文件夹路径;最多列 200 条,超出时说明“只显示前 200 条;导入会处理全部条目”。底部固定一条操作栏:开关“导入后删除来源里已导入的文件”(说明只删校验通过并已导入的文件和变空的文件夹,默认关),右侧“放弃”与强调色“开始导入”;开始后跳到任务页“导入导出”。扫描失败、取消时在原处说明。 - - **导出**(“⋯ → 导出…”,[远程 §6.4](design/remote.md#export-local)):对话框,标题“导出媒体库”、一行说明、“范围”下拉(“全部”;媒体库当前有类型、站点、来源或搜索筛选时另有“当前筛选”)、目标文件夹输入框,“取消”与强调色“开始导出”;目标为空、范围内没有内容时在框下说明原因;开始后跳到任务页“导入导出”。 + - **导出**(“⋯ → 导出…”或“多选 › 批量导出”,[远程 §6.4](design/remote.md#export-local)):对话框,标题“导出媒体库”、一行说明、“范围”下拉(“全部”;媒体库当前有类型、站点、来源或搜索筛选时另有“当前筛选”;多选已勾选条目时提供并默认选中“已选 N 项”)、目标文件夹输入框,“取消”与强调色“开始导出”;目标为空、范围内没有内容时在框下说明原因;开始后退出多选并跳到任务页“导入导出”。 - 网格:卡片约 240px 宽,按页面宽度每行 2~6 个;**16:9 圆角缩略图**(圆角 14px),视频右下角显示时长、正中播放图标;**不显示状态圆点**(媒体库里都是已缓存的内容,DEC-039);缩略图下方是**最多两行的标题**(14px,600)、一行元信息(作者名,直播录像附清晰度与编码如“原画 · AVC”)和右侧一个“⋯”按钮。虚拟滚动,滚到底继续加载。 - 点击缩略图或标题直接在原地打开对应文件的看图层或**播放层**(DEC-033、DEC-037、DEC-049 ③),不按网格位置猜测分 P、不跳转到解析路由、不发任何站点网络请求;点击右下角“⋯”展开菜单:**详情**(在媒体库自己的本机详情路由 `/library/item` 打开所属动态、视频、作品或直播录像,保持“媒体库”图标高亮与媒体库侧栏,返回时保留原筛选与滚动位置,只读本机数据,仅在详情“⋯”里留“在解析页打开”作为明确联网入口)、**在资源管理器中显示**、**删除**。播放层和看图层一样是浮在应用上方的深色圆角面板(点面板外关闭;全屏时铺满窗口),**打开即自动播放**(DEC-040),底部悬浮条只保留圆形**播放/暂停**、**进度条**、**音量**、**全屏**(当分 P 有 `chapters` 章节看点时,进度条上方浮现可点击的章节胶囊栏,点击直接跳转到该章节起点 `FromSec`,字幕显示位置自动上移避让),右上角保留圆形**“⋯”更多菜单**与**关闭**。音量按钮展开 0~100% 滑块与静音开关;全屏作用于原生窗口,切分段保持全屏,关闭播放或登录失效时恢复。**弹幕**(开关、透明度滑块 20%~100%、显示区域上方 1/4 / 上半屏 / 全屏、密度低/中/高/不限)、**字幕**(语言选择与关闭)、**分段切换**(多 P 或多段直播录像的“上一段 / 下一段”)、**在文件夹中显示**、**用系统播放器打开**统一收进“⋯”菜单。鼠标静止约 2 秒后悬浮控件自动隐藏,鼠标移动或任意按键时重新出现;菜单打开时保持控件可见。音量、静音、弹幕与字幕偏好记住并沿用,保存失败显示原因。 - - 每个条目的“删除”打开确认弹窗:写明预计清理的已登记缓存文件数与大小;标题行写“类型:标题”(动态没有标题时用正文第一行);删除动态时说明一并删除的引用视频数,以及“这条动态引用的 N 个视频单独缓存过或还被别的动态引用,将保留”;删除后文件夹里还有非 TRACE 文件时提示“已保留 N 个不是 TRACE 创建的文件”。 + - 单条“删除”或“多选 › 批量删除”打开同一个安全删除确认弹窗:单条显示“类型:标题”(动态没有标题时用正文第一行),批量显示“已选择 N 个媒体库条目”;写明预计清理的已登记缓存文件数与总大小、随批一并删除的独占引用视频数、因单独缓存或仍被未选动态引用而保留的共用视频数、以及目录内将原样保留的非 TRACE 用户文件数,并提供“同时删除磁盘上的 TRACE 缓存文件”开关;删除完成后刷新媒体库、自动退出多选,若保留了非 TRACE 文件则在顶部横幅提示“已保留 N 个不是 TRACE 创建的文件”。 - 空状态:“还没有符合筛选的媒体。缓存图片、视频或直播录像后,它们会出现在这里”。 - **任务**(图标栏“任务”,DEC-049 ①、DEC-050 ②、DEC-051 ③、[DEC-076](decisions.md#dec-076) ⑤):通过上下文侧栏(≥ 1000 宽;窄窗 `< 1000` 时退回为页面顶部的可换行分段选择,720 宽无横向溢出)组织七部分内容,点哪一项主面板显示哪一项: 1. **下载任务(N)**(N 为排队与进行中的下载任务数,与图标栏“任务”角标一致):顶部栏右侧提供“检查画质更新”按钮(执行时显示“检查 M / N · 取消”),列表上方固定批量操作栏——存在可重试任务(失败、部分完成或非用户手动暂停的暂停任务,按 `IsRetryableTask` 计数,不含用户手动暂停)时提供强调色“批量重试(N)”按钮(点击调用 `RetryAllTasks` 并按已登录站点隔离批量重新入队、在顶部横幅反馈重试/缺登录跳过/重复跳过结果),存在已结束(已完成 / 已取消)的任务时并排提供“清除已结束(N)”按钮。任务列表使用 `ui.List` 虚拟化滚动(仅渲染可见卡片,配合轻量摘要查询 `ListTasksSummary`、256px 缩略图与按 `libraryRev` 缓存的封面,不随每秒下载进度清空重查,单条操作只刷新任务列表),任务增多时仍流畅滚动。每行是对象缩略图、标题、站点小字、进度条与“已下载 / 总大小”、状态文字和操作(进行中/排队可暂停或取消;已暂停可继续;失败/部分完成可重试或移除;已完成/已取消可移除,不能取消;DEC-033)。失败原因(`LastError`)直接显示在任务行内;移除失败或部分完成的任务前,行内弹出确认提示“确认移除该任务?会删除未完成的临时文件,已缓存完成的文件会保留”。点“展开详情”(FR-CACHE-009)按需读取逐文件进度清单与脱敏后的分段重试记录。 diff --git a/internal/library/batch_storage_test.go b/internal/library/batch_storage_test.go new file mode 100644 index 0000000..19c643e --- /dev/null +++ b/internal/library/batch_storage_test.go @@ -0,0 +1,436 @@ +package library + +import ( + "fmt" + "os" + "path/filepath" + "testing" + "time" + + "github.com/chialecode/trace/internal/storage" +) + +func openBatchTestStore(t *testing.T) (*Store, string) { + t.Helper() + tmp := t.TempDir() + db, _, _, err := storage.OpenSQLite(filepath.Join(tmp, "library.db")) + if err != nil { + t.Fatalf("OpenSQLite: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + cacheDir := filepath.Join(tmp, "cache") + store, err := OpenWithDataDir(db, cacheDir, tmp) + if err != nil { + t.Fatalf("OpenWithDataDir: %v", err) + } + return store, cacheDir +} + +func saveSyntheticMediaItem(t *testing.T, store *Store, dir string, meta ItemMetadata, files map[string][]byte) ItemMetadata { + t.Helper() + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatalf("mkdir %s: %v", dir, err) + } + for rel, data := range files { + p := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + t.Fatalf("mkdir parent %s: %v", p, err) + } + if err := os.WriteFile(p, data, 0o600); err != nil { + t.Fatalf("write %s: %v", p, err) + } + } + saved, err := store.SaveItem(dir, meta) + if err != nil { + t.Fatalf("SaveItem %s: %v", meta.ID, err) + } + return saved +} + +func TestPlanDeleteBatchAndDeleteBatchSharedVideosAndUserFiles(t *testing.T) { + store, cacheDir := openBatchTestStore(t) + + // Video V_excl: referenced ONLY by D1 and D2 (not directly cached), has a user-owned file. + vExclDir := filepath.Join(cacheDir, "bilibili", "1001", "videos", "BV1excl001") + vExcl := saveSyntheticMediaItem(t, store, vExclDir, ItemMetadata{ + Version: 1, + ID: "BV1excl001", + Site: "bilibili", + Kind: "video", + Status: "complete", + Title: "Shared Only By Selected Batch", + PubTs: 1700000100, + DirectCached: false, + Author: ItemAuthor{Mid: 1001, Name: "UP1"}, + Media: []MediaFile{{Role: "video", Path: "P01.mp4"}}, + Parts: []VideoPartRecord{{CID: 1, Page: 1, File: "P01.mp4"}}, + }, map[string][]byte{ + "P01.mp4": []byte("exclusive-video-bytes"), + "keep-note.txt": []byte("user-personal-note"), + }) + + // Video V_keep: referenced by D1, D2 AND unselected D3 (must be preserved). + vKeepDir := filepath.Join(cacheDir, "bilibili", "1001", "videos", "BV1keep002") + vKeep := saveSyntheticMediaItem(t, store, vKeepDir, ItemMetadata{ + Version: 1, + ID: "BV1keep002", + Site: "bilibili", + Kind: "video", + Status: "complete", + Title: "Referenced By Unselected Dynamic", + PubTs: 1700000110, + DirectCached: false, + Author: ItemAuthor{Mid: 1001, Name: "UP1"}, + Media: []MediaFile{{Role: "video", Path: "P01.mp4"}}, + Parts: []VideoPartRecord{{CID: 2, Page: 1, File: "P01.mp4"}}, + }, map[string][]byte{ + "P01.mp4": []byte("shared-preserved-video-bytes"), + }) + + // Video V_direct: directly cached video also referenced by D1 and D2 (must be preserved). + vDirectDir := filepath.Join(cacheDir, "bilibili", "1001", "videos", "BV1dir0003") + vDirect := saveSyntheticMediaItem(t, store, vDirectDir, ItemMetadata{ + Version: 1, + ID: "BV1dir0003", + Site: "bilibili", + Kind: "video", + Status: "complete", + Title: "Directly Cached Video", + PubTs: 1700000120, + DirectCached: true, + Author: ItemAuthor{Mid: 1001, Name: "UP1"}, + Media: []MediaFile{{Role: "video", Path: "P01.mp4"}}, + Parts: []VideoPartRecord{{CID: 3, Page: 1, File: "P01.mp4"}}, + }, map[string][]byte{ + "P01.mp4": []byte("direct-video-bytes"), + }) + + // Dynamics D1, D2 (selected in batch) and D3 (unselected). + d1 := saveSyntheticMediaItem(t, store, filepath.Join(cacheDir, "bilibili", "1001", "dynamics", "dyn_b1"), ItemMetadata{ + Version: 1, ID: "dyn_b1", Site: "bilibili", Kind: "dynamic", Status: "complete", + Title: "Dyn 1", PubTs: 1700000200, Author: ItemAuthor{Mid: 1001, Name: "UP1"}, + Videos: []string{"BV1excl001", "BV1keep002", "BV1dir0003"}, + }, nil) + d2 := saveSyntheticMediaItem(t, store, filepath.Join(cacheDir, "bilibili", "1001", "dynamics", "dyn_b2"), ItemMetadata{ + Version: 1, ID: "dyn_b2", Site: "bilibili", Kind: "dynamic", Status: "complete", + Title: "Dyn 2", PubTs: 1700000210, Author: ItemAuthor{Mid: 1001, Name: "UP1"}, + Videos: []string{"BV1excl001", "BV1keep002", "BV1dir0003"}, + }, nil) + d3 := saveSyntheticMediaItem(t, store, filepath.Join(cacheDir, "bilibili", "1001", "dynamics", "dyn_b3"), ItemMetadata{ + Version: 1, ID: "dyn_b3", Site: "bilibili", Kind: "dynamic", Status: "complete", + Title: "Dyn 3 Unselected", PubTs: 1700000220, Author: ItemAuthor{Mid: 1001, Name: "UP1"}, + Videos: []string{"BV1keep002"}, + }, nil) + + // Recording live item: must be refused in batch plan and batch delete. + rec := saveSyntheticMediaItem(t, store, filepath.Join(cacheDir, "bilibili", "1001", "lives", "777-1700000300"), ItemMetadata{ + Version: 1, ID: "777:1700000300", Site: "bilibili", Kind: "live", Status: "recording", + Title: "Live Recording", PubTs: 1700000300, Author: ItemAuthor{Mid: 1001, Name: "UP1"}, + }, nil) + + // Standalone item under a separate author to verify empty author/kind dir cleanup + // while keeping the site folder and cache root intact. + soloDir := filepath.Join(cacheDir, "bilibili", "2002", "videos", "BV1solo004") + solo := saveSyntheticMediaItem(t, store, soloDir, ItemMetadata{ + Version: 1, ID: "BV1solo004", Site: "bilibili", Kind: "video", Status: "complete", + Title: "Solo Video", PubTs: 1700000250, DirectCached: true, + Author: ItemAuthor{Mid: 2002, Name: "UP2"}, + Media: []MediaFile{{Role: "video", Path: "P01.mp4"}}, + Parts: []VideoPartRecord{{CID: 4, Page: 1, File: "P01.mp4"}}, + }, map[string][]byte{"P01.mp4": []byte("solo-bytes")}) + + // 1. Empty batch rejected. + if _, err := store.PlanDeleteBatch(nil); err == nil { + t.Fatal("expected empty PlanDeleteBatch to fail") + } + + // 2. Batch containing recording item rejected with no side effects. + if _, err := store.PlanDeleteBatch([]string{d1.ItemKey, rec.ItemKey}); err == nil { + t.Fatal("expected PlanDeleteBatch containing recording item to fail") + } + if _, err := store.DeleteBatch([]string{d1.ItemKey, rec.ItemKey}, true); err == nil { + t.Fatal("expected DeleteBatch containing recording item to fail") + } + if _, ok, _ := store.GetItem(d1.ItemKey); !ok { + t.Fatal("failed batch delete must not remove non-recording item d1") + } + + // 3. PlanDeleteBatch([d1, d2, d1]) deduplicates keys, includes vExcl (exclusively + // referenced by the batch), preserves vKeep and vDirect once each, and detects keep-note.txt. + plan, err := store.PlanDeleteBatch([]string{d1.ItemKey, d2.ItemKey, d1.ItemKey}) + if err != nil { + t.Fatalf("PlanDeleteBatch: %v", err) + } + if len(plan.TargetKeys) != 2 { + t.Fatalf("TargetKeys = %v, want 2 deduplicated keys", plan.TargetKeys) + } + wantDeleteSet := map[string]bool{d1.ItemKey: true, d2.ItemKey: true, vExcl.ItemKey: true} + if len(plan.ItemKeys) != len(wantDeleteSet) { + t.Fatalf("ItemKeys = %v, want %v", plan.ItemKeys, wantDeleteSet) + } + for _, k := range plan.ItemKeys { + if !wantDeleteSet[k] { + t.Fatalf("unexpected key %q in ItemKeys %v", k, plan.ItemKeys) + } + } + wantSharedSet := map[string]bool{vKeep.ItemKey: true, vDirect.ItemKey: true} + if len(plan.PreservedSharedVideos) != len(wantSharedSet) { + t.Fatalf("PreservedSharedVideos = %v, want %v", plan.PreservedSharedVideos, wantSharedSet) + } + for _, k := range plan.PreservedSharedVideos { + if !wantSharedSet[k] { + t.Fatalf("unexpected key %q in PreservedSharedVideos %v", k, plan.PreservedSharedVideos) + } + } + if len(plan.PreservedUserFiles) != 1 || plan.PreservedUserFiles[0] != "keep-note.txt" { + t.Fatalf("PreservedUserFiles = %v, want [keep-note.txt]", plan.PreservedUserFiles) + } + + // 4. Selecting both a dynamic and its referenced video directly must not duplicate keys + // or count the explicitly selected video as preserved. + planWithDirect := func() DeletePlan { + p, pErr := store.PlanDeleteBatch([]string{d1.ItemKey, vKeep.ItemKey}) + if pErr != nil { + t.Fatalf("PlanDeleteBatch(d1, vKeep): %v", pErr) + } + return p + }() + for _, k := range planWithDirect.PreservedSharedVideos { + if k == vKeep.ItemKey { + t.Fatalf("explicitly selected video %s must not appear in PreservedSharedVideos: %v", vKeep.ItemKey, planWithDirect.PreservedSharedVideos) + } + } + + // 5. Execute DeleteBatch([d1, d2, d1], true). + res, err := store.DeleteBatch([]string{d1.ItemKey, d2.ItemKey, d1.ItemKey}, true) + if err != nil { + t.Fatalf("DeleteBatch: %v", err) + } + if len(res.PreservedUserFiles) != 1 || res.PreservedUserFiles[0] != "keep-note.txt" { + t.Fatalf("DeleteBatch PreservedUserFiles = %v, want [keep-note.txt]", res.PreservedUserFiles) + } + for _, gone := range []string{d1.ItemKey, d2.ItemKey, vExcl.ItemKey} { + if _, ok, _ := store.GetItem(gone); ok { + t.Fatalf("expected %s deleted from DB", gone) + } + } + if _, err := os.Stat(filepath.Join(vExclDir, "P01.mp4")); !os.IsNotExist(err) { + t.Fatalf("expected vExcl registered P01.mp4 deleted, err=%v", err) + } + if _, err := os.Stat(filepath.Join(vExclDir, "item.json")); !os.IsNotExist(err) { + t.Fatalf("expected vExcl item.json deleted, err=%v", err) + } + if data, err := os.ReadFile(filepath.Join(vExclDir, "keep-note.txt")); err != nil || string(data) != "user-personal-note" { + t.Fatalf("non-TRACE user file keep-note.txt was not preserved: err=%v data=%q", err, string(data)) + } + for _, kept := range []string{vKeep.ItemKey, vDirect.ItemKey, d3.ItemKey} { + if _, ok, _ := store.GetItem(kept); !ok { + t.Fatalf("expected %s preserved in DB", kept) + } + } + if _, err := os.Stat(filepath.Join(vKeepDir, "P01.mp4")); err != nil { + t.Fatalf("expected preserved shared video file to stay on disk: %v", err) + } + if _, err := os.Stat(filepath.Join(vDirectDir, "P01.mp4")); err != nil { + t.Fatalf("expected directly cached video file to stay on disk: %v", err) + } + + // 6. DeleteBatch on solo author item cleans up empty item/kind/author dirs while + // preserving site root (/bilibili) and cache root. + if _, err := store.DeleteBatch([]string{solo.ItemKey}, true); err != nil { + t.Fatalf("DeleteBatch solo: %v", err) + } + if _, err := os.Stat(filepath.Join(cacheDir, "bilibili", "2002")); !os.IsNotExist(err) { + t.Fatalf("expected empty author dir 2002 removed, err=%v", err) + } + if _, err := os.Stat(filepath.Join(cacheDir, "bilibili")); err != nil { + t.Fatalf("site root folder must be preserved: %v", err) + } + if _, err := os.Stat(cacheDir); err != nil { + t.Fatalf("cache root folder must be preserved: %v", err) + } +} + +func TestStatisticsAuthorItemCountAndBytesWithViaAnd5000Items(t *testing.T) { + store, cacheDir := openBatchTestStore(t) + + // Verify collab and forward via-owner attribution sums ItemCount and TotalBytes accurately. + saveSyntheticMediaItem(t, store, filepath.Join(cacheDir, "bilibili", "1001", "videos", "BV1own1"), ItemMetadata{ + Version: 1, ID: "BV1own1", Site: "bilibili", Kind: "video", Status: "complete", + Title: "Own Video", PubTs: 1700000100, Author: ItemAuthor{Mid: 1001, Name: "Member"}, + Media: []MediaFile{{Role: "video", Path: "P01.mp4"}}, + }, map[string][]byte{"P01.mp4": make([]byte, 1000)}) + + saveSyntheticMediaItem(t, store, filepath.Join(cacheDir, "bilibili", "1001", "videos", "BV1col1"), ItemMetadata{ + Version: 1, ID: "BV1col1", Site: "bilibili", Kind: "video", Status: "complete", + Title: "Collab Video", PubTs: 1700000110, + Author: ItemAuthor{Mid: 9999, Name: "Uploader"}, + Via: &ItemVia{Reason: ViaCollab, Site: "bilibili", UID: "1001", Name: "Member"}, + Media: []MediaFile{{Role: "video", Path: "P01.mp4"}}, + }, map[string][]byte{"P01.mp4": make([]byte, 2500)}) + + saveSyntheticMediaItem(t, store, filepath.Join(cacheDir, "bilibili", "1001", "forwards", "BV1fwd1"), ItemMetadata{ + Version: 1, ID: "BV1fwd1", Site: "bilibili", Kind: "video", Status: "complete", + Title: "Forward Video", PubTs: 1700000120, + Author: ItemAuthor{Mid: 8888, Name: "OriginAuthor"}, + Via: &ItemVia{Reason: ViaForward, Site: "bilibili", UID: "1001", Name: "Member", DynamicID: "501"}, + Media: []MediaFile{{Role: "video", Path: "P01.mp4"}}, + }, map[string][]byte{"P01.mp4": make([]byte, 4000)}) + + saveSyntheticMediaItem(t, store, filepath.Join(cacheDir, "douyin", "sec1", "works", "7001"), ItemMetadata{ + Version: 1, ID: "7001", Site: "douyin", Kind: "video", Status: "complete", + Title: "Douyin Video", PubTs: 1700000130, + Author: ItemAuthor{Site: "douyin", UID: "sec_dy_1", Name: "DouyinAuthor"}, + Media: []MediaFile{{Role: "video", Path: "video.mp4"}}, + }, map[string][]byte{"video.mp4": make([]byte, 6000)}) + + stats, err := store.Statistics() + if err != nil { + t.Fatalf("Statistics: %v", err) + } + byKey := map[string]ItemAuthor{} + for _, au := range stats.Authors { + byKey[au.Site+":"+au.UID] = au + } + if _, leaked := byKey["bilibili:9999"]; leaked { + t.Fatalf("collab uploader 9999 leaked into Statistics.Authors: %+v", stats.Authors) + } + if _, leaked := byKey["bilibili:8888"]; leaked { + t.Fatalf("forward original author 8888 leaked into Statistics.Authors: %+v", stats.Authors) + } + member := byKey["bilibili:1001"] + if member.ItemCount != 3 || member.TotalBytes != 7500 { + t.Fatalf("member stats = %+v, want ItemCount=3 TotalBytes=7500", member) + } + dy := byKey["douyin:sec_dy_1"] + if dy.ItemCount != 1 || dy.TotalBytes != 6000 { + t.Fatalf("douyin stats = %+v, want ItemCount=1 TotalBytes=6000", dy) + } + + // Scale test: 5,000 synthetic items across 50 authors must aggregate accurately and fast offline. + store5k, _ := openBatchTestStore(t) + tx, err := store5k.db.Begin() + if err != nil { + t.Fatalf("begin tx: %v", err) + } + stmt, err := tx.Prepare(` + INSERT INTO library_items ( + item_key, site, kind, raw_id, mid, author_uid, author_name, author_face, + title, summary, pub_ts, cached_at, status, item_dir, total_bytes, + upgrade_available, upgrade_hint, json_data + ) VALUES (?, ?, 'video', ?, ?, ?, ?, '', ?, '', ?, '2026-11-26T00:00:00Z', 'complete', ?, ?, 0, '', ?) + `) + if err != nil { + t.Fatalf("prepare: %v", err) + } + const totalItems = 5000 + const authorCount = 50 + var wantTotalBytes int64 + wantAuthorBytes := make(map[string]int64, authorCount) + wantAuthorCounts := make(map[string]int, authorCount) + for i := 0; i < totalItems; i++ { + aIdx := i % authorCount + uid := fmt.Sprintf("%d", 10000+aIdx) + name := fmt.Sprintf("Author_%02d", aIdx) + rawID := fmt.Sprintf("BV1s%07d", i) + key := "bilibili:video:" + rawID + sz := int64((aIdx + 1) * 1024) + wantTotalBytes += sz + wantAuthorBytes["bilibili:"+uid] += sz + wantAuthorCounts["bilibili:"+uid]++ + jsonData := fmt.Sprintf(`{"version":1,"id":"%s","site":"bilibili","kind":"video","status":"complete","title":"%s","pubTs":%d,"author":{"site":"bilibili","uid":"%s","mid":%s,"name":"%s"}}`, + rawID, rawID, 1700000000+i, uid, uid, name) + if _, err := stmt.Exec(key, "bilibili", rawID, 10000+aIdx, uid, name, rawID, 1700000000+i, "/tmp/"+rawID, sz, jsonData); err != nil { + t.Fatalf("insert %d: %v", i, err) + } + } + _ = stmt.Close() + if err := tx.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } + + start := time.Now() + stats5k, err := store5k.Statistics() + elapsed := time.Since(start) + if err != nil { + t.Fatalf("Statistics 5k: %v", err) + } + if stats5k.Items != totalItems || stats5k.Bytes != wantTotalBytes || len(stats5k.Authors) != authorCount { + t.Fatalf("stats5k = items:%d bytes:%d authors:%d, want %d / %d / %d", + stats5k.Items, stats5k.Bytes, len(stats5k.Authors), totalItems, wantTotalBytes, authorCount) + } + for _, au := range stats5k.Authors { + k := au.Site + ":" + au.UID + if au.ItemCount != wantAuthorCounts[k] || au.TotalBytes != wantAuthorBytes[k] { + t.Fatalf("author %s = (%d, %d), want (%d, %d)", k, au.ItemCount, au.TotalBytes, wantAuthorCounts[k], wantAuthorBytes[k]) + } + } + if elapsed > 2*time.Second { + t.Fatalf("Statistics() on 5,000 items too slow: %v", elapsed) + } +} + +func TestListItemsByItemKeysIncludingOver400Boundary(t *testing.T) { + store, _ := openBatchTestStore(t) + store.SetAllowMovedFiles(true) + + tx, err := store.db.Begin() + if err != nil { + t.Fatalf("begin tx: %v", err) + } + stmt, err := tx.Prepare(` + INSERT INTO library_items ( + item_key, site, kind, raw_id, mid, author_uid, author_name, author_face, + title, summary, pub_ts, cached_at, status, item_dir, total_bytes, + upgrade_available, upgrade_hint, json_data + ) VALUES (?, 'bilibili', 'video', ?, 1001, '1001', 'UP', '', ?, '', ?, '2026-11-26T00:00:00Z', 'complete', ?, 1024, 0, '', ?) + `) + if err != nil { + t.Fatalf("prepare: %v", err) + } + const total = 450 + allKeys := make([]string, 0, total) + for i := 0; i < total; i++ { + rawID := fmt.Sprintf("BV1k%07d", i) + key := "bilibili:video:" + rawID + allKeys = append(allKeys, key) + jsonData := fmt.Sprintf(`{"version":1,"id":"%s","site":"bilibili","kind":"video","status":"complete","title":"Item %d","pubTs":%d,"author":{"site":"bilibili","uid":"1001","mid":1001,"name":"UP"}}`, + rawID, i, 1700000000+i) + if _, err := stmt.Exec(key, rawID, fmt.Sprintf("Item %d", i), 1700000000+i, "/tmp/"+rawID, jsonData); err != nil { + t.Fatalf("insert %d: %v", i, err) + } + } + _ = stmt.Close() + if err := tx.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } + + // 1. Small explicit subset. + subset := []string{allKeys[3], allKeys[10], allKeys[449], allKeys[10]} + got, err := store.ListItems(FeedFilter{ItemKeys: subset, Limit: 20}) + if err != nil { + t.Fatalf("ListItems small subset: %v", err) + } + if len(got) != 3 { + t.Fatalf("ListItems small subset returned %d items, want 3", len(got)) + } + + // 2. Whitespace-only ItemKeys slice must return empty, never the whole library. + emptyGot, err := store.ListItems(FeedFilter{ItemKeys: []string{"", " "}, Limit: 20}) + if err != nil { + t.Fatalf("ListItems blank keys: %v", err) + } + if len(emptyGot) != 0 { + t.Fatalf("blank ItemKeys returned %d items, want 0", len(emptyGot)) + } + + // 3. >400 keys boundary (420 keys) via json_each fallback works without SQL parameter overflow. + largeSubset := allKeys[:420] + gotLarge, err := store.ListItems(FeedFilter{ItemKeys: largeSubset, Limit: 500}) + if err != nil { + t.Fatalf("ListItems 420 keys: %v", err) + } + if len(gotLarge) != 420 { + t.Fatalf("ListItems 420 keys returned %d items, want 420", len(gotLarge)) + } +} diff --git a/internal/library/delete.go b/internal/library/delete.go index d94fcf9..0e4ed04 100644 --- a/internal/library/delete.go +++ b/internal/library/delete.go @@ -108,46 +108,96 @@ func (s *Store) cleanupPendingDeletesLocked() error { func (s *Store) PlanDelete(itemKey string) (DeletePlan, error) { s.mu.RLock() defer s.mu.RUnlock() - return s.planDeleteLocked(itemKey) + plan, _, err := s.planDeleteBatchLocked([]string{itemKey}) + return plan, err } -func (s *Store) planDeleteLocked(itemKey string) (DeletePlan, error) { - meta, ok, err := s.getItemLocked(itemKey) - if err != nil { - return DeletePlan{}, err - } - if !ok { - return DeletePlan{}, fmt.Errorf("library: item %q not found", itemKey) +// PlanDeleteBatch computes the exact DeletePlan for multiple items as a single +// batch without modifying disk or DB (FR-LIB-003, INV-09, DEC-083). +// Shared referenced videos are evaluated excluding the entire selected batch: +// if every referencing dynamic is in the batch (and the video was not directly +// cached), the video is included in the deletion plan; if any unselected +// dynamic still references it or it was directly cached, it is preserved. +func (s *Store) PlanDeleteBatch(itemKeys []string) (DeletePlan, error) { + s.mu.RLock() + defer s.mu.RUnlock() + plan, _, err := s.planDeleteBatchLocked(itemKeys) + return plan, err +} + +func (s *Store) planDeleteBatchLocked(itemKeys []string) (DeletePlan, []ItemMetadata, error) { + var targets []ItemMetadata + selectedSet := make(map[string]bool, len(itemKeys)) + for _, rawKey := range itemKeys { + k := strings.TrimSpace(rawKey) + if k == "" { + continue + } + meta, ok, err := s.getItemLocked(k) + if err != nil { + return DeletePlan{}, nil, err + } + if !ok { + return DeletePlan{}, nil, fmt.Errorf("library: item %q not found", k) + } + if meta.Status == "recording" { + return DeletePlan{}, nil, fmt.Errorf("library: 正在录制的直播条目不能删除,请先停止录制") + } + if selectedSet[meta.ItemKey] { + continue + } + selectedSet[meta.ItemKey] = true + targets = append(targets, meta) } - if meta.Status == "recording" { - return DeletePlan{}, fmt.Errorf("library: 正在录制的直播条目不能删除,请先停止录制") + if len(targets) == 0 { + return DeletePlan{}, nil, fmt.Errorf("library: 请先选择要删除的条目") } plan := DeletePlan{ - TargetKey: meta.ItemKey, - ItemKeys: []string{meta.ItemKey}, + TargetKey: targets[0].ItemKey, + TargetKeys: make([]string, 0, len(targets)), + ItemKeys: make([]string, 0, len(targets)), + } + itemsToDelete := make([]ItemMetadata, 0, len(targets)) + seenDeleteItems := make(map[string]bool, len(targets)) + for _, meta := range targets { + plan.TargetKeys = append(plan.TargetKeys, meta.ItemKey) + plan.ItemKeys = append(plan.ItemKeys, meta.ItemKey) + itemsToDelete = append(itemsToDelete, meta) + seenDeleteItems[meta.ItemKey] = true } - itemsToDelete := []ItemMetadata{meta} - - // If deleting a dynamic item that references videos, check if each referenced video is shared or directly cached. - if meta.Kind == "dynamic" && len(meta.Videos) > 0 { + // If deleting dynamic items that reference videos, check whether each referenced + // video has any reference OUTSIDE the entire selected batch or was directly cached. + seenPreservedShared := make(map[string]bool) + for _, meta := range targets { + if meta.Kind != "dynamic" || len(meta.Videos) == 0 { + continue + } for _, vid := range meta.Videos { vidKey := CanonicalItemKey(meta.Site, "video", vid) + if seenDeleteItems[vidKey] || seenPreservedShared[vidKey] { + continue + } vMeta, vOk, err := s.getItemLocked(vidKey) if err != nil { - return DeletePlan{}, fmt.Errorf("library: check referenced video %s: %w", vidKey, err) + return DeletePlan{}, nil, fmt.Errorf("library: check referenced video %s: %w", vidKey, err) } if !vOk { continue } - var otherRefs int - if err := s.db.QueryRow(`SELECT COUNT(1) FROM item_refs WHERE to_key = ? AND from_key != ?`, vidKey, meta.ItemKey).Scan(&otherRefs); err != nil { - return DeletePlan{}, fmt.Errorf("library: check shared refs for %s: %w", vidKey, err) + hasExternalRef, err := s.hasRefOutsideBatchLocked(vidKey, selectedSet) + if err != nil { + return DeletePlan{}, nil, fmt.Errorf("library: check shared refs for %s: %w", vidKey, err) } - if otherRefs > 0 || vMeta.DirectCached { + if hasExternalRef || vMeta.DirectCached { + seenPreservedShared[vidKey] = true plan.PreservedSharedVideos = append(plan.PreservedSharedVideos, vidKey) } else { + if vMeta.Status == "recording" { + return DeletePlan{}, nil, fmt.Errorf("library: 正在录制的直播条目不能删除,请先停止录制") + } + seenDeleteItems[vidKey] = true plan.ItemKeys = append(plan.ItemKeys, vidKey) itemsToDelete = append(itemsToDelete, vMeta) } @@ -165,13 +215,32 @@ func (s *Store) planDeleteLocked(itemKey string) (DeletePlan, error) { } } for _, uf := range userFiles { - if !seenUserFiles[uf] { - seenUserFiles[uf] = true + uKey := it.ItemDir + "\x00" + uf + if !seenUserFiles[uKey] { + seenUserFiles[uKey] = true plan.PreservedUserFiles = append(plan.PreservedUserFiles, uf) } } } - return plan, nil + return plan, itemsToDelete, nil +} + +func (s *Store) hasRefOutsideBatchLocked(toKey string, selectedSet map[string]bool) (bool, error) { + rows, err := s.db.Query(`SELECT from_key FROM item_refs WHERE to_key = ?`, toKey) + if err != nil { + return false, err + } + defer rows.Close() + for rows.Next() { + var fromKey string + if err := rows.Scan(&fromKey); err != nil { + return false, err + } + if !selectedSet[fromKey] { + return true, nil + } + } + return false, rows.Err() } func collectRegisteredAndUserFiles(meta ItemMetadata) (registeredAbs []string, userRel []string) { @@ -252,7 +321,7 @@ func collectRegisteredAndUserFiles(meta ItemMetadata) (registeredAbs []string, u func (s *Store) Delete(itemKey string) (DeletePlan, error) { s.mu.Lock() defer s.mu.Unlock() - return s.deleteWithPlanLocked(itemKey, true) + return s.deleteBatchWithPlanLocked([]string{itemKey}, true) } // DeleteItem removes an item from the index and optionally deletes its registered files from disk (INV-09). @@ -260,20 +329,34 @@ func (s *Store) Delete(itemKey string) (DeletePlan, error) { func (s *Store) DeleteItem(itemKey string, deleteFiles bool) error { s.mu.Lock() defer s.mu.Unlock() - _, err := s.deleteWithPlanLocked(itemKey, deleteFiles) + _, err := s.deleteBatchWithPlanLocked([]string{itemKey}, deleteFiles) return err } -func (s *Store) deleteWithPlanLocked(itemKey string, deleteFiles bool) (DeletePlan, error) { - plan, err := s.planDeleteLocked(itemKey) +// DeleteBatch removes multiple items as a single atomic index transaction and +// optionally deletes their registered files from disk (FR-LIB-003, INV-09, DEC-083). +// It NEVER calls os.RemoveAll on any directory; non-TRACE user files are strictly preserved. +func (s *Store) DeleteBatch(itemKeys []string, deleteFiles bool) (DeletePlan, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.deleteBatchWithPlanLocked(itemKeys, deleteFiles) +} + +func (s *Store) deleteBatchWithPlanLocked(itemKeys []string, deleteFiles bool) (DeletePlan, error) { + plan, itemsToDelete, err := s.planDeleteBatchLocked(itemKeys) if err != nil { return DeletePlan{}, err } var itemDirs []string - for _, k := range plan.ItemKeys { - if m, ok, _ := s.getItemLocked(k); ok && m.ItemDir != "" { - itemDirs = append(itemDirs, m.ItemDir) + seenDirs := make(map[string]bool, len(itemsToDelete)) + for _, m := range itemsToDelete { + if m.ItemDir != "" { + clean := filepath.Clean(m.ItemDir) + if !seenDirs[clean] { + seenDirs[clean] = true + itemDirs = append(itemDirs, clean) + } } } @@ -281,43 +364,40 @@ func (s *Store) deleteWithPlanLocked(itemKey string, deleteFiles bool) (DeletePl if deleteFiles && len(plan.RegisteredFiles) > 0 { pending, err := s.readPendingDeletesLocked() if err != nil { - return plan, err - } - for _, k := range plan.ItemKeys { - m, ok, _ := s.getItemLocked(k) - if ok { - regFiles, _ := collectRegisteredAndUserFiles(m) - pending = append(pending, pendingDeleteRecord{ - ItemKey: k, - ItemDir: m.ItemDir, - RegisteredFiles: regFiles, - }) - } + return DeletePlan{}, err + } + for _, m := range itemsToDelete { + regFiles, _ := collectRegisteredAndUserFiles(m) + pending = append(pending, pendingDeleteRecord{ + ItemKey: m.ItemKey, + ItemDir: m.ItemDir, + RegisteredFiles: regFiles, + }) } if err := s.writePendingDeletesLocked(pending); err != nil { - return plan, err + return DeletePlan{}, err } } // 2. Remove from index and references. tx, err := s.db.Begin() if err != nil { - return plan, err + return DeletePlan{}, err } defer tx.Rollback() for _, k := range plan.ItemKeys { if _, err := tx.Exec(`DELETE FROM library_items WHERE item_key = ?`, k); err != nil { - return plan, err + return DeletePlan{}, err } if _, err := tx.Exec(`DELETE FROM item_refs WHERE from_key = ? OR to_key = ?`, k, k); err != nil { - return plan, err + return DeletePlan{}, err } if _, err := tx.Exec(`UPDATE feed_items SET cached = 0, cache_status = '', item_key = '' WHERE item_key = ?`, k); err != nil { - return plan, err + return DeletePlan{}, err } } if err := tx.Commit(); err != nil { - return plan, err + return DeletePlan{}, err } s.mutationSeq++ diff --git a/internal/library/feed.go b/internal/library/feed.go index 0ccd390..85ec538 100644 --- a/internal/library/feed.go +++ b/internal/library/feed.go @@ -2,6 +2,7 @@ package library import ( "database/sql" + "encoding/json" "errors" "fmt" "strconv" @@ -154,10 +155,43 @@ func appendSiteAndAuthorClausesVia(clauses []string, args []any, colPrefix, site return clauses, args } +// maxItemKeySQLParams caps direct IN (?,?,...) placeholders before switching to +// json_each(?) so ListItems never overflows SQLite bind-parameter limits. +const maxItemKeySQLParams = 400 + // ListItems returns cached library items matching filter. func (s *Store) ListItems(filter FeedFilter) ([]ItemMetadata, error) { var clauses []string var args []any + if len(filter.ItemKeys) > 0 { + cleanKeys := make([]string, 0, len(filter.ItemKeys)) + seen := make(map[string]bool, len(filter.ItemKeys)) + for _, raw := range filter.ItemKeys { + k := strings.TrimSpace(raw) + if k == "" || seen[k] { + continue + } + seen[k] = true + cleanKeys = append(cleanKeys, k) + } + if len(cleanKeys) == 0 { + return nil, nil + } + if len(cleanKeys) <= maxItemKeySQLParams { + ph := strings.TrimSuffix(strings.Repeat("?,", len(cleanKeys)), ",") + clauses = append(clauses, "item_key IN ("+ph+")") + for _, k := range cleanKeys { + args = append(args, k) + } + } else { + rawJSON, err := json.Marshal(cleanKeys) + if err != nil { + return nil, err + } + clauses = append(clauses, "item_key IN (SELECT value FROM json_each(?))") + args = append(args, string(rawJSON)) + } + } switch filter.Kind { case "image": clauses = append(clauses, "(EXISTS (SELECT 1 FROM json_each(json_data, '$.media') WHERE json_extract(value, '$.role') = 'image' OR COALESCE(json_extract(value, '$.gif'), 0) = 1) OR EXISTS (SELECT 1 FROM json_each(json_data, '$.notePages') WHERE json_extract(value, '$.kind') IN ('image', 'motion') OR COALESCE(json_extract(value, '$.gif'), 0) = 1))") diff --git a/internal/library/schema.go b/internal/library/schema.go index af7e135..185787b 100644 --- a/internal/library/schema.go +++ b/internal/library/schema.go @@ -175,6 +175,8 @@ type ItemAuthor struct { Name string `json:"name"` Face string `json:"face"` LatestPubTs int64 `json:"latestPubTs,omitempty"` + ItemCount int `json:"itemCount,omitempty"` + TotalBytes int64 `json:"totalBytes,omitempty"` } // Reasons recorded in ItemVia. @@ -396,9 +398,10 @@ type DotState struct { Upgrade string `json:"upgrade,omitempty"` } -// DeletePlan describes the exact files and items that PlanDelete / Delete will remove or preserve (FR-LIB-003, INV-09). +// DeletePlan describes the exact files and items that PlanDelete / PlanDeleteBatch / Delete / DeleteBatch will remove or preserve (FR-LIB-003, INV-09). type DeletePlan struct { TargetKey string `json:"targetKey"` + TargetKeys []string `json:"targetKeys,omitempty"` ItemKeys []string `json:"itemKeys"` RegisteredFiles []string `json:"registeredFiles"` PreservedSharedVideos []string `json:"preservedSharedVideos,omitempty"` @@ -475,6 +478,7 @@ type FeedFilter struct { AuthorUID string `json:"authorUid,omitempty"` Authors []int64 `json:"authors,omitempty"` AuthorRefs []AuthorRef `json:"authorRefs,omitempty"` + ItemKeys []string `json:"itemKeys,omitempty"` CachedOnly bool `json:"cachedOnly"` // true = local library view Keyword string `json:"keyword"` Sort string `json:"sort,omitempty"` // "newest", "oldest" diff --git a/internal/library/statistics.go b/internal/library/statistics.go index 8773949..6927ada 100644 --- a/internal/library/statistics.go +++ b/internal/library/statistics.go @@ -21,9 +21,9 @@ func (s *Store) Statistics() (Statistics, error) { // A collaboration or forwarded video cached under another creator's folder is // listed under that creator in the media library, not under the uploader (DEC-056, DEC-061). rows, err := s.db.Query(` - SELECT site, owner_uid, MAX(owner_mid), MAX(owner_name), MAX(owner_face), COALESCE(MAX(pub_ts), 0) + SELECT site, owner_uid, MAX(owner_mid), MAX(owner_name), MAX(owner_face), COALESCE(MAX(pub_ts), 0), COUNT(*), COALESCE(SUM(total_bytes), 0) FROM ( - SELECT site, pub_ts, + SELECT site, pub_ts, total_bytes, CASE WHEN ` + viaOwnerSQL + ` THEN ` + viaUIDSQL + ` ELSE author_uid END AS owner_uid, CASE WHEN ` + viaOwnerSQL + ` THEN 0 ELSE mid END AS owner_mid, CASE WHEN ` + viaOwnerSQL + ` THEN COALESCE(json_extract(json_data, '$.via.name'), '') ELSE author_name END AS owner_name, @@ -40,7 +40,7 @@ func (s *Store) Statistics() (Statistics, error) { defer rows.Close() for rows.Next() { var author ItemAuthor - if err := rows.Scan(&author.Site, &author.UID, &author.Mid, &author.Name, &author.Face, &author.LatestPubTs); err != nil { + if err := rows.Scan(&author.Site, &author.UID, &author.Mid, &author.Name, &author.Face, &author.LatestPubTs, &author.ItemCount, &author.TotalBytes); err != nil { return stats, err } if author.Site == "bilibili" && author.Mid <= 0 { diff --git a/internal/service/interfaces.go b/internal/service/interfaces.go index 0dc390f..9a2cf3a 100644 --- a/internal/service/interfaces.go +++ b/internal/service/interfaces.go @@ -221,8 +221,10 @@ type LibraryService interface { GetLibraryItemMetaOnly(keyOrID string) (library.ItemMetadata, bool, error) MediaPath(key, relPath string) (string, error) PlanDelete(key string) (library.DeletePlan, error) + PlanDeleteBatch(keys []string) (library.DeletePlan, error) Delete(key string) error DeleteLibraryItem(itemKey string, deleteFiles bool) error + DeleteLibraryItems(itemKeys []string, deleteFiles bool) (library.DeletePlan, error) RebuildLibraryIndex() (library.RebuildReport, error) // RefreshLibrary rescans the library folders for files deleted or changed // outside TRACE (presence and size, no hashing) and reports what changed. diff --git a/internal/service/library_service.go b/internal/service/library_service.go index 2c77096..a70e99c 100644 --- a/internal/service/library_service.go +++ b/internal/service/library_service.go @@ -579,6 +579,14 @@ func (b *Backend) PlanDelete(key string) (library.DeletePlan, error) { return b.lib.PlanDelete(key) } +// PlanDeleteBatch computes the safe file deletion plan for a batch of item keys. +func (b *Backend) PlanDeleteBatch(keys []string) (library.DeletePlan, error) { + if err := b.requireAnyLogin(); err != nil { + return library.DeletePlan{}, err + } + return b.lib.PlanDeleteBatch(keys) +} + // Delete executes a safe manifest-only file deletion for an item key. func (b *Backend) Delete(key string) error { return b.DeleteLibraryItem(key, true) @@ -646,6 +654,20 @@ func (b *Backend) DeleteLibraryItem(itemKey string, deleteFiles bool) error { return nil } +// DeleteLibraryItems removes multiple items as a single batch and optionally +// deletes their registered files from disk (FR-LIB-003, DEC-083). +func (b *Backend) DeleteLibraryItems(itemKeys []string, deleteFiles bool) (library.DeletePlan, error) { + if err := b.requireAnyLogin(); err != nil { + return library.DeletePlan{}, err + } + plan, err := b.lib.DeleteBatch(itemKeys, deleteFiles) + if len(plan.ItemKeys) > 0 { + b.pruneAccountAvatars() + b.events.Publish(EventLibraryChanged, fmt.Sprintf("deleted_batch:%d", len(plan.ItemKeys))) + } + return plan, err +} + // MigrateCacheDir changes the active cache directory, optionally moves existing files, and updates settings.json. func (b *Backend) MigrateCacheDir(newDir string, moveExisting bool) (library.RebuildReport, error) { if err := b.requireDesktop(); err != nil { diff --git a/internal/service/transfer_jobs.go b/internal/service/transfer_jobs.go index 3be52a5..1592648 100644 --- a/internal/service/transfer_jobs.go +++ b/internal/service/transfer_jobs.go @@ -307,11 +307,63 @@ func (b *Backend) StartExport(target string, filter library.FeedFilter) (Transfe // exportPageSize is how many items exportItems reads at a time. var exportPageSize = 500 +// exportKeyChunkSize is how many explicit ItemKeys exportItems passes to +// ListItems per SQL query so SQLite bind parameters always stay bounded. +var exportKeyChunkSize = 400 + // exportItems lists every item of filter, page by page (ListItems returns -// at most one page). +// at most one page). When filter.ItemKeys is set, keys are deduplicated and +// queried in safe chunks. func exportItems(lib interface { ListItems(library.FeedFilter) ([]library.ItemMetadata, error) }, filter library.FeedFilter) ([]library.ItemMetadata, error) { + if len(filter.ItemKeys) > 0 { + cleanKeys := make([]string, 0, len(filter.ItemKeys)) + seenKey := make(map[string]bool, len(filter.ItemKeys)) + for _, raw := range filter.ItemKeys { + k := strings.TrimSpace(raw) + if k == "" || seenKey[k] { + continue + } + seenKey[k] = true + cleanKeys = append(cleanKeys, k) + } + if len(cleanKeys) == 0 { + return nil, nil + } + chunkSize := exportKeyChunkSize + if chunkSize <= 0 { + chunkSize = 400 + } + out := make([]library.ItemMetadata, 0, len(cleanKeys)) + seenItem := make(map[string]bool, len(cleanKeys)) + for start := 0; start < len(cleanKeys); start += chunkSize { + end := min(start+chunkSize, len(cleanKeys)) + chunkFilter := filter + chunkFilter.ItemKeys = cleanKeys[start:end] + chunkFilter.Limit = end - start + chunkFilter.Offset = 0 + chunkFilter.Sort = "oldest" + items, err := lib.ListItems(chunkFilter) + if err != nil { + return nil, err + } + for _, it := range items { + if seenItem[it.ItemKey] { + continue + } + seenItem[it.ItemKey] = true + out = append(out, it) + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].PubTs != out[j].PubTs { + return out[i].PubTs < out[j].PubTs + } + return out[i].ItemKey < out[j].ItemKey + }) + return out, nil + } page := exportPageSize filter.Limit, filter.Sort = page, "oldest" var out []library.ItemMetadata diff --git a/internal/service/transfer_jobs_test.go b/internal/service/transfer_jobs_test.go index 93f1b31..93941a6 100644 --- a/internal/service/transfer_jobs_test.go +++ b/internal/service/transfer_jobs_test.go @@ -124,3 +124,120 @@ func TestTransferJobsExportEverythingAndImportElsewhere(t *testing.T) { t.Fatal("dropped plan imported") } } + +type stubChunkListLib struct { + maxChunkSeen int + calls int + itemsByKey map[string]library.ItemMetadata +} + +func (s *stubChunkListLib) ListItems(filter library.FeedFilter) ([]library.ItemMetadata, error) { + s.calls++ + if len(filter.ItemKeys) > s.maxChunkSeen { + s.maxChunkSeen = len(filter.ItemKeys) + } + var out []library.ItemMetadata + for _, k := range filter.ItemKeys { + if it, ok := s.itemsByKey[k]; ok { + out = append(out, it) + } + } + return out, nil +} + +func TestTransferJobsBatchExportSelectedItemsAndChunking(t *testing.T) { + oldChunk := exportKeyChunkSize + exportKeyChunkSize = 2 + t.Cleanup(func() { exportKeyChunkSize = oldChunk }) + + src := transferTestBackend(t) + var keys []string + for i := 1; i <= 5; i++ { + id := fmt.Sprintf("BV1bx%05d", i) + dir := filepath.Join(src.lib.CacheDir(), "bilibili", "1001", "video", id) + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + data := []byte("批量导出样本 " + id) + if err := os.WriteFile(filepath.Join(dir, "P01.mp4"), data, 0o600); err != nil { + t.Fatal(err) + } + sum := sha256.Sum256(data) + meta := library.ItemMetadata{ + Version: 1, ID: "video:" + id, Site: "bilibili", Kind: "video", Title: "样本 " + id, Status: "complete", + PubTs: int64(1700000000 + i*10), + Author: library.ItemAuthor{Mid: 1001, Name: "合成作者"}, + Media: []library.MediaFile{{Role: "video", Path: "P01.mp4", Bytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:])}}, + } + saved, err := src.lib.SaveItem(dir, meta) + if err != nil { + t.Fatal(err) + } + keys = append(keys, saved.ItemKey) + } + + selected := []string{keys[0], keys[2], keys[4], keys[2]} // 3 unique items across 2 chunks (chunkSize=2) + out := filepath.Join(t.TempDir(), "batch-export") + job, err := src.StartExport(out, library.FeedFilter{ItemKeys: selected}) + if err != nil { + t.Fatalf("StartExport selected: %v", err) + } + done := waitTransfer(t, src, job.ID, TransferDone) + if done.Export == nil || done.Export.Items != 3 || done.Export.Files != 3 { + t.Fatalf("selected export summary = %+v, want 3 items / 3 files", done.Export) + } + + // Verify only the 3 selected items are imported into a fresh destination library. + dst := transferTestBackend(t) + scan, err := dst.StartImportScan(out) + if err != nil { + t.Fatal(err) + } + ready := waitTransfer(t, dst, scan.ID, TransferReady) + if ready.Counts[transfer.CategoryNew] != 3 { + t.Fatalf("imported scan counts = %v, want 3 new items", ready.Counts) + } + if _, err := dst.StartImport(scan.ID, transfer.Choices{}); err != nil { + t.Fatal(err) + } + waitTransfer(t, dst, scan.ID, TransferDone) + importedItems, err := dst.lib.ListItems(library.FeedFilter{Limit: 20}) + if err != nil || len(importedItems) != 3 { + t.Fatalf("importedItems = %d, err=%v (want 3)", len(importedItems), err) + } + gotKeys := map[string]bool{} + for _, it := range importedItems { + gotKeys[it.ItemKey] = true + } + for _, want := range []string{keys[0], keys[2], keys[4]} { + if !gotKeys[want] { + t.Fatalf("missing selected exported item %s in %v", want, gotKeys) + } + } + for _, unwanted := range []string{keys[1], keys[3]} { + if gotKeys[unwanted] { + t.Fatalf("unselected item %s should not have been exported", unwanted) + } + } + + // Verify default 400-key chunking boundary on >400 selected item keys. + exportKeyChunkSize = 400 + stub := &stubChunkListLib{itemsByKey: make(map[string]library.ItemMetadata, 850)} + largeKeys := make([]string, 0, 850) + for i := 0; i < 850; i++ { + k := fmt.Sprintf("bilibili:video:BV1c%07d", i) + largeKeys = append(largeKeys, k) + stub.itemsByKey[k] = library.ItemMetadata{ItemKey: k, PubTs: int64(1700000000 + (850 - i))} + } + gotAll, err := exportItems(stub, library.FeedFilter{ItemKeys: largeKeys}) + if err != nil { + t.Fatalf("exportItems 850 keys: %v", err) + } + if len(gotAll) != 850 || stub.calls != 3 || stub.maxChunkSeen != 400 { + t.Fatalf("exportItems 850 keys = len:%d calls:%d maxChunk:%d (want 850 / 3 / 400)", + len(gotAll), stub.calls, stub.maxChunkSeen) + } + if gotAll[0].PubTs > gotAll[len(gotAll)-1].PubTs { + t.Fatalf("expected exportItems oldest-first order, got %d .. %d", gotAll[0].PubTs, gotAll[len(gotAll)-1].PubTs) + } +} diff --git a/internal/ui/app.go b/internal/ui/app.go index 72cb6f1..c41f9cc 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -118,7 +118,9 @@ type PlayerOverlayState struct { // DeleteConfirmState holds state for the library item deletion confirmation modal. type DeleteConfirmState struct { Open bool + Batch bool Item library.ItemMetadata + TargetKeys []string Plan library.DeletePlan FileCount int TotalBytes int64 @@ -148,12 +150,14 @@ type compactLibEntry struct { } type libraryPanelRow struct { - isSub bool - sub subscription.Subscription - author library.ItemAuthor - site string - uid string - authorKey string + isSub bool + sub subscription.Subscription + author library.ItemAuthor + site string + uid string + authorKey string + itemCount int + totalBytes int64 } type libraryPanelSig struct { @@ -163,6 +167,9 @@ type libraryPanelSig struct { statsRev int authorsN int authorsFirst *library.ItemAuthor + siteFilter string + subFilter string + sortBySize bool } // App manages the MyGo immediate-mode UI tree and state for TRACE. @@ -546,14 +553,17 @@ type App struct { // parse) and cached count, keyed "site:uid" (DEC-061). accountWorks map[string]service.AccountWorks // videoCacheFor is the creator page the open video came from (DEC-061). - videoCacheFor videoCacheContext - douyinCacheFor douyinCacheContext - weiboCacheFor weiboCacheContext - xCacheFor xCacheContext - libraryOffset int - LibraryAuthorMenu bool - ExpandedItemKey string - DeleteConfirm DeleteConfirmState + videoCacheFor videoCacheContext + douyinCacheFor douyinCacheContext + weiboCacheFor weiboCacheContext + xCacheFor xCacheContext + libraryOffset int + LibraryAuthorMenu bool + LibrarySourceSortBySize bool + LibrarySelectMode bool + LibrarySelectedKeys map[string]bool + ExpandedItemKey string + DeleteConfirm DeleteConfirmState // Tasks Page TasksSection string // "downloads" | "queue" | "conflicts" | "live" | "incidents" | "checks" | "transfers" @@ -695,6 +705,7 @@ func NewApp(backend service.BackendAPI, audioSink player.AudioSink) *App { ImportSelectedKeys: make(map[string]bool), LibrarySiteFilter: "all", LibrarySort: "pub_ts", + LibrarySelectedKeys: make(map[string]bool), TasksSection: "downloads", ConflictBatchChoice: service.DefaultConflictChoice, SettingsCategory: "account", @@ -1219,3 +1230,25 @@ func (a *App) View(c *ui.Context) { a.renderPlayerOverlay(c, w, h) } } + +// hasOpenModalOverlay reports whether any modal dialog or fullscreen media +// overlay is currently open on top of the active route. +func (a *App) hasOpenModalOverlay() bool { + return a.ConfirmLogoutOpen || + a.Remote.ConfirmPushXOpen || + a.DeleteConfirm.Open || + (a.RestartConfirmOpen && a.updater != nil) || + a.AddSubDialogOpen || + a.SubLinks.Open || + a.ImportSubModalOpen || + a.RuleBatch.Open || + a.MultiTagBatch.Open || + a.SubscribePicker.Open || + a.LibraryRefresh.Open || + a.Transfer.ExportOpen || + a.SubFile.ExportOpen || + a.SubFile.ImportOpen || + a.ConflictDiff.Open || + a.ImageViewer.Open || + a.PlayerOverlay.Open +} diff --git a/internal/ui/library_batch_storage_test.go b/internal/ui/library_batch_storage_test.go new file mode 100644 index 0000000..2f4e913 --- /dev/null +++ b/internal/ui/library_batch_storage_test.go @@ -0,0 +1,454 @@ +package ui + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/chialecode/trace/internal/library" + "github.com/chialecode/trace/internal/service" + "github.com/chialecode/trace/internal/subscription" + "github.com/egoist/mygo/ui" +) + +type libraryOfflineGuardBackend struct { + service.BackendAPI + netCalls atomic.Int32 +} + +func (b *libraryOfflineGuardBackend) FetchImage(context.Context, string) ([]byte, error) { + b.netCalls.Add(1) + return nil, errors.New("unexpected remote image request on offline library") +} + +func seedLibraryBytesItem(t *testing.T, lib *library.Store, dir string, meta library.ItemMetadata, files map[string][]byte) library.ItemMetadata { + t.Helper() + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + for rel, data := range files { + p := filepath.Join(dir, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, data, 0o600); err != nil { + t.Fatal(err) + } + } + for i := range meta.Media { + if data, ok := files[meta.Media[i].Path]; ok { + meta.Media[i].Bytes = int64(len(data)) + sum := sha256.Sum256(data) + meta.Media[i].SHA256 = hex.EncodeToString(sum[:]) + } + } + saved, err := lib.SaveItem(dir, meta) + if err != nil { + t.Fatal(err) + } + return saved +} + +func TestLibrarySidebarStorageUsageSortingFilteringAndOfflineZeroNetwork(t *testing.T) { + app, _, cleanup := newTestUIApp(t) + defer cleanup() + seedUIFeed(t, app, 0) + realBackend := app.backend.(*service.Backend) + lib := realBackend.LibraryStore() + + // Subscription SubA combines a Bilibili account (10 KiB) + a Douyin account (20 KiB) => 2 items, 30 KiB. + subA, err := realBackend.CreateSubscription("多站创作者A", "", []subscription.AccountRef{ + {Site: "bilibili", UID: "3001", Name: "B站号A", Face: "https://image.example.invalid/face_a.png"}, + {Site: "douyin", UID: "sec_dy_a", Name: "抖音号A", Face: "https://image.example.invalid/face_dy_a.png"}, + }, subscription.SubRules{}) + if err != nil { + t.Fatal(err) + } + seedLibraryBytesItem(t, lib, filepath.Join(lib.CacheDir(), "bilibili", "3001", "videos", "BV1subA01"), library.ItemMetadata{ + Version: 1, Site: "bilibili", Kind: "video", ID: "BV1subA01", Title: "订阅A B站视频", PubTs: 1700000100, + Author: library.ItemAuthor{Site: "bilibili", Mid: 3001, UID: "3001", Name: "B站号A", Face: "https://image.example.invalid/face_a.png"}, + Media: []library.MediaFile{{Role: "video", Path: "P01.mp4"}}, + }, map[string][]byte{"P01.mp4": make([]byte, 10*1024)}) + + seedLibraryBytesItem(t, lib, filepath.Join(lib.CacheDir(), "douyin", "sec_dy_a", "works", "70001"), library.ItemMetadata{ + Version: 1, Site: "douyin", Kind: "video", ID: "70001", Title: "订阅A 抖音作品", PubTs: 1700000110, + Author: library.ItemAuthor{Site: "douyin", UID: "sec_dy_a", Name: "抖音号A"}, + Media: []library.MediaFile{{Role: "video", Path: "video.mp4"}}, + }, map[string][]byte{"video.mp4": make([]byte, 20*1024)}) + + // Unsubscribed author HeavyB has 1 large Bilibili video (200 KiB) — much larger than SubA! + seedLibraryBytesItem(t, lib, filepath.Join(lib.CacheDir(), "bilibili", "4002", "videos", "BV1heavy01"), library.ItemMetadata{ + Version: 1, Site: "bilibili", Kind: "video", ID: "BV1heavy01", Title: "大体积独立UP视频", PubTs: 1700000120, + Author: library.ItemAuthor{Site: "bilibili", Mid: 4002, UID: "4002", Name: "大体积UP", Face: "https://image.example.invalid/heavy.png"}, + Media: []library.MediaFile{{Role: "video", Path: "P01.mp4"}}, + }, map[string][]byte{"P01.mp4": make([]byte, 200*1024)}) + + guard := &libraryOfflineGuardBackend{BackendAPI: realBackend} + app.backend = guard + app.RefreshData() + app.Navigate(RouteLibrary) + + // Default ordering: subscriptions first (SubA), then unsubscribed authors (HeavyB). + rows := app.libraryPanelRows() + if len(rows) < 2 || !rows[0].isSub || rows[0].sub.ID != subA.ID { + t.Fatalf("default order should put subscription first, got %+v", rows) + } + if rows[0].itemCount != 2 || rows[0].totalBytes != 30*1024 { + t.Fatalf("SubA aggregated usage = (%d items, %d bytes), want (2, 30720)", rows[0].itemCount, rows[0].totalBytes) + } + if rows[1].isSub || rows[1].author.Mid != 4002 || rows[1].itemCount != 1 || rows[1].totalBytes != 200*1024 { + t.Fatalf("HeavyB usage = %+v, want mid=4002 (1, 204800)", rows[1]) + } + + tt := ui.NewTester(app.View, 1280, 860) + tt.Frame() + if !tt.HasText("2 项 · 30 KB") || !tt.HasText("1 项 · 200 KB") { + t.Fatalf("sidebar missing formatted item count / storage size readouts (want 2 项 · 30 KB and 1 项 · 200 KB)") + } + + // Click "按占用空间" toggle: HeavyB (200 KiB) must move above SubA (30 KiB). + if err := tt.Click("媒体库来源按占用空间排序"); err != nil { + t.Fatalf("click sort by size: %v", err) + } + tt.Frame() + if !app.LibrarySourceSortBySize { + t.Fatal("LibrarySourceSortBySize did not toggle on") + } + sortedRows := app.libraryPanelRows() + if len(sortedRows) < 2 || sortedRows[0].isSub || sortedRows[0].author.Mid != 4002 { + t.Fatalf("expected HeavyB first when sorted by storage usage, got %+v", sortedRows) + } + + // Clicking HeavyB filters the library grid to that author. + if err := tt.Click("按UP主筛选 4002"); err != nil { + t.Fatalf("click author row: %v", err) + } + tt.Frame() + if app.LibraryCreatorMid != 4002 || len(app.LibraryItems) != 1 || app.LibraryItems[0].RawID != "BV1heavy01" { + t.Fatalf("filtering to HeavyB yielded %+v", app.LibraryItems) + } + + // Switching site filter to "douyin" aggregates SubA's Douyin items only (1 item, 20 KiB) and omits Bilibili-only HeavyB. + if err := tt.Click("媒体库站点筛选:抖音"); err != nil { + t.Fatalf("click douyin filter: %v", err) + } + tt.Frame() + dyRows := app.libraryPanelRows() + if len(dyRows) != 1 || !dyRows[0].isSub || dyRows[0].itemCount != 1 || dyRows[0].totalBytes != 20*1024 { + t.Fatalf("douyin site filter panel rows = %+v, want only SubA (1, 20480)", dyRows) + } + + // Narrow window (720px) exposes author filter + storage usage + sort toggle without overflow. + app.LibrarySiteFilter = "all" + app.selectLibraryFilter() + narrow := ui.NewTester(app.View, 720, 860) + narrow.Frame() + if err := narrow.Click("媒体库作者筛选"); err != nil { + t.Fatalf("click narrow author filter: %v", err) + } + narrow.Frame() + if _, ok := narrow.Find("媒体库来源按占用空间排序"); !ok { + t.Fatal("narrow author filter missing 按占用空间 toggle") + } + if !narrow.HasText("1 项 · 200 KB") { + t.Fatal("narrow author filter missing storage size readout") + } + centerRect, okC := narrow.Find("中栏内容") + if !okC || centerRect.X+centerRect.W > 720.5 { + t.Fatalf("720px narrow library overflowed horizontally: %+v", centerRect) + } + + // Strictly zero remote network requests across all offline Library interactions. + if guard.netCalls.Load() != 0 { + t.Fatalf("offline library triggered %d remote image requests (want 0)", guard.netCalls.Load()) + } +} + +func TestLibraryMultiSelectTileSyncBatchDeleteAndBatchExport(t *testing.T) { + app, _, cleanup := newTestUIApp(t) + defer cleanup() + seedUIFeed(t, app, 0) + realBackend := app.backend.(*service.Backend) + lib := realBackend.LibraryStore() + + // 1. Multi-tile dynamic D1 (2 images => 2 grid tiles) referencing exclusive video V_excl and shared video V_shared. + vExclDir := filepath.Join(lib.CacheDir(), "bilibili", "5001", "videos", "BV1uiexcl1") + vExcl := seedLibraryBytesItem(t, lib, vExclDir, library.ItemMetadata{ + Version: 1, Site: "bilibili", Kind: "video", ID: "BV1uiexcl1", Title: "独占引用视频", PubTs: 1700000100, + DirectCached: false, Author: library.ItemAuthor{Site: "bilibili", Mid: 5001, UID: "5001", Name: "作者甲"}, + Media: []library.MediaFile{{Role: "video", Path: "P01.mp4"}}, + Parts: []library.VideoPartRecord{{CID: 11, Page: 1, File: "P01.mp4"}}, + }, map[string][]byte{ + "P01.mp4": make([]byte, 4096), + "my-notes.txt": []byte("preserve-me"), + }) + + vShared := seedLibraryBytesItem(t, lib, filepath.Join(lib.CacheDir(), "bilibili", "5001", "videos", "BV1uishr02"), library.ItemMetadata{ + Version: 1, Site: "bilibili", Kind: "video", ID: "BV1uishr02", Title: "共用保留视频", PubTs: 1700000105, + DirectCached: false, Author: library.ItemAuthor{Site: "bilibili", Mid: 5001, UID: "5001", Name: "作者甲"}, + Media: []library.MediaFile{{Role: "video", Path: "P01.mp4"}}, + Parts: []library.VideoPartRecord{{CID: 12, Page: 1, File: "P01.mp4"}}, + }, map[string][]byte{"P01.mp4": make([]byte, 2048)}) + + d1 := seedLibraryBytesItem(t, lib, filepath.Join(lib.CacheDir(), "bilibili", "5001", "dynamics", "dyn_multi_1"), library.ItemMetadata{ + Version: 1, Site: "bilibili", Kind: "dynamic", ID: "dyn_multi_1", Title: "多图动态一", PubTs: 1700000300, + Author: library.ItemAuthor{Site: "bilibili", Mid: 5001, UID: "5001", Name: "作者甲"}, + Videos: []string{"BV1uiexcl1", "BV1uishr02"}, + Media: []library.MediaFile{ + {Role: "image", Path: "images/01.png"}, + {Role: "image", Path: "images/02.png"}, + }, + }, map[string][]byte{ + "images/01.png": []byte("fake-png-1"), + "images/02.png": []byte("fake-png-2"), + }) + + d2 := seedLibraryBytesItem(t, lib, filepath.Join(lib.CacheDir(), "bilibili", "5001", "dynamics", "dyn_multi_2"), library.ItemMetadata{ + Version: 1, Site: "bilibili", Kind: "dynamic", ID: "dyn_multi_2", Title: "单图动态二", PubTs: 1700000290, + Author: library.ItemAuthor{Site: "bilibili", Mid: 5001, UID: "5001", Name: "作者甲"}, + Videos: []string{"BV1uiexcl1"}, + Media: []library.MediaFile{{Role: "image", Path: "images/01.png"}}, + }, map[string][]byte{"images/01.png": []byte("fake-png-3")}) + + // Unselected dynamic D3 keeping V_shared alive. + d3 := seedLibraryBytesItem(t, lib, filepath.Join(lib.CacheDir(), "bilibili", "5001", "dynamics", "dyn_keep_3"), library.ItemMetadata{ + Version: 1, Site: "bilibili", Kind: "dynamic", ID: "dyn_keep_3", Title: "保留动态三", PubTs: 1700000280, + Author: library.ItemAuthor{Site: "bilibili", Mid: 5001, UID: "5001", Name: "作者甲"}, + Videos: []string{"BV1uishr02"}, + Media: []library.MediaFile{{Role: "image", Path: "images/01.png"}}, + }, map[string][]byte{"images/01.png": []byte("fake-png-4")}) + + guard := &libraryOfflineGuardBackend{BackendAPI: realBackend} + app.backend = guard + app.RefreshData() + app.Navigate(RouteLibrary) + + tt := ui.NewTester(app.View, 1280, 860) + tt.Frame() + + // Enter multi-select via header toggle button. + if err := tt.Click("媒体库多选"); err != nil { + t.Fatalf("click multi-select toggle: %v", err) + } + tt.Frame() + if !app.LibrarySelectMode { + t.Fatal("LibrarySelectMode not enabled") + } + if _, ok := tt.Find("媒体库批量操作栏"); !ok { + t.Fatal("batch action bar missing in multi-select mode") + } + // Card "⋯" menus must be hidden in multi-select mode. + if _, found := tt.Find("媒体更多:" + d1.ItemKey); found { + t.Fatal("card ⋯ menu should be hidden in multi-select mode") + } + + // Clicking tile 1 of multi-tile dynamic d1 selects d1.ItemKey (without opening viewer) + // and visually syncs BOTH tile 1 and tile 2! + if err := tt.Click("媒体缩略图 " + d1.ItemKey); err != nil { + t.Fatalf("click tile 1 of d1: %v", err) + } + tt.Frame() + if app.ImageViewer.Open || app.PlayerOverlay.Open { + t.Fatal("clicking a card in multi-select mode must not open viewer/player") + } + if app.librarySelectedCount() != 1 || !app.LibrarySelectedKeys[d1.ItemKey] { + t.Fatalf("expected 1 selected item (%s), got %v", d1.ItemKey, app.LibrarySelectedKeys) + } + if _, ok := tt.Find("已选媒体:" + d1.ItemKey); !ok { + t.Fatal("tile 1 missing selected badge") + } + if _, ok := tt.Find("已选媒体:" + d1.ItemKey + ":images/02.png"); !ok { + t.Fatal("tile 2 of same multi-tile item did not stay visually synced") + } + + // Clicking tile 2 toggles d1 OFF and unchecks both tiles. + if err := tt.Click("媒体缩略图 " + d1.ItemKey + ":images/02.png"); err != nil { + t.Fatalf("click tile 2 of d1: %v", err) + } + tt.Frame() + if app.librarySelectedCount() != 0 { + t.Fatalf("expected 0 selected items after toggling tile 2, got %d", app.librarySelectedCount()) + } + + // Select all loaded / clear all. + if err := tt.Click("媒体库全选已加载"); err != nil { + t.Fatalf("click select all loaded: %v", err) + } + tt.Frame() + if app.librarySelectedCount() != 5 { + t.Fatalf("expected all 5 loaded items selected, got %d", app.librarySelectedCount()) + } + if _, ok := tt.Find("媒体库取消全选"); !ok { + t.Fatal("expected 取消全选 button after selecting all loaded items") + } + if err := tt.Click("媒体库取消全选"); err != nil { + t.Fatalf("click clear all: %v", err) + } + tt.Frame() + if app.librarySelectedCount() != 0 { + t.Fatalf("expected 0 selected items after clear all, got %d", app.librarySelectedCount()) + } + + // Verify responsive widths 720, 1000, 1280 have zero horizontal overflow with batch bar active. + app.toggleLibraryItemSelection(d1.ItemKey) + app.toggleLibraryItemSelection(d2.ItemKey) + for _, w := range []int{720, 1000, 1280} { + rt := ui.NewTester(app.View, w, 860) + rt.Frame() + centerRect, okC := rt.Find("中栏内容") + barRect, okB := rt.Find("媒体库批量操作栏") + if !okC || !okB { + t.Fatalf("width %d missing center or batch bar: okC=%v okB=%v", w, okC, okB) + } + if centerRect.X+centerRect.W > float32(w)+0.5 || barRect.X+barRect.W > float32(w)+0.5 { + t.Fatalf("width %d horizontal overflow: center=%+v bar=%+v", w, centerRect, barRect) + } + for _, lbl := range []string{"媒体库批量导出", "媒体库批量删除", "退出多选"} { + r, ok := rt.Find(lbl) + if !ok || r.X+r.W > float32(w)+0.5 { + t.Fatalf("width %d batch button %q clipped or missing: ok=%v rect=%+v", w, lbl, ok, r) + } + } + } + + // Batch Export: opens export modal pre-selected to "selected" scope ("已选 2 项"), exports ONLY d1 & d2. + tt.Frame() + if err := tt.Click("媒体库批量导出"); err != nil { + t.Fatalf("click batch export: %v", err) + } + tt.Frame() + if !app.Transfer.ExportOpen || app.Transfer.ExportScope != "selected" { + t.Fatalf("expected ExportOpen=true ExportScope=selected, got open=%v scope=%q", app.Transfer.ExportOpen, app.Transfer.ExportScope) + } + if !tt.HasText("已选 2 项") { + t.Fatal("export dialog missing 已选 2 项 scope text") + } + // Esc closes export dialog WITHOUT exiting multi-select! + tt.Key(0, ui.KeyEscape) + tt.Frame() + if app.Transfer.ExportOpen { + t.Fatal("Esc did not close export dialog") + } + if !app.LibrarySelectMode || app.librarySelectedCount() != 2 { + t.Fatalf("Esc while modal was open must keep multi-select active: mode=%v count=%d", app.LibrarySelectMode, app.librarySelectedCount()) + } + + // Re-open batch export and run real export. + if err := tt.Click("媒体库批量导出"); err != nil { + t.Fatal(err) + } + tt.Frame() + exportDir := filepath.Join(t.TempDir(), "ui-batch-export") + app.Transfer.ExportPath = exportDir + if err := tt.Click("开始导出"); err != nil { + t.Fatalf("click start export: %v", err) + } + tt.Frame() + if app.CurrentRoute != RouteTasks || app.TasksSection != "transfers" { + t.Fatalf("expected navigation to Tasks transfers, got route=%s section=%s", app.CurrentRoute, app.TasksSection) + } + if app.LibrarySelectMode || app.librarySelectedCount() != 0 { + t.Fatal("starting batch export must exit and clear multi-select") + } + deadline := time.Now().Add(10 * time.Second) + var finishedJob *service.TransferJob + for time.Now().Before(deadline) { + for _, j := range realBackend.TransferJobs() { + if j.Kind == "export" && !j.Active() { + cp := j + finishedJob = &cp + break + } + } + if finishedJob != nil { + break + } + time.Sleep(20 * time.Millisecond) + } + if finishedJob == nil || finishedJob.Status != service.TransferDone || finishedJob.Export == nil || finishedJob.Export.Items != 2 { + t.Fatalf("batch export job did not export exactly 2 items: %+v", finishedJob) + } + + // Navigate back to Library, test Esc exiting multi-select when no modal is open, and nav-away clearing. + app.Navigate(RouteLibrary) + app.enterLibrarySelectMode() + app.toggleLibraryItemSelection(d1.ItemKey) + tt.Frame() + tt.Key(0, ui.KeyEscape) + tt.Frame() + if app.LibrarySelectMode || app.librarySelectedCount() != 0 { + t.Fatal("Esc with no modal open must exit multi-select and clear selection") + } + + app.enterLibrarySelectMode() + app.toggleLibraryItemSelection(d1.ItemKey) + app.Navigate(RouteHome) + if app.LibrarySelectMode || app.librarySelectedCount() != 0 { + t.Fatal("navigating away from Library must exit multi-select and clear selection") + } + + // Batch Delete Confirmation & Execution: select d1 + d2 (exclusively holding vExcl, sharing vShared with unselected d3). + app.Navigate(RouteLibrary) + app.enterLibrarySelectMode() + app.toggleLibraryItemSelection(d1.ItemKey) + app.toggleLibraryItemSelection(d2.ItemKey) + tt.Frame() + if err := tt.Click("媒体库批量删除"); err != nil { + t.Fatalf("click batch delete: %v", err) + } + tt.Frame() + if !app.DeleteConfirm.Open || !app.DeleteConfirm.Batch { + t.Fatalf("expected batch delete confirmation open, got %+v", app.DeleteConfirm) + } + for _, wantText := range []string{ + "批量删除缓存确认", + "已选择 2 个媒体库条目", + "同时删除所选动态独占引用的 1 个视频", + "所选动态引用的 1 个视频单独缓存过或还被未选动态引用,将保留", + "安全保留:目录内 1 个不是 TRACE 创建的文件将原样保留", + } { + if !tt.HasText(wantText) { + t.Fatalf("batch delete modal missing text %q", wantText) + } + } + + if err := tt.Click("确认删除"); err != nil { + t.Fatalf("click confirm batch delete: %v", err) + } + tt.Frame() + if app.DeleteConfirm.Open || app.LibrarySelectMode || app.librarySelectedCount() != 0 { + t.Fatalf("batch delete did not cleanly close modal and exit multi-select: open=%v mode=%v count=%d", + app.DeleteConfirm.Open, app.LibrarySelectMode, app.librarySelectedCount()) + } + if !strings.Contains(app.BannerInfo, "保留了 1 个不是 TRACE 创建的文件") { + t.Fatalf("expected BannerInfo to note preserved non-TRACE file, got %q", app.BannerInfo) + } + if _, ok, _ := lib.GetItem(d1.ItemKey); ok { + t.Fatal("d1 should be deleted") + } + if _, ok, _ := lib.GetItem(d2.ItemKey); ok { + t.Fatal("d2 should be deleted") + } + if _, ok, _ := lib.GetItem(vExcl.ItemKey); ok { + t.Fatal("exclusively referenced vExcl should be deleted") + } + if _, ok, _ := lib.GetItem(vShared.ItemKey); !ok { + t.Fatal("vShared referenced by unselected d3 should be preserved") + } + if _, ok, _ := lib.GetItem(d3.ItemKey); !ok { + t.Fatal("unselected d3 should be preserved") + } + if data, err := os.ReadFile(filepath.Join(vExclDir, "my-notes.txt")); err != nil || string(data) != "preserve-me" { + t.Fatalf("user file my-notes.txt was not preserved: err=%v data=%q", err, string(data)) + } + if guard.netCalls.Load() != 0 { + t.Fatalf("offline library batch operations triggered %d network calls (want 0)", guard.netCalls.Load()) + } +} diff --git a/internal/ui/library_view.go b/internal/ui/library_view.go index cf770de..afcf1d7 100644 --- a/internal/ui/library_view.go +++ b/internal/ui/library_view.go @@ -66,11 +66,177 @@ func (a *App) libraryTiles() []libraryTile { return tiles } +func (a *App) enterLibrarySelectMode() { + a.LibrarySelectMode = true + if a.LibrarySelectedKeys == nil { + a.LibrarySelectedKeys = make(map[string]bool) + } + a.ExpandedItemKey = "" + a.Transfer.MenuOpen = false +} + +func (a *App) exitLibrarySelectMode() { + a.LibrarySelectMode = false + a.clearLibrarySelection() +} + +func (a *App) clearLibrarySelection() { + if a.LibrarySelectedKeys != nil { + clear(a.LibrarySelectedKeys) + } +} + +func (a *App) toggleLibraryItemSelection(itemKey string) { + itemKey = strings.TrimSpace(itemKey) + if itemKey == "" { + return + } + if a.LibrarySelectedKeys == nil { + a.LibrarySelectedKeys = make(map[string]bool) + } + if a.LibrarySelectedKeys[itemKey] { + delete(a.LibrarySelectedKeys, itemKey) + } else { + a.LibrarySelectedKeys[itemKey] = true + } +} + +func (a *App) libraryVisibleItemKeys(tiles []libraryTile) []string { + keys := make([]string, 0, len(tiles)) + seen := make(map[string]bool, len(tiles)) + for _, t := range tiles { + if t.item.ItemKey == "" || seen[t.item.ItemKey] { + continue + } + seen[t.item.ItemKey] = true + keys = append(keys, t.item.ItemKey) + } + return keys +} + +func (a *App) selectedLibraryItemKeys() []string { + if len(a.LibrarySelectedKeys) == 0 { + return nil + } + out := make([]string, 0, len(a.LibrarySelectedKeys)) + seen := make(map[string]bool, len(a.LibrarySelectedKeys)) + for _, it := range a.LibraryItems { + if a.LibrarySelectedKeys[it.ItemKey] && !seen[it.ItemKey] { + seen[it.ItemKey] = true + out = append(out, it.ItemKey) + } + } + var extra []string + for k, ok := range a.LibrarySelectedKeys { + if ok && k != "" && !seen[k] { + extra = append(extra, k) + } + } + if len(extra) > 1 { + sort.Strings(extra) + } + out = append(out, extra...) + return out +} + +func (a *App) librarySelectedCount() int { + n := 0 + for k, ok := range a.LibrarySelectedKeys { + if ok && k != "" { + n++ + } + } + return n +} + +func (a *App) librarySelectedStats() (count int, totalBytes int64) { + if len(a.LibrarySelectedKeys) == 0 { + return 0, 0 + } + seen := make(map[string]bool, len(a.LibrarySelectedKeys)) + for _, it := range a.LibraryItems { + if a.LibrarySelectedKeys[it.ItemKey] && !seen[it.ItemKey] { + seen[it.ItemKey] = true + count++ + totalBytes += it.TotalBytes + } + } + for k, ok := range a.LibrarySelectedKeys { + if ok && k != "" && !seen[k] { + seen[k] = true + count++ + } + } + return count, totalBytes +} + +func (a *App) renderLibraryBatchBar(c *ui.Context, tiles []libraryTile) { + selectedCount, selectedBytes := a.librarySelectedStats() + visibleKeys := a.libraryVisibleItemKeys(tiles) + allLoadedSelected := len(visibleKeys) > 0 + for _, k := range visibleKeys { + if !a.LibrarySelectedKeys[k] { + allLoadedSelected = false + break + } + } + summaryText := "已选 0 项" + if selectedCount > 0 { + summaryText = fmt.Sprintf("已选 %d 项 · %s", selectedCount, FormatBytes(selectedBytes)) + } + ui.Row(c). + Label("媒体库批量操作栏"). + FillWidth(). + Padding(8, 16). + Gap(8). + Wrap(). + Shrink(0). + AlignItems(ui.Center). + Justify(ui.SpaceBetween). + Background(ColorBgPanel). + BorderWidth(0, 0, 1, 0). + BorderColor(ColorBorder). + ClipX(). + Children(func() { + ui.Text(c, summaryText).FontSize(13).FontWeight(600).TextColor(ColorTextMain).SingleLine() + ui.Row(c).Gap(6).Wrap().AlignItems(ui.Center).ClipX().Children(func() { + if allLoadedSelected { + if OutlinePillButton(c, "取消全选", "媒体库取消全选").Clicked() { + a.clearLibrarySelection() + } + } else { + if OutlinePillButton(c, "全选已加载", "媒体库全选已加载").Disabled(len(visibleKeys) == 0).Clicked() && len(visibleKeys) > 0 { + if a.LibrarySelectedKeys == nil { + a.LibrarySelectedKeys = make(map[string]bool, len(visibleKeys)) + } + for _, k := range visibleKeys { + a.LibrarySelectedKeys[k] = true + } + } + } + if AccentPillButton(c, "批量导出", "媒体库批量导出").Disabled(selectedCount == 0).Clicked() && selectedCount > 0 { + a.openBatchExportDialog() + } + if DangerOutlinePillButton(c, "批量删除", "媒体库批量删除").Disabled(selectedCount == 0).Clicked() && selectedCount > 0 { + a.requestLibraryBatchDelete() + } + if OutlinePillButton(c, "退出多选", "退出多选").Clicked() { + a.exitLibrarySelectMode() + } + }) + }) +} + func (a *App) renderLibraryRoute(c *ui.Context) { if a.Transfer.ImportPage { a.renderImportPage(c) return } + if a.LibrarySelectMode && !a.hasOpenModalOverlay() && !a.Transfer.MenuOpen && a.ExpandedItemKey == "" { + if c.Shortcut(0, ui.KeyEscape) { + a.exitLibrarySelectMode() + } + } // The kinds and sources are in the context panel; a narrow window // without it has them here (DEC-039). if !a.panelShown { @@ -80,11 +246,11 @@ func (a *App) renderLibraryRoute(c *ui.Context) { {Key: "video", Text: "视频", AccessLabel: "筛选类型:视频"}, {Key: "live", Text: "直播录像", AccessLabel: "筛选类型:直播录制"}, {Key: "forward", Text: "转发", AccessLabel: "筛选类型:转发"}, - }, func(key string) { a.LibraryKindFilter = key; a.reloadLibraryItems() }) + }, func(key string) { a.LibraryKindFilter = key; a.selectLibraryFilter() }) ui.Row(c).FillWidth().Padding(6, 16, 0, 16).Children(func() { renderThreeSegmentSiteFilter(c, "媒体库站点筛选:", a.LibrarySiteFilter, func(next string) { a.LibrarySiteFilter = normalizeSiteFilter(next) - a.reloadLibraryItems() + a.selectLibraryFilter() }) }) } @@ -98,10 +264,12 @@ func (a *App) renderLibraryRoute(c *ui.Context) { st.librarySearchDirty = true } else { st.librarySearchDirty = false + a.clearLibrarySelection() a.reloadLibraryItems() } } else if st.librarySearchDirty && !input.Composing() { st.librarySearchDirty = false + a.clearLibrarySelection() a.reloadLibraryItems() } a.renderLibraryRefreshButton(c) @@ -110,55 +278,66 @@ func (a *App) renderLibraryRoute(c *ui.Context) { } }) if a.LibraryAuthorMenu && !a.panelShown { - ui.Scroll(c).FillWidth().Height(220).Gap(4).Children(func() { - if OutlinePillButton(c, "全部作者", "清除UP主筛选").Clicked() { - a.LibraryCreatorMid = 0 - a.LibraryAuthorKey = "" - a.LibrarySubFilter = "" - a.LibraryAuthorMenu = false - a.reloadLibraryItems() - } - ownedKeys := make(map[string]bool) - ownedMids := make(map[int64]bool) - for _, sub := range a.Subscriptions { - for _, account := range sub.Accounts { - normSite := normalizeSiteIDUI(account.Site) - uid := strings.TrimSpace(account.UID) - if uid != "" { - ownedKeys[normSite+":"+uid] = true - } - if normSite == "bilibili" { - if id, err := strconv.ParseInt(uid, 10, 64); err == nil && id > 0 { - ownedMids[id] = true - } - } - } - if AccentOutlinePillButton(c, "订阅:"+sub.Name, "媒体库订阅筛选:"+sub.ID).Clicked() { - a.LibrarySubFilter = sub.ID + panelRows := a.libraryPanelRows() + ui.Column(c).FillWidth().Gap(6).ClipX().Children(func() { + ui.Row(c).FillWidth().AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(8).ClipX().Children(func() { + if OutlinePillButton(c, "全部作者", "清除UP主筛选").Clicked() { a.LibraryCreatorMid = 0 a.LibraryAuthorKey = "" + a.LibrarySubFilter = "" a.LibraryAuthorMenu = false - a.reloadLibraryItems() - } - } - for _, author := range stats.Authors { - aSite := normalizeSiteIDUI(author.Site) - aUID := strings.TrimSpace(author.UID) - if aUID == "" && author.Mid > 0 { - aUID = strconv.FormatInt(author.Mid, 10) + a.selectLibraryFilter() } - aKey := aSite + ":" + aUID - if ownedKeys[aKey] || (aSite == "bilibili" && ownedMids[author.Mid]) { - continue - } - btnLabel := fmt.Sprintf("按UP主筛选 %d", author.Mid) - if aSite != "bilibili" || author.Mid <= 0 { - btnLabel = "按作者筛选 " + aKey - } - ui.Row(c).FillWidth().Gap(8).AlignItems(ui.Center).Children(func() { - // Offline library view: use local avatar or initial fallback only (0 remote requests). - a.renderAccountAvatar(c, aSite, author.Name, aUID, author.Mid, 28, false, "", nil) - if OutlinePillButton(c, author.Name, btnLabel).Clicked() { + a.renderLibrarySourceSortToggle(c) + }) + ui.Scroll(c).FillWidth().Height(220).Gap(4).Children(func() { + for _, row := range panelRows { + usageText := librarySourceUsageText(row.itemCount, row.totalBytes) + if row.isSub { + sub := row.sub + active := a.LibrarySubFilter == sub.ID + pSite, pUID := subscriptionPrimarySiteAndUID(sub) + if panelItem(c, "媒体库订阅筛选:"+sub.ID, active, func() { + a.renderOfflineAccountAvatar(c, pSite, sub.Name, pUID, sub.Mid, 24, "", nil) + ui.Column(c).Grow(1).Gap(1).ClipX().Children(func() { + nameCol := ColorTextMain + if active { + nameCol = ColorAccent + } + ui.Text(c, "订阅:"+sub.Name).FontSize(13).FontWeight(500).TextColor(nameCol).SingleLine() + ui.Text(c, usageText).FontSize(11).TextColor(ColorTextMuted).SingleLine() + }) + }) { + a.LibrarySubFilter = sub.ID + a.LibraryCreatorMid = 0 + a.LibraryAuthorKey = "" + a.LibraryAuthorMenu = false + a.selectLibraryFilter() + } + continue + } + author := row.author + aSite := row.site + aKey := row.authorKey + btnLabel := fmt.Sprintf("按UP主筛选 %d", author.Mid) + active := aSite == "bilibili" && author.Mid > 0 && a.LibraryCreatorMid == author.Mid && a.LibraryAuthorKey == "" + if aSite != "bilibili" || author.Mid <= 0 { + btnLabel = "按作者筛选 " + aKey + active = a.LibraryAuthorKey == aKey + } else if a.LibraryAuthorKey == aKey { + active = true + } + if panelItem(c, btnLabel, active, func() { + a.renderOfflineAccountAvatar(c, aSite, author.Name, row.uid, author.Mid, 24, "", nil) + ui.Column(c).Grow(1).Gap(1).ClipX().Children(func() { + nameCol := ColorTextMain + if active { + nameCol = ColorAccent + } + ui.Text(c, author.Name).FontSize(13).FontWeight(500).TextColor(nameCol).SingleLine() + ui.Text(c, usageText).FontSize(11).TextColor(ColorTextMuted).SingleLine() + }) + }) { if aSite == "bilibili" && author.Mid > 0 { a.LibraryCreatorMid = author.Mid a.LibraryAuthorKey = "" @@ -168,16 +347,20 @@ func (a *App) renderLibraryRoute(c *ui.Context) { } a.LibrarySubFilter = "" a.LibraryAuthorMenu = false - a.reloadLibraryItems() + a.selectLibraryFilter() } - }) - } + } + }) }) } if !a.panelShown { ui.Text(c, fmt.Sprintf("共 %d 项缓存 · 占用 %s", stats.Items, FormatBytes(stats.Bytes))).FontSize(12).TextColor(ColorTextMuted) } }) + tiles := a.libraryTiles() + if a.LibrarySelectMode { + a.renderLibraryBatchBar(c, tiles) + } if a.LibraryError != "" { ui.Box(c).FillWidth().Padding(8, 16, 0, 16).Children(func() { renderErrorBanner(c, "", a.LibraryError, func() { @@ -187,7 +370,6 @@ func (a *App) renderLibraryRoute(c *ui.Context) { }) }) } - tiles := a.libraryTiles() if len(tiles) == 0 { ui.Column(c).FillWidth().Grow(1).Padding(40, 16).Gap(10).Center().Children(func() { ui.Text(c, "还没有符合筛选的媒体").FontSize(16).FontWeight(600).TextColor(ColorTextMain) @@ -256,6 +438,7 @@ func (a *App) renderLibraryTile(c *ui.Context, tile libraryTile, thumbSize float tileKey += ":" + tile.file.Path } menuOpen := a.ExpandedItemKey == tileKey || (tile.index == 0 && a.ExpandedItemKey == item.ItemKey) + selected := a.LibrarySelectMode && a.LibrarySelectedKeys[item.ItemKey] ui.Column(c).Grow(1).Basis(0).Gap(8).ClipX().Children(func() { label := "媒体缩略图 " + tileKey @@ -264,9 +447,34 @@ func (a *App) renderLibraryTile(c *ui.Context, tile libraryTile, thumbSize float button.Children(func() { // Everything in the library is cached: no status dot (DEC-039). a.renderMediaThumb(c, item.ItemKey, rel, item.Title, FormatDuration(tile.file.Duration), "", tile.video, 0, thumbSize) + if a.LibrarySelectMode { + if selected { + ui.Box(c).Absolute().Left(0).Top(0).Right(0).Bottom(0).Radius(12). + Background(ColorAccent.Alpha(0.10)). + Border(2.5, ColorAccent) + } + badge := ui.Box(c).Absolute().Top(8).Left(8).Size(22, 22).Radius(6) + if selected { + badge.Label("已选媒体:"+tileKey).Background(ColorAccent).Border(1.5, ColorWhite) + badge.Draw(func(p *ui.Painter, r ui.Rect) { + s := func(v float32) float32 { return v * r.W / 18.0 } + mark := (&ui.Path{}). + MoveTo(r.X+s(4.2), r.Y+s(9.2)). + LineTo(r.X+s(7.6), r.Y+s(12.6)). + LineTo(r.X+s(13.8), r.Y+s(5.6)) + p.StrokePath(mark, 2.2, ColorWhite) + }) + } else { + badge.Label("未选媒体:"+tileKey).Background(ui.RGBA(0, 0, 0, 0.36)).Border(1.5, ColorWhite) + } + } }) if button.Clicked() { - a.openLibraryTile(tile) + if a.LibrarySelectMode { + a.toggleLibraryItemSelection(item.ItemKey) + } else { + a.openLibraryTile(tile) + } } authorLine := item.Author.Name @@ -283,30 +491,40 @@ func (a *App) renderLibraryTile(c *ui.Context, tile libraryTile, thumbSize float ui.Column(c).Grow(1).Gap(2).ClipX().Children(func() { title := ui.ButtonBase(c).Label("打开媒体:" + tileKey).FillWidth().Justify(ui.Start).AlignItems(ui.Start) title.Children(func() { - ui.Text(c, item.Title).FontSize(14).LineHeight(LineHeightHeading).FontWeight(600).MaxLines(2).TextColor(ColorTextMain) + titleCol := ColorTextMain + if selected { + titleCol = ColorAccent + } + ui.Text(c, item.Title).FontSize(14).LineHeight(LineHeightHeading).FontWeight(600).MaxLines(2).TextColor(titleCol) }) if title.Clicked() { - a.openLibraryTile(tile) + if a.LibrarySelectMode { + a.toggleLibraryItemSelection(item.ItemKey) + } else { + a.openLibraryTile(tile) + } } ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(4).ClipX().Children(func() { ui.Text(c, authorLine).FontSize(12).SingleLine().TextColor(ColorTextMuted).Shrink(1) renderSiteSmallBadgeWithDot(c, item.Site, "媒体库站点:"+tileKey) }) }) - open := menuOpen - MoreMenuButton(c, "媒体更多:"+tileKey, 28, &open, func(m *ui.Menu) { - if m.Item("详情").Chosen() { - a.OpenLibraryItemDetail(item) - } - if m.Item("在资源管理器中显示").Chosen() { - a.showError(a.backend.OpenItemFolder(item.ItemKey)) - } - m.Separator() - if m.Item("删除").Danger().Chosen() { - a.requestLibraryDelete(item) - } - }) - keyedMenuOpen(&a.ExpandedItemKey, tileKey, open) + if !a.LibrarySelectMode { + open := menuOpen + MoreMenuButton(c, "媒体更多:"+tileKey, 28, &open, func(m *ui.Menu) { + if m.Item("详情").Chosen() { + a.OpenLibraryItemDetail(item) + } + if m.Item("在资源管理器中显示").Chosen() { + a.showError(a.backend.OpenItemFolder(item.ItemKey)) + } + m.Separator() + if m.Item("删除").Danger().Chosen() { + a.requestLibraryDelete(item) + } + }) + keyedMenuOpen(&a.ExpandedItemKey, tileKey, open) + } }) }) } @@ -331,6 +549,45 @@ func (a *App) requestLibraryDelete(item library.ItemMetadata) { a.DeleteConfirm = DeleteConfirmState{ Open: true, Item: item, + TargetKeys: append([]string(nil), plan.TargetKeys...), + Plan: plan, + FileCount: len(plan.RegisteredFiles), + TotalBytes: total, + DeleteFiles: true, + } +} + +// requestLibraryBatchDelete builds a unified DeletePlan for all selected +// library items (handling shared referenced videos across the entire batch) +// and opens the consolidated confirmation modal. +func (a *App) requestLibraryBatchDelete() { + keys := a.selectedLibraryItemKeys() + if len(keys) == 0 { + return + } + plan, err := a.backend.PlanDeleteBatch(keys) + if err != nil { + a.showError(err) + return + } + loadedBytes := make(map[string]int64, len(a.LibraryItems)) + for _, it := range a.LibraryItems { + loadedBytes[it.ItemKey] = it.TotalBytes + } + var total int64 + for _, key := range plan.ItemKeys { + if b, ok := loadedBytes[key]; ok { + total += b + continue + } + if ref, ok, err := a.backend.GetLibraryItemMetaOnly(key); err == nil && ok { + total += ref.TotalBytes + } + } + a.DeleteConfirm = DeleteConfirmState{ + Open: true, + Batch: true, + TargetKeys: append([]string(nil), plan.TargetKeys...), Plan: plan, FileCount: len(plan.RegisteredFiles), TotalBytes: total, diff --git a/internal/ui/navigation.go b/internal/ui/navigation.go index eead284..7c3d547 100644 --- a/internal/ui/navigation.go +++ b/internal/ui/navigation.go @@ -159,6 +159,7 @@ func (a *App) closeAllModalsAndOverlays() { a.SubFile.ExportOpen = false a.SubFile.ImportOpen = false a.subImportGen++ + a.exitLibrarySelectMode() } func (a *App) handleSiteAccountLoss(evSite, kind string) { @@ -325,6 +326,9 @@ func (a *App) navigate(rawRoute string, fromBack bool) { if route != RouteLibraryItem { a.CurrentLibraryDetail = nil } + if prevRoute == RouteLibrary && route != RouteLibrary { + a.exitLibrarySelectMode() + } if route == RouteHome && a.CurrentRoute == RouteHome && a.HomeActorFilter != nil { a.closeHomeActorFeed() } @@ -606,6 +610,7 @@ func (a *App) selectLibraryFilter() { a.CurrentRoute = RouteLibrary a.CurrentLibraryDetail = nil } + a.clearLibrarySelection() a.reloadLibraryItems() } diff --git a/internal/ui/overlays.go b/internal/ui/overlays.go index 3833b20..0e85701 100644 --- a/internal/ui/overlays.go +++ b/internal/ui/overlays.go @@ -150,21 +150,41 @@ func (a *App) renderRemotePushXConfirmOverlay(c *ui.Context, w, h float32) { func (a *App) renderDeleteConfirmOverlay(c *ui.Context, w, h float32) { cardW := min(float32(480), max(float32(300), w-40)) renderDialog(c, &a.DeleteConfirm.Open, "关闭删除确认对话框(点击空白处)", "删除确认对话框", cardW, 0, nil, func() { - ui.Text(c, "删除缓存确认").FontSize(18).FontWeight(600).TextColor(ColorTextMain).SingleLine() - ui.Text(c, fmt.Sprintf("%s:%s", itemKindLabel(a.DeleteConfirm.Item.Kind), deleteConfirmTitle(a.DeleteConfirm.Item))). + isBatch := a.DeleteConfirm.Batch + targetCount := len(a.DeleteConfirm.TargetKeys) + if targetCount == 0 { + targetCount = len(a.DeleteConfirm.Plan.TargetKeys) + } + if targetCount == 0 { + targetCount = 1 + } + title := "删除缓存确认" + subtitle := fmt.Sprintf("%s:%s", itemKindLabel(a.DeleteConfirm.Item.Kind), deleteConfirmTitle(a.DeleteConfirm.Item)) + if isBatch { + title = "批量删除缓存确认" + subtitle = fmt.Sprintf("已选择 %d 个媒体库条目", targetCount) + } + ui.Text(c, title).FontSize(18).FontWeight(600).TextColor(ColorTextMain).SingleLine() + ui.Text(c, subtitle). FontSize(14).FontWeight(600).TextColor(ColorTextMain).MaxLines(2) ui.Text(c, fmt.Sprintf("预计清理已登记缓存文件:%d 个(共 %s)", a.DeleteConfirm.FileCount, FormatBytes(a.DeleteConfirm.TotalBytes))). FontSize(13).TextColor(ColorTextMuted).MaxLines(2) - if n := len(a.DeleteConfirm.Plan.ItemKeys) - 1; n > 0 { - ui.Text(c, fmt.Sprintf("同时删除这条动态引用的 %d 个视频(没有单独缓存,也没有别的动态引用)", n)). - FontSize(13).TextColor(ColorTextMuted).MaxLines(2) + if extraVideos := len(a.DeleteConfirm.Plan.ItemKeys) - targetCount; extraVideos > 0 { + extraMsg := fmt.Sprintf("同时删除这条动态引用的 %d 个视频(没有单独缓存,也没有别的动态引用)", extraVideos) + if isBatch { + extraMsg = fmt.Sprintf("同时删除所选动态独占引用的 %d 个视频(没有单独缓存,也没有其他未选动态引用)", extraVideos) + } + ui.Text(c, extraMsg).FontSize(13).TextColor(ColorTextMuted).MaxLines(2) } if len(a.DeleteConfirm.Plan.PreservedSharedVideos) > 0 { + sharedMsg := fmt.Sprintf("这条动态引用的 %d 个视频单独缓存过或还被别的动态引用,将保留", len(a.DeleteConfirm.Plan.PreservedSharedVideos)) + if isBatch { + sharedMsg = fmt.Sprintf("所选动态引用的 %d 个视频单独缓存过或还被未选动态引用,将保留", len(a.DeleteConfirm.Plan.PreservedSharedVideos)) + } ui.Box(c).FillWidth().Padding(8, 12).Radius(8).Background(ColorInfoBlueBg).Children(func() { - ui.Text(c, fmt.Sprintf("这条动态引用的 %d 个视频单独缓存过或还被别的动态引用,将保留", len(a.DeleteConfirm.Plan.PreservedSharedVideos))). - FontSize(12).FontWeight(600).TextColor(ColorInfoBlue).MaxLines(2) + ui.Text(c, sharedMsg).FontSize(12).FontWeight(600).TextColor(ColorInfoBlue).MaxLines(2) }) } if len(a.DeleteConfirm.Plan.PreservedUserFiles) > 0 { @@ -192,11 +212,31 @@ func (a *App) renderDeleteConfirmOverlay(c *ui.Context, w, h float32) { a.DeleteConfirm.Open = false } if AccentPillButton(c, "确认删除", "确认删除").Clicked() { + if isBatch { + keys := append([]string(nil), a.DeleteConfirm.TargetKeys...) + plan, err := a.backend.DeleteLibraryItems(keys, a.DeleteConfirm.DeleteFiles) + if err != nil { + a.showError(err) + } else { + if len(plan.PreservedUserFiles) > 0 { + a.BannerInfo = fmt.Sprintf("已删除 %d 个条目,并保留了 %d 个不是 TRACE 创建的文件", targetCount, len(plan.PreservedUserFiles)) + } else { + a.BannerInfo = fmt.Sprintf("已批量删除 %d 个条目", targetCount) + } + a.exitLibrarySelectMode() + } + a.DeleteConfirm.Open = false + a.RefreshData() + return + } deletedKey := a.DeleteConfirm.Item.ItemKey err := a.backend.DeleteLibraryItem(deletedKey, a.DeleteConfirm.DeleteFiles) if err != nil { a.showError(err) } else { + if a.LibrarySelectedKeys != nil { + delete(a.LibrarySelectedKeys, deletedKey) + } if len(a.DeleteConfirm.Plan.PreservedUserFiles) > 0 { a.BannerInfo = fmt.Sprintf("已删除缓存记录,并保留了 %d 个不是 TRACE 创建的文件", len(a.DeleteConfirm.Plan.PreservedUserFiles)) } else { diff --git a/internal/ui/shell.go b/internal/ui/shell.go index b32d398..0d86e22 100644 --- a/internal/ui/shell.go +++ b/internal/ui/shell.go @@ -2,6 +2,7 @@ package ui import ( "fmt" + "sort" "strconv" "strings" @@ -355,8 +356,32 @@ func (a *App) renderSubscriptionsPanel(c *ui.Context) { }) } +func librarySourceUsageText(itemCount int, totalBytes int64) string { + if itemCount == 0 && totalBytes == 0 { + return "0 项" + } + return fmt.Sprintf("%d 项 · %s", itemCount, FormatBytes(totalBytes)) +} + +func (a *App) renderOfflineAccountAvatar(c *ui.Context, siteID, name, uid string, mid int64, size float32, label string, onClick func()) ui.Element { + normSite := normalizeSiteIDUI(siteID) + seed := mid + if seed <= 0 { + seed = accountSeedHash(normSite, firstNonEmptyStrUI(uid, name)) + } + lookupUID := strings.TrimSpace(uid) + if lookupUID == "" && normSite == "bilibili" && mid > 0 { + lookupUID = strconv.FormatInt(mid, 10) + } + bmp := a.lookupAccountAvatarBitmap(normSite, lookupUID) + // Pure-offline Library views never fall back to remote URLs. + a.pendingLocalAvatar = true + return a.renderAvatarWithBitmap(c, name, seed, size, false, label, onClick, bmp) +} + func (a *App) libraryPanelRows() []libraryPanelRow { stats := a.libraryStatistics + siteFilter := normalizeSiteFilter(a.LibrarySiteFilter) var subsFirst *subscription.Subscription if len(a.Subscriptions) > 0 { subsFirst = &a.Subscriptions[0] @@ -372,20 +397,62 @@ func (a *App) libraryPanelRows() []libraryPanelRow { statsRev: a.statsRev, authorsN: len(stats.Authors), authorsFirst: authorsFirst, + siteFilter: siteFilter, + subFilter: a.LibrarySubFilter, + sortBySize: a.LibrarySourceSortBySize, } if a.libraryPanelValid && a.libraryPanelSig == sig { return a.libraryPanelRowsCache } + + type authorUsage struct { + count int + bytes int64 + } + usageByKey := make(map[string]authorUsage, len(stats.Authors)) + for _, author := range stats.Authors { + aSite := normalizeSiteIDUI(author.Site) + if siteFilter != "all" && aSite != siteFilter { + continue + } + aUID := strings.TrimSpace(author.UID) + if aUID == "" && author.Mid > 0 { + aUID = strconv.FormatInt(author.Mid, 10) + } + if aUID == "" { + continue + } + k := aSite + ":" + aUID + u := usageByKey[k] + u.count += author.ItemCount + u.bytes += author.TotalBytes + usageByKey[k] = u + } + ownedKeys := make(map[string]bool, len(a.Subscriptions)*2) ownedMids := make(map[int64]bool, len(a.Subscriptions)) rows := make([]libraryPanelRow, 0, len(a.Subscriptions)+len(stats.Authors)) for _, sub := range a.Subscriptions { - rows = append(rows, libraryPanelRow{isSub: true, sub: sub}) + seenSubKeys := make(map[string]bool, len(sub.Accounts)) + var subCount int + var subBytes int64 + hasSiteAccount := siteFilter == "all" for _, account := range sub.Accounts { normSite := normalizeSiteIDUI(account.Site) uid := strings.TrimSpace(account.UID) if uid != "" { - ownedKeys[normSite+":"+uid] = true + k := normSite + ":" + uid + ownedKeys[k] = true + if siteFilter == "all" || normSite == siteFilter { + hasSiteAccount = true + if !seenSubKeys[k] { + seenSubKeys[k] = true + if u, ok := usageByKey[k]; ok { + subCount += u.count + subBytes += u.bytes + } + } + } } if normSite == "bilibili" { if id, err := strconv.ParseInt(uid, 10, 64); err == nil && id > 0 { @@ -393,22 +460,77 @@ func (a *App) libraryPanelRows() []libraryPanelRow { } } } + if len(sub.Accounts) == 0 && sub.Mid > 0 { + ownedMids[sub.Mid] = true + k := "bilibili:" + strconv.FormatInt(sub.Mid, 10) + ownedKeys[k] = true + if siteFilter == "all" || siteFilter == "bilibili" { + hasSiteAccount = true + if u, ok := usageByKey[k]; ok { + subCount += u.count + subBytes += u.bytes + } + } + } + if hasSiteAccount || subCount > 0 || a.LibrarySubFilter == sub.ID { + rows = append(rows, libraryPanelRow{ + isSub: true, + sub: sub, + itemCount: subCount, + totalBytes: subBytes, + }) + } } for _, author := range stats.Authors { aSite := normalizeSiteIDUI(author.Site) + if siteFilter != "all" && aSite != siteFilter { + continue + } aUID := strings.TrimSpace(author.UID) if aUID == "" && author.Mid > 0 { aUID = strconv.FormatInt(author.Mid, 10) } aKey := aSite + ":" + aUID - if ownedKeys[aKey] || (aSite == "bilibili" && ownedMids[author.Mid]) { + if ownedKeys[aKey] || (aSite == "bilibili" && author.Mid > 0 && ownedMids[author.Mid]) { continue } rows = append(rows, libraryPanelRow{ - author: author, - site: aSite, - uid: aUID, - authorKey: aKey, + author: author, + site: aSite, + uid: aUID, + authorKey: aKey, + itemCount: author.ItemCount, + totalBytes: author.TotalBytes, + }) + } + if a.LibrarySourceSortBySize { + rowName := func(r libraryPanelRow) string { + if r.isSub { + return r.sub.Name + } + return r.author.Name + } + rowID := func(r libraryPanelRow) string { + if r.isSub { + return "sub:" + r.sub.ID + } + return "author:" + r.authorKey + } + sort.SliceStable(rows, func(i, j int) bool { + if rows[i].totalBytes != rows[j].totalBytes { + return rows[i].totalBytes > rows[j].totalBytes + } + if rows[i].itemCount != rows[j].itemCount { + return rows[i].itemCount > rows[j].itemCount + } + if rows[i].isSub != rows[j].isSub { + return rows[i].isSub + } + ni, nj := rowName(rows[i]), rowName(rows[j]) + if ni != nj { + return ni < nj + } + return rowID(rows[i]) < rowID(rows[j]) }) } a.libraryPanelRowsCache = rows @@ -425,8 +547,36 @@ var libraryPanelKinds = [5]struct{ key, icon, text, label string }{ {"forward", "share", "转发", "筛选类型:转发"}, } +func (a *App) renderLibrarySourceSortToggle(c *ui.Context) { + sortBtn := ui.ButtonBase(c). + Label("媒体库来源按占用空间排序"). + Tooltip("按占用空间从高到低排序"). + Padding(2, 8). + Radius(999). + Shrink(0) + if a.LibrarySourceSortBySize { + sortBtn.Background(ColorAccentBg).Border(1, ColorAccent) + } else { + sortBtn.Background(ColorBgMain).Border(1, ColorBorder) + if sortBtn.Hovered() { + sortBtn.Background(ColorHover) + } + } + sortBtn.Children(func() { + col := ColorTextMuted + if a.LibrarySourceSortBySize { + col = ColorAccent + } + ui.Text(c, "按占用空间").FontSize(11).FontWeight(600).TextColor(col).SingleLine() + }) + if sortBtn.Clicked() { + a.LibrarySourceSortBySize = !a.LibrarySourceSortBySize + } +} + // renderLibraryPanel holds the library's filters: the kind, then the 来源 -// section (site 3-segment switcher + virtualized subscriptions and creators). +// section (site 5-segment switcher + virtualized subscriptions and creators +// with per-source item counts and storage usage). func (a *App) renderLibraryPanel(c *ui.Context) { stats := a.libraryStatistics rows := a.libraryPanelRows() @@ -443,7 +593,10 @@ func (a *App) renderLibraryPanel(c *ui.Context) { } } - panelSection(c, "来源") + ui.Row(c).FillWidth().Padding(14, 10, 4, 10).AlignItems(ui.Center).Justify(ui.SpaceBetween).Gap(6).ClipX().Children(func() { + ui.Text(c, "来源").FontSize(12).FontWeight(500).TextColor(ColorTextMuted).SingleLine() + a.renderLibrarySourceSortToggle(c) + }) ui.Row(c).FillWidth().Padding(2, 2, 4, 2).Children(func() { renderThreeSegmentSiteFilter(c, "媒体库站点筛选:", a.LibrarySiteFilter, func(next string) { a.LibrarySiteFilter = normalizeSiteFilter(next) @@ -474,14 +627,22 @@ func (a *App) renderLibraryPanel(c *ui.Context) { return } row := rows[i] + usageText := librarySourceUsageText(row.itemCount, row.totalBytes) ui.Column(c).FillWidth().Padding(1, 8).Children(func() { if row.isSub { sub := row.sub active := a.LibrarySubFilter == sub.ID if panelItem(c, "媒体库订阅筛选:"+sub.ID, active, func() { pSite, pUID := subscriptionPrimarySiteAndUID(sub) - a.renderAccountAvatar(c, pSite, sub.Name, pUID, sub.Mid, 24, false, "", nil, sub.Face) - panelItemText(c, sub.Name, active) + a.renderOfflineAccountAvatar(c, pSite, sub.Name, pUID, sub.Mid, 24, "", nil) + ui.Column(c).Grow(1).Gap(1).ClipX().Children(func() { + nameCol := ColorTextMain + if active { + nameCol = ColorAccent + } + ui.Text(c, sub.Name).FontSize(13).FontWeight(500).TextColor(nameCol).SingleLine() + ui.Text(c, usageText).FontSize(11).TextColor(ColorTextMuted).SingleLine() + }) }) { a.LibrarySubFilter, a.LibraryCreatorMid, a.LibraryAuthorKey = sub.ID, 0, "" a.selectLibraryFilter() @@ -500,8 +661,15 @@ func (a *App) renderLibraryPanel(c *ui.Context) { active = true } if panelItem(c, label, active, func() { - a.renderAccountAvatar(c, aSite, author.Name, row.uid, author.Mid, 24, false, "", nil, author.Face) - panelItemText(c, author.Name, active) + a.renderOfflineAccountAvatar(c, aSite, author.Name, row.uid, author.Mid, 24, "", nil) + ui.Column(c).Grow(1).Gap(1).ClipX().Children(func() { + nameCol := ColorTextMain + if active { + nameCol = ColorAccent + } + ui.Text(c, author.Name).FontSize(13).FontWeight(500).TextColor(nameCol).SingleLine() + ui.Text(c, usageText).FontSize(11).TextColor(ColorTextMuted).SingleLine() + }) }) { if aSite == "bilibili" && author.Mid > 0 { a.LibraryCreatorMid, a.LibraryAuthorKey, a.LibrarySubFilter = author.Mid, "", "" diff --git a/internal/ui/transfer_view.go b/internal/ui/transfer_view.go index b081c42..c31c187 100644 --- a/internal/ui/transfer_view.go +++ b/internal/ui/transfer_view.go @@ -31,7 +31,7 @@ type TransferUIState struct { // Export dialog. ExportOpen bool ExportPath string - ExportScope string // "all" or "filter" + ExportScope string // "all", "filter", or "selected" ExportErr string Jobs []service.TransferJob @@ -79,6 +79,7 @@ func transferCategoryText(cat transfer.Category) string { } func (a *App) openImportPage() { + a.exitLibrarySelectMode() a.Navigate(RouteLibrary) a.Transfer.ImportPage = true a.Transfer.ImportErr = "" @@ -90,7 +91,17 @@ func (a *App) openImportPage() { func (a *App) openExportDialog() { a.Transfer.ExportOpen = true a.Transfer.ExportErr = "" - if a.Transfer.ExportScope == "" { + if a.Transfer.ExportScope == "" || (a.Transfer.ExportScope == "selected" && a.librarySelectedCount() == 0) { + a.Transfer.ExportScope = "all" + } +} + +func (a *App) openBatchExportDialog() { + a.Transfer.ExportOpen = true + a.Transfer.ExportErr = "" + if a.librarySelectedCount() > 0 { + a.Transfer.ExportScope = "selected" + } else if a.Transfer.ExportScope == "" { a.Transfer.ExportScope = "all" } } @@ -475,26 +486,43 @@ func (a *App) renderExportOverlay(c *ui.Context, w, h float32) { t := &a.Transfer cardW := min(float32(520), max(float32(320), w-40)) filtered := a.libraryFilterActive() + selectedKeys := a.selectedLibraryItemKeys() + selectedLabel := fmt.Sprintf("已选 %d 项", len(selectedKeys)) renderDialog(c, &t.ExportOpen, "关闭导出对话框(点击空白处)", "导出媒体库对话框", cardW, 0, nil, func() { ui.Text(c, "导出媒体库").FontSize(18).FontWeight(600).TextColor(ColorTextMain).SingleLine() ui.Text(c, "复制已完成的文件和 item.json,另一台 TRACE 可以直接导入。正在缓存或录制的条目只导出已完成的部分。"). FontSize(12).TextColor(ColorTextMuted).MaxLines(3) - scope := "全部" - if t.ExportScope == "filter" { - scope = "当前筛选" - } opts := []string{"全部"} if filtered { opts = append(opts, "当前筛选") - } else if scope == "当前筛选" { - scope = "全部" + } + if len(selectedKeys) > 0 { + opts = append(opts, selectedLabel) + } + scope := "全部" + switch t.ExportScope { + case "selected": + if len(selectedKeys) > 0 { + scope = selectedLabel + } else { + t.ExportScope = "all" + } + case "filter": + if filtered { + scope = "当前筛选" + } else { + t.ExportScope = "all" + } } ui.Row(c).FillWidth().Gap(8).AlignItems(ui.Center).Children(func() { ui.Text(c, "范围").FontSize(13).TextColor(ColorTextMain).SingleLine() if ui.Select(c, &scope, opts).Label("导出范围").Changed() { - if scope == "当前筛选" { + switch scope { + case selectedLabel: + t.ExportScope = "selected" + case "当前筛选": t.ExportScope = "filter" - } else { + default: t.ExportScope = "all" } } @@ -509,7 +537,9 @@ func (a *App) renderExportOverlay(c *ui.Context, w, h float32) { } if AccentPillButton(c, "开始导出", "开始导出").Clicked() { filter := library.FeedFilter{} - if scope == "当前筛选" { + if scope == selectedLabel && len(selectedKeys) > 0 { + filter = library.FeedFilter{ItemKeys: selectedKeys} + } else if scope == "当前筛选" { filter = a.libraryExportFilter() } path := strings.Trim(strings.TrimSpace(t.ExportPath), `"`) @@ -517,6 +547,7 @@ func (a *App) renderExportOverlay(c *ui.Context, w, h float32) { t.ExportErr = userErrorText(err) } else { t.ExportOpen, t.ExportErr = false, "" + a.exitLibrarySelectMode() a.refreshTransferJobs() a.Navigate(RouteTasks) a.selectTasksTransfers() diff --git a/internal/ui/views.go b/internal/ui/views.go index 0769d46..b28cec0 100644 --- a/internal/ui/views.go +++ b/internal/ui/views.go @@ -418,7 +418,18 @@ func (a *App) renderRouteHeaderActions(c *ui.Context) { }) case RouteLibrary: if !a.Transfer.ImportPage { - a.renderLibraryMoreMenu(c) + ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() { + if a.LibrarySelectMode { + if AccentOutlinePillButton(c, "多选", "媒体库多选").Clicked() { + a.exitLibrarySelectMode() + } + } else { + if OutlinePillButton(c, "多选", "媒体库多选").Clicked() { + a.enterLibrarySelectMode() + } + } + a.renderLibraryMoreMenu(c) + }) } case RouteTasks: if a.effectiveTasksSection() != "downloads" { diff --git a/tools/uishots/scenes.go b/tools/uishots/scenes.go index 30b6701..70e4b0b 100644 --- a/tools/uishots/scenes.go +++ b/tools/uishots/scenes.go @@ -1797,11 +1797,17 @@ func buildCoreScenes(env *fixtureEnv, app *ui.App) []sceneSpec { { Name: "library", Setup: func() { + app.DeleteConfirm.Open = false + app.Transfer.ExportOpen = false + app.LibrarySelectMode = false + app.LibrarySelectedKeys = map[string]bool{} + app.LibrarySourceSortBySize = false app.LibrarySiteFilter = "all" app.Navigate(ui.RouteLibrary) app.ExpandedItemKey = savedDynamicItem.ItemKey }, RequiredLabels: []string{ + "媒体库多选", "媒体库站点筛选:全部", "媒体库站点筛选:B 站", "媒体库站点筛选:抖音", @@ -1813,16 +1819,49 @@ func buildCoreScenes(env *fixtureEnv, app *ui.App) []sceneSpec { "媒体库站点:" + savedWeiboPost.ItemKey, "媒体库站点:" + savedXPost.ItemKey, }, + PanelRequiredLabels: []string{"媒体库来源按占用空间排序"}, + }, + { + Name: "library-multiselect", + Setup: func() { + app.DeleteConfirm.Open = false + app.Transfer.ExportOpen = false + app.LibrarySiteFilter = "all" + app.LibrarySourceSortBySize = true + app.Navigate(ui.RouteLibrary) + app.ExpandedItemKey = "" + app.LibrarySelectMode = true + app.LibrarySelectedKeys = map[string]bool{ + savedDynamicItem.ItemKey: true, + savedDouyinVideo.ItemKey: true, + } + }, + RequiredLabels: []string{ + "媒体库多选", + "媒体库批量操作栏", + "媒体库批量导出", + "媒体库批量删除", + "退出多选", + "已选媒体:" + savedDynamicItem.ItemKey, + "已选媒体:" + savedDouyinVideo.ItemKey, + }, + PanelRequiredLabels: []string{"媒体库来源按占用空间排序"}, + ForbiddenLabels: []string{"媒体更多:" + savedDynamicItem.ItemKey}, }, { Name: "library-delete", Setup: func() { + app.Transfer.ExportOpen = false + app.LibrarySelectMode = false + app.LibrarySelectedKeys = map[string]bool{} + app.LibrarySourceSortBySize = false app.Navigate(ui.RouteLibrary) app.ExpandedItemKey = "" plan, _ := b.PlanDelete(savedItem.ItemKey) app.DeleteConfirm = ui.DeleteConfirmState{ Open: true, Item: savedItem, + TargetKeys: plan.TargetKeys, Plan: plan, FileCount: len(plan.RegisteredFiles), TotalBytes: savedItem.TotalBytes, @@ -1830,10 +1869,68 @@ func buildCoreScenes(env *fixtureEnv, app *ui.App) []sceneSpec { } }, }, + { + Name: "library-batch-delete", + Setup: func() { + app.Transfer.ExportOpen = false + app.LibrarySiteFilter = "all" + app.LibrarySourceSortBySize = true + app.Navigate(ui.RouteLibrary) + app.ExpandedItemKey = "" + app.LibrarySelectMode = true + app.LibrarySelectedKeys = map[string]bool{ + savedDynamicItem.ItemKey: true, + savedDouyinVideo.ItemKey: true, + } + plan, _ := b.PlanDeleteBatch([]string{savedDynamicItem.ItemKey, savedDouyinVideo.ItemKey}) + var totalBytes int64 + for _, k := range plan.ItemKeys { + if it, ok, err := b.GetLibraryItemMetaOnly(k); err == nil && ok { + totalBytes += it.TotalBytes + } + } + app.DeleteConfirm = ui.DeleteConfirmState{ + Open: true, + Batch: true, + TargetKeys: plan.TargetKeys, + Plan: plan, + FileCount: len(plan.RegisteredFiles), + TotalBytes: totalBytes, + DeleteFiles: true, + } + }, + RequiredLabels: []string{"删除确认对话框", "确认删除", "取消删除"}, + RequiredTexts: []string{"批量删除缓存确认", "已选择 2 个媒体库条目"}, + }, + { + Name: "library-batch-export", + Setup: func() { + app.DeleteConfirm.Open = false + app.LibrarySiteFilter = "all" + app.LibrarySourceSortBySize = true + app.Navigate(ui.RouteLibrary) + app.ExpandedItemKey = "" + app.LibrarySelectMode = true + app.LibrarySelectedKeys = map[string]bool{ + savedDynamicItem.ItemKey: true, + savedDouyinVideo.ItemKey: true, + } + app.Transfer.ExportOpen = true + app.Transfer.ExportScope = "selected" + app.Transfer.ExportPath = `E:\trace-export-selected` + app.Transfer.ExportErr = "" + }, + RequiredLabels: []string{"导出媒体库对话框", "导出范围", "开始导出"}, + RequiredTexts: []string{"导出媒体库", "已选 2 项"}, + }, { Name: "tasks", Setup: func() { app.DeleteConfirm.Open = false + app.Transfer.ExportOpen = false + app.LibrarySelectMode = false + app.LibrarySelectedKeys = map[string]bool{} + app.LibrarySourceSortBySize = false seedRecentAndLive() app.Navigate(ui.RouteTasks) app.TasksSection = "downloads"