diff --git "a/docs/design/assets/ios-\347\234\237\346\234\272/01-xcode-apple-account.png" "b/docs/design/assets/ios-\347\234\237\346\234\272/01-xcode-apple-account.png" new file mode 100644 index 0000000..c2c3da4 Binary files /dev/null and "b/docs/design/assets/ios-\347\234\237\346\234\272/01-xcode-apple-account.png" differ diff --git "a/docs/design/assets/ios-\347\234\237\346\234\272/02-signing-app.png" "b/docs/design/assets/ios-\347\234\237\346\234\272/02-signing-app.png" new file mode 100644 index 0000000..8d842b8 Binary files /dev/null and "b/docs/design/assets/ios-\347\234\237\346\234\272/02-signing-app.png" differ diff --git "a/docs/design/assets/ios-\347\234\237\346\234\272/03-signing-share.png" "b/docs/design/assets/ios-\347\234\237\346\234\272/03-signing-share.png" new file mode 100644 index 0000000..ccb1ba2 Binary files /dev/null and "b/docs/design/assets/ios-\347\234\237\346\234\272/03-signing-share.png" differ diff --git "a/docs/design/assets/ios-\347\234\237\346\234\272/04-wechat-open-in.png" "b/docs/design/assets/ios-\347\234\237\346\234\272/04-wechat-open-in.png" new file mode 100644 index 0000000..2ba0d58 Binary files /dev/null and "b/docs/design/assets/ios-\347\234\237\346\234\272/04-wechat-open-in.png" differ diff --git "a/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/01-\345\276\256\344\277\241\350\275\254\345\217\221-\350\275\254\345\210\260\345\205\266\344\273\226\345\272\224\347\224\250\345\205\245\345\217\243.png" "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/01-\345\276\256\344\277\241\350\275\254\345\217\221-\350\275\254\345\210\260\345\205\266\344\273\226\345\272\224\347\224\250\345\205\245\345\217\243.png" new file mode 100644 index 0000000..804bf30 Binary files /dev/null and "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/01-\345\276\256\344\277\241\350\275\254\345\217\221-\350\275\254\345\210\260\345\205\266\344\273\226\345\272\224\347\224\250\345\205\245\345\217\243.png" differ diff --git "a/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/02-\345\217\202\347\205\247-Yoink-AppStore\344\273\213\347\273\215.webp" "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/02-\345\217\202\347\205\247-Yoink-AppStore\344\273\213\347\273\215.webp" new file mode 100644 index 0000000..ee06cce Binary files /dev/null and "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/02-\345\217\202\347\205\247-Yoink-AppStore\344\273\213\347\273\215.webp" differ diff --git "a/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/03-\345\276\256\344\277\241\345\257\274\345\207\272ZIP-\347\263\273\347\273\237\345\210\206\344\272\253\351\235\242\346\235\277.png" "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/03-\345\276\256\344\277\241\345\257\274\345\207\272ZIP-\347\263\273\347\273\237\345\210\206\344\272\253\351\235\242\346\235\277.png" new file mode 100644 index 0000000..f345f70 Binary files /dev/null and "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/03-\345\276\256\344\277\241\345\257\274\345\207\272ZIP-\347\263\273\347\273\237\345\210\206\344\272\253\351\235\242\346\235\277.png" differ diff --git "a/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/04-WorkBuddy-\350\275\254\345\217\221\345\206\205\345\256\271\345\215\241\347\211\207.png" "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/04-WorkBuddy-\350\275\254\345\217\221\345\206\205\345\256\271\345\215\241\347\211\207.png" new file mode 100644 index 0000000..26ebb26 Binary files /dev/null and "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/04-WorkBuddy-\350\275\254\345\217\221\345\206\205\345\256\271\345\215\241\347\211\207.png" differ diff --git "a/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/05-WorkBuddy-\350\275\254\345\217\221\345\206\205\345\256\271\350\257\246\346\203\205.png" "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/05-WorkBuddy-\350\275\254\345\217\221\345\206\205\345\256\271\350\257\246\346\203\205.png" new file mode 100644 index 0000000..a1d1145 Binary files /dev/null and "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/05-WorkBuddy-\350\275\254\345\217\221\345\206\205\345\256\271\350\257\246\346\203\205.png" differ diff --git "a/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/06-ChatGPT-\346\216\245\346\224\266ZIP\351\231\204\344\273\266.png" "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/06-ChatGPT-\346\216\245\346\224\266ZIP\351\231\204\344\273\266.png" new file mode 100644 index 0000000..5e8fcb7 Binary files /dev/null and "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/06-ChatGPT-\346\216\245\346\224\266ZIP\351\231\204\344\273\266.png" differ diff --git "a/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/07-Yoink\345\275\225\345\261\217\346\212\275\345\270\247-00-27\347\247\222.jpg" "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/07-Yoink\345\275\225\345\261\217\346\212\275\345\270\247-00-27\347\247\222.jpg" new file mode 100644 index 0000000..c442ef3 Binary files /dev/null and "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/07-Yoink\345\275\225\345\261\217\346\212\275\345\270\247-00-27\347\247\222.jpg" differ diff --git "a/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/08-Yoink\345\275\225\345\261\217\346\212\275\345\270\247-30-55\347\247\222.jpg" "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/08-Yoink\345\275\225\345\261\217\346\212\275\345\270\247-30-55\347\247\222.jpg" new file mode 100644 index 0000000..342bae2 Binary files /dev/null and "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/08-Yoink\345\275\225\345\261\217\346\212\275\345\270\247-30-55\347\247\222.jpg" differ diff --git "a/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/README.md" "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/README.md" new file mode 100644 index 0000000..61e4897 --- /dev/null +++ "b/docs/design/assets/ios-\351\252\214\350\257\201\347\264\240\346\235\220/README.md" @@ -0,0 +1,18 @@ +# iOS 验证素材 + +真机实测截图与录屏抽帧,供 [iOS 功能点确认](../../ios-feature-baseline.zh-CN.md) 和 [中转站第一版设计](../../ios-relay-v1.zh-CN.md) 引用。 + +| 文件 | 内容 | 结论 | +|---|---|---| +| 01-微信转发-转到其他应用入口.png | 微信转发聊天记录 → 转到其他应用(QQ、WorkBuddy 推广位 + 选择手机中的应用) | iOS 微信有第三方入口 | +| 02-参照-Yoink-AppStore介绍.webp | Yoink 的 App Store 介绍 | 产品形态参照 | +| 03-微信导出ZIP-系统分享面板.png | 系统分享面板,内容为 `聊天记录_20261024_001520.zip`(170 KB) | 导出格式为 ZIP | +| 04-WorkBuddy-转发内容卡片.png | WorkBuddy 输入框上方的「转发内容」卡片:6 条消息 · 1 个附件 | 接收端卡片参照 | +| 05-WorkBuddy-转发内容详情.png | 点开卡片后的聊天详情 | 详情页参照 | +| 06-ChatGPT-接收ZIP附件.png | ChatGPT 输入框中的 ZIP 附件 | ChatGPT 接受 ZIP | +| 07-Yoink录屏抽帧-00-27秒.jpg | 录屏 0–27.5 秒:微信多选 → 合并转发 → 分享面板找到 Yoink → 存入 | 存入流程参照 | +| 08-Yoink录屏抽帧-30-55秒.jpg | 录屏 30–52.5 秒:Yoink 列表 → ZIP 预览 → 原始 TXT → 编辑与快捷指令 | Yoink 的不足之处 | + +未收入:原始录屏 `ScreenRecording_10-24-2026 01-00-30_1.MP4`(约 50 MB)和样本 `聊天记录_20261024_001520.zip`,仍在 `~/Downloads`。 + +文字类实测结论(豆包、千问不接受 ZIP,但接受 TXT 和图片)来自用户口述,没有截图。 diff --git a/docs/design/ios-dev-spec.zh-CN.md b/docs/design/ios-dev-spec.zh-CN.md new file mode 100644 index 0000000..c550f76 --- /dev/null +++ b/docs/design/ios-dev-spec.zh-CN.md @@ -0,0 +1,741 @@ +# 微信流 iOS v1 · 开发技术文档(可交给 Agent 执行) + +> 日期:2026-10-23 +> 读者:接手开发的 Agent 或工程师。**只读这一份加上 [档期文档](ios-schedule.zh-CN.md),就应该能把 iOS v1 做完并验证交付。** +> 产品设计依据:[中转站第一版设计](ios-relay-v1.zh-CN.md)、[功能点确认](ios-feature-baseline.zh-CN.md)。产品形态以那两份为准;本文件把它们落成可执行的工程规格。两者冲突时,以本文件为准,并回头修正设计文档。 +> 验证素材:[assets/ios-验证素材/](assets/ios-验证素材/) + +--- + +## 0. 给执行者的工作规则(必须遵守) + +1. **工作位置**:只在工作树 `/Users/wn/me-code/WeChatBridge-HUB/.worktrees/ios-relay`(分支 `feat_ai_ios_relay`)里改代码。下文所有相对路径都以这个目录为根,记作 `$ROOT`。 +2. **不要碰** `/Users/wn/me-code/WeChatBridge-HUB/WeChatBridge`(主检出)。那里有用户尚未提交的云端积分改动和 `stash@{0}`。 +3. **提交规则**:每个任务(§9 的 T 编号)完成并通过验收后单独提交。提交标题必须以 `[AI]` 开头,例如 `[AI] feat(ios): 分享扩展写入收件箱`。**不 push、不开 PR**,除非用户在对话里明确要求。 +4. **Mac 不能退化**:任何改到 `macos/` 的提交,提交前都必须跑 `cd macos && swift test`,结果是 186 个测试(含 1 个跳过)0 失败。新增测试后,基线数相应增加。 +5. **不能验证的就写明没验证**:真机步骤无法自动完成时,在 `docs/design/ios-验收记录.zh-CN.md` 里标「待真机」,不要标通过。 +6. **语言**:界面文字是简体中文;代码注释用英文,风格跟 `macos/Sources/WeChatBridgeCore` 一致(解释“为什么”,不复述代码)。 +7. **不做**:画中画、剪贴板监听、自定义键盘、iCloud、Handoff、邮件、云端积分、`wcb`、Shortcuts、小组件。见 §12。 + +--- + +## 1. 环境前提 + +| 项 | 要求 | 当前这台 Mac | 怎么检查 / 怎么补 | +|---|---|---|---| +| Xcode | 26.6 | ✅ 26.6 | `xcodebuild -version` | +| iOS 平台(含模拟器运行时) | iOS 26.5 | ❌ 未安装;装着一个 Xcode 26.6 用不了的 26.4.1 运行时(7.9 GB) | 见下方命令。约需 8–9 GB 磁盘 | +| 磁盘 | 安装平台后至少还剩 5 GB | 约 17 GB 可用 | `df -h /` | +| XcodeGen | 任意 2.x | ✅ `/opt/homebrew/bin/xcodegen` | `xcodegen --version` | +| 签名(模拟器) | 不需要账号 | ✅ | — | +| 签名(真机,含 App Group) | **付费** Apple Developer Program 团队。免费的 Personal Team 不支持 App Group,主 App 和扩展无法共享收件箱,真机端到端走不通 | 代码里使用的 Team 是 `DLKMC3ZRZQ`,但这台 Mac 的钥匙串里只有自签名的 “WeChatBridge Dev” 证书 | 用户在 Xcode → Settings → Accounts 登录付费团队账号后才能做真机验收 | + +安装 iOS 平台(需要用户同意后再执行,删除操作不可撤销): + +```bash +xcrun simctl runtime delete DAE0A5F5-0151-4E6F-BC40-B5B2C8D2F37D +``` + +```bash +xcodebuild -downloadPlatform iOS +``` + +装好后确认能看到模拟器目标: + +```bash +xcrun simctl list runtimes | grep "iOS 26.5" +``` + +**平台未安装时**仍然可以做的验证:`swift test`(Mac)和 §8.2 的 iOS SDK 类型检查。档期里依赖模拟器的任务在平台装好之前一律算阻塞,不能标完成。 + +--- + +## 2. 仓库现状(开工前先核对) + +```bash +cd /Users/wn/me-code/WeChatBridge-HUB/.worktrees/ios-relay && git log --oneline -3 && git status --short +``` + +预期结果: + +``` +aa1f63a [AI] docs: 新增 iOS 功能点确认、中转站第一版设计与验证素材 +af3ef33 [AI] feat: WeChatBridgeCore 支持 iOS 平台编译 +b630373 Merge pull request #47 ... +``` + +工作区干净(本文件和档期文件除外)。 + +目录: + +``` +$ROOT/ +├── macos/ Swift 包:WeChatBridgeApp、WeChatBridgeShare、WeChatBridgeCore、测试。依赖 Sparkle 2.9.6 +│ ├── Package.swift platforms: [.macOS(.v14), .iOS(.v17)] +│ ├── Sources/WeChatBridgeCore/ ← iOS 复用的全部逻辑 +│ ├── Sources/WeChatBridgeShare/ ← Mac 分享扩展,iOS 扩展的参照 +│ └── Tests/ +├── shared/ Skills、Screenshots、AppLogos、Design +├── windows/ C# WPF,与本任务无关 +├── docs/design/ 设计文档与本文件 +└── ios/ ← 本任务新建 +``` + +已经完成的 Core 移植(`af3ef33`),**不要重做**: + +| 文件 | 改动 | +|---|---| +| `Package.swift` | 加 `.iOS(.v17)` | +| `FilePasteboard.swift` | `NSPasteboard` 的 4 个方法放进 `#if canImport(AppKit)`;`shellLine`、`shellQuoted` 两端共用(`PastePlan` 依赖) | +| `AppGroup.swift` | `StorageMode.sharedRoot` 的 macOS 逻辑放进 `#if os(macOS)`;iOS 回退到本进程 Application Support,只给测试用 | +| `InboxSignal.swift` | iOS 用 Darwin 通知中心发 `com.xiangming.wechatbridge.inbox.didChange` | +| `PointerPlacement.swift` | 补 `import CoreGraphics` | + +--- + +## 3. 输入数据规格(微信 iOS 导出) + +来源:用户真机,2026-10-24。iOS 微信路径:聊天记录多选 → 转发 → 转到其他应用 → 选择手机中的应用 → 系统分享面板。 + +- 分享面板里给出的是**一个文件**:`聊天记录__.zip`。 +- ZIP:deflate 压缩;条目名是 UTF-8 字节,但**没有设置 UTF-8 标志位**(和 Mac 版导出一样,Core 已经处理)。 +- 结构: + +``` +聊天记录.txt +聊天记录内的图片、视频和文件/ + 微信图片_202610240015_1.jpg + … +``` + +- `聊天记录.txt` 的格式(真实字节): + +``` +·蜗牛\n2026年10月24日 00:14\n你好\n\n·蜗牛\n2026年10月24日 00:14\n[图片] 微信图片_202610240015_1.jpg\n\n·蜗牛\n2026年10月24日 00:14\n[破涕为笑]\n +``` + + 每条消息是 `·<发送者>` 一行、`yyyy年M月d日 HH:mm` 一行、正文(可以多行),消息之间空一行。正文里可能出现的占位: + +| 占位 | 例子 | 详情页怎么显示 | +|---|---|---| +| 图片 | `[图片] 微信图片_xxx.jpg` | 内联显示同名文件 | +| 视频 | `[视频] xxx.mp4`(待真机样本确认写法) | 缩略图加播放按钮;文件不在包里时显示“未包含视频文件” | +| 文件 | `[文件] xxx.pdf`(待确认) | 文件行,点击用 QuickLook 预览 | +| 链接 | `[链接] <标题> ` | 标题卡片,点击用 Safari 打开 | +| 视频号 | `[视频号] <标题> ` | 视频号卡片,点击打开 URL | +| 表情 | `[破涕为笑]` | 原样显示文字 | + + 无法识别的方括号内容一律原样显示,**不要因为解析失败而丢消息**。 + +测试样本: + +| 样本 | 位置 | 说明 | +|---|---|---| +| 真机单人样本 | `/Users/wn/Downloads/聊天记录_20261024_001520.zip`(仓库外,用户私人数据,**不要提交进仓库**) | 6 条消息、1 张图 | +| Mac 测试夹具 | `macos/Tests/WeChatBridgeAppTests/Fixtures/collection-86.zip`、`collection-100.zip` | 可以复制给 iOS 测试用 | +| 合成样本 | 由 T1.4 的脚本生成,提交进仓库 | 多人、链接、视频号、图片、视频、文件 | + +--- + +## 4. 架构 + +``` +┌──────────── 微信 ────────────┐ +│ 分享 ZIP │ +└──────────────┬───────────────┘ + ▼ +┌─────── WeChatBridgeiOSShare(iOS 分享扩展) ───────┐ +│ ShareViewController │ +│ ① AttachmentImporter → BatchStaging(复制原字节) │ +│ ② staging.commit(manifest, action: .collect) │ +│ ③ DiagnosticsLog / ShareFailure │ +│ ④ InboxSignal.post() │ +│ ⑤ ReceiptView:已存入 · N 条 · N 个附件,1.2 秒后自动关闭 │ +└──────────────┬────────────────────────────────────┘ + │ App Group 容器 /Inbox/Ready// + ▼ +┌────────── WeChatBridgeiOS(iOS 主 App) ───────────┐ +│ RelayStore(@MainActor, ObservableObject) │ +│ InboxReader.loadBatches() → [RelayEntry] │ +│ RelayEntry = ReadyBatch + 解析结果(缓存) │ +│ 页面:中转站 / 详情 / 投递面板 / 场景 / 设置 / 引导 │ +│ 投递:DeliveryPlanner → DeliveryPackage │ +│ ├ App 类目标 → UIPasteboard + UIActivityViewController │ +│ └ Obsidian/文件夹 → KnowledgeDelivery(书签目录) │ +└────────────────────────────────────────────────────┘ +``` + +关键约束: + +- **扩展只收和存**。扩展里不解压、不渲染详情、不弹第二个分享面板。iOS 分享扩展内存上限约 120 MB,大文件必须流式复制(`AttachmentImporter` 已经按 `Representation` 选择文件 URL 或文件表示)。 +- 扩展提交的批次 `action` 一律用 `ShareAction.collect`(iOS 没有“分享即投递”的入口;`collect.needsIntent == false`,不会写 intent)。扩展 Info.plist 的 `DKShareAction` 设为 `collect`,`ShareAction.declared` 就会读到它。 +- **主 App 是 Ready 目录的唯一删除者**(与 Mac 相同的约定)。 +- 主 App 的解析结果(消息数、发言人、首尾时间、附件数、摘要两条)缓存在 `Ready//relay-cache.json`,由主 App 写;缓存缺失或 `schemaVersion` 不符时重算。 + +--- + +## 5. 工程搭建(T1.x) + +### 5.1 目录 + +``` +ios/ +├── project.yml XcodeGen 规格(提交);WeChatBridge.xcodeproj 不提交,加进 .gitignore +├── Config/ +│ ├── App.entitlements +│ ├── Share.entitlements +│ ├── App-Info.plist +│ ├── Share-Info.plist +│ └── Signing.xcconfig DEVELOPMENT_TEAM 等;本地覆盖放 Signing.local.xcconfig(不提交) +├── App/ +│ ├── WeChatBridgeApp.swift @main +│ ├── Model/ RelayStore.swift RelayEntry.swift RelayCache.swift Preferences.swift InboxObserver.swift +│ ├── Relay/ RelayListView.swift RelayCardView.swift +│ ├── Detail/ TranscriptView.swift MessageRow.swift MessageToken.swift +│ ├── Deliver/ TargetProfile.swift DeliveryPlanner.swift TranscriptMerge.swift DeliverySheet.swift ActivitySheet.swift +│ ├── Scenes/ SceneListView.swift SceneEditorView.swift +│ ├── Settings/ SettingsView.swift FolderBookmark.swift +│ └── Onboarding/ OnboardingView.swift +├── ShareExtension/ +│ ├── ShareViewController.swift +│ └── ReceiptView.swift +├── Resources/ Assets.xcassets(AppIcon 用 shared/AppLogos) Localizable.xcstrings +├── Tests/ WeChatBridgeiOSTests/*.swift Fixtures/*.zip +└── Scripts/ + ├── make-fixtures.py + └── verify.sh 一键跑 §8 的全部自动验证 +``` + +### 5.2 Core 的引用方式 + +v1 **不搬动 Core**,iOS 工程把 `../macos` 当作本地 Swift 包引用,只链接 `WeChatBridgeCore` 这个 product。Sparkle 会被解析下载,但不会被链接进 iOS 产物。 + +`macos/Sources/WeChatBridgeShare/AttachmentImporter.swift` 只依赖 Foundation、UniformTypeIdentifiers 和 Core,**移进 Core**(T1.2),两端共用: + +- 移到 `macos/Sources/WeChatBridgeCore/AttachmentImporter.swift`,把 `AttachmentSource`、`ImportedAttachment`、`AttachmentImporter`、`ImportRejection` 改成 `public`(含需要的 `init` 和属性)。 +- Mac 的 `ShareViewController.swift` 不需要改调用,只要能编译。 +- 移完跑 `swift test` 和 §8.2 的类型检查。 + +`macos/Sources/WeChatBridgeApp/KnowledgeDelivery.swift` 和 `FolderDelivery.swift` 也只依赖 Foundation、Darwin 和 Core,**同样移进 Core**(T4.1)并改为 `public`,测试 `Tests/KnowledgeDeliveryTests.swift`、`Tests/FolderDeliveryTests.swift` 跟着改 import(必要时把它们移到 `WeChatBridgeCoreTests`,并在 `Package.swift` 的 `WeChatBridgeDeliveryTests` 的 `sources` 中去掉对应文件)。 + +### 5.3 project.yml 要点 + +以 `ios/project.yml` 为准。target 名带 `iOS`,是为了不和 Mac 包里的 `WeChatBridgeApp`/`WeChatBridgeShare` 产品重名: + +| target | 类型 | 源码 | Bundle ID | +|---|---|---|---| +| `WeChatBridgeiOS` | application | `App`、`Resources` | `com.xiangming.wechatbridge.ios` | +| `WeChatBridgeiOSShare` | app-extension | `ShareExtension` | `com.xiangming.wechatbridge.ios.share` | +| `WeChatBridgeiOSTests` | bundle.unit-test | `Tests`(`Tests/Fixtures` 作为文件夹资源) | `com.xiangming.wechatbridge.ios.tests` | + +- 两个 target 都依赖本地包 `WeChatBridgeKit`(`path: ../macos`)的 `WeChatBridgeCore` 产品,主 App 内嵌扩展。 +- Info.plist 和 entitlements 用 `INFOPLIST_FILE` / `CODE_SIGN_ENTITLEMENTS` 指向 `Config/` 下的文件(不用 XcodeGen 的 `info:` 生成,避免覆盖手写键)。 +- 主 App 和扩展 `SWIFT_VERSION = 5.0`(和 Mac App 层一致);Core 保持 Swift 6。 +- 测试 target 用 `TEST_HOST = $(BUILT_PRODUCTS_DIR)/WeChatBridgeiOS.app/WeChatBridgeiOS`,`@testable import WeChatBridgeiOS`。 +- scheme 是 `WeChatBridgeiOS`(build 两个 target,test `WeChatBridgeiOSTests`)。 + +`Config/Signing.xcconfig`: + +``` +DEVELOPMENT_TEAM = DLKMC3ZRZQ +CODE_SIGN_STYLE = Automatic +#include? "Signing.local.xcconfig" +``` + + +### 5.4 标识与配置(全部写死,不要另起名字) + +| 项 | 值 | +|---|---| +| 主 App Bundle ID | `com.xiangming.wechatbridge.ios` | +| 扩展 Bundle ID | `com.xiangming.wechatbridge.ios.share` | +| App Group | `group.com.xiangming.wechatbridge`(iOS 的 App Group 必须以 `group.` 开头;Mac 的 `DLKMC3ZRZQ.com.xiangming.wechatbridge.shared` 是 macOS 专用写法,iOS 不能用) | +| 显示名 | 微信流 | +| 最低系统 | iOS 17.0,仅 iPhone | + +两个 entitlements 文件内容相同: + +```xml +com.apple.security.application-groups +group.com.xiangming.wechatbridge +``` + +两个 Info.plist **都要**加(缺了 `DKStorageMode`,`StorageMode.current` 会默认成 `.sharedDirectory`,主 App 和扩展就各读各的目录): + +```xml +DKAppGroupIdentifiergroup.com.xiangming.wechatbridge +DKStorageModeapp-group +CFBundleDisplayName微信流 +``` + +扩展 Info.plist 另加: + +```xml +DKShareActioncollect +NSExtension + + NSExtensionPointIdentifiercom.apple.share-services + NSExtensionPrincipalClass$(PRODUCT_MODULE_NAME).ShareViewController + NSExtensionAttributes + + NSExtensionActivationRule + + NSExtensionActivationSupportsFileWithMaxCount32 + NSExtensionActivationSupportsImageWithMaxCount32 + NSExtensionActivationSupportsMovieWithMaxCount32 + + + +``` + +(`DKShareAction` 是 `ShareAction.infoDictionaryKey`,`DKAppGroupIdentifier`、`DKStorageMode` 是 `AppGroup.infoDictionaryKey`、`AppGroup.storageModeKey`,已与源码核对。) + +主 App Info.plist 另加 `UIApplicationSceneManifest`(SwiftUI 默认)和 URL scheme `wechatbridge`(v1 只用于本地通知点开后定位批次:`wechatbridge://batch/`)。 + +--- + +## 6. 模块规格 + +### 6.1 分享扩展 `ShareExtension/ShareViewController.swift`(T2.1) + +`UIViewController` 子类;`viewDidLoad` 里启动导入,流程照搬 Mac 版 `macos/Sources/WeChatBridgeShare/ShareViewController.swift` 的 `run(action:context:)`,差异只有这些: + +| Mac | iOS | +|---|---| +| 1×1 透明视图,导入完马上 `completeRequest` | 用 `UIHostingController(rootView: ReceiptView(...))` 显示收据;导入成功 1.2 秒后自动 `completeRequest`,用户也可以点「完成」立即关闭 | +| `FilePasteboard.write` | 不写剪贴板 | +| `launchContainingApp()` | 删除。iOS 扩展不能正式拉起主 App | +| `action` 有多种 | 固定 `.collect` | + +必须保留的行为(Mac 版已经过真机验证): + +1. 先 `Inbox.resolve()`,再判空;容器拿不到时报 `InboxError.containerUnavailable`。 +2. `BatchStaging.create(in:)` 失败与容器失败分开报错。 +3. 任何一个附件失败,整批 `staging.discard()`,不留半批。 +4. 提交成功后才写诊断、`inbox.pruneStaging()`、`InboxSignal.post()`。 +5. 失败时 `ShareFailure.record(...)` 写进收件箱,`cancelRequest(withError:)`,收据卡显示失败原因。 +6. `hasStarted` 防重入。 + +`ReceiptView`(SwiftUI)显示: + +- 成功:「已存入中转站」、文件名、`N 个文件 · 大小`(`ByteFormat`)。**扩展里不解析消息条数**,避免为显示一个数字而读整包 ZIP(主 App 打开时再算)。 +- 失败:错误文案加「完成」按钮。 +- 进行中:转圈加「正在存入…」。 + +验收:§8.4 的 S1–S4。 + +### 6.2 收件箱监听 `App/Model/InboxObserver.swift`(T2.2) + +- 用 `CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), ...)` 监听 `InboxSignal.didChange.rawValue`;回调切回主线程触发 `RelayStore.reload()`。 +- 另外在 `scenePhase == .active` 时也 `reload()`,因为主 App 在后台时收不到 Darwin 通知。 +- 回调是 C 函数指针,不能捕获上下文;用 `Unmanaged.passUnretained(self).toOpaque()` 传 observer,或用一个全局的 `AsyncStream` continuation。 + +### 6.3 `RelayStore` 和 `RelayEntry`(T3.1) + +```swift +struct RelayEntry: Identifiable, Hashable { + let batch: ReadyBatch // 来自 InboxReader + var summary: RelaySummary? // nil 表示还没解析完 + var id: UUID { batch.id } +} + +struct RelaySummary: Codable, Hashable { + static let schemaVersion = 1 + var schemaVersion: Int + var title: String // ObsidianNote.title(chatName: batch.chatName, transcript:, archiveName:) + var messageCount: Int? + var senders: [String] // 出现顺序去重 + var start: Date? + var end: Date? + var preview: [String] // 前两条:「发送者:正文首行」,各截到 40 个字符 + var mediaCount: Int // ZIP 里「聊天记录内的图片、视频和文件/」下的文件数 + var parseFailed: Bool // 不是微信导出 ZIP(例如用户分享了普通文件) +} + +@MainActor final class RelayStore: ObservableObject { + @Published private(set) var entries: [RelayEntry] = [] // createdAt 倒序 + @Published var failures: [ShareFailure] = [] // InboxReader.consumeFailures(),展示一次 + func reload() + func delete(_ ids: Set) throws // InboxReader(removal: .delete).discard(batchID:) + func entry(_ id: UUID) -> RelayEntry? + func markDelivered(_ ids: [UUID], target: String, scene: String?) // InboxReader.recordOutcome / recordContext +} +``` + +- 解析放在 `Task.detached(priority: .utility)`,每批一次:读 ZIP `Data`,调 `WeChatNativeArchive.transcript(_:)`、`WeChatBatchInsightsReader.read(urls:)`,数媒体条目,写 `relay-cache.json`。 +- 一批里有多个文件时,只解析第一个能被 `WeChatNativeArchive.transcript` 认出的 ZIP;其余文件计入附件数。 +- `markDelivered` 写 `recordOutcome(BatchOutcome(kind: .delivered, detail: , at: Date()), targetName: target.displayName, for: id)`,再 `recordContext(chatName:sceneID:sceneName:for:)`。状态标签从 `ReadyBatch.outcome` 和 `targetName` 读。 +- 启动时调用 `InboxReader.pruneHistory(olderThan: 保留天数 * 86400, excluding: 收集中的批次ID)`。保留天数默认 7 天(与 Mac 的 `defaultHistoryRetentionDays` 一致),设置页可改为 1 / 7 / 30 / 永久。 +- `InboxReader` 在 iOS 上一律用 `InboxReader(inbox:, removal: .delete)`(`Removal` 只有 `.trash` 和 `.delete` 两个 case;iOS 的 App 容器没有可用的废纸篓)。 + +### 6.4 中转站列表 `Relay/`(T3.2) + +- `NavigationStack` + `List`。卡片:标题(`summary.title`)、两行预览、`N 条消息 · N 个附件`、时间范围(`M月d日 HH:mm–HH:mm`;跨天时两端都写日期)、状态标签(未投递 / 已投递到 X / 收集中 / 解析失败)。 +- 筛选 `Picker`:全部 / 未投递 / 收集中。 +- 编辑模式多选:底部工具栏「合并投递」「删除」。 +- 左滑删除;删除前不二次确认,但提供 5 秒「撤销」toast。实现方式:`RelayStore` 先把这些 ID 放进 `pendingDeletion` 并从 `entries` 隐藏,5 秒后(或 App 进入后台时)才调用 `discard(batchID:)`;撤销就是从 `pendingDeletion` 移除。**不要用** `InboxReader.trashRecoverably`:它在 `.trash` 模式下依赖系统废纸篓(iOS 的 App 容器里不可用),在 `.delete` 模式下会移到名为 `TestTrash` 的测试目录。 +- 空状态:一句说明加「查看如何从微信发过来」按钮(打开引导第 1 步)。 +- `ShareFailure` 有内容时,列表顶部显示一次横幅。 + +### 6.5 详情 `Detail/`(T3.3) + +- 首次打开时把 ZIP 解压到 `Caches/Relay//`(`WeChatNativeArchive.extract(_:to:)`,**目标目录必须先创建**)。缓存可被系统清理,打开时不存在就重解。 +- 消息列表用 `LazyVStack`;`WeChatTranscriptRecord.parse(body)` 拿到 `[WeChatTranscriptRecord]`。 +- 同一发送者连续消息合并头像和名字;日期变化时插入日期分隔。 +- `MessageToken.tokenize(_ text: String) -> [MessageToken]`,纯函数,必须有单元测试: + +```swift +enum MessageToken: Equatable { + case text(String) + case image(name: String) + case video(name: String) + case file(name: String) + case link(title: String, url: URL) + case channels(title: String, url: URL) // [视频号] +} +``` + + 规则:一行以 `[图片] `、`[视频] `、`[文件] ` 开头,取剩下的部分作为文件名;以 `[链接] ` 或 `[视频号] ` 开头,取行内最后一个 `http(s)://` 开始的连续非空白串作为 URL,中间部分去掉首尾空白作为标题;都不匹配就是 `.text`。 +- 图片:在解压目录里按文件名找,用 `UIImage(contentsOfFile:)` 降采样到屏宽显示;点开全屏、双指缩放、可分享单张。 +- 解析失败(`summary.parseFailed`):详情页显示文件列表,可以用 QuickLook 预览,并且仍然可以投递(按“其他 App”处理)。 +- 底部按钮:「投递」「加入收集」。 + +### 6.6 目标能力表 `Deliver/TargetProfile.swift`(T5.1) + +```swift +enum DeliveryFormat: String, Codable { case archive, transcriptAndImages, knowledgeNote, folder } + +struct TargetProfile: Identifiable, Hashable, Codable { + let id: String + let displayName: String + let format: DeliveryFormat + let maxAttachments: Int? // nil = 不限;超出时分多次分享,见 6.7 + let hint: String // 分享面板弹出前的提示:「请在下一屏选择 豆包」 + static let builtIn: [TargetProfile] +} +``` + +内置表(顺序就是投递面板网格的默认顺序): + +| id | 显示名 | format | maxAttachments | 依据 | +|---|---|---|---|---| +| `chatgpt` | ChatGPT | archive | nil | 真机:接受 ZIP | +| `doubao` | 豆包 | transcriptAndImages | nil(待 R2 实测后填) | 真机:拒 ZIP,收 TXT 和图片 | +| `qwen` | 千问 | transcriptAndImages | nil(待 R2) | 真机:「格式不支持」,收 TXT 和图片 | +| `workbuddy` | WorkBuddy | archive | nil | 真机:接受 ZIP | +| `claude` | Claude | transcriptAndImages | nil | 未测,先按不收 ZIP;R4 后改 | +| `deepseek` | DeepSeek | transcriptAndImages | nil | 未测,同上 | +| `obsidian` | Obsidian | knowledgeNote | — | 写入书签目录 | +| `folder` | 文件夹 | folder | — | 写入书签目录 | +| `other` | 其他 App | archive | nil | 通用兜底 | + +设置页可以给每个目标切换「发送 ZIP / 发送 TXT 和图片」,覆盖值存在偏好里(键 `com.xiangming.wechatbridge.ios.targetFormatOverrides`,`[String: String]`)。用户还可以隐藏目标、调整顺序。 + +### 6.7 投递规划 `Deliver/DeliveryPlanner.swift`(T5.2) + +纯逻辑,不碰 UIKit,必须有单元测试。 + +```swift +struct DeliveryRequest { + let batches: [ReadyBatch] // 1 个或多个(合并投递) + let target: TargetProfile + let prompt: String? // ScenePrompt.render 的结果,可为空 +} + +struct DeliveryPackage { + let workDirectory: URL // tmp/Deliveries//,投递完成或下次启动时清理 + let shares: [[URL]] // 一次或多次 UIActivityViewController,每次的文件列表 + let prompt: String? + let omitted: [String] // 这个格式没带上的文件名(视频、文件),预览里列出 +} + +enum DeliveryPlanner { + static func plan(_ request: DeliveryRequest, fileManager: FileManager = .default) throws -> DeliveryPackage +} +``` + +规则: + +- **archive**:把每批原始 ZIP 复制到 `workDirectory`(**用复制,不要直接分享 App Group 里的原件**,防止接收方或系统改动原件)。文件名保持原名,重名时加 ` (2)`。`omitted` 为空。 +- **transcriptAndImages**: + 1. 每批解压到 `workDirectory/src//`。 + 2. 一批时:输出 `聊天记录.txt` 原文(**字节不改**)和所有 `UTType(filenameExtension:)` 符合 `.image` 的文件。 + 3. 多批时:用 `TranscriptMerge` 合成一份 `聊天记录.txt`;图片重名且内容不同的,改名为 `名字 (2).jpg`,并把合并后 TXT 里对应的 `[图片] 名字.jpg` 改成新名字。 + 4. 视频和其他文件放进 `omitted`。 + 5. TXT 永远排在第一个。 + 6. `maxAttachments` 不为 nil 且文件数超出时,按 `maxAttachments` 切成多组,TXT 只放在第一组。 +- **knowledgeNote / folder**:不产生 `shares`,由 6.9 处理。 +- 提示词**不写进** TXT。 + +`TranscriptMerge`(同文件或单独文件): + +```swift +enum TranscriptMerge { + static func render(_ records: [WeChatTranscriptRecord], timeZone: TimeZone = .current) -> String + static func merge(_ bodies: [String], timeZone: TimeZone = .current) throws -> String +} +``` + +- `render` 输出与微信相同的格式:`·\n\n\n\n`,最后一条后面只留一个 `\n`。 +- `merge`:各份分别 `WeChatTranscriptRecord.parse`,按 `date` 稳定排序(时间相同的保持原顺序),去掉 sender、date、text 三者完全相同的重复条,再 `render`。 +- 必须满足的测试:`parse(render(records)) == records`(往返一致);两份交错的记录合并后按时间有序;完全重复的一批合并后条数不变。 + +### 6.8 投递面板 `Deliver/DeliverySheet.swift` + `ActivitySheet.swift`(T5.3) + +底部弹层(`.presentationDetents([.medium, .large])`): + +1. **目标网格**:`TargetProfile` 列表(去掉隐藏的),上次选过的排第一(键 `com.xiangming.wechatbridge.ios.lastTarget`)。 +2. **场景**:`SceneResolver.resolve(groupName: batch.chatName, settings:, memories:, senders:)` 的结果预选;可以改成别的场景或「不带场景」。提示词由 `ScenePrompt.render(scene:previousSummaryAt:currentEnd:)` 生成,显示在可编辑的文本框里。 +3. **预览**:`将发送:聊天记录_xxx.zip` 或 `将发送:聊天记录.txt + 3 张图片`;`omitted` 不为空时,显示「未随附 2 个文件」和「改发原始 ZIP」按钮(把本次的 format 临时改成 archive)。 +4. **发送**: + - 提示词非空:先 `UIPasteboard.general.string = prompt`,显示 toast「提示词已复制,可在对方输入框粘贴」。 + - 弹出 `UIActivityViewController(activityItems: [prompt(若有)] + shares[0], applicationActivities: nil)`。弹出前在面板上显示 `target.hint` 1 秒。 + - `completionWithItemsHandler`:`completed == true` 时记一次投递(`RelayStore.markDelivered`),更新 `GroupMemory.advancing(...)`;如果还有下一组 `shares`,弹出「继续发送第 2/3 组」按钮。`completed == false` 不记录。 + - **注意**:`completed` 只代表用户选了某个目标,不代表对方 App 真的收到了;`activityType` 可能是对方扩展的 Bundle ID,记录下来写进诊断,方便以后修正能力表。 + +`ActivitySheet` 用 `UIViewControllerRepresentable` 包装 `UIActivityViewController`。 + +### 6.9 Obsidian 和文件夹 `Settings/FolderBookmark.swift`(T6.1) + +- 设置页「选择 Obsidian 库」「选择默认文件夹」:`UIDocumentPickerViewController(forOpeningContentTypes: [.folder])`。 +- 选中后 `url.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil)` 存进偏好(键 `com.xiangming.wechatbridge.ios.obsidianBookmark`、`...folderBookmark`)。iOS 上**不要**用 `.withSecurityScope`(那是 macOS 选项)。 +- 使用时 `URL(resolvingBookmarkData:options:relativeTo:bookmarkDataIsStale:)`,`startAccessingSecurityScopedResource()`,写完 `stop...`;`isStale` 为真时重新生成书签并保存。 +- 写入复用移进 Core 的 `KnowledgeDelivery.deliver(urls:vaultPath:subfolder:chatName:sceneName:)` / `deliver(urls:folderPath:...)`。子文件夹默认「微信流」。 +- 成功后 toast「已保存到 Obsidian · <笔记名>」;Obsidian 目标额外提供「在 Obsidian 中打开」:`obsidian://open?path=<笔记的绝对路径,百分号编码>`(打不开就不显示按钮)。 + +### 6.10 场景 `Scenes/`(T7.1) + +- 数据:`SceneSettings`,存在 App Group 的 `UserDefaults(suiteName: "group.com.xiangming.wechatbridge")` 里,键沿用 Mac 的 `com.xiangming.wechatbridge.scenes.v3`;首次启动用 `SceneSettings.makeDefault()`,再调用 `installOfficialScenes()`。 +- 群记忆:`[String: GroupMemory]`,键 `com.xiangming.wechatbridge.groupMemory.v1`,字典键用 `GroupName.normalize(displayName)`。 +- 列表:官方场景 / 我的场景;开关启用;左滑删除(官方场景只能停用);编辑页编辑 `name`、`summary`、`instruction`、`outputSpec`、`keywords`。 +- JSON 导入导出:`ScenePackage.encoder()/decoder()`,导出走分享面板,导入走文档选择器。 +- 群绑定:详情页标题旁「绑定场景」,选择后写入 `GroupMemory.boundSceneIDs`。没有群名时(iOS 拿不到微信标题栏),用 `summary.title` 作为 `displayName`,并且记录 `senders`。 +- 识别:投递面板打开时调用 `SceneResolver.resolve(..., senders: Set(summary.senders))`。`GroupFingerprint` 至少要 2 个发言人,阈值 0.7。单人聊天识别不到是预期行为。 + +### 6.11 合并收集(T8.1) + +- 两种入口:列表多选后「合并投递」(一次性,不建收集);详情页「加入收集」(复用 `BatchCollectionLedger`,存在 App Group 的 `Inbox/collections.json`,用 `load(from:)` / `save(to:)`)。 +- 收集也显示成一张卡片(顶部置顶),可以改名、移出批次、投递。投递时 `beginDelivery` → 投递 → `finishDelivery(succeeded:target:detail:scene:)`;启动时 `recoverInterruptedDeliveries()`。 +- 收集中的批次不被 `pruneHistory` 清理(`ledger.protectedBatchIDs`)。 + +### 6.12 首次引导(T8.2) + +三步,可以跳过,设置页里可以重新打开: + +1. 「在微信里找到微信流」:步骤图用 `docs/design/assets/ios-验证素材/01-微信转发-转到其他应用入口.png` 和 `03-微信导出ZIP-系统分享面板.png` 重新截图或裁剪成的引导图(不要直接放用户聊天内容,**打码后**再放进 Assets)。 +2. 「把微信流加到分享面板的个人收藏」:文字说明加示意图。 +3. 「可选:选择 Obsidian 库」:调用 6.9。 + +完成状态存键 `com.xiangming.wechatbridge.ios.onboardingDone`。 + +### 6.13 本地化 + +只做简体中文。所有界面字符串放进 `Localizable.xcstrings`;Core 里的 `L10n.text(...)` 已经返回中文,不要重复翻译。 + +### 6.14 隐私清单 + +主 App 和扩展都加 `PrivacyInfo.xcprivacy`:不收集数据、不跟踪;`NSPrivacyAccessedAPITypes` 声明 `NSPrivacyAccessedAPICategoryUserDefaults`(理由 `1C8F.1`,App Group 共享)和 `NSPrivacyAccessedAPICategoryFileTimestamp`(理由 `C617.1`,`pruneStaging` 读修改时间)。 + +--- + +## 7. 偏好键汇总 + +全部存在 `UserDefaults(suiteName: "group.com.xiangming.wechatbridge")`。 + +| 键 | 类型 | 说明 | +|---|---|---| +| `com.xiangming.wechatbridge.scenes.v3` | Data(JSON `SceneSettings`) | 与 Mac 同名 | +| `com.xiangming.wechatbridge.groupMemory.v1` | Data(JSON `[String: GroupMemory]`) | 与 Mac 同名 | +| `com.xiangming.wechatbridge.historyRetentionDays` | Int | 默认 7;0 表示永久 | +| `com.xiangming.wechatbridge.obsidianSubfolder` | String | 默认「微信流」 | +| `com.xiangming.wechatbridge.folderDeliverySubfolder` | String | 默认「微信流」 | +| `com.xiangming.wechatbridge.ios.obsidianBookmark` | Data | 书签 | +| `com.xiangming.wechatbridge.ios.folderBookmark` | Data | 书签 | +| `com.xiangming.wechatbridge.ios.targetFormatOverrides` | [String: String] | 目标 id → `DeliveryFormat.rawValue` | +| `com.xiangming.wechatbridge.ios.hiddenTargets` | [String] | | +| `com.xiangming.wechatbridge.ios.targetOrder` | [String] | | +| `com.xiangming.wechatbridge.ios.lastTarget` | String | | +| `com.xiangming.wechatbridge.ios.onboardingDone` | Bool | | + +--- + +## 8. 验证方法 + +### 8.1 Mac 回归(每次改到 `macos/` 都要跑) + +```bash +cd /Users/wn/me-code/WeChatBridge-HUB/.worktrees/ios-relay/macos && swift test 2>&1 | grep -E "Executed .* tests" | tail -1 +``` + +通过标准:`Executed N tests, with 1 test skipped and 0 failures`,N ≥ 186。 + +### 8.2 iOS SDK 类型检查(不需要安装 iOS 平台) + +```bash +cd /Users/wn/me-code/WeChatBridge-HUB/.worktrees/ios-relay && SDK=$(xcrun --sdk iphonesimulator --show-sdk-path) && xcrun swiftc -typecheck -sdk "$SDK" -target arm64-apple-ios17.0-simulator -swift-version 6 -application-extension -module-name WeChatBridgeCore macos/Sources/WeChatBridgeCore/*.swift && echo TYPECHECK_OK +``` + +通过标准:输出 `TYPECHECK_OK`。 + +### 8.3 iOS 构建和单元测试(需要 iOS 26.5 平台) + +```bash +cd /Users/wn/me-code/WeChatBridge-HUB/.worktrees/ios-relay/ios && xcodegen generate && xcodebuild -project WeChatBridge.xcodeproj -scheme WeChatBridgeiOS -destination 'platform=iOS Simulator,name=iPhone 17' -derivedDataPath build/DerivedData CODE_SIGNING_ALLOWED=NO test 2>&1 | tail -20 +``` + +通过标准:`** TEST SUCCEEDED **`。模拟器名字以 `xcrun simctl list devices available` 为准。`ios/Scripts/verify.sh` 依次跑 8.1、8.2、8.3,任何一步失败就以非零退出。 + +iOS 单元测试至少覆盖: + +| 测试文件 | 内容 | +|---|---| +| `MessageTokenTests` | 6 种占位;URL 前标题有空格;无法识别的方括号 | +| `TranscriptMergeTests` | 往返一致;交错合并有序;完全重复去重;多行正文 | +| `DeliveryPlannerTests` | archive 复制原件且字节一致;单批 TXT 字节与 ZIP 内原文一致;多批图片重名改名且 TXT 引用同步;`omitted` 列出视频和文件;`maxAttachments = 2` 时正确分组且 TXT 在第一组 | +| `RelaySummaryTests` | 用夹具 ZIP 算出的条数、发言人、媒体数、标题;非微信 ZIP 时 `parseFailed == true` | +| `TargetProfileTests` | 覆盖值生效;隐藏和排序 | + +### 8.4 模拟器端到端(需要 iOS 平台;不需要账号) + +模拟器上没有微信,用「文件」App 代替: + +```bash +xcrun simctl boot "iPhone 17" && open -a Simulator +``` + +```bash +xcrun simctl addmedia booted /Users/wn/Downloads/聊天记录_20261024_001520.zip +``` + +如果 `addmedia` 不接受 ZIP,就把文件拖进模拟器窗口(会存进「文件」App),或者用 `xcrun simctl get_app_container booted com.apple.DocumentsApp` 不可行时改用拖拽。 + +| 编号 | 步骤 | 预期 | +|---|---|---| +| S1 | 「文件」App 长按 ZIP → 共享 → 微信流 | 收据卡显示「已存入中转站」,1.2 秒后自动关闭 | +| S2 | 打开微信流 | 中转站出现一张卡片:「蜗牛的聊天」、`6 条消息 · 1 个附件`、时间 `10月24日 00:14` | +| S3 | 同时选 3 个文件分享 | 一批,三个文件都在 `Ready//items/` 下 | +| S4 | 分享一个 0 字节文件 | 收据卡显示失败;Ready 下没有新增批次;主 App 列表顶部出现一次失败横幅 | +| S5 | 打开卡片 | 详情 6 条消息,第 3 条内联显示图片,表情占位按原文显示 | +| S6 | 投递 → ChatGPT → 发送 | 分享面板里有一个 ZIP 和提示词文本;剪贴板里是提示词(`xcrun simctl pbpaste booted`) | +| S7 | 投递 → 豆包 → 发送 → 选「存储到文件」 | 文件夹里有 `聊天记录.txt` 和 1 张 jpg;TXT 与 ZIP 里的原文字节一致(`cmp`) | +| S8 | 多选 2 张卡片 → 合并投递 → 豆包 → 存储到文件 | 一份合并 TXT,消息按时间排序 | +| S9 | 设置 → 选择文件夹(「我的 iPhone」下新建一个)→ 投递 → 文件夹 | 该文件夹 `微信流/` 下有 `蜗牛的聊天.md` 和 `附件/` | +| S10 | 删除卡片 → 撤销 | 卡片恢复;不撤销时 5 秒后 `Ready/` 消失 | +| S11 | 杀掉 App 后从「文件」再分享一次,再打开 App | 新卡片出现(`scenePhase` 重新加载生效) | + +查看 App Group 容器内容: + +```bash +xcrun simctl get_app_container booted com.xiangming.wechatbridge.ios group.com.xiangming.wechatbridge +``` + +### 8.5 真机验收(需要付费团队签名;由用户操作,Agent 记录结果) + +| 编号 | 内容 | 记录什么 | +|---|---|---| +| R1 | 微信 → 转到其他应用 → 微信流,单人和多人群各一次;多人群样本要含链接、视频号、视频、文件 | 收据卡、卡片、详情截图;把新样本的 `聊天记录.txt` 占位写法补进 §3 的表 | +| R2 | 投递到豆包、千问:TXT + 3 张图 + 提示词 | 对方收到了几个附件,文本是否进了输入框;据此填 `maxAttachments` | +| R3 | 投递到 ChatGPT、WorkBuddy:ZIP + 提示词 | 对方是否读到了 ZIP 内的聊天内容 | +| R4 | Claude、DeepSeek、WeSight 是否接受 ZIP | 更新 6.6 的表 | +| R5 | Obsidian:库放在 iCloud 和「我的 iPhone」各一次 | Obsidian 打开后能否立刻看到新笔记 | +| R6 | 30 MB 以上的 ZIP 从微信分享 | 扩展不崩溃(内存);耗时 | +| R7 | 分享扩展发本地通知(可选,见 §11 的 Q3) | 能否发出、点开能否定位到批次 | + +结果写进 `docs/design/ios-验收记录.zh-CN.md`,格式:编号、日期、设备和系统版本、App 版本、结果(通过 / 不通过 / 待真机)、证据(截图放 `docs/design/assets/ios-验收/`,**先打码聊天内容**)。 + +--- + +## 9. 任务清单(按依赖顺序) + +每个任务的“完成”= 代码 + 测试 + 列出的验证全部通过 + 一个 `[AI]` 前缀的提交。工期见[档期文档](ios-schedule.zh-CN.md)。 + +| ID | 任务 | 依赖 | 产出 | 验证 | +|---|---|---|---|---| +| T0.1 | 安装 iOS 26.5 平台(用户同意后) | — | 可用的模拟器 | `xcrun simctl list runtimes` 有 26.5 | +| T1.1 | `ios/` 骨架:project.yml、两个 target、entitlements、Info.plist、空白 SwiftUI 首页、`.gitignore` | — | 能生成工程 | `xcodegen generate` 成功;8.3 能构建(平台未装时只做 generate) | +| T1.2 | `AttachmentImporter` 移进 Core 并 public | — | Core 变更 | 8.1 + 8.2 | +| T1.3 | `ios/Scripts/verify.sh` | T1.1 | 一键验证 | 脚本退出码 0 | +| T1.4 | `ios/Scripts/make-fixtures.py` 生成合成夹具(多人、链接、视频号、图片、小 mp4、pdf)到 `ios/Tests/Fixtures/`;条目名不带 UTF-8 标志位(若 Python 无法关掉标志位,就带标志位,同时保留复制过来的 Mac 夹具做对照) | — | 夹具 | 用 Core 的 `WeChatNativeArchive.transcript` 能解析,条数符合脚本里的预期 | +| T2.1 | 分享扩展 + 收据卡 | T1.1 T1.2 | 扩展 | 8.4 S1 S3 S4 | +| T2.2 | `InboxObserver` | T1.1 | 自动刷新 | S11;App 在前台时分享后列表 1 秒内刷新 | +| T3.1 | `RelayStore`、`RelaySummary`、缓存 | T2.1 | 数据层 | `RelaySummaryTests` | +| T3.2 | 中转站列表、筛选、多选删除、撤销 | T3.1 | 首页 | S2 S10 | +| T3.3 | 详情、`MessageToken`、图片查看 | T3.1 | 详情页 | `MessageTokenTests`;S5 | +| T4.1 | `KnowledgeDelivery`、`FolderDelivery` 移进 Core 并 public | — | Core 变更 | 8.1 + 8.2 | +| T5.1 | `TargetProfile` 和设置覆盖 | T1.1 | 能力表 | `TargetProfileTests` | +| T5.2 | `DeliveryPlanner`、`TranscriptMerge` | T5.1 | 规划逻辑 | `DeliveryPlannerTests`、`TranscriptMergeTests` | +| T5.3 | 投递面板、`ActivitySheet`、剪贴板、投递记录 | T5.2 T3.2 | 投递 | S6 S7 S8 | +| T6.1 | `FolderBookmark`、Obsidian / 文件夹投递 | T4.1 T5.3 | 知识库投递 | S9 | +| T7.1 | 场景列表、编辑、导入导出、群绑定、自动识别 | T5.3 | 场景 | 用合成多人夹具:第一次绑定场景,第二次导入同群(换一批消息,发言人重合 ≥ 70%)时自动预选同一场景(单元测试 + 手测) | +| T8.1 | 合并收集 | T5.3 | 收集 | 3 批加入收集后投递,合并 TXT 按时间排序;杀 App 重开后收集还在 | +| T8.2 | 首次引导 | T6.1 | 引导 | 首装出现;跳过后不再出现;设置里能重开 | +| T8.3 | 隐私清单、图标、本地化查漏、空状态和错误文案 | 全部 | 打磨 | Xcode 构建无 Warning 级别的隐私清单问题;所有界面无英文残留 | +| T9.1 | 真机验收 R1–R6,按结果修正能力表和占位规则 | T8.x + 付费签名 | 验收记录 | §8.5 | +| T9.2 | 交付检查(§10) | T9.1 | 交付 | §10 全部打勾 | + +--- + +## 10. 交付定义(全部满足才算 v1 完成) + +- [ ] 8.1 Mac 回归全过,测试数 ≥ 186。 +- [ ] 8.2 类型检查通过。 +- [ ] 8.3 iOS 单元测试全过,§8.3 表里的 5 个测试文件都存在且覆盖了列出的用例。 +- [ ] 8.4 S1–S11 全部通过,结果写进验收记录。 +- [ ] 8.5 R1–R5 已由用户在真机上完成并记录;R6、R7 有结论(通过、不通过或明确不做)。 +- [ ] 能力表与真机结果一致,未测的目标在表里标明“未测”。 +- [ ] 设计文档 [ios-relay-v1.zh-CN.md](ios-relay-v1.zh-CN.md) 的 §8 开发顺序与 §9 待测项已按结果更新。 +- [ ] 所有提交标题以 `[AI]` 开头;工作区干净;未经用户同意没有 push。 +- [ ] 仓库里没有用户真实聊天内容(真机样本、未打码的截图)。 + +--- + +## 11. 待决问题(需要用户回答,不要自己猜) + +| # | 问题 | 影响 | 没有答案时的默认做法 | +|---|---|---|---| +| Q1 | Team `DLKMC3ZRZQ` 属于哪个账号?能不能用它做 iOS 真机签名和后续上架? | T9.1 无法开始 | 先只做模拟器,T9.1 标阻塞 | +| Q2 | iOS 显示名用「微信流」是否有商标风险?上架中国区需要 App 备案 | 上架,不影响 v1 开发 | 开发期先用「微信流」 | +| Q3 | 分享扩展是否要发本地通知(“已存入,点此投递”)?需要主 App 先申请通知权限 | 引导多一步 | v1 不做,R7 只做技术验证 | +| Q4 | 是否在 v1 就把 Core 抽到 `shared/WeChatBridgeCore`? | Mac 构建脚本要跟着改 | 不抽,iOS 引用 `../macos` 包 | +| Q5 | 记录默认保留 7 天是否合适? | 存储占用 | 7 天,与 Mac 一致 | + +--- + +## 12. 不在 v1 + +云端账号和积分、云端执行技能、手机作为 Mac `wcb` 的审批端、iCloud 同步、Shortcuts / App Intents、小组件、灵动岛、画中画、剪贴板监听、自定义键盘、Handoff、邮件、英文界面、iPad 布局。 + +--- + +## 附录 A:Core API 速查(以源码为准,签名有出入时先 `grep` 核对) + +| API | 签名 | 备注 | +|---|---|---| +| `Inbox.resolve` | `static func resolve(appGroupIdentifier: String = AppGroup.identifier, storageMode: AppGroup.StorageMode = .current, ...) throws -> Inbox` | 目录:`staging` `ready` `diagnostics` `failures` | +| `Inbox.pruneStaging` | `func pruneStaging(olderThan: TimeInterval = 1800, now: Date = Date(), ...) -> Int` | | +| `BatchStaging.create` | `static func create(in: Inbox, batchID: UUID = UUID(), ...) throws -> BatchStaging` | | +| `BatchStaging.commit` | `func commit(manifest: BatchManifest, diagnostics: ImportDiagnostics?, intent: BatchIntent?, in: Inbox, ...) throws -> URL` | 原子 rename 到 Ready | +| `BatchManifest.init` | `(batchID:createdAt:items:action:)` | `schemaVersion = 1` | +| `InboxReader` | `init(inbox:fileManager:removal: .trash/.delete)`;`loadBatches() -> [ReadyBatch]`;`discard(batchID:)`;`pruneHistory(olderThan:now:excluding:) -> Int`;`consumeFailures() -> [ShareFailure]`;`recordOutcome(_ outcome: BatchOutcome, targetName: String? = nil, for batchID: UUID) throws`;`recordContext(chatName:sceneID:sceneName:for:) throws` | iOS 用 `.delete`;不用 `trashRecoverably` | +| `ReadyBatch` | `id directory createdAt action items outcome targetName chatName sceneID sceneName isFirstSeen byteCount` | | +| `ReadyItem` | `id batchID displayName url byteCount contentType createdAt action` | | +| `InboxSignal.post()` | iOS 走 Darwin 通知 `com.xiangming.wechatbridge.inbox.didChange` | 主 App 监听见 6.2 | +| `ShareFailure.record(_:in:)` | | 主 App 用 `consumeFailures()` 读一次 | +| `DiagnosticsLog.record(_:in:)` | 保留最近 20 条 | | +| `WeChatNativeArchive.transcript` | `static func transcript(_ data: Data, checkCancellation: () throws -> Void = {}) throws -> Transcript?` | `Transcript { path, body, records: [WeChatTranscriptRecord]?, start, end }` | +| `WeChatNativeArchive.extract` | `static func extract(_ data: Data, to: URL, ...) throws -> [String]` | **目标目录必须已存在** | +| `WeChatNativeArchive.messageCount` | `static func messageCount(_ data: Data, ...) throws -> Int?` | | +| `WeChatTranscriptRecord.parse` | `static func parse(_ body: String, timeZone: TimeZone = .current) throws -> [Self]` | `sender date text`;日期格式 `yyyy年M月d日 HH:mm` | +| `WeChatBatchInsightsReader.read` | `static func read(urls: [URL], ...) throws -> WeChatBatchInsights` | `senders: Set`、`end: Date?` | +| `ObsidianNote.title` | `(chatName: String?, transcript: Transcript?, archiveName: String) -> String` | 样本得到「蜗牛的聊天」 | +| `ObsidianNote.render` / `merge` | 见源码 | `KnowledgeDelivery` 内部使用 | +| `SceneSettings` | `makeDefault()`、`installOfficialScenes()`、`enabledScenes`、`scene(id:)`、`add/remove/replace` | | +| `SceneResolver.resolve` | `(groupName: String?, settings: SceneSettings, memories: [String: GroupMemory], senders: Set = [], allowDefault: Bool = true) -> SceneResolution` | `.scene`、`.scenes`、`.source` | +| `GroupFingerprint.match` | `(senders: Set, memories: [String: GroupMemory]) -> String?` | 最少 2 个发言人,阈值 0.7 | +| `GroupMemory.advancing` | `(_ existing:, displayName:, sceneID:, senders:, end:, at:) -> GroupMemory` | 投递成功后调用 | +| `ScenePrompt.render` | `(scene:, previousSummaryAt:, currentEnd:, skills: nil, locale:, timeZone:) -> String?` | iOS 传 `skills: nil` | +| `BatchCollectionLedger` | `current`、`protectedBatchIDs`、`append`、`beginDelivery`、`finishDelivery`、`recoverInterruptedDeliveries`、`load(from:)`、`save(to:)` | | +| `DisplayName.sanitize` / `subfolderPath` | | | +| `ByteFormat`、`L10n` | | | + +**iOS 不使用**:`ShareAction` 的除 `.collect` 以外的 case、`ForwardTarget`、`CustomForwardDecision`、`PointerPlacement`、`AppLink`、`AgentID`、`Skills`、`FilePasteboard` 的写剪贴板方法。 diff --git a/docs/design/ios-feature-baseline.zh-CN.md b/docs/design/ios-feature-baseline.zh-CN.md new file mode 100644 index 0000000..55d399c --- /dev/null +++ b/docs/design/ios-feature-baseline.zh-CN.md @@ -0,0 +1,145 @@ +# iOS 版功能点确认(以 macOS 版为基准) + +> 基准:`feat_ai_wechatbridge_batch-collection_port` 合并 `origin/main`(`64b2d23`)后的 macOS 代码,外加工作区未提交的云端账号、积分、wcb 等改动 +> 审查范围:`WeChatBridge/`(macos、windows、shared、docs、site)以及 HUB 下的 `WeChatBridge-Server`、`WeChatBridge-Web` +> 日期:2026-10-23 + +## 0. 结论 + +1. **仓库里目前没有任何 iOS 代码或服务。** 全仓库搜索 `iOS / iPhone / UIKit / iphoneos / StoreKit`,只在产品文档和路演提示词中出现过“不提供 iOS 版本”。`macos/Package.swift` 只声明了 `.macOS(.v14)`。 +2. **可以直接复用的部分不少:** + - `WeChatBridgeCore` 约 5800 行,基本只依赖 Foundation、CryptoKit、zlib。移植到 iOS 只需改 4 个文件(详见 [中转站第一版设计](ios-relay-v1.zh-CN.md) §7)。批次、收集、场景、技能模型、Obsidian 笔记生成、微信原生 ZIP 解析、云端 Commerce 契约,都能在 iOS 上直接编译。 + - `WeChatBridge-Server`(Go,含积分、买断、按量授权、执行和 OpenAPI 契约)本身与平台无关,iOS 可以作为它的新客户端。 +3. **Mac 的核心交互在 iOS 上做不了:** 自动激活目标 App 并 `⌘V`、辅助功能、屏幕录制识别群名、全局快捷键、写入其他 Agent 的技能目录、本地 `wcb` CLI。iOS 版必须换一套“交付”方式(系统分享面板、URL Scheme、文件夹书签、云端执行)。 +4. **入口已确认可行(2026-10-24 真机截图):** iOS 微信转发聊天记录时,选「转到其他应用 → 选择手机中的应用」,会弹出系统分享面板,内容是 `聊天记录_20261024_001520.zip`(ZIP 归档,约 170 KB)。 + - **ZIP 结构与 Mac 版一致(2026-10-23 已验证):** 包含 `聊天记录.txt` 和 `聊天记录内的图片、视频和文件/` 两部分。条目名是 UTF-8,但没有设置 UTF-8 标志位;压缩方式为 deflate。用现有的 `WeChatNativeArchive`、`WeChatBatchInsightsReader`、`ObsidianNote` 跑这份样本,6 条消息、发言人、时间、媒体解压、笔记标题「蜗牛的聊天」和 Markdown 都正确,不需要改代码。样本只有 1 位发言人,并且只有图片,还需要补测多人群聊,以及含视频、文件的导出。 + - **豆包 iOS 不接受 ZIP(用户实测):** 豆包虽然出现在分享面板里,但不收压缩包。所以“原样转发 ZIP”在 iOS 上行不通,微信流必须**先解包,再转成 Agent 能接收的形式**:聊天文本(TXT/Markdown,或直接作为分享文本),加上解出来的图片和文件。这件事正好成为 iOS 版的核心价值。每个 Agent 能接收哪些类型,需要逐个实测。 + - **各 Agent 接收 ZIP 的实测结果(持续补充):** + + | Agent(iOS) | 是否接收 ZIP | 备注 | + |---|---|---| + | ChatGPT | ✅ | 以文件附件形式出现在输入框上方,点开可以查看。发送后模型能否读到 ZIP 里的内容,还需要实测 | + | WorkBuddy | ✅ | 从微信推广位进入,显示为「转发内容」卡片,见下一条 | + | 豆包 | ❌ | 不接受压缩包;✅ 接受 TXT 和图片 | + | 千问 | ❌ | 提示格式不支持;✅ 接受 TXT 和图片 | + | Claude、DeepSeek、WeSight 等 | ❓ | 待测 | + + 结论:问题不是“iOS 不能转发 ZIP”,而是“部分 Agent 不接受 ZIP”。对于接受 ZIP 的 Agent,微信流原样转发,再附上场景提示词即可;不接受的(如豆包),才需要先转换成文本、.md 或图片再发送。 + - **参照物:WorkBuddy iOS(用户实测)。** 从微信「转到其他应用」的推广位发给 WorkBuddy 后,输入框上方出现一张「转发内容」卡片,显示前几条消息摘要、「6 条消息 · 1 个附件」,点开是按发言人和时间排列的聊天详情(图片内联显示)。上方还有快捷动作:保存到资料库、总结并创建腾讯文档、召唤聊天总结专家。这基本就是微信流 iOS 版接收端该有的样子,快捷动作对应我们的“场景”。❓ 待确认:WorkBuddy 是自己解压了 ZIP,还是通过腾讯内部通道拿到了结构化数据?验证方法:在「文件」App 里把同一个 ZIP 分享给 WorkBuddy,看是否出现同样的卡片。 +5. **产品形态(已确认):** 做成类似 Yoink 的“暂存中转站”。收进来的每一批都先放进中转站,用户想投到哪个 Agent 就投到哪个;对方不收 ZIP 时,自动改发 `聊天记录.txt` 加图片。具体流程:微信 → 微信流(分享扩展接收并暂存)→ 加上场景提示词 → 通过系统分享面板发给豆包、千问等 Agent。差异化在于能读懂聊天记录(群名、发言人、时间、场景、合并多批、Obsidian),而不只是一个通用暂存架。 + +图例:✅ 可直接做或复用 🟡 需改造 ❌ iOS 做不了或无意义 ❓ 需实测 + +## 1. 功能逐项对照 + +### 1.1 入口与接收 + +| Mac 功能 | Mac 实现 | 仓库内可复用 | iOS 可行性 | 说明 | +|---|---|---|---|---| +| 微信转发菜单里的 12 个入口 | `Scripts/share-slots.sh`,12 个 Share Extension | `ShareAction` 枚举 | 🟡❓ | iOS 系统分享面板里,多个扩展会占多个图标,体验差。建议参考 Windows 的做法:只做 1 个入口,在扩展内选择 12 个动作 | +| 接收 ZIP / 文件型附件(最多 32 项,恢复原名) | `WeChatBridgeShare/AttachmentImporter.swift` | `Representation`、`DisplayName` | ✅❓ | `NSItemProvider` 在 iOS 上同样可用;关键是 iOS 微信实际会给出什么类型的数据 | +| 原子批次 Staging → Ready、App Group 共享 | `BatchStaging`、`Inbox`、`AppGroup` | 整体可复用 | ✅ | iOS 的 App Group 容器机制相同 | +| 一次性 intent、90 秒过期 | `InboxSignal`、`BatchState` | 可复用 | 🟡 | iOS 扩展不能在后台拉起主 App。需要改成“扩展内直接完成交付”或“打开主 App 继续”,90 秒过期规则需要重新定义 | +| 微信原生 ZIP / TXT 解析(发言人、时间) | `WeChatNativeArchive`、`WeChatForward`、`WeChatBatchInsights` | 可复用 | ✅❓ | 前提是 iOS 微信导出的格式和 Mac 一致 | + +### 1.2 交付到目标 + +| Mac 功能 | Mac 实现 | iOS 可行性 | iOS 替代方案 | +|---|---|---|---| +| 发给 Codex / Claude / 豆包 / 千问办公 / WorkBuddy / WeSight / DeepSeek Harness,激活并自动粘贴 | `AutoPaste`、`ActionRunner`、`DoubaoAttachment`(AX) | ❌ 自动粘贴 | 🟡 弹出系统分享面板(`UIActivityViewController`)发给对方 App 的分享扩展;或者把提示词复制到剪贴板,再通过 URL Scheme 打开对方 App,由用户手动粘贴。每个 Agent 的 iOS App 是否存在、是否接收 ZIP,都需要逐个实测 | +| 先贴场景提示词,再贴文件(`PastePlan`) | `PastePlan` | 🟡 | 提示词作为分享文本、文件作为附件,一起交给分享面板;对方是否同时接收文本和文件,因 App 而异 | +| 沉淀到 Obsidian(复制 ZIP 到附件目录,生成 `<聊天名>的聊天.md`) | `KnowledgeDelivery`、`ObsidianNote` | ✅ | 用 `UIDocumentPicker` 选择库目录,保存安全作用域书签后写入(库在 iCloud 或“我的 iPhone”里都可以);笔记生成逻辑直接复用 | +| 保存到文件夹 | `FolderDelivery` | ✅ | 同上,用文件夹书签 | +| 复制到剪贴板 | `FilePasteboard`(AppKit) | 🟡 | iOS 的 `UIPasteboard` 可以放文件数据,但大多数 App 不接受粘贴文件。建议降级为“复制提示词 + 分享文件” | +| 发送到自定义 App(按 bundle id,终端只贴路径) | `ForwardTarget`、`ForwardTargets` | ❌ | iOS 无法枚举已安装的 App。系统分享面板本身就是“自定义目标”;“只贴路径”在 iOS 上没有意义 | +| 目标选择面板、最近使用优先 | `TargetPickerPanel` | ✅ | 改成扩展内或主 App 内的 SwiftUI 列表 | + +### 1.3 分批收集 + +| Mac 功能 | iOS 可行性 | 说明 | +|---|---|---| +| 连续接收多批 ZIP,统一选择目标和场景交付 | ✅ | `BatchCollection`、`BatchManifest` 可直接复用 | +| 浮条(首尾消息参考) | 🟡 | iOS 没有悬浮窗。可以改成扩展内的“已收集 N 批”提示,加主 App 内的收集页,或者用灵动岛 / Live Activity | +| 记录页恢复、冻结交付、失败重试 | ✅ | 逻辑复用,界面重写 | + +### 1.4 场景 + +| Mac 功能 | iOS 可行性 | 说明 | +|---|---|---| +| 场景模型(关键词、附加指令、输出规范、所需技能、兼容 Agent) | ✅ | `Scene.swift` 复用 | +| 官方场景、我的场景、JSON 导入导出 | ✅ | 文件导入走 `UIDocumentPicker` | +| 一个群绑定多个候选场景 | 🟡 | Mac 的群名来自屏幕录制 OCR(`WeChatTitleReader`),iOS 不能截取其他 App 的画面。不过 Core 里已经有 `GroupFingerprint.match(senders:memories:)`,可以按发言人集合识别已知群(至少 2 个发言人),iOS 直接用它;识别不出来时让用户手动选群 | +| 按群名自动匹配场景 | 🟡 | 依赖上一条的群名来源 | +| `⌃⌥1–9` 快捷选场景(保留 60 秒) | ❌ | 改成在分享扩展里直接点选场景 | +| 未绑定群时弹出单选场景面板 | ✅ | 在分享扩展里做 | + +### 1.5 技能与云端 + +| Mac 功能 | Mac 实现 | iOS 可行性 | 说明 | +|---|---|---|---| +| 把 SKILL.md 安装到 `~/.codex/skills`、`~/.qwenworkcn/skills`、`~/.workbuddy/skills` | `SkillLibrary`、`AgentID` | ❌ | iOS 沙盒无法写入其他 App 的目录 | +| 技能 ZIP 导出,由用户导入豆包 / Claude | `SkillArchive` | 🟡 | 可以通过分享面板导出 ZIP;对方 iOS App 能否导入技能,需要实测 | +| 内置技能:公众号文章提取 / 下载、视频号视频下载、视频信息读取 | `shared/Skills/*`(含 Python、Node 脚本) | ❌ 本地执行 | 这些技能都依赖本机 Agent 运行脚本,iOS 上跑不了,只能改为云端执行(见下一行) | +| 云端账号、积分、买断、按量授权与审批 | `CloudAccount`、`CloudPane`、`Commerce`、`SkillMonetization`;服务端 `WeChatBridge-Server` | ✅ | Commerce 契约(`contracts/openapi.json`、`examples.json`)可直接复用;iOS 上的 App 内审批 UI 需要重写。注意:iOS 上售卖数字内容/积分受 App Store 规则约束,通常要求走 IAP(见 §3) | +| `wcb` CLI(Agent 发起报价、授权、执行) | `Sources/wcb` | ❌ | iOS 没有本地 Agent 和 CLI。iOS 只能做“审批端”:Mac 上的 Agent 发起请求,手机上批准 | +| 技能安装状态、冲突替换、手动确认 | `SkillsPane` | ❌ / 🟡 | 只剩云端技能的购买和管理部分有意义 | + +### 1.6 记录、设置与系统集成 + +| Mac 功能 | iOS 可行性 | 说明 | +|---|---|---| +| 记录(状态、重发、复制、在 Finder 中显示、废纸篓、清空、保留时长) | ✅🟡 | “在 Finder 中显示”改为“在文件 App 中显示 / 分享”,其余逻辑复用 `HistoryLabel`、`BatchState` | +| 启用 / 关闭每个分享入口(`pluginkit`) | ❌ | iOS 由用户在分享面板里自行编辑;如果改成单入口,可以改为在 App 内开关“动作” | +| 登录时启动、Dock 图标、菜单栏图标 | ❌ | 不适用 | +| 辅助功能 / 屏幕录制权限页 | ❌ | 不适用;iOS 需要的是文件夹访问和通知权限 | +| 三步首次引导 | 🟡 | 内容需重写:教用户在微信里分享到微信流、选择 Obsidian 文件夹 | +| 交付通知 / Toast | ✅ | `UNUserNotificationCenter` | +| 中英文本地化 | ✅ | `Localizable.strings` 大部分可复用,但 Mac 专属文案需要清理 | +| 诊断日志、导入诊断 | ✅ | `DiagnosticsLog`、`ImportDiagnostics` 复用 | + +### 1.7 分发与更新 + +| Mac 功能 | iOS 可行性 | 说明 | +|---|---|---| +| Developer ID 签名、公证、DMG、Homebrew、Universal 2 | ❌ | 改为 App Store / TestFlight | +| Sparkle 更新、蓝奏云检查更新 | ❌ | App Store 自动更新;蓝奏云的检查更新在 iOS 上不应出现(审核风险) | +| 官网 `WeChatBridge-Web`、`site/appcast.xml` | 🟡 | 官网写的是“macOS 14+”,需要补充 iOS 下载入口 | + +## 2. 仓库现有资产对 iOS 的价值 + +| 资产 | 位置 | 对 iOS 的价值 | +|---|---|---| +| 核心库 | `macos/Sources/WeChatBridgeCore`(约 5800 行) | 高。建议在 `Package.swift` 里加上 `.iOS(.v17)`,把 `FilePasteboard` 用 `#if canImport(AppKit)` 隔离,再让 iOS App 依赖它。同时可以考虑把它从 `macos/` 挪到 `shared/` | +| 核心测试 | `macos/Tests/WeChatBridgeCoreTests` | 高。iOS 模拟器上跑同一套测试,就能证明复用没有出问题 | +| 技能目录、场景、Logo、截图 | `shared/` | 中。目录元数据可复用,脚本执行不行 | +| 云端服务 | `WeChatBridge-Server`(Go + PostgreSQL) | 高。但它目前只监听 loopback,是本机开发形态,还没有可供手机访问的 HTTPS 部署;而且这个目录的 `main` 分支还没有任何提交 | +| Windows 版的“单入口 + 应用内 12 个动作”设计 | `windows/docs/MACOS_PARITY.zh-CN.md` | 中。与 iOS 分享面板的限制非常接近,可以直接借鉴交互 | +| 产品能力文档 | `PRODUCT_CAPABILITIES.zh-CN.md` | 注意:文档日期是 2026-09-20,还没写入 DeepSeek Harness、文件夹、分批收集、云端积分这些新功能,并且明确写了“不提供 iOS”,需要同步更新 | + +## 3. 需要你确认的功能点 + +**先做真机实测,再定范围:** + +1. ✅ iOS 微信可以通过「选择手机中的应用」把聊天记录以 ZIP 形式分享出去(`聊天记录_<日期>_<时间>.zip`)。内部结构与 Mac 版相同,现有解析器可以直接使用。❓ 补测:多人群聊,以及含视频、文件的导出。 +2. ❌ 豆包 iOS 不接受 ZIP。❓ 其余 Agent(千问、Claude、ChatGPT、WorkBuddy 等)分别接受:纯文本、.txt/.md 文件、图片、多个附件中的哪些? +3. ❓ Codex(ChatGPT)、Claude、千问、WorkBuddy、WeSight、DeepSeek 的 iOS App 是否存在?是否有分享扩展?能否同时接收文本提示词和附件? +4. ❓ Obsidian iOS 的库放在 iCloud 和放在“我的 iPhone”里时,写入后 Obsidian 能否立即识别。 + +**请勾选第一版要做的范围:** + +- [ ] 单个分享入口,扩展内选择动作(建议),还是多个分享扩展 +- [ ] 交付到 Agent:通过系统分享面板转交 +- [ ] 沉淀到 Obsidian +- [ ] 保存到文件夹 +- [ ] 分批收集 +- [ ] 场景(含群绑定;群名来源选:TXT 推断 / 手动选择) +- [ ] 记录与重发 +- [ ] 云端账号与积分(如果包含:积分购买是否走 IAP?) +- [ ] 手机作为 Mac `wcb` 请求的审批端 +- [ ] 云端执行技能(文章下载、视频下载等,需要服务端实现真实能力) + +**需要定的方向:** + +- 核心库是否抽到 `shared/` 作为 Mac、iOS 共用的 Swift Package +- 最低支持的 iOS 版本(建议 17,可以用 Observation 和较新的 SwiftUI) +- App Store 审核:名称和描述里使用“微信”、导出聊天记录场景是否存在审核与商标风险,需要提前评估 diff --git a/docs/design/ios-relay-v1.zh-CN.md b/docs/design/ios-relay-v1.zh-CN.md new file mode 100644 index 0000000..01417b3 --- /dev/null +++ b/docs/design/ios-relay-v1.zh-CN.md @@ -0,0 +1,232 @@ +# 微信流 iOS 中转站 · 第一版设计 + +> 日期:2026-10-23 +> 前置文档:[iOS 版功能点确认](ios-feature-baseline.zh-CN.md)(真机实测结论与各 Agent 接收情况) +> 落地文档:[开发技术文档](ios-dev-spec.zh-CN.md)(任务、接口、验证)· [档期文档](ios-schedule.zh-CN.md)(里程碑与工期) +> 范围:第一版(v1)只做 **收进来 → 存着看 → 投出去**。云端技能、积分、Mac 联动不在本版。 + +## 1. 一句话 + +微信里转发聊天记录 → 选「转到其他应用 → 选择手机中的应用 → 微信流」→ 记录进入**中转站** → 用户随时挑一批(或合并几批),选好场景,投给 ChatGPT、豆包、千问、Obsidian 或任意 App。对方不收 ZIP 时,微信流自动改发 `聊天记录.txt` 加图片。 + +## 2. 已确认的前提(真机实测) + +| 事实 | 来源 | +|---|---| +| iOS 微信转发聊天记录,可以通过系统分享面板导出 `聊天记录_<日期>_<时间>.zip` | 用户截图,2026-10-24 | +| ZIP 内部结构与 Mac 版一致:`聊天记录.txt` 加 `聊天记录内的图片、视频和文件/` | 用 Mac Core 解析样本,2026-10-23 | +| 现有 `WeChatNativeArchive`、`WeChatBatchInsightsReader`、`ObsidianNote` 不改代码就能正确解析这份样本 | 同上 | +| ChatGPT、WorkBuddy 接受 ZIP;豆包、千问不接受 ZIP,但接受 TXT 和图片 | 用户实测 | +| `WeChatBridgeCore` 改 4 个文件后,能以 `-application-extension` 通过 iOS 17 模拟器 SDK 的类型检查;Mac 的 186 个测试全部通过 | `feat_ai_ios_relay` 分支,`swiftc -typecheck` 加 `swift test`,2026-10-23 | + +仍需实测的点列在 §9。 + +## 3. 用户流程 + +### 3.1 收:从微信进中转站 + +``` +微信 · 聊天记录 ─▶ 转发 ─▶ 转到其他应用 ─▶ 选择手机中的应用 ─▶ 系统分享面板 ─▶ 微信流 + │ + 分享扩展(WeChatBridgeShare) ▼ + ① 复制附件到 Staging(BatchStaging,原名、原字节) + ② 一次性提交到 Ready(原子操作,不会出现半批) + ③ 解析:消息数、发言人、首尾时间、附件数(WeChatNativeArchive) + ④ 群识别:发言人集合与已知群做指纹匹配(GroupFingerprint) + ⑤ 显示收据卡片:「已存入中转站 · 6 条消息 · 1 个附件」 + [完成] [加入收集中的「XX群」](有进行中的收集时显示) +``` + +- 扩展**只负责收和存,不负责投**。原因:iOS 扩展的内存上限很低;扩展里再弹系统分享面板,其他 App 的分享扩展通常不会出现;扩展也不能正式地拉起自家主 App。 +- 收完可以发一条本地通知「已存入中转站,点此投递」,点击后打开主 App,并定位到这一批(扩展能否发通知需实测,见 §9)。 +- 用户如果在分享面板里把微信流设成“个人收藏”,下次就会出现在第一排。 + +### 3.2 存:中转站里看和整理 + +- 每一批显示为一张卡片,形式参照 WorkBuddy 的「转发内容」卡片:群名或参与者、前两条消息摘要、`N 条消息 · N 个附件`、时间范围、状态(未投递 / 已投递到 X / 投递失败)。 +- 点进卡片是聊天详情:按发言人和时间排列,图片内联显示。数据全部来自 `聊天记录.txt` 和解压出来的媒体。 +- 可以**多选几批合并**成一个收集(复用 `BatchCollection`),合并后作为一份投出去。 + +### 3.3 投:选目标、选场景、发出去 + +``` +中转站卡片 ─▶ [投递] ─▶ 投递面板 + ├─ 选目标:ChatGPT / 豆包 / 千问 / WorkBuddy / Claude / Obsidian / 文件夹 / 其他 App + ├─ 选场景:按群绑定的候选场景优先,也可以不带场景 + ├─ 预览:将发出的内容(ZIP,或者 TXT 加 N 张图)和提示词 + └─ [发送] + ├─ App 类目标 → 提示词写入剪贴板 → 弹出系统分享面板 → 用户点目标 App + └─ Obsidian / 文件夹 → 直接写入用户授权的目录 → Toast「已保存」 +``` + +关于 iOS 的限制,需要写进引导里:**第三方 App 不能直接把内容送进某个指定 App**,只能准备好内容,再弹出系统分享面板,由用户点一下目标。所以“选目标”这一步决定的是**发什么格式**,面板里最后点哪个 App 仍由用户决定。为了减少出错,面板弹出前会提示一句“请选择 豆包”。 + +提示词怎么带过去: + +1. 先写入剪贴板,同时作为分享面板的文本项一起传过去(有的 App 会把它直接填进输入框)。 +2. 如果对方丢掉了文本项,用户在对方输入框里长按粘贴即可。投递面板会提示「提示词已复制」。 +3. 不往 `聊天记录.txt` 里插入提示词,保持原文不被改动(与 Mac 版的原则一致)。 + +## 4. 投递格式:目标能力表 + +每个目标对应一条能力描述,投递时由它决定发什么。 + +```swift +struct TargetProfile { + let id: String // "chatgpt" "doubao" "qwen" "workbuddy" "claude" "obsidian" "folder" "other" + let acceptsZip: Bool + let acceptsText: Bool // .txt / .md + let acceptsImages: Bool + let maxAttachments: Int? // 实测后填 +} +``` + +| 目标 | 发送内容 | 依据 | +|---|---|---| +| ChatGPT、WorkBuddy | 原始 ZIP(合并时为多个 ZIP) | 实测接受 ZIP | +| 豆包、千问 | `聊天记录.txt` 加解压出的图片(合并时把多份 TXT 按时间拼成一份) | 实测不接受 ZIP,接受 TXT 和图片 | +| Claude、DeepSeek 等 | 默认按“不接受 ZIP”处理,实测后再改 | 待测 | +| 其他 App | 原始 ZIP | 通用兜底 | +| Obsidian | 写入 `<聊天名>的聊天.md` 加原始 ZIP | 复用 `ObsidianNote` | +| 文件夹 | 原始 ZIP 加解压内容 | 同 Mac 的文件夹投递 | + +视频和文件附件:第一版对“不接受 ZIP”的目标只发图片,视频和文件在预览里列出“未随附 N 个文件”,并提供“改发原始 ZIP”的按钮。 + +## 5. 页面 + +| # | 页面 | 内容 | 对应的 Mac 功能 | +|---|---|---|---| +| 1 | 中转站(首页) | 卡片列表;筛选:全部 / 未投递 / 收集中;多选合并;左滑删除 | 记录页、分批收集 | +| 2 | 记录详情 | 聊天气泡式详情、图片预览;底部按钮「投递」「合并到…」 | 新增(参照 WorkBuddy) | +| 3 | 投递面板(底部弹层) | 目标网格、场景选择、发送内容预览、发送 | 目标选择面板、场景选择面板 | +| 4 | 场景 | 官方场景 / 我的场景;编辑;JSON 导入导出;群绑定 | 场景设置 | +| 5 | 设置 | 目标管理(显示 / 隐藏、排序)、Obsidian 库目录、默认文件夹、记录保留时间、语言、关于 | 通用、入口、记录保留 | +| 6 | 首次引导(3 步) | ① 在微信里找到微信流(配动图)② 把微信流加到分享面板个人收藏 ③ 可选:选择 Obsidian 库 | 三步设置向导 | +| E | 分享扩展收据 | 一张小卡片:已存入、条数、附件数、[完成]、[加入收集] | Share Extension | + +## 6. 复用的 Core 模块 + +`WeChatBridgeCore` 已经以 `-application-extension` 编译,扩展里不能用的 API 编译器会直接报错,所以它天然能放进 iOS 分享扩展。 + +| 模块 | iOS 用途 | 处理方式 | +|---|---|---| +| `AppGroup` | 主 App 与扩展共享的目录 | 改:`StorageMode.sharedDirectory` 的回退路径只在 macOS 上编译(`#if os(macOS)`),iOS 固定使用 App Group 容器 | +| `Inbox`、`BatchStaging`、`BatchManifest`、`InboxReader`、`InboxSignal`、`InboxError` | 扩展写入 Staging → Ready,主 App 读取 Ready | 直接复用 | +| `BatchState`、`HistoryLabel` | 卡片状态与命名 | 直接复用 | +| `BatchCollection` | 多批合并 | 直接复用 | +| `Representation`、`DisplayName`、`ImportDiagnostics`、`ShareFailure` | 从 `NSItemProvider` 取文件、清理文件名、记录脱敏诊断 | 直接复用 | +| `WeChatNativeArchive`、`WeChatForward`、`WeChatBatchInsights` | 解析 ZIP、聊天记录、发言人和时间 | 直接复用(已用 iOS 样本验证) | +| `Scene`(`SceneResolver`、`GroupFingerprint`、`GroupMemory`) | 场景、群绑定、**按发言人集合识别群** | 直接复用。iOS 没有标题栏 OCR,群识别改为依赖发言人指纹(至少 2 个发言人),识别不出来时让用户手动选 | +| `ObsidianNote` | 生成 Markdown 笔记 | 直接复用 | +| `ByteFormat`、`L10n`、`DiagnosticsLog` | 大小格式化、本地化、日志 | 直接复用 | +| `PastePlan` | 描述“先提示词、后文件”的投递内容 | 复用其数据结构,iOS 上把它翻译成分享面板的条目 | +| `FilePasteboard` | macOS 剪贴板 | 写剪贴板的方法只在 macOS 上编译;`shellLine` 和 `shellQuoted` 保留,因为 `PastePlan` 会用到。iOS 另写 `UIPasteboard` 版本 | +| `ShareAction`、`ForwardTarget`、`CustomForwardDecision`、`PointerPlacement`、`AppLink` | macOS 的分享入口、自定义 App、窗口定位 | 不用。iOS 改用 §4 的 `TargetProfile` | +| `AgentID`、`Skills` | 技能安装 | v1 不用(代码可以编译,但不调用)。云端积分的 `Commerce`、`SkillMonetization` 还在 `feat_ai_wechatbridge_batch-collection_port` 的未提交改动里,main 上还没有 | + +**需要新写的 iOS 代码(只放在 iOS 端):** + +- `TargetProfile` 和投递规划:按目标决定发 ZIP,还是发 TXT 加图片 +- `TranscriptMerge`:多份 `聊天记录.txt` 按时间合并(按“不接受 ZIP”路线投递收集时使用) +- `RelayShareSheet`:把投递内容包装成 `UIActivityViewController` 的条目 +- `FolderBookmark`:Obsidian 和文件夹的安全作用域书签(对应 Mac 的 `KnowledgeDelivery`、`FolderDelivery`,这两个在 Mac 的 App 层,需要移植其中的写入逻辑) +- 全部 SwiftUI 页面 + +## 7. 工程结构 + +建议把 Core 从 `macos/` 提到 `shared/` 下,作为独立的 Swift Package,供 Mac 和 iOS 共用。只有路径变化,Mac 的构建脚本需要跟着改引用。 + +``` +WeChatBridge/ +├── shared/ +│ └── WeChatBridgeCore/ ← 从 macos/Sources/WeChatBridgeCore 移过来 +│ ├── Package.swift platforms: [.macOS(.v14), .iOS(.v17)] +│ ├── Sources/WeChatBridgeCore/ +│ └── Tests/WeChatBridgeCoreTests/ Mac 和 iOS 模拟器跑同一套测试 +├── macos/ +│ └── Package.swift 依赖 ../shared/WeChatBridgeCore +├── windows/ +└── ios/ + ├── WeChatBridge.xcodeproj (或者用 XcodeGen 的 project.yml 生成,避免 pbxproj 冲突) + ├── App/ 主 App · SwiftUI + │ ├── RelayApp.swift + │ ├── Relay/ 中转站列表、卡片、多选合并 + │ ├── Detail/ 聊天详情 + │ ├── Deliver/ 投递面板、TargetProfile、RelayShareSheet、TranscriptMerge + │ ├── Scenes/ 场景列表与编辑 + │ ├── Settings/ 设置、FolderBookmark + │ └── Onboarding/ + ├── ShareExtension/ 分享扩展 · 只收和存 + │ ├── ShareViewController.swift 参照 macos/Sources/WeChatBridgeShare + │ └── ReceiptView.swift + ├── Resources/ Localizable.strings(从 Mac 版筛选可用条目)、Assets + └── Tests/ TargetProfile、TranscriptMerge、投递规划的单元测试 +``` + +**目标与签名:** + +| 目标 | Bundle ID(示意) | 关键配置 | +|---|---|---| +| 主 App | `.wechatbridge.ios` | App Group、文件夹书签 | +| 分享扩展 | `.wechatbridge.ios.share` | `NSExtensionActivationRule` 只接受文件(ZIP、`public.data`),最多 32 项;共用同一个 App Group | + +两个目标都依赖 `WeChatBridgeCore`。分享扩展不能链接任何依赖 UIKit App 生命周期的代码。 + +**Core 移植的改动(已在 `feat_ai_ios_relay` 完成,iOS 类型检查和 Mac 测试都通过):** + +1. `Package.swift`:平台加上 `.iOS(.v17)`。 +2. `FilePasteboard.swift`:`import AppKit` 和写 `NSPasteboard` 的 4 个方法放进 `#if canImport(AppKit)`;`shellLine` 和 `shellQuoted` 两端共用。 +3. `AppGroup.swift`:`sharedRoot` 在 macOS 上保持原逻辑;iOS 上改用本进程的 Application Support 目录,只给测试和预览用。iOS 包必须在 Info.plist 里声明 `DKStorageMode = app-group`,否则主 App 和扩展会各读各的收件箱。 +4. `InboxSignal.swift`:iOS 没有 `DistributedNotificationCenter`,改用 Darwin 通知中心,同样不携带任何数据。 +5. `PointerPlacement.swift`:补上 `import CoreGraphics`(macOS 的 Foundation 会顺带导入它,iOS 不会)。 + +## 7.5 参照 Yoink:借鉴、改进、不做 + +依据:用户录屏(2026-10-24,55 秒),完整走了一遍“微信多选消息 → 合并转发 → 其他应用 → 分享面板找到 Yoink → 存入 → 在 Yoink 里查看”。 + +**借鉴:** + +- **存入几乎无感**:分享后只出现一行「正在将项目添加到 Yoink…」就自动退回微信,不需要额外点击。我们的收据卡片也应该做到这么轻:自动消失,「加入收集」作为可选按钮,不点也能存。 +- **大卡片列表、编辑多选、批量删除**:直接沿用这种交互。 +- **Siri 快捷指令**(如“从 Yoink 复制最新项目”):对应到我们,可以是“把最新一批发给豆包”,放到 v2。 + +**改进(这些是 Yoink 作为通用暂存工具做不到、而我们能做好的):** + +| Yoink 的现状 | 微信流的做法 | +|---|---| +| ZIP 卡片的缩略图是一片空白,只有文件名「聊天记录_20261024_010035」,看不出是谁的聊天 | 卡片直接显示群名或参与者、前两条消息、条数、附件数、时间范围 | +| 点开后是一个通用 ZIP 图标「170 KB · 2 份文件 · 预览内容」,要再点一层 | 点开直接进入聊天详情 | +| 预览就是原始 TXT:整面纯文本,`[链接]` 后面跟着一长串 mp.weixin URL | 气泡式详情:`[链接]` 渲染成标题卡片,`[视频号]` 渲染成视频卡片,图片内联,表情占位保持原样 | +| 在分享面板里要往下滑很久才能找到 Yoink | 首次引导第 ② 步,教用户把微信流加到分享面板的「个人收藏」;投递时也提示“请选择 豆包” | +| 投出去时只能原样分享文件 | 按目标自动决定发 ZIP 还是 TXT 加图片,并附上场景提示词 | + +**不做:**画中画浮窗、剪贴板监视、自带键盘、iCloud 同步、Handoff、电子邮件支持。这些是 Yoink 作为通用暂存工具的卖点,与“微信聊天记录中转”无关,v1 一律不做。 + +**录屏里发现的新内容类型**:聊天记录里除了文字、图片、表情,还会有 `[链接] <标题> ` 和 `[视频号] <标题> `。详情页需要识别这两类,以后也可以把它们直接接到“公众号文章下载”“视频号视频下载”技能上。补测样本时要包含这两类消息。 + +## 8. 开发顺序 + +| 步骤 | 内容 | 完成标准 | +|---|---|---| +| 1 | ✅ Core 加上 iOS 平台并完成上面的改动;抽到 `shared/`(可选,未做) | ✅ Mac 186 个测试全部通过;iOS 模拟器 SDK 类型检查通过(Xcode 尚未安装 iOS 平台,还没做完整构建) | +| 2 | iOS 工程骨架:主 App、分享扩展、App Group | 在真机上,从微信分享 ZIP 后,Ready 目录里出现这一批 | +| 3 | 中转站列表和记录详情 | 卡片上的条数和附件数与 ZIP 内容一致,详情页能看图 | +| 4 | 投递:ZIP 路线(ChatGPT) | 真机上投递到 ChatGPT 后,提示词可以粘贴 | +| 5 | 投递:TXT 加图片路线(豆包、千问) | 真机上豆包和千问都能收到 TXT 和图片 | +| 6 | Obsidian 和文件夹 | Obsidian iOS 打开后能看到新笔记 | +| 7 | 场景和群绑定 | 多人群第二次导入时能自动匹配到上次的场景 | +| 8 | 合并收集、首次引导、本地化 | 三批合并后投递,内容按时间排序 | + +## 9. 待实测(会影响设计) + +1. 多人群聊、含视频和文件的 iOS 导出,结构是否仍和样本一致。 +2. 系统分享面板一次发“TXT + 多张图 + 文本”时,豆包、千问、ChatGPT 各自收到了什么:是全收,还是只收第一个附件,文本有没有被丢掉。 +3. 分享扩展里能否发本地通知,点击后能否打开主 App 并定位到这一批。 +4. Claude、DeepSeek、WeSight 是否接受 ZIP。 +5. ChatGPT 收到 ZIP 后,模型是否真的读到了里面的内容。 +6. Obsidian iOS 的库在 iCloud 和“我的 iPhone”两种位置下,写入后能否立即看到。 +7. App Store 审核:名称和描述中使用“微信”是否存在商标风险。 + +## 10. 不在第一版 + +云端账号和积分、云端执行技能、手机作为 Mac `wcb` 请求的审批端、iCloud 同步到 Mac 版、Shortcuts 和 App Intents、小组件、灵动岛。 diff --git a/docs/design/ios-schedule.zh-CN.md b/docs/design/ios-schedule.zh-CN.md new file mode 100644 index 0000000..c048165 --- /dev/null +++ b/docs/design/ios-schedule.zh-CN.md @@ -0,0 +1,134 @@ +# 微信流 iOS v1 · 档期文档 + +> 日期:2026-10-23(周五) +> 配套:[开发技术文档](ios-dev-spec.zh-CN.md)。任务编号(T…)、验证编号(S…、R…)、交付定义都以那份为准,本文件只管**顺序、工期、闸门和汇报**。 +> 计划按 1 个执行者(Agent 或工程师)全职推进估算,单位是工作日。用户需要亲自做的事(同意安装平台、真机测试、签名账号)单列出来。 + +## 1. 总览 + +| 里程碑 | 内容 | 任务 | 工期 | 计划日期 | 出口闸门(全部满足才能进下一个) | +|---|---|---|---|---|---| +| M0 | 环境与骨架 | T0.1 T1.1 T1.2 T1.3 T1.4 | 2 天 | 10-26 周一 – 10-27 周二 | iOS 26.5 平台已装;`ios/Scripts/verify.sh` 退出码 0;`xcodegen generate` 成功;空白 App 在模拟器里能启动 | +| M1 | 收:分享扩展进收件箱 | T2.1 T2.2 | 2 天 | 10-28 周三 – 10-29 周四 | S1 S3 S4 S11 通过 | +| M2 | 存:中转站列表与详情 | T3.1 T3.2 T3.3 | 3 天 | 10-30 周五 – 11-03 周二 | S2 S5 S10 通过;`RelaySummaryTests`、`MessageTokenTests` 通过 | +| M3 | 投:ZIP 与 TXT+图片两条路线 | T4.1 T5.1 T5.2 T5.3 | 3 天 | 11-04 周三 – 11-06 周五 | S6 S7 S8 通过;`DeliveryPlannerTests`、`TranscriptMergeTests`、`TargetProfileTests` 通过;Mac 回归通过 | +| M4 | Obsidian、文件夹、场景 | T6.1 T7.1 | 3 天 | 11-09 周一 – 11-11 周三 | S9 通过;场景自动识别的单元测试和手测通过 | +| M5 | 收集、引导、打磨 | T8.1 T8.2 T8.3 | 2 天 | 11-12 周四 – 11-13 周五 | §10 交付定义里除真机项以外全部打勾 | +| M6 | 真机验收与修正 | T9.1 T9.2 | 3 天(含用户测试时间) | 11-16 周一 – 11-18 周三 | R1–R5 已记录;能力表按结果更新;§10 全部打勾 | +| 缓冲 | | | 2 天 | 11-19 周四 – 11-20 周五 | — | + +**计划交付:2026-11-18;最晚 2026-11-20。** 开发和验收共 18 个工作日,另加 2 天缓冲。 + +## 2. 关键路径与可并行的任务 + +``` +T0.1 ─┐ +T1.1 ─┼─▶ T2.1 ─▶ T3.1 ─▶ T3.2 ─┐ +T1.2 ─┘ └─▶ T3.3 ├─▶ T5.3 ─▶ T6.1 ─▶ T7.1 ─▶ T8.1 ─▶ T8.2 ─▶ T8.3 ─▶ T9.1 ─▶ T9.2 + T5.1 ─▶ T5.2 ─┘ ▲ + T4.1 ────────────────────┘ +``` + +- **关键路径**:T1.1 → T2.1 → T3.1 → T3.2 → T5.3 → T6.1 → T7.1 → T8.x → T9.1。 +- **可以提前做、不依赖模拟器的任务**:T1.2、T1.4、T4.1、T5.1、T5.2(纯逻辑和 Core 改动,用 `swift test` 加类型检查就能验证)。如果 T0.1 被卡住(磁盘、用户未同意),先做这几个,不要空等。 +- 如果有第二个执行者:一人走关键路径;另一人做 T1.2 → T4.1 → T5.1 → T5.2 → T7.1 的逻辑部分。两人改的文件不重叠:Core 改动(T1.2、T4.1)由同一人负责,避免冲突。 + +## 3. 每个里程碑的工作分解 + +### M0 环境与骨架(2 天) + +| 天 | 任务 | 当天结束时能看到 | +|---|---|---| +| D1 上午 | 请用户同意 T0.1 的删除和安装命令;后台安装平台(约 8–9 GB,下载时间视网络而定) | 安装进行中 | +| D1 | T1.2 `AttachmentImporter` 移进 Core | Mac 回归和类型检查通过,提交 | +| D1 | T1.4 合成夹具脚本 | `ios/Tests/Fixtures/` 下有夹具,Core 能解析,提交 | +| D2 | T1.1 骨架、T1.3 `verify.sh` | 模拟器里能打开空白的「微信流」,提交 | + +### M1 收(2 天) + +| 天 | 任务 | 当天结束时能看到 | +|---|---|---| +| D3 | T2.1 扩展导入与提交 | 从「文件」App 分享后,`Ready/` 下出现批次 | +| D4 | T2.1 收据卡、失败路径;T2.2 监听 | S1 S3 S4 S11 通过,提交 | + +### M2 存(3 天) + +| 天 | 任务 | +|---|---| +| D5 | T3.1 数据层和缓存,`RelaySummaryTests` | +| D6 | T3.2 列表、筛选、多选、撤销删除 | +| D7 | T3.3 详情、`MessageToken`、图片查看 | + +### M3 投(3 天) + +| 天 | 任务 | +|---|---| +| D8 | T4.1 投递代码移进 Core;T5.1 能力表 | +| D9 | T5.2 规划与合并,以及全部单元测试 | +| D10 | T5.3 投递面板、分享面板、剪贴板、投递记录 | + +### M4 知识库与场景(3 天) + +| 天 | 任务 | +|---|---| +| D11 | T6.1 书签和写入 | +| D12–D13 | T7.1 场景列表、编辑、导入导出、绑定、自动识别 | + +### M5 收集、引导、打磨(2 天) + +| 天 | 任务 | +|---|---| +| D14 | T8.1 合并收集 | +| D15 | T8.2 引导;T8.3 隐私清单、图标、文案、空状态 | + +### M6 真机验收(3 天) + +| 天 | 任务 | 谁 | +|---|---|---| +| D16 | 准备真机测试清单和测试包(Xcode 直接装到用户手机) | 执行者 | +| D16–D17 | R1–R6 | **用户**操作,执行者记录 | +| D18 | 按结果修正能力表、占位规则;T9.2 交付检查 | 执行者 | + +## 4. 需要用户在什么时候做什么 + +| 最晚时间 | 事项 | 不做的后果 | +|---|---|---| +| 10-26 上午 | 同意删除旧的 iOS 26.4.1 运行时并安装 iOS 26.5 平台 | M0 之后所有模拟器验证都卡住 | +| 11-06 | 回答 Q1:哪个付费开发者账号用于真机签名,并在 Xcode 里登录 | M6 无法开始 | +| 11-13 | 准备一份**多人群**聊天记录导出(包含链接、视频号、视频、文件),以及装好豆包、千问、ChatGPT、WorkBuddy、Claude、DeepSeek、Obsidian 的 iPhone | R1–R5 无法完成 | +| 11-16 – 11-17 | 按清单做真机测试,把截图发给执行者 | 交付推迟 | +| 任意时间 | Q2–Q5(见开发文档 §11);不回答就按默认做法 | 无 | + +## 5. 风险与应对 + +| 风险 | 可能性 | 影响 | 应对 | +|---|---|---|---| +| 磁盘不够装 iOS 平台(剩 17 GB,平台约 8–9 GB) | 中 | M0 卡住 | 先删旧运行时(7.9 GB);仍不够时请用户清理;同时先做不依赖模拟器的任务(§2) | +| 没有付费签名,App Group 在真机上用不了 | 中 | M6 卡住 | 模拟器上能完成 S1–S11;真机项标「待真机」,交付推迟到账号就绪 | +| 豆包、千问一次只收第一个附件或丢掉文本 | 中 | 投递体验变差 | `maxAttachments` 分组发送已经在设计里;提示词有剪贴板兜底 | +| 大 ZIP 让分享扩展超过内存上限 | 低 | 收不进来 | `AttachmentImporter` 走文件表示流式复制;R6 专门测;如果还是崩,扩展里改成只复制、不读入内存 | +| 多人群样本的占位写法与假设不同 | 中 | 详情页渲染错误 | `MessageToken` 不认识时按原文显示,不丢内容;R1 后补规则 | +| Swift 6 严格并发在 SwiftUI 层产生大量告警 | 中 | 进度变慢 | 主 App 允许降到 Swift 5 模式(开发文档 5.3),Core 保持 Swift 6 | +| 本地包引用 `../macos` 时 Sparkle 解析失败(离线) | 低 | 无法构建 | 联网解析一次即可;仍有问题时执行 Q4(把 Core 抽到 `shared/`),工期 +1 天 | + +## 6. 进度汇报格式 + +每完成一个任务,在对话里用下面的格式汇报一次;每个里程碑结束时,把同样的内容追加到 `docs/design/ios-验收记录.zh-CN.md`: + +``` +[任务] T3.2 中转站列表 +[状态] 完成 / 阻塞 / 进行中 +[提交] <短 SHA> [AI] feat(ios): … +[验证] swift test 186/186(1 跳过);类型检查 OK;xcodebuild test 23/23;S2 S10 通过 +[未验证] 无 / 列出原因 +[下一步] T3.3 +[需要用户] 无 / 具体事项 +``` + +阻塞超过半天就立刻汇报,同时切换到 §2 里不依赖它的任务。 + +## 7. 变更规则 + +- 工期变化超过 1 天:更新本文件 §1 的表,并在汇报里说明原因。 +- 产品范围变化(加功能或砍功能):先问用户;同意后同时改开发文档 §9、§10、§12 和本文件。 +- 真机结果推翻了能力表或数据格式的假设:改开发文档 §3 和 §6.6,并在验收记录里注明依据。 diff --git "a/docs/design/ios-\347\234\237\346\234\272\345\256\211\350\243\205.zh-CN.md" "b/docs/design/ios-\347\234\237\346\234\272\345\256\211\350\243\205.zh-CN.md" new file mode 100644 index 0000000..188369d --- /dev/null +++ "b/docs/design/ios-\347\234\237\346\234\272\345\256\211\350\243\205.zh-CN.md" @@ -0,0 +1,108 @@ +# 用免费 Apple ID 把微信流装到 iPhone + +没有付费开发者账号也能在自己的 iPhone 上跑微信流,用于演示和真机验收([验收记录](ios-验收记录.zh-CN.md) R1–R7)。代价是:签名 **7 天后过期**,过期后 App 打不开,要重新装一次。 + +已验证环境:Xcode 26,iPhone 16 Pro / iOS 26.5,免费 Personal Team。分享扩展和 App Group 在免费团队下都能用。 + +## 1. 在 Xcode 登录 Apple ID + +Xcode → Settings → Apple Accounts → 左下角「+」→ Apple ID,登录后会出现一个 **Personal Team**。 + +![Xcode 里的 Personal Team](assets/ios-真机/01-xcode-apple-account.png) + +## 2. 换成自己的 Bundle ID 和 App Group + +仓库默认的 `com.xiangming.*` 属于付费团队,免费团队用不了,要换成自己的前缀(随便取,全球唯一即可,比如 Apple ID 的用户名)。 + +在 `ios/Config/` 下新建 `Signing.local.xcconfig`(已被 git 忽略,不会提交): + +``` +// Local only (git-ignored): free Apple ID "Personal Team" for on-device demos. +DEVELOPMENT_TEAM = <你的 Team ID> +APP_BUNDLE_ID = com.<前缀>.wechatbridge.ios +APP_GROUP_ID = group.com.<前缀>.wechatbridge +``` + +Team ID 可以先空着,第 3 步在 Xcode 里选完团队后,从 Build Settings → Development Team 里看到 10 位 ID 再填回来;填了以后重新生成工程也不会丢。 + +三个值会一起带到:主 App 和扩展的 Bundle ID(扩展是 `$(APP_BUNDLE_ID).share`)、两个 entitlements 里的 App Group、Info.plist 的 `DKAppGroupIdentifier`。 + +然后在 `ios/` 下重新生成工程: + +```bash +xcodegen generate -q +``` + +## 3. 两个 target 都选上 Personal Team + +打开 `ios/WeChatBridge.xcodeproj`,分别选中 **WeChatBridgeiOS** 和 **WeChatBridgeiOSShare**,在 Signing & Capabilities 里: + +- 勾选 Automatically manage signing +- Team 选「<你的名字> (Personal Team)」 +- App Groups 下勾选 `group.com.<前缀>.wechatbridge` + +![主 App 的签名设置](assets/ios-真机/02-signing-app.png) + +![分享扩展的签名设置](assets/ios-真机/03-signing-share.png) + +截图里的「Communication with Apple failed / no devices」是正常的:免费团队必须先连上一台真机,Xcode 才能生成描述文件。做完第 4 步再点 Try Again,或者直接走第 5 步的命令行构建,警告会消失。 + +## 4. 连接并准备 iPhone + +1. 用数据线连 Mac,手机上点「信任这台电脑」。 +2. 如果 Xcode 里设备显示未配对,在 Mac 上执行一次配对,手机上确认: + + ```bash + xcrun devicectl list devices + ``` + + ```bash + xcrun devicectl manage pair --device <设备标识> + ``` + +3. 打开开发者模式:设置 → 隐私与安全性 → 开发者模式 → 打开,按提示重启手机,重启后再确认一次。 + - 菜单里没有「开发者模式」时,先让 Xcode 往手机装一次(第 5 步),失败后这个开关就会出现。 + +## 5. 构建并安装 + +在 `ios/` 下执行。设备 ID 用 `xcrun xctrace list devices`(构建用)和 `xcrun devicectl list devices`(安装用)查,两者格式不同。 + +```bash +xcodebuild -project WeChatBridge.xcodeproj -scheme WeChatBridgeiOS -destination 'id=' -derivedDataPath build/Device -allowProvisioningUpdates -allowProvisioningDeviceRegistration build +``` + +```bash +xcrun devicectl device install app --device build/Device/Build/Products/Debug-iphoneos/WeChatBridgeiOS.app +``` + +```bash +xcrun devicectl device process launch --device com.<前缀>.wechatbridge.ios +``` + +也可以直接在 Xcode 里选中手机,点 Run。 + +## 6. 在手机上信任开发者 + +第一次启动会被系统拦下(「不受信任的开发者」)。到 设置 → 通用 → VPN 与设备管理 → 开发者 App 下点你的 Apple ID → 信任。之后 App 就能正常打开。 + +## 7. 从微信分享进来(R1) + +1. 微信里多选聊天记录 → 转发 → 右上角「转到其他应用」→「选择手机中的应用」。 +2. 在系统分享面板里选「微信流」。第一次找不到时,划到最右边点「更多」,把微信流打开并拖到前面。 +3. 收据卡显示「已存入中转站」,回到微信流就能看到新卡片。 + +![微信里的「选择手机中的应用」](assets/ios-真机/04-wechat-open-in.png) + +## 7 天过期之后 + +免费团队的描述文件 7 天有效。过期后 App 图标还在,但点开会闪退或提示无法验证。重新执行第 5 步的构建和安装即可,数据(中转站里的批次、设置)保留;不需要重新信任。演示前最好先重装一次。 + +## 常见问题 + +| 现象 | 处理 | +|---|---| +| Xcode 提示 Bundle ID 不可用 | 前缀被别人占了,换一个前缀,改 `Signing.local.xcconfig` 后重新 `xcodegen generate -q` | +| 构建报 Developer Mode disabled | 第 4 步第 3 条,打开开发者模式并重启 | +| 安装成功但启动被拒绝 | 第 6 步,信任开发者 | +| 设备在 Xcode 里显示 unpaired | 第 4 步第 2 条,`devicectl manage pair` | +| 免费团队最多同时 3 个 App | 删掉手机上别的自签 App 再装 | diff --git "a/docs/design/ios-\351\252\214\346\224\266\350\256\260\345\275\225.zh-CN.md" "b/docs/design/ios-\351\252\214\346\224\266\350\256\260\345\275\225.zh-CN.md" new file mode 100644 index 0000000..77a832c --- /dev/null +++ "b/docs/design/ios-\351\252\214\346\224\266\350\256\260\345\275\225.zh-CN.md" @@ -0,0 +1,80 @@ +# iOS 微信流验收记录 + +对应 [开发规格](ios-dev-spec.zh-CN.md) §8.4(模拟器)和 §8.5(真机)。 + +- 分支:`feat_ai_ios_relay` +- App 版本:0.1.0 (1) +- 模拟器:iPhone 17 Simulator,iOS 26.5 +- 真机样本 ZIP(`聊天记录_20261024_001520.zip`)只在本机使用,不入库;本记录不含聊天原文,也不附截图。 + +## 自动化验证 + +`ios/Scripts/verify.sh`(Mac `swift test` + 类型检查 + iOS 单元测试)在下列修复全部合入后重跑,结果见文末「复跑」一节。 + +## 模拟器验收(§8.4) + +模拟器上没有微信,用「文件」App 代替:把样本 ZIP、合成夹具 `group-a.zip`、`interleave.zip` 和一个 0 字节文件放进「我的 iPhone」,再从「文件」分享。 + +| 编号 | 日期 | 设备/系统 | App 版本 | 结果 | 证据 | +|---|---|---|---|---|---| +| S1 | 2026-10-23 | iPhone 17 Simulator / iOS 26.5 | 0.1.0 (1) | 通过 | 收据卡显示「已存入中转站」后自动关闭;`Inbox/Ready/` 新增一个批次 | +| S2 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过 | 卡片:`蜗牛的聊天`、`6 条消息 · 1 个附件`、`10月24日 00:14`;合成夹具卡片标题、条数、时间段也正确 | +| S3 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过 | 三个 ZIP 同时分享,生成一个批次,三个文件都在 `Ready//items/` 下。卡片按第一个能解析的 ZIP 出摘要,其余 ZIP 计入附件数(见「已知限制」) | +| S4 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过(修复后) | 收据卡显示「没有存入」并说明是空文件;`Ready/` 无新增;主 App 顶部出现「有 1 次分享没有保存成功」横幅。修复前扩展会接收 0 字节文件,见 cfbced3 | +| S5 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过 | 详情 6 条消息,第 3 条内联显示图片,表情占位按原文显示 | +| S6 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过 | 分享面板里有一个 ZIP 和提示词文本;`xcrun simctl pbpaste booted` 返回「日常摘要」提示词;取消分享面板后投递面板仍在。ChatGPT 是否真的读到内容属于 R3 | +| S7 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过(修复后) | 存储到文件后得到 `聊天记录.txt`、1 张 jpg,另有一个 `text.txt`(随分享带出的提示词);TXT 和 jpg 与 ZIP 内原文件逐字节一致(Python 读 ZIP 成员后比对,`unzip` 因非 UTF-8 文件名无法解压到磁盘)。发现发送完成后按钮显示「继续发送第 2/1 组」,已修复 | +| S8 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过(修复后) | 合并 TXT 共 10 条,按时间升序交错;附带 1 张图片。发现编辑模式底部的「合并投递 / 删除」被标签栏挡住、已选计数被截成「已选…」,已修复 | +| S9 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过(修复后) | 选择「我的 iPhone/投递测试」后投递到文件夹:生成 `微信流/蜗牛的聊天.md`(frontmatter 含 chat、scene、messages、archive)和 `微信流/附件/`(jpg + 原始 ZIP)。发现设置页子文件夹输入框没有标签、投递后目标宫格当场重排,已修复 | +| S10 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过 | 删除后 5 秒内点「撤销」,`Ready/` 下批次保留;不撤销时 5 秒后 `Ready/` 被删除 | +| S11 | 2026-10-23 | 同上 | 0.1.0 (1) | 通过 | `simctl terminate` 杀掉 App,从「文件」再分享 `interleave.zip`,重新打开后出现新卡片(未投递) | + +另外顺带验证:引导页 3 页、「开始使用」结束引导;卡片右滑直接打开投递面板;场景开关和导入场景(修复后)。 + +## 验收中发现并修复的问题 + +| 现象 | 原因 | 提交 | +|---|---|---| +| 0 字节文件也被存进中转站 | 分享扩展没有检查空文件 | cfbced3 `[AI] fix: share extension rejects empty files` | +| 点卡片不进详情,只高亮 | 非编辑状态下 `List(selection:)` 吞掉了点击 | 0d48b3f | +| 引导页第 3 页的 Obsidian 按钮压住页码点 | 按钮在 Spacer 之下 | 0d48b3f | +| 场景开关打不开,投递面板只有「不带场景」 | 绑定用了只查已启用场景的 `scene(id:)` 和保留旧开关的 `replace(_:)`;导入同理 | 767fedd | +| 单组发送完成后按钮显示「继续发送第 2/1 组」 | 标题没有处理全部发完的情况 | 34e2d5a | +| 编辑模式下「合并投递 / 删除」被标签栏挡住;计数被截断 | 底部工具栏和标签栏重叠 | 34e2d5a | +| 设置页两行「微信流」看不出是什么 | 子文件夹 TextField 没有标签 | 34e2d5a | +| 投递成功后目标宫格当场重排,刚点的目标跳走 | 宫格直接读 `preferences.targets`,记录投递时最近使用的目标会排到最前 | 34e2d5a | +| 真机:微信导出的单条消息(ZIP 里一个 TXT,只有 `·` 标题行、没有时间行)显示「解析失败」 | 只认聊天记录格式。现在按内容分三种:聊天记录、普通文本(卡片标「文本」,详情显示全文、链接可点,投递时用原文件名)、无文本(仍是「解析失败」,只能发原文件) | 本次提交 | + +## 已知限制(未改) + +- 一个批次里有多个 ZIP 时,卡片标题和条数取第一个能解析的 ZIP,其余 ZIP 只计入附件数(`RelaySummary.make(for:)`)。规格没有要求多 ZIP 的合并摘要;投递时多个 ZIP 会全部带上。 +- 撤销窗口是 5 秒(规格值)。 + +## 真机验收(§8.5) + +由用户在真机上操作,Agent 记录结果。 + +真机环境已就绪(2026-10-23):iPhone 16 Pro / iOS 26.5,免费 Apple ID 的 Personal Team 签名,Bundle ID 和 App Group 用 `Signing.local.xcconfig` 换成个人前缀(b896943 起支持覆盖)。主 App 和分享扩展都已装上,App 能打开,App Group 在免费团队下可用。安装步骤见 [真机安装](ios-真机安装.zh-CN.md);免费签名 7 天过期,验收前先重装。 + +| 编号 | 内容 | 日期 | 设备/系统 | App 版本 | 结果 | 证据 | +|---|---|---|---|---|---|---| +| R1 | 微信 → 转到其他应用 → 微信流,单人和多人群各一次;多人群样本含链接、视频号、视频、文件 | 2026-10-24 | iPhone 16 Pro / iOS 26.5 | 0.1.0 (1) | 部分通过 | 单人聊天:卡片 8 条消息、1 个附件,详情里图片、表情占位、链接卡片、视频号文字都正常显示。单条消息导出(无时间行)修复后显示为「文本」卡片(ab0681b)。多人群样本未测 | +| R2 | 投递到豆包、千问:TXT + 3 张图 + 提示词;记录对方收到几个附件、文本是否进输入框,据此填 `maxAttachments` | 2026-10-24 | iPhone 16 Pro / iOS 26.5 | 0.1.0 (1) | 部分通过 | 豆包:投递面板提示「请在下一屏选择豆包」,分享面板显示「纯文本和1张图像」,豆包输入区收到 2 个附件(1 张图 + `聊天记录` TXT);提示词**没有**进输入框,需从剪贴板粘贴。样本只有 1 张图,`maxAttachments` 未测出。千问:TXT+图片只收到图片;图片在前也只有图片;文字+图片都显示了,但随后弹出「格式不支持」;单个 PDF(图片插在对应消息下)完整收到,千问改为发 PDF。附件类文件:「放到「文件」」导出到 我的iPhone › 微信流 后,在千问「添加文件」里可多选,PDF、Word、Excel、TXT、日志、JSON 可选,图片、视频、7z 置灰;导出改为把图片并入「聊天记录.pdf」,全选即可一次发出(真机确认:PDF 与各文档全部进了千问的同一个输入框),视频和压缩包仍发不了。随后按用户意见统一为:豆包、千问的分享只发聊天记录 TXT(提示词走剪贴板),TXT 里提到的图片和附件在发送时自动放到 我的iPhone › 微信流 › 以聊天命名的文件夹,需要时再从对方 App 的「添加文件」选;千问只收 TXT 是否正常待真机确认。真机发现千问「添加文件」里图片、视频都选不了,改为(方案 A):发送时图片和视频存到「照片」(只要添加权限),在千问点「相册」选;其他附件仍放 我的iPhone › 微信流;千问相册能否选视频待确认。真机反馈:文字转进去后图片和视频加不进去,改回默认发「图文合一 PDF」,「设置 › 豆包、千问等 › 图片怎么发」可切到「只发 TXT,图片存到照片」;两种方式下视频都存「照片」,其他附件放 微信流 文件夹 | +| R3 | 投递到 ChatGPT、WorkBuddy:ZIP + 提示词;对方是否读到 ZIP 内的聊天内容 | — | — | — | 待真机 | — | +| R4 | Claude、DeepSeek、WeSight 是否接受 ZIP;结果更新规格 6.6 的表 | — | — | — | 待真机 | — | +| R5 | Obsidian 库放在 iCloud 和「我的 iPhone」各一次;Obsidian 打开后能否立刻看到新笔记 | — | — | — | 待真机 | — | +| R6 | 30 MB 以上的 ZIP 从微信分享;扩展不崩溃,记录耗时 | — | — | — | 待真机 | — | +| R7 | 分享扩展发本地通知(可选,§11 Q3);能否发出、点开能否定位到批次 | 2026-10-24 | iPhone 17 Simulator / iOS 26.5 | 0.1.0 (1) | 模拟器通过,待真机 | 「快速投递」:从「文件」分享后弹出「已存入中转站 · 点一下投递到「ChatGPT」,长按换目标」;点横幅回到微信流,投递面板预选上次的目标并自动弹出分享面板,取消后停在面板、不重复发送。长按出目标按钮在模拟器里无法触发(注入的触摸不算长按),只有单元测试覆盖,待真机 | + +真机截图放 `docs/design/assets/ios-验收/`,入库前先给聊天内容打码。 + +## 复跑 + +2026-10-23,34e2d5a 之后运行 `ios/Scripts/verify.sh`,退出码 0: + +- Mac `swift test`:186 个测试,1 个跳过,0 失败 +- iOS 类型检查 WeChatBridgeCore:通过 +- xcodegen:通过 +- iOS 单元测试(iPhone 17 Simulator):28 个测试,0 失败 + +2026-10-24,加入快速投递后重跑,退出码 0:Mac `swift test` 186 个测试(1 个跳过),iOS 单元测试 40 个,均 0 失败。 diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..bcea894 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,3 @@ +WeChatBridge.xcodeproj/ +build/ +Config/Signing.local.xcconfig diff --git a/ios/App/Deliver/ActivitySheet.swift b/ios/App/Deliver/ActivitySheet.swift new file mode 100644 index 0000000..549c82c --- /dev/null +++ b/ios/App/Deliver/ActivitySheet.swift @@ -0,0 +1,40 @@ +import UIKit + +/// Presents the system share sheet from UIKit directly. Wrapped in a SwiftUI +/// `.sheet` it lands inside a second, mostly empty sheet; presented from the +/// top view controller it looks the way every other app's does. +enum ActivitySheet { + struct Result { + let completed: Bool + /// Often the receiving extension's bundle id: kept in the delivery + /// detail so the target table can be corrected from real use. + let activityType: String? + } + + @MainActor + static func present(items: [Any], completion: @escaping (Result) -> Void) { + guard let top = topViewController() else { + completion(Result(completed: false, activityType: nil)) + return + } + let controller = UIActivityViewController(activityItems: items, applicationActivities: nil) + controller.completionWithItemsHandler = { type, completed, _, _ in + completion(Result(completed: completed, activityType: type?.rawValue)) + } + controller.popoverPresentationController?.sourceView = top.view + top.present(controller, animated: true) + } + + @MainActor + private static func topViewController() -> UIViewController? { + let window = UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene } + .flatMap(\.windows) + .first(where: \.isKeyWindow) + var top = window?.rootViewController + while let presented = top?.presentedViewController, !presented.isBeingDismissed { + top = presented + } + return top + } +} diff --git a/ios/App/Deliver/DeliveryActivityController.swift b/ios/App/Deliver/DeliveryActivityController.swift new file mode 100644 index 0000000..34121aa --- /dev/null +++ b/ios/App/Deliver/DeliveryActivityController.swift @@ -0,0 +1,56 @@ +import ActivityKit +import Foundation + +/// Starts and steers the delivery Live Activity. Only one is up at a time: a +/// new delivery replaces the last one's. +@MainActor +enum DeliveryActivityController { + /// Started just before the share sheet, while the app is still in front + /// (ActivityKit refuses a request from the background). + static func start( + batchID: UUID, + title: String, + detail: String, + target: TargetProfile, + prompt: String, + enabled: Bool + ) { + guard enabled, ActivityAuthorizationInfo().areActivitiesEnabled else { return } + endAll() + UserDefaults.standard.set(prompt, forKey: DeliveryActivityPrompt.key) + let attributes = DeliveryActivityAttributes( + batchID: batchID.uuidString, + title: title, + detail: detail, + targetID: target.id, + targetName: target.displayName + ) + let state = DeliveryActivityAttributes.ContentState(phase: .choosing, hasPrompt: !prompt.isEmpty) + _ = try? Activity.request(attributes: attributes, content: content(state), pushType: nil) + } + + static func markSent() { + for activity in Activity.activities { + var state = activity.content.state + state.phase = .sent + Task { await activity.update(content(state)) } + } + } + + /// The share sheet was cancelled: nothing went out, nothing to come back to. + static func cancel() { + endAll() + } + + static func endAll() { + UserDefaults.standard.removeObject(forKey: DeliveryActivityPrompt.key) + for activity in Activity.activities { + Task { await activity.end(nil, dismissalPolicy: .immediate) } + } + } + + /// Greyed after an hour; by then the hand-off is long done. + private static func content(_ state: DeliveryActivityAttributes.ContentState) -> ActivityContent { + ActivityContent(state: state, staleDate: Date().addingTimeInterval(60 * 60)) + } +} diff --git a/ios/App/Deliver/DeliveryPlanner.swift b/ios/App/Deliver/DeliveryPlanner.swift new file mode 100644 index 0000000..3582eb4 --- /dev/null +++ b/ios/App/Deliver/DeliveryPlanner.swift @@ -0,0 +1,221 @@ +import Foundation +import UniformTypeIdentifiers +import WeChatBridgeCore + +struct DeliveryRequest { + /// One batch, or several for a merged delivery. + let batches: [ReadyBatch] + let target: TargetProfile + let prompt: String? +} + +struct DeliveryPackage { + /// Removed when the delivery ends, and at the next launch otherwise. + let workDirectory: URL + /// One share sheet per group; the transcript is always first in the first. + let shares: [[URL]] + let prompt: String? + /// File names this format leaves out (videos, documents), for the preview. + let omitted: [String] + /// Images drawn into the PDF, which the export leaves out; empty when + /// the images go as files. + var inPDF: Set = [] + + var fileCount: Int { shares.reduce(0) { $0 + $1.count } } + + /// Just the transcript: 豆包 and 千问 read it whole, and the images and + /// attachments it names go to 「我的iPhone › 微信流」 instead (seen on + /// device: 千问 keeps only the images when a share mixes them with a TXT). + func transcriptOnly() -> DeliveryPackage { + guard let transcript = shares.first?.first else { return self } + let rest = shares.flatMap { $0 }.dropFirst().map(\.lastPathComponent) + return DeliveryPackage(workDirectory: workDirectory, shares: [[transcript]], prompt: prompt, omitted: rest + omitted) + } +} + +/// Turns batches into the files one share sheet hands over. Pure file work, no +/// UIKit, so every rule here is covered by unit tests. +enum DeliveryPlanner { + enum Failure: LocalizedError { + case noArchive + case unsupportedFormat + + var errorDescription: String? { + switch self { + case .noArchive: "这批内容里没有可读的文本,可以改为发送原始文件。" + case .unsupportedFormat: "这个目标不通过分享面板投递。" + } + } + } + + static let transcriptName = "聊天记录.txt" + + static var deliveriesRoot: URL { + FileManager.default.temporaryDirectory.appendingPathComponent("Deliveries", isDirectory: true) + } + + static func plan(_ request: DeliveryRequest, fileManager: FileManager = .default) throws -> DeliveryPackage { + let work = deliveriesRoot.appendingPathComponent(UUID().uuidString, isDirectory: true) + try fileManager.createDirectory(at: work, withIntermediateDirectories: true) + do { + switch request.target.format { + case .archive: + return try archive(request, into: work, fileManager: fileManager) + case .transcriptAndImages: + return try transcriptAndImages(request, into: work, fileManager: fileManager) + case .knowledgeNote, .folder: + throw Failure.unsupportedFormat + } + } catch { + try? fileManager.removeItem(at: work) + throw error + } + } + + /// Leftovers from a delivery the app was killed during. + static func cleanUp(fileManager: FileManager = .default) { + try? fileManager.removeItem(at: deliveriesRoot) + } + + // MARK: - Archive + + /// Copies, never the originals in the App Group: a receiving app or the + /// system may touch what it is handed. + private static func archive(_ request: DeliveryRequest, into work: URL, fileManager: FileManager) throws -> DeliveryPackage { + var used = Set() + var urls: [URL] = [] + for item in request.batches.flatMap(\.items) { + let name = uniqueName(item.displayName, used: &used) + let destination = work.appendingPathComponent(name) + try fileManager.copyItem(at: item.url, to: destination) + urls.append(destination) + } + return DeliveryPackage( + workDirectory: work, + shares: group(urls, max: request.target.maxAttachments), + prompt: request.prompt, + omitted: [] + ) + } + + // MARK: - Transcript and images + + private struct Source { + let body: String + /// False for a text in another layout, which cannot be merged by time. + let isChat: Bool + let transcriptPath: String + let directory: URL + let names: [String] + } + + private static func transcriptAndImages(_ request: DeliveryRequest, into work: URL, fileManager: FileManager) throws -> DeliveryPackage { + var sources: [Source] = [] + var omitted: [String] = [] + for batch in request.batches { + var found = false + for item in batch.items { + if item.url.pathExtension.lowercased() == "zip", + let data = try? Data(contentsOf: item.url, options: .mappedIfSafe), + let transcript = try WeChatNativeArchive.transcript(data) { + let directory = work.appendingPathComponent("src/\(batch.id.uuidString)/\(item.id.uuidString)", isDirectory: true) + try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + let names = try WeChatNativeArchive.extract(data, to: directory) + sources.append(Source(body: transcript.body, isChat: transcript.records != nil, transcriptPath: transcript.path, directory: directory, names: names)) + found = true + } else { + omitted.append(item.displayName) + } + } + if !found { throw Failure.noArchive } + } + + let output = work.appendingPathComponent("out", isDirectory: true) + try fileManager.createDirectory(at: output, withIntermediateDirectories: true) + + // Images first, so a renamed duplicate is known before the merged + // transcript is written and can point at its new name. + var used: Set = [transcriptName] + var byName: [String: URL] = [:] + var images: [URL] = [] + var renames: [[String: String]] = [] + for source in sources { + var renamed: [String: String] = [:] + for name in source.names where name != source.transcriptPath && !name.hasSuffix("/") { + let file = source.directory.appendingPathComponent(name) + let leaf = (name as NSString).lastPathComponent + guard isImage(leaf) else { + omitted.append(leaf) + continue + } + if let existing = byName[leaf], fileManager.contentsEqual(atPath: existing.path, andPath: file.path) { + continue + } + let finalName = uniqueName(leaf, used: &used) + if finalName != leaf { renamed[leaf] = finalName } + let destination = output.appendingPathComponent(finalName) + try fileManager.copyItem(at: file, to: destination) + if byName[leaf] == nil { byName[leaf] = destination } + images.append(destination) + } + renames.append(renamed) + } + + // A text that is not a chat record keeps its own name. + let textName = sources.contains(where: \.isChat) ? transcriptName : (sources[0].transcriptPath as NSString).lastPathComponent + let transcriptURL = output.appendingPathComponent(textName) + if sources.count == 1 { + // Byte for byte: a single export goes out exactly as WeChat wrote it. + let original = sources[0].directory.appendingPathComponent(sources[0].transcriptPath) + try fileManager.copyItem(at: original, to: transcriptURL) + } else { + let bodies = zip(sources, renames).map { source, renamed in + renamed.reduce(source.body) { body, pair in + body.replacingOccurrences(of: "[图片] \(pair.key)", with: "[图片] \(pair.value)") + } + } + // Only chat records carry times to interleave by; anything else + // goes out in the order it was picked. + let merged = sources.allSatisfy(\.isChat) + ? try TranscriptMerge.merge(bodies) + : bodies.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.joined(separator: "\n\n") + try merged.write(to: transcriptURL, atomically: true, encoding: .utf8) + } + + try? fileManager.removeItem(at: work.appendingPathComponent("src")) + return DeliveryPackage( + workDirectory: work, + shares: group([transcriptURL] + images, max: request.target.maxAttachments), + prompt: request.prompt, + omitted: omitted + ) + } + + // MARK: - Helpers + + static func isImage(_ name: String) -> Bool { + guard let type = UTType(filenameExtension: (name as NSString).pathExtension) else { return false } + return type.conforms(to: .image) + } + + /// `name.jpg`, then `name (2).jpg`, `name (3).jpg`… + static func uniqueName(_ name: String, used: inout Set) -> String { + var candidate = name + var index = 2 + let base = (name as NSString).deletingPathExtension + let ext = (name as NSString).pathExtension + while used.contains(candidate) { + candidate = ext.isEmpty ? "\(base) (\(index))" : "\(base) (\(index)).\(ext)" + index += 1 + } + used.insert(candidate) + return candidate + } + + /// Splits into share sheets of at most `max` files. The transcript (first + /// url) only goes in the first group either way. + static func group(_ urls: [URL], max: Int?) -> [[URL]] { + guard let max, max > 0, urls.count > max else { return urls.isEmpty ? [] : [urls] } + return stride(from: 0, to: urls.count, by: max).map { Array(urls[$0.. { Set(summaries.flatMap(\.senders)) } + private var end: Date? { summaries.compactMap(\.end).max() } + private var parseFailed: Bool { !summaries.isEmpty && summaries.allSatisfy(\.parseFailed) } + + /// The chosen target as it will actually be used this time. + private var effectiveTarget: TargetProfile? { + guard var target else { return nil } + if target.format.usesShareSheet && (forceArchive || parseFailed) { target.format = .archive } + return target + } + + var body: some View { + NavigationStack { + Form { + Section("投递到") { targetGrid } + if effectiveTarget != nil { + Section { scenePicker } + Section("预览") { preview } + } + } + .navigationTitle(entries.count > 1 ? "合并投递 \(entries.count) 批" : "投递") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("关闭") { finishSheet() } } + } + .safeAreaInset(edge: .bottom) { sendBar } + .overlay(alignment: .top) { ToastView(text: $toast) } + .overlay { + if let hint { + Text(hint) + .font(.title3.weight(.semibold)) + .multilineTextAlignment(.center) + .padding(24) + .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 16)) + } + } + } + // Full height: at medium only the grid showed, with send and preview + // below the fold and the chat bleeding through the glass. + .presentationDetents([.large]) + .presentationBackground(Color(.systemGroupedBackground)) + .onAppear(perform: setUp) + .onChange(of: target) { _ in replan() } + .onChange(of: forceArchive) { _ in replan() } + .onChange(of: sceneID) { _ in renderPrompt() } + } + + // MARK: - Sections + + private var targetGrid: some View { + LazyVGrid(columns: [GridItem(.adaptive(minimum: 76), spacing: 12)], spacing: 14) { + ForEach(targets) { profile in + let selected = target?.id == profile.id + Button { target = profile } label: { + VStack(spacing: 6) { + TargetIcon(profile: profile, size: 50) + .padding(3) + .overlay { + RoundedRectangle(cornerRadius: 14, style: .continuous) + .strokeBorder(Color.accentColor, lineWidth: selected ? 2.5 : 0) + } + .overlay(alignment: .topTrailing) { + if selected { + Image(systemName: "checkmark.circle.fill") + .font(.system(size: 18)) + .symbolRenderingMode(.palette) + .foregroundStyle(.white, Color.accentColor) + .offset(x: 6, y: -6) + } + } + Text(profile.displayName) + .font(.caption.weight(selected ? .semibold : .regular)) + .foregroundStyle(selected ? Color.accentColor : .primary) + .lineLimit(1) + } + } + .buttonStyle(.plain) + .accessibilityAddTraits(target?.id == profile.id ? .isSelected : []) + } + } + .padding(.vertical, 4) + } + + private var scenePicker: some View { + Group { + Picker("场景", selection: $sceneID) { + Text("不带场景").tag("") + ForEach(preferences.scenes.enabledScenes) { Text($0.name).tag($0.id) } + } + if !sceneID.isEmpty { + TextEditor(text: $prompt) + .frame(minHeight: 100) + .font(.footnote) + Text("发送时会复制到剪贴板,可在对方输入框里粘贴。") + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + + @ViewBuilder + private var preview: some View { + if let target = effectiveTarget { + switch target.format { + case .knowledgeNote: + LabeledContent("写入", value: FolderBookmark.name(of: preferences.obsidianBookmark).map { "\($0)/\(preferences.obsidianSubfolder)" } ?? "未选择 Obsidian 库") + case .folder: + LabeledContent("写入", value: FolderBookmark.name(of: preferences.folderBookmark).map { "\($0)/\(preferences.folderSubfolder)" } ?? "未选择文件夹") + case .archive, .transcriptAndImages: + if planning { + ProgressView() + } else if let planError { + Text(planError).foregroundStyle(.red) + } else if let package { + ForEach(Self.rows(package), id: \.title) { row in + HStack(spacing: 12) { + Image(systemName: row.symbol) + .foregroundStyle(Color.accentColor) + .frame(width: 24) + Text(row.title).lineLimit(1).truncationMode(.middle) + Spacer() + Text(ByteFormat.string(row.bytes)).font(.footnote).foregroundStyle(.secondary) + } + } + if package.shares.count > 1 { + Text("文件较多,将分 \(package.shares.count) 次发送").font(.caption).foregroundStyle(.secondary) + } + if !package.omitted.isEmpty { + VStack(alignment: .leading, spacing: 6) { + Text(Self.sideNote(package.omitted)) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(3) + Button("改发原始 ZIP") { forceArchive = true } + .font(.footnote) + .buttonStyle(.borderless) + } + } + } + } + } + } + + private var sendBar: some View { + VStack(spacing: 8) { + if let savedNote, effectiveTarget?.id == "obsidian", let url = Self.obsidianURL(for: savedNote) { + Button("在 Obsidian 中打开") { openURL(url) } + } + Button(action: send) { + Text(sendTitle).frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + .disabled(!canSend) + } + .padding() + .background(.bar) + } + + private var sendTitle: String { + guard let package, nextGroup > 0 else { return "发送" } + // Past the last group the counter would read "2/1". + if nextGroup >= package.shares.count { return "已发送" } + return "继续发送第 \(nextGroup + 1)/\(package.shares.count) 组" + } + + private var canSend: Bool { + guard let target = effectiveTarget, !busy else { return false } + if target.format.usesShareSheet { return package != nil && nextGroup < (package?.shares.count ?? 0) } + return true + } + + // MARK: - Planning + + private func setUp() { + targets = preferences.targets + target = selection.quickTargetID.flatMap { id in targets.first { $0.id == id } } ?? targets.first + let resolution = SceneResolver.resolve( + groupName: chatName, + settings: preferences.scenes, + memories: preferences.groupMemory, + senders: senders + ) + sceneID = resolution.scene?.id ?? "" + renderPrompt() + } + + private func renderPrompt() { + guard let scene = preferences.scenes.scene(id: sceneID) else { prompt = ""; return } + let memory = chatName.flatMap { preferences.groupMemory[GroupName.normalize($0)] } + prompt = ScenePrompt.render(scene: scene, previousSummaryAt: memory?.lastSummaryAt, currentEnd: end) ?? "" + } + + private func replan() { + if let package { try? FileManager.default.removeItem(at: package.workDirectory) } + package = nil + planError = nil + nextGroup = 0 + savedNote = nil + guard let target = effectiveTarget, target.format.usesShareSheet else { + // Writers need no planning; a quick delivery writes straight away. + if effectiveTarget != nil { sendIfQuick() } + return + } + planning = true + let request = DeliveryRequest(batches: entries.map(\.batch), target: target, prompt: nil) + let imagesInPDF = preferences.imagesInPDF + Task { + let result = await Task.detached(priority: .userInitiated) { Result { + let package = try DeliveryPlanner.plan(request) + guard request.target.format == .transcriptAndImages else { return package } + return imagesInPDF ? try package.foldedIntoPDF() : package.transcriptOnly() + } }.value + // A newer choice may have replaced this one while it ran. + guard effectiveTarget == target else { + if case .success(let stale) = result { try? FileManager.default.removeItem(at: stale.workDirectory) } + return + } + planning = false + switch result { + case .success(let package): + self.package = package + sendIfQuick() + case .failure(let error): planError = error.localizedDescription + } + } + } + + // MARK: - Sending + + /// The notification already said where this goes; the user's next tap + /// should be the app in the share sheet, not 「发送」. + private func sendIfQuick() { + guard selection.quickTargetID != nil, !quickSent, canSend else { return } + quickSent = true + send() + } + + /// The images and attachments the TXT names: media into Photos for the + /// target's 相册 picker, the rest into 「我的iPhone › 微信流」 for its file + /// picker. Run only once the share went through, so a cancelled one + /// leaves nothing behind. Images the PDF already carries are skipped. + private func exportForPicking(_ package: DeliveryPackage) async -> String? { + let jobs = entries.map { FilesExport.Job(batch: $0.batch, name: FilesExport.folderName(for: $0), inPDF: package.inPDF) } + do { + let summary = try await FilesExport.exportForPicking(jobs) + return summary.isEmpty ? nil : summary.message + } catch { + return "图片和附件没能存下:\(error.localizedDescription)" + } + } + + /// Whether a completed share of the first group also exports. + private func exports(_ package: DeliveryPackage, target: TargetProfile) -> Bool { + target.format == .transcriptAndImages && !package.omitted.isEmpty + } + + /// 「发送时存到…」 under the preview: which names go where. + static func sideNote(_ omitted: [String]) -> String { + let media = omitted.filter(FilesExport.isMedia) + let files = omitted.filter { !FilesExport.isMedia($0) } + var parts: [String] = [] + if !media.isEmpty { parts.append("图片和视频存到「照片」:\(media.joined(separator: "、"))") } + if !files.isEmpty { parts.append("附件放到「我的iPhone › 微信流」:\(files.joined(separator: "、"))") } + return "发送时" + parts.joined(separator: ";") + } + + private func send() { + guard let target = effectiveTarget else { return } + if nextGroup == 0, let id = selection.collectionID, store.beginCollectionDelivery(id) == nil { return } + let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines) + switch target.format { + case .archive, .transcriptAndImages: + guard let package, nextGroup < package.shares.count else { return } + if !text.isEmpty { + UIPasteboard.general.string = text + toast = "提示词已复制,可在对方输入框粘贴" + } + let group = package.shares[nextGroup] + let asksPhotos = nextGroup == 0 && exports(package, target: target) && package.omitted.contains(where: FilesExport.isMedia) + busy = true + let message = target.sendHint(hasPrompt: !text.isEmpty) + withAnimation { hint = message.isEmpty ? nil : message } + if nextGroup == 0, let batchID = selection.batchIDs.first { + DeliveryActivityController.start( + batchID: batchID, + title: chatName ?? entries.first?.batch.items.first?.displayName ?? "聊天记录", + detail: activityDetail, + target: target, + prompt: text, + enabled: preferences.liveActivity + ) + } + Task { + // Before the share sheet, so the one-time prompt never lands on it. + if asksPhotos { _ = await PhotosSaver.authorize() } + // Long enough to read the second line when there is one. + try? await Task.sleep(nanoseconds: message.contains("\n") ? 2_500_000_000 : 1_000_000_000) + withAnimation { hint = nil } + let items: [Any] = (nextGroup == 0 && !text.isEmpty && !target.dropsSharedText ? [text] : []) + group + ActivitySheet.present(items: items) { result in + busy = false + shareFinished(result, target: target, package: package) + } + } + case .knowledgeNote, .folder: + writeNote(target: target) + } + } + + private func shareFinished(_ result: ActivitySheet.Result, target: TargetProfile, package: DeliveryPackage) { + guard result.completed else { + if nextGroup == 0 { DeliveryActivityController.cancel() } + if nextGroup == 0, let id = selection.collectionID { + store.finishCollectionDelivery(id, succeeded: false, target: target.displayName, scene: sceneName) + } + return + } + let exporting = nextGroup == 0 && exports(package, target: target) + if nextGroup == 0 { + recordDelivery(target: target, detail: "\(target.format.label) · \(result.activityType ?? "未知去向")") + DeliveryActivityController.markSent() + } + nextGroup += 1 + let hasPrompt = !prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + let done = nextGroup < package.shares.count ? nil + : hasPrompt && target.dropsSharedText ? TargetProfile.pasteHint : "已交给分享面板" + guard exporting else { + if let done { toast = done } + return + } + busy = true + Task { + // Said once the share sheet is gone; a toast under it would never be seen. + let note = await exportForPicking(package) + busy = false + toast = [done, note].compactMap { $0 }.joined(separator: "\n") + } + } + + private func writeNote(target: TargetProfile) { + let urls = entries.flatMap(\.batch.items).map(\.url) + let isObsidian = target.format == .knowledgeNote + busy = true + defer { busy = false } + do { + let written = try FolderBookmark.access( + isObsidian ? preferences.obsidianBookmark : preferences.folderBookmark, + refresh: { renewed in + if isObsidian { preferences.obsidianBookmark = renewed } else { preferences.folderBookmark = renewed } + } + ) { folder in + isObsidian + ? try KnowledgeDelivery.deliver(urls: urls, vaultPath: folder.path, subfolder: preferences.obsidianSubfolder, chatName: chatName, sceneName: sceneName) + : try KnowledgeDelivery.deliver(urls: urls, folderPath: folder.path, subfolder: preferences.folderSubfolder, chatName: chatName, sceneName: sceneName) + } + let note = written.first { $0.pathExtension == "md" } + savedNote = note + recordDelivery(target: target, detail: note?.lastPathComponent ?? target.displayName) + toast = "已保存到 \(target.displayName) · \(note?.deletingPathExtension().lastPathComponent ?? "")" + } catch { + if let id = selection.collectionID { + store.finishCollectionDelivery(id, succeeded: false, target: target.displayName, scene: sceneName) + } + toast = error.localizedDescription + } + } + + private var sceneName: String? { preferences.scenes.scene(id: sceneID)?.name } + + /// 「4 条消息 · 1 个附件」 for the Live Activity; empty for plain text. + private var activityDetail: String { + var parts: [String] = [] + let messages = summaries.compactMap(\.messageCount).reduce(0, +) + if messages > 0 { parts.append("\(messages) 条消息") } + let media = summaries.map(\.mediaCount).reduce(0, +) + if media > 0 { parts.append("\(media) 个附件") } + return parts.joined(separator: " · ") + } + + private func recordDelivery(target: TargetProfile, detail: String) { + let scene = preferences.scenes.scene(id: sceneID) + store.markDelivered(selection.batchIDs, targetName: target.displayName, detail: detail, chatName: chatName, scene: scene) + if let id = selection.collectionID { + store.finishCollectionDelivery(id, succeeded: true, target: target.displayName, scene: scene?.name) + } + if let scene, let chatName { + preferences.rememberGroup(displayName: chatName, sceneID: scene.id, senders: senders, end: end) + } + preferences.lastTarget = target.id + } + + private func finishSheet() { + if let package { try? FileManager.default.removeItem(at: package.workDirectory) } + dismiss() + } + + // MARK: - Text + + struct PreviewRow { + let symbol: String + let title: String + let bytes: Int64 + } + + /// One row per file, except that images fold into one 「3 张图片」 row. + static func rows(_ package: DeliveryPackage, fileManager: FileManager = .default) -> [PreviewRow] { + func size(_ url: URL) -> Int64 { + ((try? fileManager.attributesOfItem(atPath: url.path))?[.size] as? NSNumber)?.int64Value ?? 0 + } + let urls = package.shares.flatMap { $0 } + let images = urls.filter { DeliveryPlanner.isImage($0.lastPathComponent) } + var rows = urls.filter { !DeliveryPlanner.isImage($0.lastPathComponent) }.map { url in + PreviewRow( + symbol: url.pathExtension.lowercased() == "zip" ? "doc.zipper" : "doc.text", + title: url.lastPathComponent, + bytes: size(url) + ) + } + if !images.isEmpty { + rows.append(PreviewRow(symbol: "photo.on.rectangle", title: "\(images.count) 张图片", bytes: images.map(size).reduce(0, +))) + } + return rows + } + + static func obsidianURL(for note: URL) -> URL? { + var components = URLComponents() + components.scheme = "obsidian" + components.host = "open" + components.queryItems = [URLQueryItem(name: "path", value: note.path)] + guard let url = components.url, UIApplication.shared.canOpenURL(url) else { return nil } + return url + } +} diff --git a/ios/App/Deliver/FilesExport.swift b/ios/App/Deliver/FilesExport.swift new file mode 100644 index 0000000..81644b7 --- /dev/null +++ b/ios/App/Deliver/FilesExport.swift @@ -0,0 +1,218 @@ +import Foundation +import Photos +import UniformTypeIdentifiers +import WeChatBridgeCore + +/// Copies a chat's attachments into the app's Documents folder, which Files +/// shows as 「我的iPhone › 微信流」, and its images and videos into Photos. +/// 千问 takes documents only from its file picker and media only from 相册, +/// and neither through a share beside the TXT. +enum FilesExport { + static var root: URL { URL.documentsDirectory } + + /// Files lists 「微信流」 only once Documents holds something; on a phone + /// that never exported, the user would find no folder to open. + static func placeGuide(in root: URL = root) { + let guide = root.appendingPathComponent("使用说明.txt") + let text = "投递到豆包、千问时,聊天记录发过去(PDF 里带图片,或只发 TXT,可在「设置」里选);视频存到「照片」,其他附件放进这里以聊天命名的文件夹。\n需要时在对方 App 里点「相册」选图片和视频,点「添加文件」→ 我的iPhone → 微信流 选附件。也可以在中转站长按一条聊天,选「存图片和附件」。\n" + // Rewritten when the wording changes, so an older guide never lingers. + guard (try? Data(contentsOf: guide)) != Data(text.utf8) else { return } + try? Data(text.utf8).write(to: guide) + } + + /// `标题 10-20 09.00`: the chat's own name, and its start so two exports of + /// one group stay apart. Slashes and colons are not allowed in Files. + static func folderName(title: String, date: Date) -> String { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "zh_CN") + formatter.dateFormat = "MM-dd HH.mm" + let clean = title.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: "-") + return "\(clean) \(formatter.string(from: date))" + } + + static func folderName(for entry: RelayEntry) -> String { + folderName( + title: entry.summary?.title ?? entry.batch.chatName ?? entry.batch.items.first?.displayName ?? "聊天记录", + date: entry.summary?.start ?? entry.batch.createdAt + ) + } + + struct Exported { + /// The chat's folder under 「微信流」; nil when no document went there. + var folder: URL? + /// Images and videos, when the caller asked for them apart. + var media: [URL] = [] + } + + /// Photos takes these; 千问's file picker greys them out and its 相册 + /// picker is the only way they reach it. + static func isMedia(_ name: String) -> Bool { + guard let type = UTType(filenameExtension: (name as NSString).pathExtension) else { return false } + return type.conforms(to: .image) || type.conforms(to: .movie) + } + + /// One flat folder per chat with the files its TXT names, under their own + /// names; the TXT itself goes out by share. With `mediaInto`, images and + /// videos land there instead, for Photos. `inPDF` names the archive's + /// images already drawn into the shared PDF. The folder is built aside and + /// replaces the old one only once complete. + @discardableResult + static func export(_ batch: ReadyBatch, name: String, into root: URL = root, mediaInto mediaRoot: URL? = nil, inPDF: Set = [], fileManager: FileManager = .default) throws -> Exported { + let folder = root.appendingPathComponent(name, isDirectory: true) + let staging = fileManager.temporaryDirectory.appendingPathComponent("export-\(UUID().uuidString)", isDirectory: true) + defer { try? fileManager.removeItem(at: staging) } + let built = staging.appendingPathComponent("folder", isDirectory: true) + + var used: Set = [] + var usedMedia: Set = [] + var media: [URL] = [] + func place(_ file: URL, as leaf: String) throws { + if let mediaRoot, isMedia(leaf) { + try fileManager.createDirectory(at: mediaRoot, withIntermediateDirectories: true) + let destination = mediaRoot.appendingPathComponent(DeliveryPlanner.uniqueName(leaf, used: &usedMedia)) + try fileManager.copyItem(at: file, to: destination) + media.append(destination) + return + } + try fileManager.createDirectory(at: built, withIntermediateDirectories: true) + try fileManager.copyItem(at: file, to: built.appendingPathComponent(DeliveryPlanner.uniqueName(leaf, used: &used))) + } + for item in batch.items { + guard item.url.pathExtension.lowercased() == "zip", + let data = try? Data(contentsOf: item.url, options: .mappedIfSafe), + let transcript = try? WeChatNativeArchive.transcript(data) else { + // Not a WeChat export: the file itself is what the user has. + try place(item.url, as: item.displayName) + continue + } + let unpacked = staging.appendingPathComponent(item.id.uuidString, isDirectory: true) + try fileManager.createDirectory(at: unpacked, withIntermediateDirectories: true) + for path in try WeChatNativeArchive.extract(data, to: unpacked) where path != transcript.path { + let leaf = (path as NSString).lastPathComponent + var isDirectory: ObjCBool = false + let file = unpacked.appendingPathComponent(path) + guard !leaf.hasPrefix("."), !path.contains("__MACOSX"), !inPDF.contains(leaf), + fileManager.fileExists(atPath: file.path, isDirectory: &isDirectory), !isDirectory.boolValue else { continue } + try place(file, as: leaf) + } + } + try? fileManager.removeItem(at: folder) + guard fileManager.fileExists(atPath: built.path) else { return Exported(folder: nil, media: media) } + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + try fileManager.moveItem(at: built, to: folder) + return Exported(folder: folder, media: media) + } + + /// What one 「存图片和附件」 did, in the words the user reads. + struct Summary { + var folders: [String] = [] + var savedMedia = 0 + /// Media Photos refused or had no permission for, kept in the folders. + var keptMedia = 0 + var photosDenied = false + + var isEmpty: Bool { folders.isEmpty && savedMedia == 0 } + + var message: String { + var lines: [String] = [] + if savedMedia > 0 { lines.append("\(savedMedia) 个图片/视频已存到「照片」,在千问等 App 里点「相册」选取。") } + if photosDenied { + lines.append("没有添加照片的权限,图片和视频放进了下面的文件夹。可在「设置 › 微信流 › 照片」里打开。") + } else if keptMedia > 0 { + lines.append("\(keptMedia) 个图片/视频「照片」不收,放进了下面的文件夹。") + } + if !folders.isEmpty { lines.append("文件在「我的iPhone › 微信流 › \(folders.joined(separator: "、"))」,点「添加文件」选取。") } + return lines.isEmpty ? "这条聊天只有文字,没有图片或附件。" : lines.joined(separator: "\n") + } + } + + struct Job { + let batch: ReadyBatch + let name: String + var inPDF: Set = [] + } + + /// Exports every job, its media into its own subfolder of `mediaRoot` so + /// two chats' same-named images never meet. Names are made unique, so two + /// jobs never replace each other's folder. + static func stage(_ jobs: [Job], into root: URL = root, mediaRoot: URL) throws -> (names: [String], media: [[URL]]) { + var used: Set = [] + var names: [String] = [] + var media: [[URL]] = [] + for (index, job) in jobs.enumerated() { + let name = DeliveryPlanner.uniqueName(job.name, used: &used) + let exported = try export(job.batch, name: name, into: root, mediaInto: mediaRoot.appendingPathComponent("\(index)"), inPDF: job.inPDF) + names.append(name) + media.append(exported.media) + } + return (names, media) + } + + /// Media Photos did not take go into their chat's folder instead. + static func keep(_ files: [URL], in name: String, root: URL = root, fileManager: FileManager = .default) throws { + guard !files.isEmpty else { return } + let folder = root.appendingPathComponent(name, isDirectory: true) + try fileManager.createDirectory(at: folder, withIntermediateDirectories: true) + var used = Set((try? fileManager.contentsOfDirectory(atPath: folder.path)) ?? []) + for file in files { + try fileManager.copyItem(at: file, to: folder.appendingPathComponent(DeliveryPlanner.uniqueName(file.lastPathComponent, used: &used))) + } + } + + /// Images and videos into Photos, everything else into 「微信流」 folders. + static func exportForPicking(_ jobs: [Job]) async throws -> Summary { + let mediaRoot = FileManager.default.temporaryDirectory.appendingPathComponent("media-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: mediaRoot) } + let (names, media) = try stage(jobs, mediaRoot: mediaRoot) + var summary = Summary() + let all = media.flatMap { $0 } + if !all.isEmpty { + let refused: Set + switch await PhotosSaver.save(all) { + case .denied: + summary.photosDenied = true + refused = Set(all) + case .saved(let failed): + refused = Set(failed) + } + summary.savedMedia = all.count - refused.count + summary.keptMedia = refused.count + for (name, files) in zip(names, media) { + try keep(files.filter(refused.contains), in: name) + } + } + summary.folders = names.filter { FileManager.default.fileExists(atPath: root.appendingPathComponent($0).path) } + return summary + } +} + +enum PhotosSaver { + enum Outcome { case denied, saved(failed: [URL]) } + + /// Add-only access is enough to save and asks less of the user. Asked + /// before a share sheet opens, so the one-time prompt never lands on it. + static func authorize() async -> Bool { + let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly) + return status == .authorized || status == .limited + } + + /// The assets land at the top of 最近项目, where a picker opens. + static func save(_ files: [URL]) async -> Outcome { + guard await authorize() else { return .denied } + var failed: [URL] = [] + // One change each: a format Photos refuses must not sink the rest. + for file in files { + do { + try await PHPhotoLibrary.shared().performChanges { + let options = PHAssetResourceCreationOptions() + options.originalFilename = file.lastPathComponent + let type: PHAssetResourceType = DeliveryPlanner.isImage(file.lastPathComponent) ? .photo : .video + PHAssetCreationRequest.forAsset().addResource(with: type, fileURL: file, options: options) + } + } catch { + failed.append(file) + } + } + return .saved(failed: failed) + } +} diff --git a/ios/App/Deliver/TargetIcon.swift b/ios/App/Deliver/TargetIcon.swift new file mode 100644 index 0000000..e0b70e4 --- /dev/null +++ b/ios/App/Deliver/TargetIcon.swift @@ -0,0 +1,26 @@ +import SwiftUI + +/// A target as an app icon: its real logo when the project ships one, else an +/// SF Symbol on a tinted tile of the same shape. +struct TargetIcon: View { + let profile: TargetProfile + var size: CGFloat = 52 + + var body: some View { + let shape = RoundedRectangle(cornerRadius: size * 0.225, style: .continuous) + Group { + if let logo = profile.logo { + Image(logo).resizable().scaledToFill() + } else { + Image(systemName: profile.symbol) + .font(.system(size: size * 0.42, weight: .medium)) + .foregroundStyle(Color.accentColor) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(Color.accentColor.opacity(0.12)) + } + } + .frame(width: size, height: size) + .clipShape(shape) + .overlay(shape.strokeBorder(Color.primary.opacity(0.08), lineWidth: 0.5)) + } +} diff --git a/ios/App/Deliver/TargetProfile.swift b/ios/App/Deliver/TargetProfile.swift new file mode 100644 index 0000000..a57427b --- /dev/null +++ b/ios/App/Deliver/TargetProfile.swift @@ -0,0 +1,112 @@ +import Foundation + +enum DeliveryFormat: String, Codable, CaseIterable { + /// The original WeChat ZIP, untouched. + case archive + /// `聊天记录.txt` plus the images unpacked from the archive. + case transcriptAndImages + /// A Markdown note and the archive, written into the Obsidian vault. + case knowledgeNote + /// The same note shape, written into a folder the user picked. + case folder + + var label: String { + switch self { + case .archive: "发送 ZIP" + case .transcriptAndImages: "发送聊天记录和图片" + case .knowledgeNote: "写入 Obsidian" + case .folder: "写入文件夹" + } + } + + /// Whether this format ends in the system share sheet. + var usesShareSheet: Bool { self == .archive || self == .transcriptAndImages } +} + +/// What one destination can receive. iOS cannot hand content to a named app, +/// so choosing a target decides the *shape* of what is shared; the user still +/// taps the app in the share sheet, and `hint` tells them which. +struct TargetProfile: Identifiable, Hashable, Codable { + let id: String + let displayName: String + var format: DeliveryFormat + /// nil means no known limit. Filled from device tests (R2). + let maxAttachments: Int? + let symbol: String + + var hint: String { + switch format { + case .archive, .transcriptAndImages: + id == "other" ? "请在下一屏选择要发送到的 App" : "请在下一屏选择「\(displayName)」" + case .knowledgeNote, .folder: + "" + } + } + + /// Asset name of the app's own icon (from `shared/AppLogos`); nil for + /// targets that have none and fall back to `symbol`. + var logo: String? { + ["chatgpt", "doubao", "qwen", "workbuddy", "claude", "obsidian"].contains(id) ? "Logo-\(id)" : nil + } + + static let pasteHint = "提示词已复制,在输入框长按粘贴" + + /// Seen on device (R2, 2026-10-24): 豆包 drops the text in a share and + /// 千问 answers a text-plus-file share with 「格式不支持」, so the prompt + /// reaches these apps only through the clipboard. + var dropsSharedText: Bool { id == "doubao" || id == "qwen" } + + /// What to show before the share sheet; the paste line only when there is + /// a prompt the target will not receive. + func sendHint(hasPrompt: Bool) -> String { + guard hasPrompt, dropsSharedText, !hint.isEmpty else { return hint } + return "\(hint)\n\(Self.pasteHint)" + } + + /// Order is the default grid order. Formats follow the device tests of + /// 2026-10-24: ChatGPT and WorkBuddy took the ZIP, 豆包 and 千问 refused it + /// but took text and images. Claude and DeepSeek are untested and start on + /// the route every app tested so far accepts. + static let builtIn: [TargetProfile] = [ + TargetProfile(id: "chatgpt", displayName: "ChatGPT", format: .archive, maxAttachments: nil, symbol: "bubble.left.and.text.bubble.right"), + TargetProfile(id: "doubao", displayName: "豆包", format: .transcriptAndImages, maxAttachments: nil, symbol: "sparkles"), + TargetProfile(id: "qwen", displayName: "千问", format: .transcriptAndImages, maxAttachments: nil, symbol: "wand.and.stars"), + TargetProfile(id: "workbuddy", displayName: "WorkBuddy", format: .archive, maxAttachments: nil, symbol: "person.2"), + TargetProfile(id: "claude", displayName: "Claude", format: .transcriptAndImages, maxAttachments: nil, symbol: "asterisk"), + TargetProfile(id: "deepseek", displayName: "DeepSeek", format: .transcriptAndImages, maxAttachments: nil, symbol: "magnifyingglass"), + TargetProfile(id: "obsidian", displayName: "Obsidian", format: .knowledgeNote, maxAttachments: nil, symbol: "diamond"), + TargetProfile(id: "folder", displayName: "文件夹", format: .folder, maxAttachments: nil, symbol: "folder"), + TargetProfile(id: "other", displayName: "其他 App", format: .archive, maxAttachments: nil, symbol: "square.and.arrow.up"), + ] + + /// Only share-sheet targets can switch format; the two writers are fixed. + var canChangeFormat: Bool { format.usesShareSheet } + + /// The user's view of the list: stored order first (unknown ids keep their + /// built-in place after it), hidden ones removed, format overrides applied, + /// and the last-used target lifted to the front. + static func arranged( + _ profiles: [TargetProfile], + order: [String], + hidden: Set, + overrides: [String: String], + lastUsed: String? + ) -> [TargetProfile] { + var ordered = order.compactMap { id in profiles.first { $0.id == id } } + ordered += profiles.filter { !order.contains($0.id) } + ordered = ordered.filter { !hidden.contains($0.id) }.map { profile in + var profile = profile + if profile.canChangeFormat, + let raw = overrides[profile.id], + let format = DeliveryFormat(rawValue: raw), + format.usesShareSheet { + profile.format = format + } + return profile + } + if let lastUsed, let index = ordered.firstIndex(where: { $0.id == lastUsed }) { + ordered.insert(ordered.remove(at: index), at: 0) + } + return ordered + } +} diff --git a/ios/App/Deliver/TranscriptMerge.swift b/ios/App/Deliver/TranscriptMerge.swift new file mode 100644 index 0000000..792ad0d --- /dev/null +++ b/ios/App/Deliver/TranscriptMerge.swift @@ -0,0 +1,35 @@ +import Foundation +import WeChatBridgeCore + +/// Writes transcripts back in WeChat's own export format, so a merged +/// `聊天记录.txt` reads exactly like one WeChat produced — and parses with the +/// same `WeChatTranscriptRecord.parse` as the originals. +enum TranscriptMerge { + static func render(_ records: [WeChatTranscriptRecord], timeZone: TimeZone = .current) -> String { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .gregorian) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = timeZone + formatter.dateFormat = "yyyy年M月d日 HH:mm" + return records + .map { "·\($0.sender)\n\(formatter.string(from: $0.date))\n\($0.text)\n" } + .joined(separator: "\n") + } + + /// Time order, stable for equal minutes (WeChat stamps to the minute, so + /// ties are common and their original order is the only order there is). + /// A record appearing in two exports — overlapping forwards of the same + /// chat — is kept once. + static func merge(_ bodies: [String], timeZone: TimeZone = .current) throws -> String { + try render(mergedRecords(bodies, timeZone: timeZone), timeZone: timeZone) + } + + static func mergedRecords(_ bodies: [String], timeZone: TimeZone = .current) throws -> [WeChatTranscriptRecord] { + let all = try bodies.flatMap { try WeChatTranscriptRecord.parse($0, timeZone: timeZone) } + var seen = Set() + let unique = all.filter { seen.insert("\($0.sender)\u{1}\($0.date.timeIntervalSince1970)\u{1}\($0.text)").inserted } + return unique.enumerated() + .sorted { $0.element.date == $1.element.date ? $0.offset < $1.offset : $0.element.date < $1.element.date } + .map(\.element) + } +} diff --git a/ios/App/Deliver/TranscriptPDF.swift b/ios/App/Deliver/TranscriptPDF.swift new file mode 100644 index 0000000..fc32765 --- /dev/null +++ b/ios/App/Deliver/TranscriptPDF.swift @@ -0,0 +1,76 @@ +import UIKit + +extension DeliveryPackage { + /// The transcript and its images folded into one PDF, for targets that + /// keep only the images when a share mixes them with the TXT. A share + /// with no images stays as it is. An image that does not decode joins + /// `omitted`, so it is exported rather than lost. + func foldedIntoPDF() throws -> DeliveryPackage { + guard let group = shares.first, let transcript = group.first else { return self } + let images = shares.flatMap { $0 }.dropFirst().filter { DeliveryPlanner.isImage($0.lastPathComponent) } + guard !images.isEmpty else { return self } + let (pdf, drawn) = try TranscriptPDF.make(transcript: transcript, images: Array(images)) + let undrawn = images.filter { !drawn.contains($0) }.map(\.lastPathComponent) + return DeliveryPackage( + workDirectory: workDirectory, shares: [[pdf]], prompt: prompt, + omitted: undrawn + omitted, inPDF: Set(drawn.map(\.lastPathComponent)) + ) + } +} + +/// One A4 PDF of the transcript, each image drawn under the line that +/// mentions it; images no line mentions go at the end. Returns the images it +/// could draw. +enum TranscriptPDF { + static func make(transcript: URL, images: [URL]) throws -> (url: URL, drawn: [URL]) { + let body = try String(contentsOf: transcript, encoding: .utf8) + let page = CGRect(x: 0, y: 0, width: 595, height: 842) + let margin: CGFloat = 40 + let box = CGSize(width: page.width - margin * 2, height: page.height - margin * 2) + let style: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: 11), .foregroundColor: UIColor.black] + + var unplaced = images + var drawn: [URL] = [] + let text = NSMutableAttributedString() + func appendImage(_ url: URL) { + guard let image = UIImage(contentsOfFile: url.path), image.size.width > 0, image.size.height > 0 else { return } + // Half a page at most, so a tall screenshot never needs a page of its own. + let scale = min(1, box.width / image.size.width, box.height / 2 / image.size.height) + let attachment = NSTextAttachment() + attachment.image = image + attachment.bounds = CGRect(x: 0, y: 0, width: image.size.width * scale, height: image.size.height * scale) + text.append(NSAttributedString(attachment: attachment)) + text.append(NSAttributedString(string: "\n", attributes: style)) + drawn.append(url) + } + for line in body.components(separatedBy: .newlines) { + text.append(NSAttributedString(string: line + "\n", attributes: style)) + if let index = unplaced.firstIndex(where: { line.contains("[图片] \($0.lastPathComponent)") }) { + appendImage(unplaced.remove(at: index)) + } + } + unplaced.forEach(appendImage) + + let storage = NSTextStorage(attributedString: text) + let layout = NSLayoutManager() + storage.addLayoutManager(layout) + var containers: [NSTextContainer] = [] + repeat { + let container = NSTextContainer(size: box) + container.lineFragmentPadding = 0 + layout.addTextContainer(container) + containers.append(container) + } while NSMaxRange(layout.glyphRange(for: containers[containers.count - 1])) < layout.numberOfGlyphs && containers.count < 1000 + + let url = transcript.deletingPathExtension().appendingPathExtension("pdf") + try UIGraphicsPDFRenderer(bounds: page).writePDF(to: url) { context in + for container in containers { + context.beginPage() + let range = layout.glyphRange(for: container) + layout.drawBackground(forGlyphRange: range, at: CGPoint(x: margin, y: margin)) + layout.drawGlyphs(forGlyphRange: range, at: CGPoint(x: margin, y: margin)) + } + } + return (url, drawn) + } +} diff --git a/ios/App/Detail/ImageViewer.swift b/ios/App/Detail/ImageViewer.swift new file mode 100644 index 0000000..43b4f67 --- /dev/null +++ b/ios/App/Detail/ImageViewer.swift @@ -0,0 +1,60 @@ +import ImageIO +import SwiftUI +import UIKit + +/// Downsampled decoding: a forwarded chat can carry dozens of full-size +/// photos, and decoding them at full resolution for a thumbnail costs memory. +enum Thumbnail { + static func load(_ url: URL, maxPixel: Int) -> UIImage? { + guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) else { + return nil + } + let options: [CFString: Any] = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceThumbnailMaxPixelSize: maxPixel, + ] + guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil } + return UIImage(cgImage: image) + } +} + +struct ImageViewer: View { + let url: URL + @Environment(\.dismiss) private var dismiss + @State private var scale: CGFloat = 1 + @State private var settled: CGFloat = 1 + + var body: some View { + NavigationStack { + GeometryReader { proxy in + if let image = Thumbnail.load(url, maxPixel: Int(max(proxy.size.width, proxy.size.height) * 3)) { + Image(uiImage: image) + .resizable() + .scaledToFit() + .scaleEffect(scale) + .frame(width: proxy.size.width, height: proxy.size.height) + .gesture( + MagnificationGesture() + .onChanged { scale = min(max(settled * $0, 1), 5) } + .onEnded { _ in settled = scale } + ) + .onTapGesture(count: 2) { + withAnimation { scale = scale > 1 ? 1 : 2.5; settled = scale } + } + } else { + ContentUnavailableView("无法显示这张图片", systemImage: "photo") + } + } + .background(.black) + .toolbar { + ToolbarItem(placement: .topBarLeading) { Button("完成") { dismiss() } } + ToolbarItem(placement: .topBarTrailing) { + ShareLink(item: url) { Image(systemName: "square.and.arrow.up") } + } + } + .toolbarBackground(.visible, for: .navigationBar) + } + } +} diff --git a/ios/App/Detail/MessageToken.swift b/ios/App/Detail/MessageToken.swift new file mode 100644 index 0000000..5c955c0 --- /dev/null +++ b/ios/App/Detail/MessageToken.swift @@ -0,0 +1,65 @@ +import Foundation + +/// One line of a message body, recognised by the placeholders WeChat writes +/// into `聊天记录.txt`. Anything unrecognised stays text: a placeholder this +/// code does not know yet must still be readable, never dropped. +enum MessageToken: Equatable, Hashable { + case text(String) + case image(name: String) + case video(name: String) + case file(name: String) + case link(title: String, url: URL) + case channels(title: String, url: URL) + + static func tokenize(_ body: String) -> [MessageToken] { + var tokens: [MessageToken] = [] + var pending: [String] = [] + + func flush() { + guard !pending.isEmpty else { return } + tokens.append(.text(pending.joined(separator: "\n"))) + pending.removeAll() + } + + for line in body.components(separatedBy: "\n") { + if let token = token(for: line) { + flush() + tokens.append(token) + } else { + pending.append(line) + } + } + flush() + return tokens + } + + private static func token(for line: String) -> MessageToken? { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if let name = rest(of: trimmed, after: "[图片]") { return .image(name: name) } + if let name = rest(of: trimmed, after: "[视频]") { return .video(name: name) } + if let name = rest(of: trimmed, after: "[文件]") { return .file(name: name) } + if let rest = rest(of: trimmed, after: "[链接]"), let (title, url) = titleAndURL(rest) { + return .link(title: title, url: url) + } + if let rest = rest(of: trimmed, after: "[视频号]"), let (title, url) = titleAndURL(rest) { + return .channels(title: title, url: url) + } + return nil + } + + private static func rest(of line: String, after prefix: String) -> String? { + guard line.hasPrefix(prefix + " ") else { return nil } + let rest = line.dropFirst(prefix.count + 1).trimmingCharacters(in: .whitespaces) + return rest.isEmpty ? nil : rest + } + + /// The URL is the last whitespace-free run starting with http(s)://; the + /// title is whatever precedes it, which may itself contain spaces. + private static func titleAndURL(_ text: String) -> (String, URL)? { + guard let range = text.range(of: "https?://\\S+", options: [.regularExpression, .backwards]), + let url = URL(string: String(text[range])) + else { return nil } + let title = text[.. some View { + if let loaded, let text = loaded.text { + PlainTextView(text: text) + } else if let loaded { + TranscriptView(transcript: loaded) + } else if entry.summary?.parseFailed == true || loadError != nil { + List { + if let loadError { Text(loadError).foregroundStyle(.secondary) } + Section("文件") { + ForEach(entry.batch.items) { item in + Button { previewURL = item.url } label: { + HStack { + Label(item.displayName, systemImage: "doc") + Spacer() + Text(ByteFormat.string(item.byteCount)).foregroundStyle(.secondary) + } + } + } + } + } + } else { + ProgressView("正在读取…").frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + + private var actionBar: some View { + HStack(spacing: 8) { + Button { + store.addToCollection(batchID) + toast = "已加入收集" + } label: { + Label(store.collectionContaining(batchID) == nil ? "加入收集" : "已在收集中", systemImage: "square.stack.3d.up") + .font(.subheadline.weight(.medium)) + .padding(.horizontal, 14) + .frame(maxHeight: .infinity) + } + .disabled(store.collectionContaining(batchID) != nil) + Button { + delivering = DeliverySelection(batchIDs: [batchID]) + } label: { + Label("投递", systemImage: "paperplane.fill") + .font(.body.weight(.semibold)) + .foregroundStyle(.white) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(Color.accentColor, in: Capsule()) + } + } + .frame(height: 48) + .padding(5) + .background(.regularMaterial, in: Capsule()) + .shadow(color: .black.opacity(0.12), radius: 12, y: 4) + .padding(.horizontal, 20) + .padding(.bottom, 8) + } + + private func load() async { + guard let entry, loaded == nil else { return } + let batch = entry.batch + let result = await Task.detached(priority: .userInitiated) { LoadedTranscript.load(batch) }.value + switch result { + case .success(let transcript): loaded = transcript + case .failure(let error): loadError = error.localizedDescription + case nil: break + } + } +} + +/// The parsed transcript plus where its media was unpacked. +struct LoadedTranscript { + let records: [WeChatTranscriptRecord] + /// Set instead of `records` when the text is not in chat-record layout. + var text: String? + let mediaDirectory: URL + /// Leaf file name → unpacked path relative to `mediaDirectory`. + let media: [String: String] + + func url(for name: String) -> URL? { + media[name].map { mediaDirectory.appendingPathComponent($0) } + } + + /// nil: no WeChat archive among the batch's files. + static func load(_ batch: ReadyBatch) -> Result? { + var fallback: (Data, WeChatNativeArchive.Transcript)? + for item in batch.items where item.url.pathExtension.lowercased() == "zip" { + do { + let data = try Data(contentsOf: item.url, options: .mappedIfSafe) + guard let transcript = try WeChatNativeArchive.transcript(data) else { continue } + // A chat export later in the batch wins, as in the summary. + if transcript.records == nil, fallback == nil { fallback = (data, transcript) } + guard let records = transcript.records else { continue } + return .success(try loaded(records: records, text: nil, data: data, transcript: transcript, batchID: batch.id)) + } catch { + return .failure(error) + } + } + guard let (data, transcript) = fallback else { return nil } + return Result { try loaded(records: [], text: transcript.body, data: data, transcript: transcript, batchID: batch.id) } + } + + private static func loaded( + records: [WeChatTranscriptRecord], text: String?, data: Data, + transcript: WeChatNativeArchive.Transcript, batchID: UUID + ) throws -> LoadedTranscript { + let extracted = try RelayFiles.extract(data, batchID: batchID) + var media: [String: String] = [:] + for name in extracted.names where !name.hasSuffix("/") && name != transcript.path { + media[(name as NSString).lastPathComponent] = name + } + return LoadedTranscript(records: records, text: text, mediaDirectory: extracted.directory, media: media) + } +} + +struct ToastView: View { + @Binding var text: String? + + var body: some View { + if let text { + Text(text) + .font(.subheadline) + .padding(.horizontal, 16) + .padding(.vertical, 10) + .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 20)) + .padding(.horizontal) + .padding(.top, 8) + .transition(.move(edge: .top).combined(with: .opacity)) + .task(id: text) { + // Two seconds for a short line; a few-line report needs reading time. + let seconds = max(2, Double(text.count) / 12) + try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)) + withAnimation { self.text = nil } + } + } + } +} diff --git a/ios/App/Detail/TranscriptView.swift b/ios/App/Detail/TranscriptView.swift new file mode 100644 index 0000000..0a37081 --- /dev/null +++ b/ios/App/Detail/TranscriptView.swift @@ -0,0 +1,206 @@ +import QuickLook +import SwiftUI +import WeChatBridgeCore + +struct TranscriptView: View { + let transcript: LoadedTranscript + @State private var viewing: URL? + @State private var previewURL: URL? + + var body: some View { + ScrollView { + LazyVStack(alignment: .leading, spacing: 10) { + ForEach(Array(transcript.records.enumerated()), id: \.offset) { index, record in + let previous = index > 0 ? transcript.records[index - 1] : nil + if previous.map({ !Calendar.current.isDate($0.date, inSameDayAs: record.date) }) ?? true { + DateDivider(date: record.date) + } + MessageRow( + record: record, + showsSender: previous?.sender != record.sender, + transcript: transcript, + openImage: { viewing = $0 }, + openFile: { previewURL = $0 } + ) + } + } + .padding() + } + .fullScreenCover(item: $viewing) { ImageViewer(url: $0) } + .quickLookPreview($previewURL) + } +} + +extension URL: @retroactive Identifiable { + public var id: String { absoluteString } +} + +private struct DateDivider: View { + let date: Date + + var body: some View { + Text(date, format: .dateTime.year().month().day().weekday()) + .font(.caption) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity) + .padding(.vertical, 4) + } +} + +private struct MessageRow: View { + let record: WeChatTranscriptRecord + let showsSender: Bool + let transcript: LoadedTranscript + let openImage: (URL) -> Void + let openFile: (URL) -> Void + + var body: some View { + HStack(alignment: .top, spacing: 8) { + Avatar(name: record.sender).opacity(showsSender ? 1 : 0) + VStack(alignment: .leading, spacing: 4) { + if showsSender { + HStack(spacing: 6) { + Text(record.sender).font(.caption.weight(.semibold)).foregroundStyle(Avatar.color(for: record.sender)) + Text(record.date, format: .dateTime.hour().minute()).font(.caption2).foregroundStyle(.secondary) + } + } + ForEach(Array(MessageToken.tokenize(record.text).enumerated()), id: \.offset) { _, token in + TokenView(token: token, transcript: transcript, openImage: openImage, openFile: openFile) + } + } + Spacer(minLength: 24) + } + } +} + +private struct Avatar: View { + let name: String + + var body: some View { + Text(String(name.prefix(1))) + .font(.footnote.weight(.semibold)) + .foregroundStyle(.white) + .frame(width: 32, height: 32) + .background(Self.color(for: name), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + + /// Stable per name across launches (`hashValue` is reseeded each run), so + /// a speaker keeps one colour for avatar and name. + static func color(for name: String) -> Color { + let seed = name.unicodeScalars.reduce(UInt32(5381)) { ($0 &* 33) &+ $1.value } + return Color(hue: Double(seed % 360) / 360, saturation: 0.5, brightness: 0.72) + } +} + +private struct TokenView: View { + let token: MessageToken + let transcript: LoadedTranscript + let openImage: (URL) -> Void + let openFile: (URL) -> Void + + var body: some View { + switch token { + case .text(let text): + Text(text) + .textSelection(.enabled) + .padding(10) + .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + case .image(let name): + if let url = transcript.url(for: name), let image = Thumbnail.load(url, maxPixel: 600) { + let size = Self.displaySize(image.size) + Button { openImage(url) } label: { + Image(uiImage: image) + .resizable() + .scaledToFit() + .frame(width: size.width, height: size.height) + // A tile behind, so a tiny or transparent image is + // still a visible, tappable thing. + .frame(minWidth: 64, minHeight: 64) + .background(Color(.tertiarySystemFill)) + .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) + .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(Color.primary.opacity(0.08))) + } + .accessibilityLabel("图片 \(name)") + } else { + Attachment(symbol: "photo", title: name, subtitle: "图片未随附", action: nil) + } + case .video(let name): + Attachment(symbol: "video", title: name, subtitle: "视频", action: transcript.url(for: name).map { url in { openFile(url) } }) + case .file(let name): + Attachment(symbol: "doc", title: name, subtitle: "文件", action: transcript.url(for: name).map { url in { openFile(url) } }) + case .link(let title, let url): + Link(destination: url) { Attachment.label(symbol: "link", title: title, subtitle: url.host ?? url.absoluteString) } + .buttonStyle(.plain) + case .channels(let title, let url): + Link(destination: url) { Attachment.label(symbol: "play.rectangle", title: title, subtitle: "视频号") } + .buttonStyle(.plain) + } + } +} + +extension TokenView { + /// Fits in 220×260 pt and never blows a small image up past one point per pixel. + static func displaySize(_ pixels: CGSize) -> CGSize { + guard pixels.width > 0, pixels.height > 0 else { return CGSize(width: 64, height: 64) } + let scale = min(220 / pixels.width, 260 / pixels.height, 1) + return CGSize(width: pixels.width * scale, height: pixels.height * scale) + } +} + +private struct Attachment: View { + let symbol: String + let title: String + let subtitle: String + let action: (() -> Void)? + + var body: some View { + if let action { + Button(action: action) { Self.label(symbol: symbol, title: title, subtitle: subtitle) } + .buttonStyle(.plain) + } else { + Self.label(symbol: symbol, title: title, subtitle: subtitle) + } + } + + static func label(symbol: String, title: String, subtitle: String) -> some View { + HStack(spacing: 10) { + Image(systemName: symbol).font(.title3).foregroundStyle(Color.accentColor).frame(width: 28) + VStack(alignment: .leading, spacing: 2) { + Text(title).font(.subheadline).lineLimit(2).multilineTextAlignment(.leading) + Text(subtitle).font(.caption).foregroundStyle(.secondary) + } + } + .foregroundStyle(.primary) + .padding(10) + .frame(maxWidth: 260, alignment: .leading) + .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 12, style: .continuous)) + } +} + +/// A text that is not a chat record, shown as written with its links live. +struct PlainTextView: View { + let text: String + + var body: some View { + ScrollView { + Text(Self.linked(text)) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) + .padding() + } + } + + static func linked(_ text: String) -> AttributedString { + var attributed = AttributedString(text) + guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return attributed } + for match in detector.matches(in: text, range: NSRange(text.startIndex..., in: text)) { + guard let url = match.url, + let range = Range(match.range, in: text), + let lower = AttributedString.Index(range.lowerBound, within: attributed), + let upper = AttributedString.Index(range.upperBound, within: attributed) + else { continue } + attributed[lower.. Void + + init(onChange: @escaping @MainActor () -> Void) { + self.onChange = onChange + CFNotificationCenterAddObserver( + CFNotificationCenterGetDarwinNotifyCenter(), + Unmanaged.passUnretained(self).toOpaque(), + { _, observer, _, _, _ in + guard let observer else { return } + let me = Unmanaged.fromOpaque(observer).takeUnretainedValue() + Task { @MainActor in me.onChange() } + }, + InboxSignal.didChange.rawValue as CFString, + nil, + .deliverImmediately + ) + } + + deinit { + CFNotificationCenterRemoveEveryObserver( + CFNotificationCenterGetDarwinNotifyCenter(), + Unmanaged.passUnretained(self).toOpaque() + ) + } +} diff --git a/ios/App/Model/Preferences.swift b/ios/App/Model/Preferences.swift new file mode 100644 index 0000000..d357432 --- /dev/null +++ b/ios/App/Model/Preferences.swift @@ -0,0 +1,129 @@ +import Foundation +import WeChatBridgeCore + +/// Everything the user chooses, in the App Group's defaults so the extension +/// could read it later without a migration. Scene and group-memory keys are +/// the Mac's own names, so an exported store reads the same on both. +@MainActor +final class Preferences: ObservableObject { + enum Key { + static let scenes = "com.xiangming.wechatbridge.scenes.v3" + static let groupMemory = "com.xiangming.wechatbridge.groupMemory.v1" + static let historyRetentionDays = "com.xiangming.wechatbridge.historyRetentionDays" + static let obsidianSubfolder = "com.xiangming.wechatbridge.obsidianSubfolder" + static let folderSubfolder = "com.xiangming.wechatbridge.folderDeliverySubfolder" + static let obsidianBookmark = "com.xiangming.wechatbridge.ios.obsidianBookmark" + static let folderBookmark = "com.xiangming.wechatbridge.ios.folderBookmark" + static let targetFormatOverrides = "com.xiangming.wechatbridge.ios.targetFormatOverrides" + static let hiddenTargets = "com.xiangming.wechatbridge.ios.hiddenTargets" + static let targetOrder = "com.xiangming.wechatbridge.ios.targetOrder" + static let lastTarget = "com.xiangming.wechatbridge.ios.lastTarget" + static let onboardingDone = "com.xiangming.wechatbridge.ios.onboardingDone" + static let liveActivity = "com.xiangming.wechatbridge.ios.liveActivity" + static let imagesInPDF = "com.xiangming.wechatbridge.ios.imagesInPDF" + } + + static let defaultRetentionDays = 7 + + let defaults: UserDefaults + + @Published var scenes: SceneSettings { didSet { save(scenes, Key.scenes) } } + @Published var groupMemory: [String: GroupMemory] { didSet { save(groupMemory, Key.groupMemory) } } + /// 0 keeps everything. + @Published var retentionDays: Int { didSet { defaults.set(retentionDays, forKey: Key.historyRetentionDays) } } + @Published var obsidianSubfolder: String { didSet { defaults.set(obsidianSubfolder, forKey: Key.obsidianSubfolder) } } + @Published var folderSubfolder: String { didSet { defaults.set(folderSubfolder, forKey: Key.folderSubfolder) } } + @Published var obsidianBookmark: Data? { didSet { defaults.set(obsidianBookmark, forKey: Key.obsidianBookmark) } } + @Published var folderBookmark: Data? { didSet { defaults.set(folderBookmark, forKey: Key.folderBookmark) } } + @Published var formatOverrides: [String: String] { didSet { defaults.set(formatOverrides, forKey: Key.targetFormatOverrides) } } + @Published var hiddenTargets: [String] { didSet { defaults.set(hiddenTargets, forKey: Key.hiddenTargets); publishQuickTargets() } } + @Published var targetOrder: [String] { didSet { defaults.set(targetOrder, forKey: Key.targetOrder); publishQuickTargets() } } + @Published var lastTarget: String? { didSet { defaults.set(lastTarget, forKey: Key.lastTarget); publishQuickTargets() } } + /// 「分享后提醒我投递」; the extension reads the same key. + @Published var quickDeliver: Bool { didSet { defaults.set(quickDeliver, forKey: QuickDeliver.enabledKey) } } + /// 「投递时显示在灵动岛」. + @Published var liveActivity: Bool { didSet { defaults.set(liveActivity, forKey: Key.liveActivity) } } + /// TXT targets get one PDF with the images inline; off, the TXT alone and + /// the images go to Photos. 千问 takes images from neither a TXT share nor + /// its file picker, so the PDF is the only one-step way (2026-10-24). + @Published var imagesInPDF: Bool { didSet { defaults.set(imagesInPDF, forKey: Key.imagesInPDF) } } + @Published var onboardingDone: Bool { didSet { defaults.set(onboardingDone, forKey: Key.onboardingDone) } } + + init(defaults: UserDefaults = Preferences.sharedDefaults) { + self.defaults = defaults + var scenes = Self.load(SceneSettings.self, defaults, Key.scenes) ?? SceneSettings.makeDefault() + scenes.installOfficialScenes() + self.scenes = scenes + groupMemory = Self.load([String: GroupMemory].self, defaults, Key.groupMemory) ?? [:] + retentionDays = defaults.object(forKey: Key.historyRetentionDays) as? Int ?? Self.defaultRetentionDays + obsidianSubfolder = defaults.string(forKey: Key.obsidianSubfolder) ?? "微信流" + folderSubfolder = defaults.string(forKey: Key.folderSubfolder) ?? "微信流" + obsidianBookmark = defaults.data(forKey: Key.obsidianBookmark) + folderBookmark = defaults.data(forKey: Key.folderBookmark) + formatOverrides = defaults.dictionary(forKey: Key.targetFormatOverrides) as? [String: String] ?? [:] + hiddenTargets = defaults.stringArray(forKey: Key.hiddenTargets) ?? [] + targetOrder = defaults.stringArray(forKey: Key.targetOrder) ?? [] + lastTarget = defaults.string(forKey: Key.lastTarget) + onboardingDone = defaults.bool(forKey: Key.onboardingDone) + quickDeliver = QuickDeliver.isEnabled(defaults) + liveActivity = defaults.object(forKey: Key.liveActivity) as? Bool ?? true + imagesInPDF = defaults.object(forKey: Key.imagesInPDF) as? Bool ?? true + publishQuickTargets() + } + + /// The notification's buttons, for the extension to read. + private func publishQuickTargets() { + QuickDeliver.store(targets.map { QuickDeliver.Target(id: $0.id, name: $0.displayName) }, in: defaults) + } + + /// Falls back to the app's own defaults only when the group is missing, + /// which on iOS means a build without the entitlement — never silently in + /// a signed build, where the extension would then disagree. + nonisolated static var sharedDefaults: UserDefaults { + UserDefaults(suiteName: AppGroup.identifier) ?? .standard + } + + /// The configured targets after the user's order, visibility and format + /// choices, last-used first. + var targets: [TargetProfile] { + TargetProfile.arranged( + TargetProfile.builtIn, + order: targetOrder, + hidden: Set(hiddenTargets), + overrides: formatOverrides, + lastUsed: lastTarget + ) + } + + func rememberGroup(displayName: String, sceneID: String, senders: Set, end: Date?) { + let key = GroupName.normalize(displayName) + guard !key.isEmpty else { return } + groupMemory[key] = GroupMemory.advancing( + groupMemory[key], + displayName: displayName, + sceneID: sceneID, + senders: senders, + end: end + ) + } + + func bind(displayName: String, sceneIDs: [String], senders: Set) { + let key = GroupName.normalize(displayName) + guard !key.isEmpty else { return } + var memory = groupMemory[key] ?? GroupMemory(displayName: displayName) + memory.boundSceneIDs = sceneIDs + memory.senders.formUnion(senders) + memory.updatedAt = Date() + groupMemory[key] = memory + } + + private func save(_ value: T, _ key: String) { + guard let data = try? JSONEncoder().encode(value) else { return } + defaults.set(data, forKey: key) + } + + private static func load(_ type: T.Type, _ defaults: UserDefaults, _ key: String) -> T? { + guard let data = defaults.data(forKey: key) else { return nil } + return try? JSONDecoder().decode(type, from: data) + } +} diff --git a/ios/App/Model/RelayStore.swift b/ios/App/Model/RelayStore.swift new file mode 100644 index 0000000..a3701e0 --- /dev/null +++ b/ios/App/Model/RelayStore.swift @@ -0,0 +1,255 @@ +import Foundation +import WeChatBridgeCore + +struct RelayEntry: Identifiable, Hashable { + let batch: ReadyBatch + var summary: RelaySummary? + var id: UUID { batch.id } + + var isDelivered: Bool { batch.outcome?.kind == .delivered } +} + +/// The relay's list, and the only writer of `Ready` and the collection ledger +/// on this side. The share extension adds batches; everything that removes or +/// annotates one goes through here. +@MainActor +final class RelayStore: ObservableObject { + @Published private(set) var entries: [RelayEntry] = [] + @Published private(set) var ledger = BatchCollectionLedger() + @Published var failures: [ShareFailure] = [] + @Published var lastError: String? + /// Hidden from the list and deleted when the undo window closes. + @Published private(set) var pendingDeletion: Set = [] + + let inbox: Inbox? + private var reader: InboxReader? { inbox.map { InboxReader(inbox: $0, removal: .delete) } } + private var summarizing: Set = [] + private var deletionTask: Task? + + init(inbox: Inbox? = try? Inbox.resolve()) { + self.inbox = inbox + if let inbox { + try? inbox.prepareDirectories() + } + loadLedger() + } + + var visibleEntries: [RelayEntry] { + entries.filter { !pendingDeletion.contains($0.id) } + } + + func entry(_ id: UUID) -> RelayEntry? { + entries.first { $0.id == id } + } + + func entries(_ ids: [UUID]) -> [RelayEntry] { + ids.compactMap(entry) + } + + // MARK: - Loading + + func reload() { + guard let reader else { + // A signing problem: the group id is for the log, not the user. + NSLog("WeChatBridge: %@", InboxError.containerUnavailable(identifier: AppGroup.identifier).errorDescription ?? "") + lastError = "微信流没装好,读不到分享进来的内容。请重新安装后再试。" + return + } + let known = Dictionary(uniqueKeysWithValues: entries.map { ($0.id, $0.summary) }) + entries = reader.loadBatches().map { batch in + RelayEntry(batch: batch, summary: known[batch.id] ?? RelaySummary.cached(in: batch.directory)) + } + let fresh = reader.consumeFailures() + if !fresh.isEmpty { failures = fresh } + ingestMarked() + summarizeMissing() + } + + /// 「分批收集到微信流」 batches join the open collection, oldest first. + private func ingestMarked() { + let ids = CollectMarker.unseen(entries.map(\.batch.directory), seen: ledger.seenBatchIDs) + guard !ids.isEmpty else { return } + for id in ids { ledger.append(id) } + saveLedger() + } + + /// Parsing reads whole archives, so it runs off the main actor, one batch + /// at a time, and is cached beside the batch for every later launch. + private func summarizeMissing() { + let missing = entries.filter { $0.summary == nil && !summarizing.contains($0.id) }.map(\.batch) + guard !missing.isEmpty else { return } + summarizing.formUnion(missing.map(\.id)) + Task.detached(priority: .utility) { + for batch in missing { + let summary = RelaySummary.make(for: batch) + summary.store(in: batch.directory) + await self.apply(summary, to: batch.id) + } + } + } + + private func apply(_ summary: RelaySummary, to id: UUID) { + summarizing.remove(id) + guard let index = entries.firstIndex(where: { $0.id == id }) else { return } + entries[index].summary = summary + } + + /// Run once per launch: history older than the user's retention goes, + /// except anything a collection still needs. + func pruneHistory(retentionDays: Int) { + guard retentionDays > 0, let reader else { return } + let removed = reader.pruneHistory( + olderThan: TimeInterval(retentionDays) * 86_400, + excluding: ledger.protectedBatchIDs + ) + if removed > 0 { reload() } + cleanCaches() + } + + /// Unpacked copies whose batch is gone. + private func cleanCaches() { + let live = Set(entries.map(\.id.uuidString)) + let cached = (try? FileManager.default.contentsOfDirectory(atPath: RelayFiles.root.path)) ?? [] + for name in cached where !live.contains(name) { + try? FileManager.default.removeItem(at: RelayFiles.root.appendingPathComponent(name)) + } + } + + // MARK: - Deleting, with a short undo window + + func delete(_ ids: Set) { + pendingDeletion.formUnion(ids) + deletionTask?.cancel() + deletionTask = Task { [weak self] in + try? await Task.sleep(nanoseconds: 5_000_000_000) + guard !Task.isCancelled else { return } + self?.commitDeletion() + } + } + + func undoDeletion() { + deletionTask?.cancel() + pendingDeletion.removeAll() + } + + /// Also called when the app leaves the foreground: a batch the user + /// deleted must not come back because the timer never fired. + func commitDeletion() { + deletionTask?.cancel() + guard let reader, !pendingDeletion.isEmpty else { return } + for id in pendingDeletion { + do { + try reader.discard(batchID: id) + RelayFiles.remove(batchID: id) + for collection in ledger.collections where collection.batchIDs.contains(id) { + _ = try? ledger.remove(id, from: collection.id) + } + } catch { + lastError = error.localizedDescription + } + } + pendingDeletion.removeAll() + saveLedger() + reload() + } + + // MARK: - Delivery bookkeeping + + func markDelivered(_ ids: [UUID], targetName: String, detail: String, chatName: String?, scene: WeChatScene?) { + guard let reader else { return } + for id in ids { + try? reader.recordOutcome( + BatchOutcome(kind: .delivered, detail: detail, at: Date()), + targetName: targetName, + for: id + ) + try? reader.recordContext(chatName: chatName, sceneID: scene?.id, sceneName: scene?.name, for: id) + } + reload() + } + + // MARK: - Collections + + private var ledgerURL: URL? { inbox.map(CollectMarker.ledgerURL) } + + var collections: [BatchCollection] { + ledger.collections.filter { $0.status != .delivered && !$0.batchIDs.isEmpty } + } + + private func loadLedger() { + guard let url = ledgerURL else { return } + do { + ledger = try BatchCollectionLedger.load(from: url) + } catch { + lastError = error.localizedDescription + ledger = BatchCollectionLedger() + } + ledger.recoverInterruptedDeliveries() + saveLedger() + } + + private func saveLedger() { + guard let url = ledgerURL else { return } + do { try ledger.save(to: url) } catch { lastError = error.localizedDescription } + } + + /// Adds to the collection being gathered, starting one if none is. + func addToCollection(_ id: UUID) { + ledger.append(id) + saveLedger() + } + + func removeFromCollection(_ batchID: UUID, collection: UUID) { + do { _ = try ledger.remove(batchID, from: collection) } catch { lastError = error.localizedDescription } + saveLedger() + } + + func renameCollection(_ id: UUID, to name: String) { + do { try ledger.rename(id, to: name) } catch { lastError = error.localizedDescription } + saveLedger() + } + + func forgetCollection(_ id: UUID) { + do { try ledger.forget(id) } catch { lastError = error.localizedDescription } + saveLedger() + } + + /// Makes this the collection 「分批收集到微信流」 adds to; a no-op when it already is. + func resumeCollection(_ id: UUID) { + guard ledger.current?.id != id else { return } + do { try ledger.resume(id) } catch { lastError = error.localizedDescription } + saveLedger() + } + + /// Time order, the order a merge reads in. + func orderedBatchIDs(of collection: BatchCollection) -> [UUID] { + entries(collection.batchIDs) + .sorted { ($0.summary?.start ?? $0.batch.createdAt) < ($1.summary?.start ?? $1.batch.createdAt) } + .map(\.id) + } + + /// The batch with the latest messages: where the next batch picks up. + func lastBatch(of collection: BatchCollection) -> RelayEntry? { + orderedBatchIDs(of: collection).last.flatMap(entry) + } + + func collectionContaining(_ batchID: UUID) -> BatchCollection? { + ledger.collections.first { $0.status != .delivered && $0.batchIDs.contains(batchID) } + } + + func beginCollectionDelivery(_ id: UUID) -> [UUID]? { + do { + let ids = try ledger.beginDelivery(id) + saveLedger() + return ids + } catch { + lastError = error.localizedDescription + return nil + } + } + + func finishCollectionDelivery(_ id: UUID, succeeded: Bool, target: String, scene: String?) { + try? ledger.finishDelivery(id, succeeded: succeeded, target: target, detail: succeeded ? "已投递" : "已取消", scene: scene) + saveLedger() + } +} diff --git a/ios/App/Model/RelaySummary.swift b/ios/App/Model/RelaySummary.swift new file mode 100644 index 0000000..ad8bf73 --- /dev/null +++ b/ios/App/Model/RelaySummary.swift @@ -0,0 +1,200 @@ +import Foundation +import UniformTypeIdentifiers +import WeChatBridgeCore + +/// What a relay card shows, worked out once per batch and cached next to it. +struct RelaySummary: Codable, Hashable { + /// What the batch's archive turned out to hold. + enum Kind: String, Codable { + /// WeChat's chat-record export: `·sender`, timestamp, text. + case chat + /// A text file in another layout, such as a single long message or a + /// note exported on its own. Read and delivered as the text it is. + case text + /// No readable text at all: delivered only as the original files. + case files + } + + static let currentSchemaVersion = 3 + static let cacheFileName = "relay-cache.json" + static let mediaFolder = "聊天记录内的图片、视频和文件/" + + var schemaVersion = Self.currentSchemaVersion + var title: String + var messageCount: Int? + /// First-appearance order, which is the order a reader meets them in. + var senders: [String] + var start: Date? + var end: Date? + var preview: [String] + var mediaCount: Int + var kind: Kind + /// No text in any of the batch's files: a plain file someone shared. + /// Still deliverable, as itself. + var parseFailed: Bool { kind == .files } + + /// The archive the summary was read from, by item id; nil when none parsed. + var archiveItemID: UUID? + + /// The chat's last message with searchable words (see `SearchAnchor`): + /// where the next batch of 「分批收集」 picks up. + struct Last: Codable, Hashable { + let sender: String + let date: Date + let text: String + } + var last: Last? + /// What to search in WeChat to find `last`. + var anchor: String? + + /// WeChat stopped the selection here, so the chat likely goes on. + var hitsForwardLimit: Bool { messageCount == SearchAnchor.forwardLimit } + + static func make(for batch: ReadyBatch) -> RelaySummary { + // A chat export anywhere in the batch wins over a plain text file. + // Only the chosen archive is unpacked: the batch has one unpack folder. + var text: (item: ReadyItem, data: Data, transcript: WeChatNativeArchive.Transcript)? + for item in batch.items where item.url.pathExtension.lowercased() == "zip" { + guard let data = try? Data(contentsOf: item.url, options: .mappedIfSafe), + let transcript = try? WeChatNativeArchive.transcript(data) + else { continue } + guard let records = transcript.records else { + if text == nil { text = (item, data, transcript) } + continue + } + return make( + records: records, + transcript: transcript, + chatName: batch.chatName, + archiveName: item.displayName, + mediaCount: mediaCount(data, transcript: transcript, batch: batch), + archiveItemID: item.id + ) + } + if let (item, data, transcript) = text { + return make(text: transcript.body, archiveName: item.displayName, + mediaCount: mediaCount(data, transcript: transcript, batch: batch), archiveItemID: item.id) + } + return RelaySummary( + title: batch.items.count == 1 ? batch.items[0].displayName : "\(batch.items.count) 个文件", + messageCount: nil, + senders: [], + start: nil, + end: nil, + preview: batch.items.prefix(2).map(\.displayName), + mediaCount: batch.items.count, + kind: .files, + archiveItemID: nil + ) + } + + static func make( + records: [WeChatTranscriptRecord], + transcript: WeChatNativeArchive.Transcript, + chatName: String?, + archiveName: String, + mediaCount: Int, + archiveItemID: UUID? + ) -> RelaySummary { + let anchor = SearchAnchor.anchor(records) + var seen = Set() + let senders = records.map(\.sender).filter { seen.insert($0).inserted } + let preview = records.prefix(2).map { record -> String in + let line = record.text.components(separatedBy: .newlines).first ?? "" + return String("\(record.sender):\(line)".prefix(40)) + } + return RelaySummary( + title: ObsidianNote.title(chatName: chatName, transcript: transcript, archiveName: archiveName), + messageCount: records.count, + senders: senders, + start: transcript.start, + end: transcript.end, + preview: preview, + mediaCount: mediaCount, + kind: .chat, + archiveItemID: archiveItemID, + last: anchor.map { Last(sender: $0.record.sender, date: $0.record.date, text: String($0.record.text.prefix(200))) }, + anchor: anchor?.keyword + ) + } + + /// Files in the archive besides its text, plus the batch's other files. + private static func mediaCount(_ data: Data, transcript: WeChatNativeArchive.Transcript, batch: ReadyBatch) -> Int { + let media = (try? RelayFiles.extract(data, batchID: batch.id))? + .names.filter { $0 != transcript.path && !$0.hasSuffix("/") }.count ?? 0 + return media + batch.items.count - 1 + } + + /// The first line names the text (WeChat starts a single exported message + /// with `·`); the next lines preview it. + static func make(text: String, archiveName: String, mediaCount: Int, archiveItemID: UUID?) -> RelaySummary { + let lines = text.components(separatedBy: .newlines) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + let heading = lines.first.map { String($0.drop { $0 == "·" }).trimmingCharacters(in: .whitespaces) } ?? "" + return RelaySummary( + title: heading.isEmpty ? archiveName : String(heading.prefix(40)), + messageCount: nil, + senders: [], + start: nil, + end: nil, + preview: lines.dropFirst().prefix(2).map { String($0.prefix(40)) }, + mediaCount: mediaCount, + kind: .text, + archiveItemID: archiveItemID + ) + } + + // MARK: - Cache + + static func cached(in directory: URL) -> RelaySummary? { + let url = directory.appendingPathComponent(cacheFileName) + guard let data = try? Data(contentsOf: url), + let summary = try? BatchManifest.decoder().decode(RelaySummary.self, from: data), + summary.schemaVersion == currentSchemaVersion + else { return nil } + return summary + } + + func store(in directory: URL) { + guard let data = try? BatchManifest.encoder().encode(self) else { return } + try? data.write(to: directory.appendingPathComponent(Self.cacheFileName), options: .atomic) + } +} + +/// Where an archive is unpacked for reading. Caches, not the group container: +/// the system may purge it, and every reader re-extracts when it is missing. +enum RelayFiles { + struct Extracted { + let directory: URL + let names: [String] + } + + static var root: URL { + FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] + .appendingPathComponent("Relay", isDirectory: true) + } + + static func directory(for batchID: UUID) -> URL { + root.appendingPathComponent(batchID.uuidString, isDirectory: true) + } + + /// Idempotent: a complete earlier extraction (marked by `.done`) is reused. + static func extract(_ data: Data, batchID: UUID) throws -> Extracted { + let directory = directory(for: batchID) + let marker = directory.appendingPathComponent(".done") + let fm = FileManager.default + if let listed = try? String(contentsOf: marker, encoding: .utf8) { + return Extracted(directory: directory, names: listed.split(separator: "\n").map(String.init)) + } + try? fm.removeItem(at: directory) + try fm.createDirectory(at: directory, withIntermediateDirectories: true) + let names = try WeChatNativeArchive.extract(data, to: directory) + try names.joined(separator: "\n").write(to: marker, atomically: true, encoding: .utf8) + return Extracted(directory: directory, names: names) + } + + static func remove(batchID: UUID) { + try? FileManager.default.removeItem(at: directory(for: batchID)) + } +} diff --git a/ios/App/Onboarding/OnboardingView.swift b/ios/App/Onboarding/OnboardingView.swift new file mode 100644 index 0000000..751f881 --- /dev/null +++ b/ios/App/Onboarding/OnboardingView.swift @@ -0,0 +1,91 @@ +import SwiftUI + +struct OnboardingView: View { + @EnvironmentObject private var preferences: Preferences + let finish: () -> Void + @State private var page = 0 + @State private var picking = false + + var body: some View { + NavigationStack { + TabView(selection: $page) { + step( + symbol: "square.and.arrow.up.on.square", + title: "从微信发到微信流", + lines: [ + "在微信聊天里长按一条消息,点「多选」,勾选要带走的消息。", + "点「转发」→「转到其他应用」→「选择手机中的应用」。", + "在系统分享面板里选「微信流」,看到「已保存」就好了。", + ] + ) + .tag(0) + step( + symbol: "star.square.on.square", + title: "把微信流放到分享面板前面", + lines: [ + "第一次在分享面板里找不到时,滑到最右边点「更多」。", + "点右上角「编辑」,把「微信流」加到「个人收藏」。", + "以后每次分享,它都在第一排。", + ] + ) + .tag(1) + step( + symbol: "diamond", + title: "可选:选择 Obsidian 库", + lines: [ + "选好后,聊天记录可以直接写成 Obsidian 笔记。", + "以后也可以在「设置」里选择或更换。", + ] + ) { + Button(FolderBookmark.name(of: preferences.obsidianBookmark).map { "已选择:\($0)" } ?? "选择 Obsidian 库") { + picking = true + } + .buttonStyle(.bordered) + .frame(maxWidth: .infinity) + .padding(.top, 8) + } + .tag(2) + } + .tabViewStyle(.page(indexDisplayMode: .always)) + .indexViewStyle(.page(backgroundDisplayMode: .always)) + .safeAreaInset(edge: .bottom) { + Button(page < 2 ? "下一步" : "开始使用") { + if page < 2 { withAnimation { page += 1 } } else { finish() } + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + .padding() + } + .toolbar { + ToolbarItem(placement: .topBarTrailing) { Button("跳过", action: finish) } + } + .sheet(isPresented: $picking) { + FolderPicker { url in + preferences.obsidianBookmark = try? FolderBookmark.make(from: url) + } + .ignoresSafeArea() + } + } + } + + // The accessory sits above the step's spacer so it never slides under the page dots. + private func step(symbol: String, title: String, lines: [String], @ViewBuilder accessory: () -> some View = { EmptyView() }) -> some View { + VStack(alignment: .leading, spacing: 16) { + Image(systemName: symbol) + .font(.system(size: 56)) + .foregroundStyle(.tint) + .frame(maxWidth: .infinity) + .padding(.top, 40) + Text(title).font(.title2.bold()) + ForEach(Array(lines.enumerated()), id: \.offset) { index, line in + HStack(alignment: .top, spacing: 10) { + Text("\(index + 1)").font(.headline).foregroundStyle(.tint) + Text(line) + } + } + accessory() + Spacer() + } + .padding(24) + } +} diff --git a/ios/App/Relay/CollectionDetailView.swift b/ios/App/Relay/CollectionDetailView.swift new file mode 100644 index 0000000..a825392 --- /dev/null +++ b/ios/App/Relay/CollectionDetailView.swift @@ -0,0 +1,131 @@ +import SwiftUI +import WeChatBridgeCore + +struct CollectionDetailView: View { + @EnvironmentObject private var store: RelayStore + @Environment(\.dismiss) private var dismiss + let collectionID: UUID + @State private var name = "" + @State private var delivering: DeliverySelection? + @State private var confirmForget = false + + private var collection: BatchCollection? { store.ledger.collections.first { $0.id == collectionID } } + + var body: some View { + List { + if let collection { + Section("名称") { + TextField("未命名收集", text: $name) + .onSubmit { store.renameCollection(collectionID, to: name) } + } + ContinueCollectingSection(last: store.lastBatch(of: collection)?.summary) { + store.resumeCollection(collectionID) + } + Section { + ForEach(store.entries(collection.batchIDs)) { entry in + RelayCardView(entry: entry) + } + .onDelete { offsets in + for id in offsets.map({ collection.batchIDs[$0] }) { + store.removeFromCollection(id, collection: collectionID) + } + } + } header: { + Text("\(collection.batchIDs.count) 批") + } footer: { + Text("投递时按时间合并,前后批重叠的消息只留一份。") + } + Section { + Button("解散收集", role: .destructive) { confirmForget = true } + } footer: { + Text("解散后批次仍留在中转站。") + } + } + } + .navigationTitle(collection?.name.isEmpty == false ? collection!.name : "收集") + .navigationBarTitleDisplayMode(.inline) + .safeAreaInset(edge: .bottom) { + Button { + store.renameCollection(collectionID, to: name) + delivering = DeliverySelection(batchIDs: orderedIDs, collectionID: collectionID) + } label: { + Label("投递整个收集", systemImage: "paperplane.fill").frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + .padding() + .background(.bar) + .disabled(collection?.batchIDs.isEmpty ?? true) + } + .onAppear { name = collection?.name ?? "" } + .onDisappear { if collection != nil, name != collection?.name { store.renameCollection(collectionID, to: name) } } + .sheet(item: $delivering) { DeliverySheet(selection: $0) } + .confirmationDialog("解散这个收集?", isPresented: $confirmForget, titleVisibility: .visible) { + Button("解散", role: .destructive) { + store.forgetCollection(collectionID) + dismiss() + } + } + .onChange(of: collection == nil) { gone in if gone { dismiss() } } + } + + private var orderedIDs: [UUID] { + collection.map(store.orderedBatchIDs) ?? [] + } +} + +/// 「怎么接着收」: WeChat forwards at most 100 messages, so a long chat comes +/// in batches. The last message is the bookmark: searched in WeChat, it puts +/// the user where the next batch starts. +struct ContinueCollectingSection: View { + let last: RelaySummary? + /// Copying means the user is about to collect more: into this collection. + let willContinue: () -> Void + @State private var copied = false + + var body: some View { + Section { + if let last = last?.last { + VStack(alignment: .leading, spacing: 6) { + Text("上一批最后一句 · \(last.sender) · \(RelayFormat.day(last.date))") + .font(.caption) + .foregroundStyle(.secondary) + Text(last.text).font(.subheadline).lineLimit(3) + if let anchor = self.last?.anchor { + Button { + UIPasteboard.general.string = anchor + willContinue() + copied = true + } label: { + Label(copied ? "已复制「\(anchor)」" : "复制关键词", systemImage: copied ? "checkmark" : "doc.on.doc") + } + .buttonStyle(.bordered) + .padding(.top, 2) + } + } + .padding(.vertical, 4) + } + VStack(alignment: .leading, spacing: 8) { + step(1, "复制关键词,回微信在这个聊天里搜索,定位到这一句") + step(2, "从它后面开始多选,一次最多 100 条;多选几条重叠的也没关系") + step(3, "像平时一样分享出来,在分享面板下方的列表里选「分批收集到微信流」") + } + .padding(.vertical, 4) + } header: { + Text("怎么接着收") + } footer: { + Text("找不到「分批收集到微信流」?在分享面板最下方点「编辑操作」,把它加到个人收藏。") + } + } + + private func step(_ number: Int, _ text: String) -> some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text("\(number)") + .font(.caption.weight(.bold)) + .foregroundStyle(.white) + .frame(width: 18, height: 18) + .background(Color.accentColor, in: Circle()) + Text(text).font(.subheadline) + } + } +} diff --git a/ios/App/Relay/RelayCardView.swift b/ios/App/Relay/RelayCardView.swift new file mode 100644 index 0000000..bbeafe6 --- /dev/null +++ b/ios/App/Relay/RelayCardView.swift @@ -0,0 +1,215 @@ +import SwiftUI +import WeChatBridgeCore + +struct RelayCardView: View { + let entry: RelayEntry + var collecting = false + /// Offered on a chat cut off at WeChat's forward limit; nil hides it. + var startCollecting: (() -> Void)? + + var body: some View { + HStack(alignment: .top, spacing: 12) { + KindBadge(kind: entry.summary?.kind) + VStack(alignment: .leading, spacing: 5) { + HStack(alignment: .firstTextBaseline) { + Text(entry.summary?.title ?? entry.batch.items.first?.displayName ?? "聊天记录") + .font(.headline) + .lineLimit(1) + Spacer(minLength: 4) + StatusTag(entry: entry, collecting: collecting) + } + if let summary = entry.summary { + ForEach(Self.previewLines(summary), id: \.self) { line in + Text(line).font(.subheadline).foregroundStyle(.secondary).lineLimit(1) + } + HStack(spacing: 6) { + Text(Self.counts(summary)) + Spacer() + Text(RelayFormat.range(summary.start, summary.end) ?? "收到于 \(RelayFormat.day(entry.batch.createdAt))") + } + .font(.caption) + .foregroundStyle(.tertiary) + .padding(.top, 2) + } else { + ProgressView().controlSize(.small) + } + if let startCollecting, !collecting, entry.summary?.hitsForwardLimit == true { + ForwardLimitHint(action: startCollecting).padding(.top, 4) + } + } + } + .padding(.vertical, 6) + } +} + +/// Exactly 100 messages is where WeChat stops a selection, so the chat most +/// likely goes on beyond this batch. +private struct ForwardLimitHint: View { + let action: () -> Void + + var body: some View { + Button(action: action) { + HStack(alignment: .firstTextBaseline, spacing: 6) { + Image(systemName: "exclamationmark.circle.fill").foregroundStyle(.orange) + // Per-run colours: a button label is otherwise tinted throughout. + (Text("正好 \(SearchAnchor.forwardLimit) 条,微信一次最多转 \(SearchAnchor.forwardLimit) 条。还有前后的消息?").foregroundColor(.primary) + + Text("分批收集").bold().foregroundColor(.accentColor)) + .font(.caption) + .multilineTextAlignment(.leading) + } + .padding(8) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color.yellow.opacity(0.18), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + // Its own tap target inside the row's navigation link. + .buttonStyle(.borderless) + } +} + +/// Which kind of content a card holds, at a glance. +private struct KindBadge: View { + let kind: RelaySummary.Kind? + + var body: some View { + let (symbol, color): (String, Color) = switch kind { + case .chat: ("bubble.left.and.bubble.right.fill", .accentColor) + case .text: ("doc.plaintext.fill", .blue) + case .files: ("exclamationmark.triangle.fill", .orange) + case nil: ("tray.fill", .secondary) + } + Image(systemName: symbol) + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(color) + .frame(width: 34, height: 34) + .background(color.opacity(0.13), in: RoundedRectangle(cornerRadius: 9, style: .continuous)) + } +} + +extension RelayCardView { + /// A text's lines as written, except that a bare link shows only its + /// domain and at most one link is shown. + static func previewLines(_ summary: RelaySummary) -> [String] { + guard summary.kind == .text else { return summary.preview } + var sawLink = false + return summary.preview.compactMap { line in + let trimmed = line.trimmingCharacters(in: .whitespaces) + guard let url = URL(string: trimmed), let scheme = url.scheme, scheme.hasPrefix("http"), let host = url.host else { return line } + if sawLink { return nil } + sawLink = true + return "🔗 \(host)" + } + } + + /// `8 条消息 · 3 个附件`; a text file reads `文本`, and a lone count has no dot. + static func counts(_ summary: RelaySummary) -> String { + var parts: [String] = [] + if let count = summary.messageCount { + parts.append("\(count) 条消息") + } else if summary.kind == .text { + parts.append("文本") + } + if summary.mediaCount > 0 { parts.append("\(summary.mediaCount) 个附件") } + return parts.joined(separator: " · ") + } +} + +private struct StatusTag: View { + let entry: RelayEntry + let collecting: Bool + + var body: some View { + let (text, color): (String, Color) = { + if entry.summary?.parseFailed == true { return ("解析失败", .orange) } + if collecting { return ("收集中", .purple) } + if entry.isDelivered { return (entry.batch.targetName.map { "已投递 · \($0)" } ?? "已投递", .secondary) } + // Undelivered is the normal state and gets no tag. + return ("", .clear) + }() + if !text.isEmpty { + tag(text, color: color) + } + } + + private func tag(_ text: String, color: Color) -> some View { + Text(text) + .font(.caption2.weight(.medium)) + .lineLimit(1) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .foregroundStyle(color) + .background(color.opacity(0.12), in: Capsule()) + } +} + +extension View { + /// The relay's card look inside a plain List: a rounded tile on the + /// grouped background, drawn as the row background so the disclosure + /// chevron and edit-mode checkmarks sit inside it. + func relayCardRow() -> some View { + listRowBackground( + RoundedRectangle(cornerRadius: 14, style: .continuous) + .fill(Color(.secondarySystemGroupedBackground)) + .padding(.vertical, 5) + .padding(.horizontal, 16) + ) + .listRowInsets(EdgeInsets(top: 10, leading: 30, bottom: 10, trailing: 30)) + .listRowSeparator(.hidden) + } +} + + +struct CollectionCardView: View { + @EnvironmentObject private var store: RelayStore + let collection: BatchCollection + let continueCollecting: () -> Void + let deliver: () -> Void + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + header + // Styled buttons keep their own tap targets inside the row's link. + HStack(spacing: 10) { + Button(action: continueCollecting) { + Label("继续收集", systemImage: "plus.square.on.square").frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + Button(action: deliver) { + Label("完成并投递", systemImage: "paperplane.fill").frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + } + .controlSize(.small) + .font(.subheadline.weight(.medium)) + } + .padding(.vertical, 4) + } + + private var header: some View { + HStack(spacing: 12) { + Image(systemName: "square.stack.3d.up.fill") + .font(.system(size: 15, weight: .semibold)) + .foregroundStyle(.purple) + .frame(width: 34, height: 34) + .background(Color.purple.opacity(0.13), in: RoundedRectangle(cornerRadius: 9, style: .continuous)) + VStack(alignment: .leading, spacing: 4) { + Text(collection.name.isEmpty ? "未命名收集" : collection.name).font(.headline) + Text(line) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Image(systemName: "pin.fill").font(.caption).foregroundStyle(.secondary) + } + } + + /// `3 批 · 约 280 条 · 上一批 09:00–09:58`. 「约」: overlapping batches are + /// deduplicated only when merged. + private var line: String { + let count = store.entries(collection.batchIDs).compactMap { $0.summary?.messageCount }.reduce(0, +) + var parts = ["\(collection.batchIDs.count) 批", "约 \(count) 条"] + if let last = store.lastBatch(of: collection)?.summary, let range = RelayFormat.range(last.start, last.end) { + parts.append("上一批 \(range)") + } + return parts.joined(separator: " · ") + } +} diff --git a/ios/App/Relay/RelayListView.swift b/ios/App/Relay/RelayListView.swift new file mode 100644 index 0000000..3406134 --- /dev/null +++ b/ios/App/Relay/RelayListView.swift @@ -0,0 +1,306 @@ +import SwiftUI +import WeChatBridgeCore + +enum RelayFilter: String, CaseIterable, Identifiable { + case all = "全部" + case undelivered = "未投递" + case collecting = "收集中" + var id: Self { self } +} + +/// What a delivery sheet works on: one batch, a one-off merge, or a saved +/// collection (which has its own ledger bookkeeping). +struct DeliverySelection: Identifiable { + let id = UUID() + let batchIDs: [UUID] + var collectionID: UUID? + /// From a notification: preselect this target and send without a tap. + var quickTargetID: String? +} + +struct RelayListView: View { + @EnvironmentObject private var store: RelayStore + @Binding var showsOnboarding: Bool + @State private var filter: RelayFilter = .all + @State private var editMode: EditMode = .inactive + @State private var selection = Set() + @State private var delivering: DeliverySelection? + @ObservedObject private var router = QuickDeliverRouter.shared + @EnvironmentObject private var preferences: Preferences + @State private var path: [UUID] = [] + /// What the last 「存图片和附件」 did, for the confirmation. + @State private var exported: String? + /// How to pick up the next batch in WeChat, after 「继续收集」. + @State private var collectNote: String? + + private var rows: [RelayEntry] { + let entries = store.visibleEntries + switch filter { + case .all: return entries + case .undelivered: return entries.filter { !$0.isDelivered } + case .collecting: return entries.filter { store.collectionContaining($0.id) != nil } + } + } + + var body: some View { + NavigationStack(path: $path) { + // Bound only while editing: a live selection swallows taps that + // should push the detail view. + List(selection: editMode.isEditing ? $selection : nil) { + if !store.failures.isEmpty { + FailureBanner(failures: store.failures) { store.failures = [] } + .relayCardRow() + } + if filter != .undelivered { + ForEach(store.collections) { collection in + NavigationLink { + CollectionDetailView(collectionID: collection.id) + } label: { + CollectionCardView(collection: collection) { + continueCollecting(collection) + } deliver: { + delivering = DeliverySelection(batchIDs: store.orderedBatchIDs(of: collection), collectionID: collection.id) + } + } + .selectionDisabled() + .relayCardRow() + } + } + ForEach(rows) { entry in + NavigationLink(value: entry.id) { + RelayCardView(entry: entry, collecting: store.collectionContaining(entry.id) != nil) { + store.addToCollection(entry.id) + if let collection = store.collectionContaining(entry.id) { continueCollecting(collection) } + } + } + .relayCardRow() + .contextMenu { deliverMenu(entry) } + .swipeActions(edge: .trailing) { + Button(role: .destructive) { store.delete([entry.id]) } label: { Label("删除", systemImage: "trash") } + } + .swipeActions(edge: .leading) { + Button { delivering = DeliverySelection(batchIDs: [entry.id]) } label: { Label("投递", systemImage: "paperplane") } + .tint(.accentColor) + } + } + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + .background(Color(.systemGroupedBackground)) + .overlay { + if store.visibleEntries.isEmpty && store.collections.isEmpty { + EmptyRelayView { showsOnboarding = true } + } + } + .navigationTitle("中转站") + .navigationDestination(for: UUID.self) { id in + RelayDetailView(batchID: id) + } + .toolbar { + ToolbarItem(placement: .topBarLeading) { + Picker("筛选", selection: $filter) { + ForEach(RelayFilter.allCases) { Text($0.rawValue).tag($0) } + } + .pickerStyle(.menu) + } + ToolbarItem(placement: .topBarTrailing) { + EditButton().disabled(store.visibleEntries.isEmpty) + } + if editMode.isEditing { + ToolbarItemGroup(placement: .bottomBar) { + Button("合并投递") { + delivering = DeliverySelection(batchIDs: orderedSelection) + editMode = .inactive + } + .disabled(selection.isEmpty) + Spacer() + // Bar items get a tight width; without this the count truncates to "已选…". + Text("已选 \(selection.count) 条").font(.footnote).foregroundStyle(.secondary).fixedSize() + Spacer() + Button("删除", role: .destructive) { + store.delete(selection) + selection.removeAll() + editMode = .inactive + } + .disabled(selection.isEmpty) + } + } + } + // The tab bar would cover the edit actions in the bottom bar. + // `.automatic`, not `.visible`: a pushed detail view hides it too. + .toolbar(editMode.isEditing ? .hidden : .automatic, for: .tabBar) + .environment(\.editMode, $editMode) + .refreshable { store.reload() } + .safeAreaInset(edge: .bottom) { + if !store.pendingDeletion.isEmpty { + UndoToast(count: store.pendingDeletion.count) { store.undoDeletion() } + } + } + .alert("出错了", isPresented: Binding(get: { store.lastError != nil }, set: { if !$0 { store.lastError = nil } })) { + Button("好") { store.lastError = nil } + } message: { + Text(store.lastError ?? "") + } + .alert("存图片和附件", isPresented: Binding(get: { exported != nil }, set: { if !$0 { exported = nil } })) { + Button("好") { exported = nil } + } message: { + Text(exported ?? "") + } + .alert("接着收集", isPresented: Binding(get: { collectNote != nil }, set: { if !$0 { collectNote = nil } })) { + Button("好") { collectNote = nil } + } message: { + Text(collectNote ?? "") + } + .sheet(item: $delivering) { selection in + DeliverySheet(selection: selection) + } + .onAppear(perform: takeQuickRequest) + .onChange(of: router.pending) { _ in takeQuickRequest() } + .onChange(of: router.open) { open in + guard let open, store.entry(open.batchID) != nil else { return } + editMode = .inactive + // The finished delivery sheet would otherwise sit over the chat. + delivering = nil + path = [open.batchID] + } + } + } + + /// Long-press: straight to a recent target's share sheet, or the full panel. + @ViewBuilder + private func deliverMenu(_ entry: RelayEntry) -> some View { + Section("投递到") { + ForEach(preferences.targets.prefix(QuickDeliver.maxTargets)) { profile in + Button { + delivering = DeliverySelection(batchIDs: [entry.id], quickTargetID: profile.id) + } label: { + if let logo = profile.logo { + Label(profile.displayName, image: logo) + } else { + Label(profile.displayName, systemImage: profile.symbol) + } + } + } + Button { + delivering = DeliverySelection(batchIDs: [entry.id]) + } label: { + Label("选择目标…", systemImage: "square.grid.2x2") + } + } + Button { exportForPicking(entry) } label: { Label("存图片和附件", systemImage: "square.and.arrow.down.on.square") } + if store.collectionContaining(entry.id) == nil { + Button { store.addToCollection(entry.id) } label: { Label("加入收集", systemImage: "tray.and.arrow.down") } + } + Button(role: .destructive) { store.delete([entry.id]) } label: { Label("删除", systemImage: "trash") } + } + + /// The extension cannot be opened from here, so this points the way: + /// the collection takes the next batches, and the last message goes to + /// the clipboard for WeChat's search. + private func continueCollecting(_ collection: BatchCollection) { + store.resumeCollection(collection.id) + let steps = "从下一条开始多选,分享时在下方列表选「分批收集到微信流」。" + if let anchor = store.lastBatch(of: collection)?.summary?.anchor { + UIPasteboard.general.string = anchor + collectNote = "已复制最后一句「\(anchor)」。回微信在这个聊天里搜索它定位,\(steps)" + } else { + collectNote = "回微信找到上一批的最后一条,\(steps)" + } + } + + private func exportForPicking(_ entry: RelayEntry) { + let job = FilesExport.Job(batch: entry.batch, name: FilesExport.folderName(for: entry)) + Task { + do { + exported = try await FilesExport.exportForPicking([job]).message + } catch { + store.lastError = error.localizedDescription + } + } + } + + private func takeQuickRequest() { + guard let request = router.pending else { return } + router.pending = nil + // The share may have landed a moment ago, before any reload. + store.reload() + guard store.entry(request.batchID) != nil else { + store.lastError = "这批内容已不在中转站。" + return + } + editMode = .inactive + delivering = DeliverySelection(batchIDs: [request.batchID], quickTargetID: request.targetID) + } + + /// Time order, so a merge reads oldest first whatever order the user tapped. + private var orderedSelection: [UUID] { + store.visibleEntries + .filter { selection.contains($0.id) } + .sorted { ($0.summary?.start ?? $0.batch.createdAt) < ($1.summary?.start ?? $1.batch.createdAt) } + .map(\.id) + } +} + +private struct FailureBanner: View { + let failures: [ShareFailure] + let dismiss: () -> Void + + var body: some View { + HStack(alignment: .top) { + Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.orange) + VStack(alignment: .leading, spacing: 2) { + Text("有 \(failures.count) 次分享没有保存成功").font(.subheadline.weight(.semibold)) + if let last = failures.last { + Text(last.message).font(.footnote).foregroundStyle(.secondary) + } + } + Spacer() + Button(action: dismiss) { Image(systemName: "xmark") } + .buttonStyle(.borderless) + .accessibilityLabel("关闭") + } + .padding(.vertical, 4) + } +} + +private struct EmptyRelayView: View { + let showGuide: () -> Void + + var body: some View { + VStack(spacing: 14) { + Image(systemName: "tray.and.arrow.down.fill") + .font(.system(size: 38)) + .foregroundStyle(Color.accentColor) + .frame(width: 88, height: 88) + .background(Color.accentColor.opacity(0.12), in: Circle()) + Text("还没有收到聊天记录").font(.title3.weight(.semibold)) + Text("在微信里把聊天记录导出,分享到「微信流」,就会出现在这里。") + .font(.subheadline) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + Button("怎么从微信发过来", action: showGuide) + .buttonStyle(.borderedProminent) + .controlSize(.large) + .padding(.top, 4) + } + .padding(32) + } +} + +private struct UndoToast: View { + let count: Int + let undo: () -> Void + + var body: some View { + HStack { + Text("已删除 \(count) 条") + Spacer() + Button("撤销", action: undo).bold() + } + .padding() + .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12)) + .padding(.horizontal) + .padding(.bottom, 8) + .transition(.move(edge: .bottom).combined(with: .opacity)) + } +} diff --git a/ios/App/Scenes/ScenesView.swift b/ios/App/Scenes/ScenesView.swift new file mode 100644 index 0000000..a9ea1c0 --- /dev/null +++ b/ios/App/Scenes/ScenesView.swift @@ -0,0 +1,217 @@ +import SwiftUI +import UIKit +import UniformTypeIdentifiers +import WeChatBridgeCore + +struct ScenesView: View { + @EnvironmentObject private var preferences: Preferences + @State private var importing = false + @State private var message: String? + @State private var exportURL: URL? + + private var official: [WeChatScene] { preferences.scenes.scenes.filter(\.isOfficial) } + private var mine: [WeChatScene] { preferences.scenes.scenes.filter { !$0.isOfficial } } + + var body: some View { + NavigationStack { + List { + Section("官方场景") { + ForEach(official) { row($0) } + } + Section("我的场景") { + ForEach(mine) { row($0) } + .onDelete { offsets in + for scene in offsets.map({ mine[$0] }) { preferences.scenes.remove(id: scene.id) } + } + NavigationLink { + SceneEditorView(scene: WeChatScene(name: "", instruction: "", outputSpec: SceneSettings.standardOutputSpec, enabled: true), isNew: true) + } label: { + Label("新建场景", systemImage: "plus") + } + } + } + .navigationTitle("场景") + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Menu { + Button { importing = true } label: { Label("导入场景 JSON", systemImage: "square.and.arrow.down") } + Button(action: exportMine) { Label("导出我的场景", systemImage: "square.and.arrow.up") } + .disabled(mine.isEmpty) + } label: { + Image(systemName: "ellipsis.circle") + } + } + } + .fileImporter(isPresented: $importing, allowedContentTypes: [.json], allowsMultipleSelection: true) { result in + importScenes(result) + } + .alert("场景", isPresented: Binding(get: { message != nil }, set: { if !$0 { message = nil } })) { + Button("好") { message = nil } + } message: { + Text(message ?? "") + } + } + } + + private func row(_ scene: WeChatScene) -> some View { + NavigationLink { + SceneEditorView(scene: scene, isNew: false) + } label: { + Toggle(isOn: enabled(scene)) { + VStack(alignment: .leading, spacing: 2) { + Text(scene.name) + if !scene.summary.isEmpty { + Text(scene.summary).font(.caption).foregroundStyle(.secondary).lineLimit(2) + } + } + } + } + } + + private func enabled(_ scene: WeChatScene) -> Binding { + // Not scene(id:) / replace(_:): the first only finds enabled scenes and + // the second keeps the stored switch, so neither can flip it. + Binding { + preferences.scenes.scenes.first { $0.id == scene.id }?.enabled ?? false + } set: { on in + guard let index = preferences.scenes.scenes.firstIndex(where: { $0.id == scene.id }) else { return } + preferences.scenes.scenes[index].enabled = on + } + } + + private func importScenes(_ result: Result<[URL], Error>) { + do { + var count = 0 + for url in try result.get() { + let accessing = url.startAccessingSecurityScopedResource() + defer { if accessing { url.stopAccessingSecurityScopedResource() } } + let data = try Data(contentsOf: url) + let decoder = ScenePackage.decoder() + let packages = try (try? decoder.decode([ScenePackage].self, from: data)) ?? [decoder.decode(ScenePackage.self, from: data)] + for package in packages { + // replace(_:) adds when missing but keeps a stored switch, + // so an import turns the scene on afterwards. + preferences.scenes.replace(package.scene) + if let index = preferences.scenes.scenes.firstIndex(where: { $0.id == package.scene.id }) { + preferences.scenes.scenes[index].enabled = true + } + count += 1 + } + } + message = "已导入 \(count) 个场景" + } catch { + message = "导入失败:\(error.localizedDescription)" + } + } + + private func exportMine() { + do { + let data = try ScenePackage.encoder().encode(mine.map { ScenePackage(scene: $0) }) + let url = FileManager.default.temporaryDirectory.appendingPathComponent("微信流场景.json") + try data.write(to: url, options: .atomic) + ActivitySheet.present(items: [url]) { _ in } + } catch { + message = "导出失败:\(error.localizedDescription)" + } + } +} + +struct SceneEditorView: View { + @EnvironmentObject private var preferences: Preferences + @Environment(\.dismiss) private var dismiss + @State var scene: WeChatScene + let isNew: Bool + @State private var keywords = "" + + var body: some View { + Form { + if scene.isOfficial { + Section { + Text("官方场景不能直接修改,可以复制成我的场景后再改。") + Button("复制为我的场景") { + let copy = preferences.scenes.copiedAsUserTask(scene) + preferences.scenes.add(copy) + dismiss() + } + } + } + Section("名称") { + TextField("比如:项目群日报", text: $scene.name) + TextField("一句话说明", text: $scene.summary) + } + Section("指令") { + TextEditor(text: $scene.instruction).frame(minHeight: 120) + } + Section("输出规范") { + TextEditor(text: $scene.outputSpec).frame(minHeight: 100) + } + Section { + TextField("用逗号分隔", text: $keywords) + } header: { + Text("群名关键词") + } footer: { + Text("群名含有这些词时,自动选用这个场景。") + } + } + .disabled(scene.isOfficial) + .navigationTitle(isNew ? "新建场景" : scene.name) + .toolbar { + if !scene.isOfficial { + ToolbarItem(placement: .confirmationAction) { + Button("保存", action: save) + .disabled(scene.name.trimmingCharacters(in: .whitespaces).isEmpty) + } + } + } + .onAppear { keywords = scene.keywords.joined(separator: ",") } + } + + private func save() { + scene.keywords = keywords + .split(whereSeparator: { $0 == "," || $0 == "," || $0 == "、" }) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + if isNew { preferences.scenes.add(scene) } else { preferences.scenes.replace(scene) } + dismiss() + } +} + +/// Binds a chat to scenes. iOS never sees WeChat's title bar, so the chat is +/// known by its summary title and remembered by who speaks in it. +struct SceneBindingView: View { + @EnvironmentObject private var preferences: Preferences + @Environment(\.dismiss) private var dismiss + let summary: RelaySummary + @State private var chosen: [String] = [] + + var body: some View { + NavigationStack { + List(preferences.scenes.enabledScenes) { scene in + Button { + if let index = chosen.firstIndex(of: scene.id) { chosen.remove(at: index) } else { chosen.append(scene.id) } + } label: { + HStack { + Text(scene.name).foregroundStyle(.primary) + Spacer() + if chosen.contains(scene.id) { Image(systemName: "checkmark").foregroundStyle(.tint) } + } + } + } + .navigationTitle("「\(summary.title)」用的场景") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("保存") { + preferences.bind(displayName: summary.title, sceneIDs: chosen, senders: Set(summary.senders)) + dismiss() + } + } + } + .onAppear { + chosen = preferences.groupMemory[GroupName.normalize(summary.title)]?.boundSceneIDs ?? [] + } + } + .presentationDetents([.medium, .large]) + } +} diff --git a/ios/App/Settings/FolderBookmark.swift b/ios/App/Settings/FolderBookmark.swift new file mode 100644 index 0000000..edf65dc --- /dev/null +++ b/ios/App/Settings/FolderBookmark.swift @@ -0,0 +1,45 @@ +import Foundation + +/// A folder the user picked in Files, kept across launches. iOS bookmarks are +/// implicitly security-scoped; `.withSecurityScope` is a macOS-only option. +enum FolderBookmark { + enum Failure: LocalizedError { + case notChosen + case denied + + var errorDescription: String? { + switch self { + case .notChosen: "还没有选择文件夹,请先在设置里选择。" + case .denied: "没有权限写入这个文件夹,请在设置里重新选择。" + } + } + } + + /// Called with a URL fresh from the document picker. + static func make(from url: URL) throws -> Data { + let accessing = url.startAccessingSecurityScopedResource() + defer { if accessing { url.stopAccessingSecurityScopedResource() } } + return try url.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil) + } + + static func name(of bookmark: Data?) -> String? { + guard let bookmark else { return nil } + var stale = false + return (try? URL(resolvingBookmarkData: bookmark, options: [], relativeTo: nil, bookmarkDataIsStale: &stale))? + .lastPathComponent + } + + /// Runs `body` with access open. A stale bookmark still resolves; it is + /// renewed through `refresh` so the next use does not depend on luck. + static func access(_ bookmark: Data?, refresh: (Data) -> Void, _ body: (URL) throws -> T) throws -> T { + guard let bookmark else { throw Failure.notChosen } + var stale = false + let url = try URL(resolvingBookmarkData: bookmark, options: [], relativeTo: nil, bookmarkDataIsStale: &stale) + guard url.startAccessingSecurityScopedResource() else { throw Failure.denied } + defer { url.stopAccessingSecurityScopedResource() } + if stale, let renewed = try? url.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil) { + refresh(renewed) + } + return try body(url) + } +} diff --git a/ios/App/Settings/SettingsView.swift b/ios/App/Settings/SettingsView.swift new file mode 100644 index 0000000..866643e --- /dev/null +++ b/ios/App/Settings/SettingsView.swift @@ -0,0 +1,196 @@ +import SwiftUI +import UIKit +import UniformTypeIdentifiers +import UserNotifications +import WeChatBridgeCore + +struct SettingsView: View { + @EnvironmentObject private var preferences: Preferences + @Binding var showsOnboarding: Bool + @State private var picking: FolderKind? + @State private var error: String? + + enum FolderKind: Identifiable { + case obsidian, folder + var id: Self { self } + } + + var body: some View { + NavigationStack { + Form { + Section { + LabeledContent("Obsidian 库", value: FolderBookmark.name(of: preferences.obsidianBookmark) ?? "未选择") + Button("选择 Obsidian 库") { picking = .obsidian } + // A bare TextField shows only its value, which reads as a stray "微信流" row. + LabeledContent("子文件夹") { + TextField("子文件夹", text: $preferences.obsidianSubfolder).multilineTextAlignment(.trailing) + } + } header: { + Text("Obsidian") + } footer: { + Text("需要先在「文件」App 里能看到 Obsidian 的库。笔记写入「库/子文件夹」。") + } + Section("默认文件夹") { + LabeledContent("文件夹", value: FolderBookmark.name(of: preferences.folderBookmark) ?? "未选择") + Button("选择默认文件夹") { picking = .folder } + LabeledContent("子文件夹") { + TextField("子文件夹", text: $preferences.folderSubfolder).multilineTextAlignment(.trailing) + } + } + Section { + Toggle("分享后提醒我投递", isOn: $preferences.quickDeliver) + .onChange(of: preferences.quickDeliver) { on in + guard on else { return } + Task { _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) } + } + Toggle("投递时显示在灵动岛", isOn: $preferences.liveActivity) + .onChange(of: preferences.liveActivity) { on in + if !on { DeliveryActivityController.endAll() } + } + } header: { + Text("快速投递") + } footer: { + Text("从微信分享进来后弹一条通知:点一下直接打开分享面板,投递到上次的目标;长按通知可以换成别的目标。\n投递到别的 App 后,灵动岛和锁屏上会留一个入口:点一下回到这段聊天,也能再复制一次提示词。") + } + Section("投递目标") { + NavigationLink("调整目标") { TargetSettingsView() } + } + Section { + Picker("图片怎么发", selection: $preferences.imagesInPDF) { + Text("和文字合成一个 PDF").tag(true) + Text("只发 TXT,图片存到「照片」").tag(false) + } + } header: { + Text("豆包、千问等") + } footer: { + Text("PDF:聊天记录和图片一次发过去,图片插在对应的消息下面。\nTXT:对方收到纯文字,图片和视频存到「照片」,需要时在对方 App 里点「相册」再加。\n两种方式下,视频存到「照片」,其他附件都放到「文件 › 我的iPhone › 微信流」。") + } + Section("历史") { + Picker("保留已收到的记录", selection: $preferences.retentionDays) { + Text("1 天").tag(1) + Text("7 天").tag(7) + Text("30 天").tag(30) + Text("一直保留").tag(0) + } + } + Section { + Button("重新查看使用引导") { showsOnboarding = true } + } + Section { + LabeledContent("版本", value: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "") + } footer: { + Text("聊天记录只保存在本机,不上传任何服务器。") + } + } + .navigationTitle("设置") + .sheet(item: $picking) { kind in + FolderPicker { url in + do { + let bookmark = try FolderBookmark.make(from: url) + switch kind { + case .obsidian: preferences.obsidianBookmark = bookmark + case .folder: preferences.folderBookmark = bookmark + } + } catch { + self.error = error.localizedDescription + } + } + .ignoresSafeArea() + } + .alert("无法使用这个文件夹", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) { + Button("好") { error = nil } + } message: { + Text(error ?? "") + } + } + } +} + +struct TargetSettingsView: View { + @EnvironmentObject private var preferences: Preferences + + /// Every built-in target in the user's order, hidden ones included. + private var all: [TargetProfile] { + TargetProfile.arranged(TargetProfile.builtIn, order: preferences.targetOrder, hidden: [], overrides: preferences.formatOverrides, lastUsed: nil) + } + + var body: some View { + List { + Section { + ForEach(all) { profile in + VStack(alignment: .leading, spacing: 6) { + Toggle(isOn: visible(profile.id)) { + Label { Text(profile.displayName) } icon: { TargetIcon(profile: profile, size: 28) } + } + if profile.canChangeFormat { + Picker("发送方式", selection: format(profile)) { + Text(DeliveryFormat.archive.label).tag(DeliveryFormat.archive) + Text(DeliveryFormat.transcriptAndImages.label).tag(DeliveryFormat.transcriptAndImages) + } + .pickerStyle(.segmented) + } + } + } + .onMove { from, to in + var ids = all.map(\.id) + ids.move(fromOffsets: from, toOffset: to) + preferences.targetOrder = ids + } + } footer: { + Text("有的 App 不收 ZIP(比如豆包、千问),就改成「发送 TXT 和图片」。上次用过的目标总会排在第一个。") + } + Section { + Button("恢复默认") { + preferences.targetOrder = [] + preferences.hiddenTargets = [] + preferences.formatOverrides = [:] + } + } + } + .environment(\.editMode, .constant(.active)) + .navigationTitle("投递目标") + } + + private func visible(_ id: String) -> Binding { + Binding { + !preferences.hiddenTargets.contains(id) + } set: { shown in + preferences.hiddenTargets.removeAll { $0 == id } + if !shown { preferences.hiddenTargets.append(id) } + } + } + + private func format(_ profile: TargetProfile) -> Binding { + Binding { + profile.format + } set: { format in + let builtIn = TargetProfile.builtIn.first { $0.id == profile.id }?.format + preferences.formatOverrides[profile.id] = format == builtIn ? nil : format.rawValue + } + } +} + +/// The Files folder picker. `asCopy: false` so the result is the folder +/// itself, which a bookmark can then reopen. +struct FolderPicker: UIViewControllerRepresentable { + let picked: (URL) -> Void + + func makeUIViewController(context: Context) -> UIDocumentPickerViewController { + let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder], asCopy: false) + picker.delegate = context.coordinator + return picker + } + + func updateUIViewController(_ controller: UIDocumentPickerViewController, context: Context) {} + + func makeCoordinator() -> Coordinator { Coordinator(picked: picked) } + + final class Coordinator: NSObject, UIDocumentPickerDelegate { + let picked: (URL) -> Void + init(picked: @escaping (URL) -> Void) { self.picked = picked } + + func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { + if let url = urls.first { picked(url) } + } + } +} diff --git a/ios/App/WeChatBridgeApp.swift b/ios/App/WeChatBridgeApp.swift new file mode 100644 index 0000000..7f291a1 --- /dev/null +++ b/ios/App/WeChatBridgeApp.swift @@ -0,0 +1,125 @@ +import SwiftUI +import UserNotifications +import WeChatBridgeCore + +@main +struct WeChatBridgeApp: App { + @UIApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate + @StateObject private var store = RelayStore() + @StateObject private var preferences = Preferences() + + var body: some Scene { + WindowGroup { + RootView() + .environmentObject(store) + .environmentObject(preferences) + } + } +} + +/// Where a tapped 「已存入」 notification waits until the relay list can act on it. +@MainActor +final class QuickDeliverRouter: ObservableObject { + static let shared = QuickDeliverRouter() + + struct Request: Equatable { + let batchID: UUID + let targetID: String? + } + + @Published var pending: Request? + + /// A tap on the Live Activity: show this batch. Each tap is a new value, + /// so tapping the same batch twice still navigates. + struct Open: Equatable { + let batchID: UUID + let token = UUID() + } + + @Published var open: Open? + + /// `wechatbridge://relay/`, the Live Activity's link. + func handle(_ url: URL) { + guard url.scheme == "wechatbridge", url.host == "relay", + let id = UUID(uuidString: url.lastPathComponent) + else { return } + open = Open(batchID: id) + } +} + +final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { + // Set before launch ends, so a tap that cold-starts the app is delivered. + UNUserNotificationCenter.current().delegate = self + return true + } + + func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async { + guard let request = QuickDeliver.request(from: response) else { return } + await MainActor.run { + QuickDeliverRouter.shared.pending = .init(batchID: request.batchID, targetID: request.targetID) + } + } + + func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { + [.banner, .sound] + } +} + +struct RootView: View { + @EnvironmentObject private var store: RelayStore + @EnvironmentObject private var preferences: Preferences + @Environment(\.scenePhase) private var scenePhase + @State private var observer: InboxObserver? + @State private var showsOnboarding = false + @State private var launched = false + @State private var tab = 0 + @ObservedObject private var router = QuickDeliverRouter.shared + + var body: some View { + TabView(selection: $tab) { + RelayListView(showsOnboarding: $showsOnboarding) + .tabItem { Label("中转站", systemImage: "tray.full") } + .tag(0) + ScenesView() + .tabItem { Label("场景", systemImage: "text.badge.star") } + .tag(1) + SettingsView(showsOnboarding: $showsOnboarding) + .tabItem { Label("设置", systemImage: "gearshape") } + .tag(2) + } + // A notification tap always lands on the relay, where the sheet opens. + .onChange(of: router.pending) { request in + if request != nil { tab = 0; showsOnboarding = false } + } + .onChange(of: router.open) { open in + if open != nil { tab = 0; showsOnboarding = false } + } + .onOpenURL { router.handle($0) } + .fullScreenCover(isPresented: $showsOnboarding) { + OnboardingView { preferences.onboardingDone = true; showsOnboarding = false } + } + .onAppear(perform: launch) + .onChange(of: scenePhase) { phase in + switch phase { + case .active: store.reload() + case .background: store.commitDeletion() + default: break + } + } + } + + private func launch() { + guard !launched else { return } + launched = true + DeliveryPlanner.cleanUp() + FilesExport.placeGuide() + observer = InboxObserver { [store] in store.reload() } + store.reload() + store.pruneHistory(retentionDays: preferences.retentionDays) + if !preferences.onboardingDone && router.pending == nil { showsOnboarding = true } + if preferences.quickDeliver { + Task { _ = try? await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) } + } + } +} diff --git a/ios/CollectExtension/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/CollectExtension/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..5b0a2e1 --- /dev/null +++ b/ios/CollectExtension/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,6 @@ +{ + "images" : [ + { "filename" : "glyph.png", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" } + ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/CollectExtension/Assets.xcassets/AppIcon.appiconset/glyph.png b/ios/CollectExtension/Assets.xcassets/AppIcon.appiconset/glyph.png new file mode 100644 index 0000000..15b0039 Binary files /dev/null and b/ios/CollectExtension/Assets.xcassets/AppIcon.appiconset/glyph.png differ diff --git a/ios/CollectExtension/Assets.xcassets/Contents.json b/ios/CollectExtension/Assets.xcassets/Contents.json new file mode 100644 index 0000000..46cba7d --- /dev/null +++ b/ios/CollectExtension/Assets.xcassets/Contents.json @@ -0,0 +1 @@ +{ "info" : { "author" : "xcode", "version" : 1 } } diff --git a/ios/Config/App-Info.plist b/ios/Config/App-Info.plist new file mode 100644 index 0000000..3925d1e --- /dev/null +++ b/ios/Config/App-Info.plist @@ -0,0 +1,64 @@ + + + + + CFBundleDevelopmentRegion + zh-Hans + CFBundleDisplayName + 微信流 + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleURLTypes + + + CFBundleURLSchemes + + wechatbridge + + + + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + DKAppGroupIdentifier + $(APP_GROUP_ID) + DKStorageMode + app-group + ITSAppUsesNonExemptEncryption + + LSApplicationQueriesSchemes + + obsidian + + LSRequiresIPhoneOS + + LSSupportsOpeningDocumentsInPlace + + NSPhotoLibraryAddUsageDescription + 把聊天里的图片和视频存到「照片」,方便在千问等 App 的相册里选取。 + NSSupportsLiveActivities + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + + UIFileSharingEnabled + + UILaunchScreen + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + + + diff --git a/ios/Config/App.entitlements b/ios/Config/App.entitlements new file mode 100644 index 0000000..1f52297 --- /dev/null +++ b/ios/Config/App.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.application-groups + + $(APP_GROUP_ID) + + + diff --git a/ios/Config/Collect-Info.plist b/ios/Config/Collect-Info.plist new file mode 100644 index 0000000..9f3555a --- /dev/null +++ b/ios/Config/Collect-Info.plist @@ -0,0 +1,34 @@ + + + + + CFBundleDevelopmentRegionzh-Hans + CFBundleDisplayName分批收集到微信流 + CFBundleExecutable$(EXECUTABLE_NAME) + CFBundleIdentifier$(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion6.0 + CFBundleName$(PRODUCT_NAME) + CFBundlePackageTypeXPC! + CFBundleShortVersionString$(MARKETING_VERSION) + CFBundleVersion$(CURRENT_PROJECT_VERSION) + DKAppGroupIdentifier$(APP_GROUP_ID) + DKStorageModeapp-group + DKShareActioncollect + DKJoinsCollection + NSExtension + + NSExtensionPointIdentifiercom.apple.ui-services + NSExtensionPrincipalClass$(PRODUCT_MODULE_NAME).ShareViewController + NSExtensionAttributes + + NSExtensionActionWantsFullScreenPresentation + NSExtensionActivationRule + + NSExtensionActivationSupportsFileWithMaxCount32 + NSExtensionActivationSupportsImageWithMaxCount32 + NSExtensionActivationSupportsMovieWithMaxCount32 + + + + + diff --git a/ios/Config/PrivacyInfo.xcprivacy b/ios/Config/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..478ada5 --- /dev/null +++ b/ios/Config/PrivacyInfo.xcprivacy @@ -0,0 +1,20 @@ + + + + + NSPrivacyTracking + NSPrivacyTrackingDomains + NSPrivacyCollectedDataTypes + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPITypeNSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasonsCA92.11C8F.1 + + + NSPrivacyAccessedAPITypeNSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasonsC617.1 + + + + diff --git a/ios/Config/Share-Info.plist b/ios/Config/Share-Info.plist new file mode 100644 index 0000000..bc054d0 --- /dev/null +++ b/ios/Config/Share-Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegionzh-Hans + CFBundleDisplayName微信流 + CFBundleExecutable$(EXECUTABLE_NAME) + CFBundleIdentifier$(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion6.0 + CFBundleName$(PRODUCT_NAME) + CFBundlePackageTypeXPC! + CFBundleShortVersionString$(MARKETING_VERSION) + CFBundleVersion$(CURRENT_PROJECT_VERSION) + DKAppGroupIdentifier$(APP_GROUP_ID) + DKStorageModeapp-group + DKShareActioncollect + NSExtension + + NSExtensionPointIdentifiercom.apple.share-services + NSExtensionPrincipalClass$(PRODUCT_MODULE_NAME).ShareViewController + NSExtensionAttributes + + NSExtensionActivationRule + + NSExtensionActivationSupportsFileWithMaxCount32 + NSExtensionActivationSupportsImageWithMaxCount32 + NSExtensionActivationSupportsMovieWithMaxCount32 + + + + + diff --git a/ios/Config/Share.entitlements b/ios/Config/Share.entitlements new file mode 100644 index 0000000..1f52297 --- /dev/null +++ b/ios/Config/Share.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.application-groups + + $(APP_GROUP_ID) + + + diff --git a/ios/Config/Signing.xcconfig b/ios/Config/Signing.xcconfig new file mode 100644 index 0000000..b3d66c8 --- /dev/null +++ b/ios/Config/Signing.xcconfig @@ -0,0 +1,9 @@ +// Simulator builds need no account. A device build with the App Group needs a +// paid team; put DEVELOPMENT_TEAM overrides in Signing.local.xcconfig (ignored). +DEVELOPMENT_TEAM = DLKMC3ZRZQ +CODE_SIGN_STYLE = Automatic +// A free Apple ID (Personal Team) cannot use com.xiangming IDs, which belong +// to the paid team; override these two together with DEVELOPMENT_TEAM. +APP_BUNDLE_ID = com.xiangming.wechatbridge.ios +APP_GROUP_ID = group.com.xiangming.wechatbridge +#include? "Signing.local.xcconfig" diff --git a/ios/Config/Widget-Info.plist b/ios/Config/Widget-Info.plist new file mode 100644 index 0000000..04c1c38 --- /dev/null +++ b/ios/Config/Widget-Info.plist @@ -0,0 +1,19 @@ + + + + + CFBundleDevelopmentRegionzh-Hans + CFBundleDisplayName微信流 + CFBundleExecutable$(EXECUTABLE_NAME) + CFBundleIdentifier$(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion6.0 + CFBundleName$(PRODUCT_NAME) + CFBundlePackageTypeXPC! + CFBundleShortVersionString$(MARKETING_VERSION) + CFBundleVersion$(CURRENT_PROJECT_VERSION) + NSExtension + + NSExtensionPointIdentifiercom.apple.widgetkit-extension + + + diff --git a/ios/LiveActivity/DeliveryActivity.swift b/ios/LiveActivity/DeliveryActivity.swift new file mode 100644 index 0000000..8871ab8 --- /dev/null +++ b/ios/LiveActivity/DeliveryActivity.swift @@ -0,0 +1,84 @@ +import ActivityKit +import AppIntents +import Foundation +import UIKit + +/// The Live Activity shown while a delivery is out in another app: the user +/// picks 豆包 in the share sheet, lands in 豆包, and the Dynamic Island keeps +/// a way back to the chat and its prompt. +/// +/// Compiled into the app and the widget extension. The widget only draws it; +/// the app starts, updates and ends it, and runs its intents. +struct DeliveryActivityAttributes: ActivityAttributes { + struct ContentState: Codable, Hashable { + enum Phase: String, Codable { + /// The share sheet is up. + case choosing + /// The share sheet reported the hand-off. + case sent + } + + var phase: Phase + var hasPrompt: Bool + } + + var batchID: String + var title: String + /// 「4 条消息 · 1 个附件」, or empty. + var detail: String + var targetID: String + var targetName: String +} + +extension DeliveryActivityAttributes { + /// Opens the batch's detail page in the app. + var detailURL: URL { + URL(string: "wechatbridge://relay/\(batchID)")! + } + + /// `Logo-` in the shared asset catalog, when the target has one. + var targetLogo: String? { + ["chatgpt", "doubao", "qwen", "workbuddy", "claude", "obsidian"].contains(targetID) ? "Logo-\(targetID)" : nil + } +} + +extension DeliveryActivityAttributes.ContentState { + var status: String { + switch phase { + case .choosing: hasPrompt ? "提示词已复制 · 在分享面板选择" : "在分享面板选择" + case .sent: hasPrompt ? "已交给对方 · 提示词在剪贴板" : "已交给对方" + } + } +} + +/// The prompt the island's 「复制提示词」 puts back, in case the clipboard +/// was overwritten in the other app. Intents run in the app's process, so +/// the app's own defaults are the right place. +enum DeliveryActivityPrompt { + static let key = "com.xiangming.wechatbridge.ios.activityPrompt" +} + +struct CopyDeliveryPromptIntent: LiveActivityIntent { + static var title: LocalizedStringResource = "复制提示词" + static var isDiscoverable = false + + func perform() async throws -> some IntentResult { + if let prompt = UserDefaults.standard.string(forKey: DeliveryActivityPrompt.key), !prompt.isEmpty { + await MainActor.run { UIPasteboard.general.string = prompt } + } + return .result() + } +} + +struct EndDeliveryActivityIntent: LiveActivityIntent { + static var title: LocalizedStringResource = "结束投递" + static var isDiscoverable = false + + func perform() async throws -> some IntentResult { + for activity in Activity.activities { + await activity.end(nil, dismissalPolicy: .immediate) + } + UserDefaults.standard.removeObject(forKey: DeliveryActivityPrompt.key) + return .result() + } +} diff --git a/ios/Resources/Assets.xcassets/AccentColor.colorset/Contents.json b/ios/Resources/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..243caaa --- /dev/null +++ b/ios/Resources/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,8 @@ +{ + "colors" : [ + { "color" : { "color-space" : "srgb", "components" : { "red" : "0.027", "green" : "0.757", "blue" : "0.376", "alpha" : "1.000" } }, "idiom" : "universal" }, + { "appearances" : [ { "appearance" : "luminosity", "value" : "dark" } ], + "color" : { "color-space" : "srgb", "components" : { "red" : "0.157", "green" : "0.808", "blue" : "0.459", "alpha" : "1.000" } }, "idiom" : "universal" } + ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/Resources/Assets.xcassets/AppGlyph.imageset/Contents.json b/ios/Resources/Assets.xcassets/AppGlyph.imageset/Contents.json new file mode 100644 index 0000000..7ac778c --- /dev/null +++ b/ios/Resources/Assets.xcassets/AppGlyph.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "glyph.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/Resources/Assets.xcassets/AppGlyph.imageset/glyph.png b/ios/Resources/Assets.xcassets/AppGlyph.imageset/glyph.png new file mode 100644 index 0000000..1141049 Binary files /dev/null and b/ios/Resources/Assets.xcassets/AppGlyph.imageset/glyph.png differ diff --git a/ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png b/ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png new file mode 100644 index 0000000..4a7697d Binary files /dev/null and b/ios/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png differ diff --git a/ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..2db9931 --- /dev/null +++ b/ios/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,6 @@ +{ + "images" : [ + { "filename" : "AppIcon-1024.png", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" } + ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/Resources/Assets.xcassets/Contents.json b/ios/Resources/Assets.xcassets/Contents.json new file mode 100644 index 0000000..46cba7d --- /dev/null +++ b/ios/Resources/Assets.xcassets/Contents.json @@ -0,0 +1 @@ +{ "info" : { "author" : "xcode", "version" : 1 } } diff --git a/ios/Resources/Assets.xcassets/Logo-chatgpt.imageset/Contents.json b/ios/Resources/Assets.xcassets/Logo-chatgpt.imageset/Contents.json new file mode 100644 index 0000000..7c13eef --- /dev/null +++ b/ios/Resources/Assets.xcassets/Logo-chatgpt.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "chatgpt.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/Resources/Assets.xcassets/Logo-chatgpt.imageset/chatgpt.png b/ios/Resources/Assets.xcassets/Logo-chatgpt.imageset/chatgpt.png new file mode 100644 index 0000000..4dab4db Binary files /dev/null and b/ios/Resources/Assets.xcassets/Logo-chatgpt.imageset/chatgpt.png differ diff --git a/ios/Resources/Assets.xcassets/Logo-claude.imageset/Contents.json b/ios/Resources/Assets.xcassets/Logo-claude.imageset/Contents.json new file mode 100644 index 0000000..9078a22 --- /dev/null +++ b/ios/Resources/Assets.xcassets/Logo-claude.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "claude.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/Resources/Assets.xcassets/Logo-claude.imageset/claude.png b/ios/Resources/Assets.xcassets/Logo-claude.imageset/claude.png new file mode 100644 index 0000000..7285e51 Binary files /dev/null and b/ios/Resources/Assets.xcassets/Logo-claude.imageset/claude.png differ diff --git a/ios/Resources/Assets.xcassets/Logo-doubao.imageset/Contents.json b/ios/Resources/Assets.xcassets/Logo-doubao.imageset/Contents.json new file mode 100644 index 0000000..20e40ce --- /dev/null +++ b/ios/Resources/Assets.xcassets/Logo-doubao.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "doubao.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/Resources/Assets.xcassets/Logo-doubao.imageset/doubao.png b/ios/Resources/Assets.xcassets/Logo-doubao.imageset/doubao.png new file mode 100644 index 0000000..8feb234 Binary files /dev/null and b/ios/Resources/Assets.xcassets/Logo-doubao.imageset/doubao.png differ diff --git a/ios/Resources/Assets.xcassets/Logo-obsidian.imageset/Contents.json b/ios/Resources/Assets.xcassets/Logo-obsidian.imageset/Contents.json new file mode 100644 index 0000000..b6db5b7 --- /dev/null +++ b/ios/Resources/Assets.xcassets/Logo-obsidian.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "obsidian.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/Resources/Assets.xcassets/Logo-obsidian.imageset/obsidian.png b/ios/Resources/Assets.xcassets/Logo-obsidian.imageset/obsidian.png new file mode 100644 index 0000000..612d6f1 Binary files /dev/null and b/ios/Resources/Assets.xcassets/Logo-obsidian.imageset/obsidian.png differ diff --git a/ios/Resources/Assets.xcassets/Logo-qwen.imageset/Contents.json b/ios/Resources/Assets.xcassets/Logo-qwen.imageset/Contents.json new file mode 100644 index 0000000..976445c --- /dev/null +++ b/ios/Resources/Assets.xcassets/Logo-qwen.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "qwen.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/Resources/Assets.xcassets/Logo-qwen.imageset/qwen.png b/ios/Resources/Assets.xcassets/Logo-qwen.imageset/qwen.png new file mode 100644 index 0000000..a4cf6ab Binary files /dev/null and b/ios/Resources/Assets.xcassets/Logo-qwen.imageset/qwen.png differ diff --git a/ios/Resources/Assets.xcassets/Logo-workbuddy.imageset/Contents.json b/ios/Resources/Assets.xcassets/Logo-workbuddy.imageset/Contents.json new file mode 100644 index 0000000..9b1b085 --- /dev/null +++ b/ios/Resources/Assets.xcassets/Logo-workbuddy.imageset/Contents.json @@ -0,0 +1,4 @@ +{ + "images" : [ { "filename" : "workbuddy.png", "idiom" : "universal" } ], + "info" : { "author" : "xcode", "version" : 1 } +} diff --git a/ios/Resources/Assets.xcassets/Logo-workbuddy.imageset/workbuddy.png b/ios/Resources/Assets.xcassets/Logo-workbuddy.imageset/workbuddy.png new file mode 100644 index 0000000..778cc96 Binary files /dev/null and b/ios/Resources/Assets.xcassets/Logo-workbuddy.imageset/workbuddy.png differ diff --git a/ios/Scripts/make-fixtures.py b/ios/Scripts/make-fixtures.py new file mode 100644 index 0000000..cae26f9 --- /dev/null +++ b/ios/Scripts/make-fixtures.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Writes the synthetic WeChat exports the iOS tests read. + +Run from anywhere: python3 -I ios/Scripts/make-fixtures.py +The output is committed; re-run only when the fixture contents change. + +Entries are written the way WeChat writes them: UTF-8 names with the +language-encoding flag cleared, deflate compression. Python sets the flag on +any non-ASCII name, so the header bits are patched after writing. +""" +import io +import os +import struct +import zipfile + +OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Tests", "Fixtures") +MEDIA = "聊天记录内的图片、视频和文件/" + +# A 1x1 PNG: the smallest real image, so UIImage can decode it in tests. +PNG = bytes.fromhex( + "89504e470d0a1a0a0000000d4948445200000001000000010806000000" + "1f15c4890000000d49444154789c6360000002000154a24f5d0000000049454e44ae426082" +) + + +def message(sender, stamp, text): + return f"·{sender}\n{stamp}\n{text}\n" + + +def write(name, transcript, media): + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive: + archive.writestr("聊天记录.txt", transcript) + for path, data in media.items(): + archive.writestr(MEDIA + path, data) + data = bytearray(buffer.getvalue()) + clear_utf8_flag(data) + with open(os.path.join(OUT, name), "wb") as handle: + handle.write(data) + + +def clear_utf8_flag(data): + """Clears bit 11 in every local and central directory header.""" + offset = 0 + while True: + local = data.find(b"PK\x03\x04", offset) + if local < 0: + break + flags = struct.unpack_from("&1 | grep -E "Executed [0-9]+ tests|error:" | tail -2 + +echo "== iOS typecheck of WeChatBridgeCore" +SDK=$(xcrun --sdk iphonesimulator --show-sdk-path) +xcrun swiftc -typecheck -sdk "$SDK" -target arm64-apple-ios17.0-simulator -swift-version 6 \ + -application-extension -module-name WeChatBridgeCore "$ROOT"/macos/Sources/WeChatBridgeCore/*.swift + +echo "== xcodegen" +(cd "$ROOT/ios" && xcodegen generate --quiet) + +mkdir -p "$ROOT/ios/build" +echo "== iOS build and unit tests on $DEVICE" +xcodebuild -project "$ROOT/ios/WeChatBridge.xcodeproj" -scheme WeChatBridgeiOS \ + -destination "platform=iOS Simulator,name=$DEVICE" \ + -derivedDataPath "$ROOT/ios/build/DerivedData" \ + CODE_SIGNING_ALLOWED=NO test > "$ROOT/ios/build/test.log" 2>&1 || status=$? +grep -E "error:|Executed [0-9]+ tests|\*\* (TEST|BUILD) " "$ROOT/ios/build/test.log" | sort -u +exit "${status:-0}" diff --git a/ios/ShareExtension/ReceiptView.swift b/ios/ShareExtension/ReceiptView.swift new file mode 100644 index 0000000..306da5a --- /dev/null +++ b/ios/ShareExtension/ReceiptView.swift @@ -0,0 +1,122 @@ +import SwiftUI +import WeChatBridgeCore + +@MainActor +final class ReceiptModel: ObservableObject { + /// One batch of 「分批收集」. Counts are nil when the share was not a + /// WeChat export the extension could read. + struct Collected: Equatable { + let number: Int + let count: Int? + let start: Date? + let end: Date? + /// What went to the clipboard, for WeChat's search. + let anchor: String? + } + + enum State: Equatable { + case saving + case saved(names: [String], byteCount: Int64, anchor: String?) + case collected(Collected) + case failed(String) + } + + @Published var state: State = .saving +} + +/// One small card over the host app. Only the TXT is read for counts, never +/// the media, so the extension stays well inside its memory ceiling. +struct ReceiptView: View { + @ObservedObject var model: ReceiptModel + let done: () -> Void + + var body: some View { + VStack { + Spacer() + VStack(spacing: 12) { + icon + Text(title).font(.headline) + if let detail { + Text(detail) + .font(.subheadline) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .lineLimit(3) + } + if let hint { + Text(hint) + .font(.footnote) + .multilineTextAlignment(.center) + .padding(10) + .frame(maxWidth: .infinity) + .background(Color.green.opacity(0.12), in: RoundedRectangle(cornerRadius: 10, style: .continuous)) + } + if model.state != .saving { + Button("完成", action: done) + .buttonStyle(.borderedProminent) + .tint(.green) + .padding(.top, 4) + } + } + .padding(24) + .frame(maxWidth: 320) + .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 20, style: .continuous)) + .padding(.bottom, 48) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .animation(.easeOut(duration: 0.2), value: model.state) + } + + @ViewBuilder private var icon: some View { + switch model.state { + case .saving: + ProgressView().controlSize(.large) + case .saved: + Image(systemName: "checkmark.circle.fill").font(.system(size: 40)).foregroundStyle(.green) + case .collected: + Image(systemName: "square.stack.3d.down.forward.fill").font(.system(size: 36)).foregroundStyle(.green) + case .failed: + Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 40)).foregroundStyle(.orange) + } + } + + private var title: String { + switch model.state { + case .saving: "正在存入…" + case .saved: "已存入中转站" + case .collected(let batch): "已收第 \(batch.number) 批" + case .failed: "没有存入" + } + } + + private var detail: String? { + switch model.state { + case .saving: + return nil + case .saved(let names, let byteCount, _): + let head = names.count == 1 ? names[0] : "\(names.count) 个文件" + return "\(head) · \(ByteFormat.string(byteCount))" + case .collected(let batch): + // The title already says how many batches there are. + var parts: [String] = [] + if let count = batch.count { parts.append("这批 \(count) 条") } + if let range = RelayFormat.range(batch.start, batch.end) { parts.append(range) } + return parts.isEmpty ? nil : parts.joined(separator: " · ") + case .failed(let message): + return message + } + } + + private var hint: String? { + switch model.state { + case .collected(let batch): + let next = "回微信多选下一段,再选「分批收集到微信流」" + guard let anchor = batch.anchor else { return next } + return "已复制这批最后一句「\(anchor)」\n回微信搜索它定位,从下一条接着多选\n再选「分批收集到微信流」" + case .saved(_, _, let anchor?): + return "正好 \(SearchAnchor.forwardLimit) 条,后面可能还有。已复制最后一句「\(anchor)」,回微信搜索它接着选,用「分批收集到微信流」分批存。" + default: + return nil + } + } +} diff --git a/ios/ShareExtension/ShareViewController.swift b/ios/ShareExtension/ShareViewController.swift new file mode 100644 index 0000000..e9d60dc --- /dev/null +++ b/ios/ShareExtension/ShareViewController.swift @@ -0,0 +1,244 @@ +import SwiftUI +import UIKit +import WeChatBridgeCore + +/// The entry point of both extensions: 「微信流」 in the share row +/// (`com.apple.share-services`) and 「分批收集到微信流」 in the action list +/// (`com.apple.ui-services`, `CollectMarker.declared`). Copy what was shared +/// into the group container and stop. Only the chat's TXT is read, for the +/// receipt and the search anchor; nothing is delivered here — an +/// extension has a small memory ceiling, cannot present a second share sheet +/// that other apps' extensions reliably appear in, and cannot formally open +/// its containing app. The relay app does all of that later. +/// +/// The import is the macOS extension's, step for step (see +/// `macos/Sources/WeChatBridgeShare/ShareViewController.swift`): one atomic +/// batch, never half of one, and the files are durable before anything is +/// told about them. +@objc(ShareViewController) +final class ShareViewController: UIViewController { + private let model = ReceiptModel() + /// `viewDidLoad` is not promised to run once, and the import is not idempotent. + private var hasStarted = false + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .clear + + let host = UIHostingController(rootView: ReceiptView(model: model) { [weak self] in + self?.finish() + }) + host.view.backgroundColor = .clear + addChild(host) + host.view.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(host.view) + NSLayoutConstraint.activate([ + host.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), + host.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), + host.view.topAnchor.constraint(equalTo: view.topAnchor), + host.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + host.didMove(toParent: self) + + guard !hasStarted, let context = extensionContext else { return } + hasStarted = true + Task { @MainActor in + await run(context: context) + } + } + + @MainActor + private func run(context: NSExtensionContext) async { + let sources = Self.flatten(inputItems: context.inputItems) + let inbox = try? Inbox.resolve() + guard !sources.isEmpty else { + fail(InboxError.emptyShare, inbox: inbox) + return + } + guard let inbox else { + // A signing problem, not the user's: the group id goes to the log only. + NSLog("WeChatBridge share: %@", InboxError.containerUnavailable(identifier: AppGroup.identifier).errorDescription ?? "") + model.state = .failed(Self.installBroken) + return + } + let staging: BatchStaging + do { + staging = try BatchStaging.create(in: inbox) + } catch { + fail(error, inbox: inbox) + return + } + + var manifestItems: [ManifestItem] = [] + var diagnostics: [AttachmentDiagnostic] = [] + var failure: Error? + for source in sources { + switch await AttachmentImporter.importAttachment(source, into: staging) { + case .success(let imported): + manifestItems.append(imported.manifestItem) + diagnostics.append(imported.diagnostic) + // WeChat never exports an empty file; one arriving means the + // export failed upstream, and an empty card would only hide it. + if imported.manifestItem.byteCount == 0 { + failure = EmptyFile(name: imported.manifestItem.displayName) + } + case .failure(let error): + if let rejection = error as? ImportRejection { + diagnostics.append(rejection.diagnostic) + } + failure = error + } + if failure != nil { break } + } + + let record = ImportDiagnostics( + batchID: staging.batchID, + createdAt: Date(), + extensionVersion: Self.bundleVersion, + action: .collect, + inputItemCount: (context.inputItems as? [NSExtensionItem])?.count ?? 0, + succeeded: failure == nil, + attachments: diagnostics + ) + + // A partially copied share is never published. + if let failure { + staging.discard() + DiagnosticsLog.record(record, in: inbox) + fail(failure, inbox: inbox) + return + } + + let joinsCollection = CollectMarker.declared + let committed: URL + do { + if joinsCollection { try CollectMarker.mark(staging.directory) } + committed = try staging.commit( + manifest: BatchManifest( + batchID: staging.batchID, + createdAt: record.createdAt, + items: manifestItems, + action: .collect + ), + diagnostics: record, + intent: nil, + in: inbox + ) + } catch { + staging.discard() + fail(error, inbox: inbox) + return + } + + DiagnosticsLog.record(record, in: inbox) + inbox.pruneStaging() + InboxSignal.post() + + let chat = Self.readChat(manifestItems, in: committed) + // Writing the clipboard asks nothing of the user; only reading does. + let anchor = chat.flatMap { joinsCollection || $0.count == SearchAnchor.forwardLimit ? $0.keyword : nil } + if let anchor { UIPasteboard.general.string = anchor } + if joinsCollection { + model.state = .collected(ReceiptModel.Collected( + number: CollectMarker.batchNumber(in: inbox), + count: chat?.count, + start: chat?.start, + end: chat?.end, + anchor: anchor + )) + } else { + model.state = .saved( + names: manifestItems.map(\.displayName), + byteCount: manifestItems.reduce(0) { $0 + $1.byteCount }, + anchor: anchor + ) + } + let names = manifestItems.map(\.displayName) + // The next batch follows at once; a notification per batch would only nag. + if !joinsCollection { + await QuickDeliver.post( + batchID: staging.batchID, + head: names.count == 1 ? names[0] : "\(names.count) 个文件", + defaults: UserDefaults(suiteName: AppGroup.identifier) ?? .standard + ) + } + // Long enough to read one line, short enough that the user is back in + // WeChat before they think about it. The button closes it sooner. + // The search line needs a moment longer to read. + try? await Task.sleep(nanoseconds: anchor == nil ? 1_200_000_000 : 2_000_000_000) + finish() + } + + private var finished = false + + private func finish() { + guard !finished else { return } + finished = true + if case .failed(let message) = model.state { + extensionContext?.cancelRequest(withError: NSError( + domain: "com.xiangming.wechatbridge.share", + code: 1, + userInfo: [NSLocalizedDescriptionKey: message] + )) + } else { + extensionContext?.completeRequest(returningItems: nil, completionHandler: nil) + } + } + + /// The failure stays on screen until dismissed: unlike the Mac there is no + /// resident app to report it, so this card is the first place it is seen. + /// It is also left in the group container for the app's next launch. + private func fail(_ error: Error, inbox: Inbox?) { + let message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription + if let inbox { + ShareFailure.record(ShareFailure(at: Date(), action: .collect, message: message), in: inbox) + InboxSignal.post() + } + model.state = .failed(message) + } + + struct Chat { + let count: Int + let start: Date? + let end: Date? + let keyword: String? + } + + /// The one WeChat export in the share, read from the mapped file: only the + /// central directory and the TXT entry are touched, never the media. + /// Anything else, or a TXT that does not parse, gives nil. + static func readChat(_ items: [ManifestItem], in batch: URL) -> Chat? { + let archives = items.filter { ($0.displayName as NSString).pathExtension.lowercased() == "zip" } + guard archives.count == 1, + let data = try? Data(contentsOf: batch.appendingPathComponent(archives[0].relativePath), options: .alwaysMapped), + let transcript = try? WeChatNativeArchive.transcript(data), + let records = transcript.records, !records.isEmpty else { return nil } + return Chat(count: records.count, start: transcript.start, end: transcript.end, keyword: SearchAnchor.keyword(records)) + } + + static let installBroken = "微信流没装好,请重新安装后再试。" + + static func flatten(inputItems: [Any]) -> [AttachmentSource] { + var sources: [AttachmentSource] = [] + for (itemIndex, raw) in inputItems.enumerated() { + guard let item = raw as? NSExtensionItem else { continue } + for (attachmentIndex, provider) in (item.attachments ?? []).enumerated() { + sources.append(AttachmentSource( + provider: provider, + itemIndex: itemIndex, + attachmentIndex: attachmentIndex + )) + } + } + return sources + } + + private static var bundleVersion: String { + Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "?" + } +} + +private struct EmptyFile: LocalizedError { + let name: String + var errorDescription: String? { "「\(name)」是空文件,没有存入。请回到微信重新导出。" } +} diff --git a/ios/Shared/CollectMarker.swift b/ios/Shared/CollectMarker.swift new file mode 100644 index 0000000..7518b53 --- /dev/null +++ b/ios/Shared/CollectMarker.swift @@ -0,0 +1,76 @@ +import Foundation +import WeChatBridgeCore + +/// 「分批收集到微信流」: the action extension drops this file into its batch +/// before commit, and the app adds marked batches to the open collection on +/// its next reload. The ledger keeps one writer, the app; the marker rides +/// inside the atomic commit, so a batch is never half marked. +/// +/// The ordinary share extension cannot use `ShareAction.collect` for this: +/// it writes that action for every save. +enum CollectMarker { + static let fileName = "collection-member" + /// Set in the action extension's Info.plist only. + static let infoKey = "DKJoinsCollection" + + static var declared: Bool { + Bundle.main.object(forInfoDictionaryKey: infoKey) as? Bool ?? false + } + + static func mark(_ directory: URL) throws { + try Data().write(to: directory.appendingPathComponent(fileName), options: .atomic) + } + + static func isMarked(_ directory: URL) -> Bool { + FileManager.default.fileExists(atPath: directory.appendingPathComponent(fileName).path) + } + + /// Marked batches the ledger has not taken yet, in the order they landed. + /// Directory birth times keep two shares within one second apart, as on the Mac. + static func unseen(_ directories: [URL], seen: Set) -> [UUID] { + let dated: [(id: UUID, date: Date)] = directories.compactMap { directory in + guard let id = UUID(uuidString: directory.lastPathComponent), !seen.contains(id), isMarked(directory) else { return nil } + let created = (try? directory.resourceValues(forKeys: [.creationDateKey]).creationDate) ?? .distantPast + return (id, created) + } + return dated.sorted { $0.date == $1.date ? $0.id.uuidString < $1.id.uuidString : $0.date < $1.date }.map(\.id) + } + + static func ledgerURL(in inbox: Inbox) -> URL { + inbox.root.appendingPathComponent("collections.json") + } + + /// Which batch of the open collection the one just committed is: what the + /// ledger holds plus every marked batch the app has not taken yet, this + /// one included. Read only; a missing ledger counts as empty. + static func batchNumber(in inbox: Inbox) -> Int { + let ledger = (try? BatchCollectionLedger.load(from: ledgerURL(in: inbox))) ?? BatchCollectionLedger() + let ready = (try? FileManager.default.contentsOfDirectory(at: inbox.ready, includingPropertiesForKeys: [.creationDateKey])) ?? [] + return (ledger.current?.batchIDs.count ?? 0) + unseen(ready, seen: ledger.seenBatchIDs).count + } +} + +/// WeChat forwards at most 100 messages at a time. The next batch starts right +/// after this one's last message, so its words go to the clipboard: pasted +/// into WeChat's chat search, they land the user where to select again. +enum SearchAnchor { + static let forwardLimit = 100 + + /// The last message with words of its own, first line, short enough for + /// WeChat's search box. Images, files and other `[标签]` lines are skipped: + /// search finds only what was typed. + static func keyword(_ records: [WeChatTranscriptRecord]) -> String? { + anchor(records)?.keyword + } + + /// The message the keyword comes from, which is shown beside it. + static func anchor(_ records: [WeChatTranscriptRecord]) -> (record: WeChatTranscriptRecord, keyword: String)? { + for record in records.reversed() { + let line = record.text.split(whereSeparator: \.isNewline).first.map(String.init)? + .trimmingCharacters(in: .whitespaces) ?? "" + guard !line.isEmpty, !line.hasPrefix("[") else { continue } + return (record, String(line.prefix(30))) + } + return nil + } +} diff --git a/ios/Shared/QuickDeliver.swift b/ios/Shared/QuickDeliver.swift new file mode 100644 index 0000000..b07476c --- /dev/null +++ b/ios/Shared/QuickDeliver.swift @@ -0,0 +1,90 @@ +import Foundation +import UserNotifications + +/// 「分享后提醒我投递」: the share extension posts a notification for the batch +/// it just saved, and tapping it opens the app straight into delivery. This is +/// as close to one tap as iOS allows: an extension cannot open other apps, +/// start a Live Activity, or present a share sheet that lists them. +/// +/// Compiled into both the app and the extension; they meet only through the +/// App Group defaults and the notification's userInfo. +enum QuickDeliver { + static let enabledKey = "com.xiangming.wechatbridge.ios.quickDeliver" + /// `[[id, name]]`, the first few targets as the app arranges them, + /// written by the app because the extension has no target table. + static let targetsKey = "com.xiangming.wechatbridge.ios.quickTargets" + static let category = "relay.saved" + static let batchKey = "batchID" + static let targetKey = "targetID" + /// An action's identifier is this plus a target id. + static let actionPrefix = "deliver." + /// Notification buttons, and the card menu's quick entries. + static let maxTargets = 3 + + struct Target: Equatable { + let id: String + let name: String + } + + /// On unless the user turned it off. + static func isEnabled(_ defaults: UserDefaults) -> Bool { + defaults.object(forKey: enabledKey) as? Bool ?? true + } + + static func targets(_ defaults: UserDefaults) -> [Target] { + (defaults.array(forKey: targetsKey) as? [[String]] ?? []).compactMap { pair in + pair.count == 2 ? Target(id: pair[0], name: pair[1]) : nil + } + } + + static func store(_ targets: [Target], in defaults: UserDefaults) { + defaults.set(targets.prefix(maxTargets).map { [$0.id, $0.name] }, forKey: targetsKey) + } + + static func content(batchID: UUID, head: String, targets: [Target]) -> UNMutableNotificationContent { + let content = UNMutableNotificationContent() + content.title = "已存入中转站" + content.body = targets.first.map { "\(head) · 点一下投递到「\($0.name)」,长按换目标" } ?? "\(head) · 点一下去投递" + content.categoryIdentifier = category + content.userInfo = [batchKey: batchID.uuidString, targetKey: targets.first?.id ?? ""] + return content + } + + /// One action per recent target; each opens the app, which then shows + /// the share sheet. + static func makeCategory(targets: [Target]) -> UNNotificationCategory { + UNNotificationCategory( + identifier: category, + actions: targets.map { + UNNotificationAction(identifier: actionPrefix + $0.id, title: "投递到「\($0.name)」", options: .foreground) + }, + intentIdentifiers: [] + ) + } + + /// Fire and forget; without permission the share has still succeeded. + static func post(batchID: UUID, head: String, defaults: UserDefaults) async { + guard isEnabled(defaults) else { return } + let center = UNUserNotificationCenter.current() + guard await center.notificationSettings().authorizationStatus == .authorized else { return } + let targets = targets(defaults) + center.setNotificationCategories([makeCategory(targets: targets)]) + let request = UNNotificationRequest( + identifier: batchID.uuidString, + content: content(batchID: batchID, head: head, targets: targets), + trigger: nil + ) + try? await center.add(request) + } + + /// What a tap asks for: the batch, and the target (nil: open the panel). + static func request(from response: UNNotificationResponse) -> (batchID: UUID, targetID: String?)? { + let info = response.notification.request.content.userInfo + guard let raw = info[batchKey] as? String, let batchID = UUID(uuidString: raw) else { return nil } + if response.actionIdentifier.hasPrefix(actionPrefix) { + return (batchID, String(response.actionIdentifier.dropFirst(actionPrefix.count))) + } + let target = info[targetKey] as? String + return (batchID, target?.isEmpty == false ? target : nil) + } +} diff --git a/ios/Shared/RelayFormat.swift b/ios/Shared/RelayFormat.swift new file mode 100644 index 0000000..bfbcecc --- /dev/null +++ b/ios/Shared/RelayFormat.swift @@ -0,0 +1,25 @@ +import Foundation + +/// Dates as the relay and the share receipt write them. +enum RelayFormat { + /// `10月20日 09:00–09:07`; both ends dated when the range crosses a day. + static func range(_ start: Date?, _ end: Date?, calendar: Calendar = .current) -> String? { + guard let start else { return nil } + let day = DateFormatter() + day.locale = Locale(identifier: "zh_CN") + day.dateFormat = "M月d日 HH:mm" + let time = DateFormatter() + time.dateFormat = "HH:mm" + guard let end, end != start else { return day.string(from: start) } + let tail = calendar.isDate(start, inSameDayAs: end) ? time.string(from: end) : day.string(from: end) + return "\(day.string(from: start))–\(tail)" + } + + /// `10月24日 00:19`. + static func day(_ date: Date) -> String { + let formatter = DateFormatter() + formatter.locale = Locale(identifier: "zh_CN") + formatter.dateFormat = "M月d日 HH:mm" + return formatter.string(from: date) + } +} diff --git a/ios/Tests/CollectMarkerTests.swift b/ios/Tests/CollectMarkerTests.swift new file mode 100644 index 0000000..536842f --- /dev/null +++ b/ios/Tests/CollectMarkerTests.swift @@ -0,0 +1,44 @@ +import WeChatBridgeCore +import XCTest +@testable import WeChatBridgeiOS + +final class CollectMarkerTests: XCTestCase { + private var root: URL! + + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("collect-marker-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: root) + } + + private func batch(marked: Bool, created: Date) throws -> (UUID, URL) { + let id = UUID() + let directory = root.appendingPathComponent(id.uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + if marked { try CollectMarker.mark(directory) } + try FileManager.default.setAttributes([.creationDate: created], ofItemAtPath: directory.path) + return (id, directory) + } + + func testUnseenMarkedBatchesComeOldestFirst() throws { + let now = Date() + let (late, lateURL) = try batch(marked: true, created: now) + let (early, earlyURL) = try batch(marked: true, created: now.addingTimeInterval(-60)) + let (_, plainURL) = try batch(marked: false, created: now.addingTimeInterval(-30)) + let (seen, seenURL) = try batch(marked: true, created: now.addingTimeInterval(-90)) + XCTAssertEqual(CollectMarker.unseen([lateURL, plainURL, earlyURL, seenURL], seen: [seen]), [early, late]) + } + + private func records(_ messages: [(String, String)]) throws -> [WeChatTranscriptRecord] { + try WeChatTranscriptRecord.parse(messages.map { "·\($0.0)\n2026年10月20日 09:00\n\($0.1)\n" }.joined(separator: "\n")) + } + + func testKeywordSkipsTagsAndKeepsTheFirstLine() throws { + XCTAssertEqual(SearchAnchor.keyword(try records([("甲", "第一行\n第二行"), ("乙", "[图片] a.png"), ("丙", "[破涕为笑]")])), "第一行") + XCTAssertNil(SearchAnchor.keyword(try records([("乙", "[图片] a.png")]))) + XCTAssertEqual(SearchAnchor.keyword(try records([("甲", String(repeating: "长", count: 50))]))?.count, 30) + } +} diff --git a/ios/Tests/DeliveryPlannerTests.swift b/ios/Tests/DeliveryPlannerTests.swift new file mode 100644 index 0000000..b5e3369 --- /dev/null +++ b/ios/Tests/DeliveryPlannerTests.swift @@ -0,0 +1,149 @@ +import UIKit +import WeChatBridgeCore +import XCTest +@testable import WeChatBridgeiOS + +final class DeliveryPlannerTests: XCTestCase { + private var fixtures: FixtureBatches! + private var packages: [DeliveryPackage] = [] + + override func setUpWithError() throws { + fixtures = try FixtureBatches() + } + + override func tearDown() { + for package in packages { try? FileManager.default.removeItem(at: package.workDirectory) } + fixtures = nil + } + + private func target(_ format: DeliveryFormat, max: Int? = nil) -> TargetProfile { + TargetProfile(id: "t", displayName: "测试", format: format, maxAttachments: max, symbol: "circle") + } + + private func plan(_ batches: [ReadyBatch], _ target: TargetProfile) throws -> DeliveryPackage { + let package = try DeliveryPlanner.plan(DeliveryRequest(batches: batches, target: target, prompt: "提示")) + packages.append(package) + return package + } + + func testArchiveCopiesOriginalsWithUniqueNames() throws { + let a = try fixtures.batch("group-a.zip") + let b = try fixtures.batch("group-a.zip") + let package = try plan([a, b], target(.archive)) + let urls = try XCTUnwrap(package.shares.first) + XCTAssertEqual(urls.map(\.lastPathComponent), ["group-a.zip", "group-a (2).zip"]) + XCTAssertTrue(urls.allSatisfy { $0.path.hasPrefix(package.workDirectory.path) }) + XCTAssertEqual(try Data(contentsOf: urls[0]), try Data(contentsOf: a.items[0].url)) + XCTAssertEqual(package.omitted, []) + XCTAssertEqual(package.prompt, "提示") + } + + func testSingleBatchSendsOriginalTranscriptBytesFirstThenImages() throws { + let batch = try fixtures.batch("group-a.zip") + let package = try plan([batch], target(.transcriptAndImages)) + let urls = try XCTUnwrap(package.shares.first) + XCTAssertEqual(urls.map(\.lastPathComponent), ["聊天记录.txt", "微信图片_20261020_1.png"]) + let original = try XCTUnwrap(WeChatNativeArchive.transcript(Data(contentsOf: batch.items[0].url))) + XCTAssertEqual(try String(contentsOf: urls[0], encoding: .utf8), original.body) + XCTAssertEqual(Set(package.omitted), ["录屏_1.mp4", "需求文档.pdf"]) + XCTAssertFalse(try String(contentsOf: urls[0], encoding: .utf8).contains("提示")) + } + + func testShareCarriesOnlyTheTranscript() throws { + let planned = try plan([try fixtures.batch("group-a.zip")], target(.transcriptAndImages)) + let package = planned.transcriptOnly() + XCTAssertEqual(package.shares.map { $0.map(\.lastPathComponent) }, [["聊天记录.txt"]]) + XCTAssertEqual(Set(package.omitted), ["微信图片_20261020_1.png", "录屏_1.mp4", "需求文档.pdf"]) + XCTAssertTrue(try XCTUnwrap(TargetProfile.builtIn.first { $0.id == "qwen" }).dropsSharedText) + } + + func testPDFModeFoldsTheImageIn() throws { + let planned = try plan([try fixtures.batch("group-a.zip")], target(.transcriptAndImages)) + let group = try XCTUnwrap(planned.shares.first) + // Draw a real image, so the test does not lean on the fixture's bytes. + let image = UIGraphicsImageRenderer(size: CGSize(width: 300, height: 200)).pngData { context in + UIColor.systemGreen.setFill() + context.fill(CGRect(x: 0, y: 0, width: 300, height: 200)) + } + try image.write(to: group[1]) + let package = try planned.foldedIntoPDF() + XCTAssertEqual(package.shares.map { $0.map(\.lastPathComponent) }, [["聊天记录.pdf"]]) + XCTAssertEqual(Set(package.omitted), ["录屏_1.mp4", "需求文档.pdf"]) + XCTAssertEqual(package.inPDF, ["微信图片_20261020_1.png"]) + XCTAssertGreaterThanOrEqual(try XCTUnwrap(CGPDFDocument(package.shares[0][0] as CFURL)).numberOfPages, 1) + } + + func testImageThatDoesNotDecodeIsExportedInstead() throws { + let planned = try plan([try fixtures.batch("group-a.zip")], target(.transcriptAndImages)) + try Data("not a png".utf8).write(to: try XCTUnwrap(planned.shares.first)[1]) + let package = try planned.foldedIntoPDF() + XCTAssertEqual(Set(package.omitted), ["微信图片_20261020_1.png", "录屏_1.mp4", "需求文档.pdf"]) + XCTAssertEqual(package.inPDF, []) + } + + func testTextOnlyShareIsNotFoldedIntoPDF() throws { + let planned = try plan([try fixtures.batch("text-note.zip")], target(.transcriptAndImages)) + XCTAssertEqual(try planned.foldedIntoPDF().shares, planned.shares) + } + + func testMergeRenamesConflictingImageAndRewritesReference() throws { + let package = try plan([try fixtures.batch("group-a.zip"), try fixtures.batch("group-a-later.zip")], target(.transcriptAndImages)) + let urls = try XCTUnwrap(package.shares.first) + XCTAssertEqual(urls.map(\.lastPathComponent), ["聊天记录.txt", "微信图片_20261020_1.png", "微信图片_20261020_1 (2).png"]) + let text = try String(contentsOf: urls[0], encoding: .utf8) + let records = try WeChatTranscriptRecord.parse(text) + XCTAssertEqual(records.count, 11) + XCTAssertEqual(records[1].text, "[图片] 微信图片_20261020_1.png") + XCTAssertEqual(records[9].text, "[图片] 微信图片_20261020_1 (2).png") + } + + func testIdenticalImagesAreNotDuplicated() throws { + let package = try plan([try fixtures.batch("group-a.zip"), try fixtures.batch("group-a.zip")], target(.transcriptAndImages)) + XCTAssertEqual(package.shares.flatMap { $0 }.map(\.lastPathComponent), ["聊天记录.txt", "微信图片_20261020_1.png"]) + XCTAssertEqual(try WeChatTranscriptRecord.parse(String(contentsOf: package.shares[0][0], encoding: .utf8)).count, 8) + } + + func testMaxAttachmentsSplitsWithTranscriptFirst() throws { + let package = try plan([try fixtures.batch("group-a.zip"), try fixtures.batch("group-a-later.zip")], target(.transcriptAndImages, max: 2)) + XCTAssertEqual(package.shares.map { $0.map(\.lastPathComponent) }, [ + ["聊天记录.txt", "微信图片_20261020_1.png"], + ["微信图片_20261020_1 (2).png"], + ]) + } + + func testArchiveWithoutTextCannotBeUnpacked() throws { + XCTAssertThrowsError(try plan([try fixtures.batch("files-only.zip")], target(.transcriptAndImages))) + let package = try plan([try fixtures.batch("files-only.zip")], target(.archive)) + XCTAssertEqual(package.fileCount, 1) + } + + func testPlainTextGoesOutUnderItsOwnName() throws { + let batch = try fixtures.batch("text-note.zip") + let package = try plan([batch], target(.transcriptAndImages)) + let urls = try XCTUnwrap(package.shares.first) + XCTAssertEqual(urls.map(\.lastPathComponent), ["资料合集.txt"]) + let original = try XCTUnwrap(WeChatNativeArchive.transcript(Data(contentsOf: batch.items[0].url))) + XCTAssertEqual(try String(contentsOf: urls[0], encoding: .utf8), original.body) + } + + func testPlainTextMergesWithChatInPickedOrder() throws { + let package = try plan([try fixtures.batch("group-a.zip"), try fixtures.batch("text-note.zip")], target(.transcriptAndImages)) + let urls = try XCTUnwrap(package.shares.first) + XCTAssertEqual(urls[0].lastPathComponent, "聊天记录.txt") + let text = try String(contentsOf: urls[0], encoding: .utf8) + let chat = try XCTUnwrap(text.range(of: "早上好")) + let note = try XCTUnwrap(text.range(of: "资料合集")) + XCTAssertLessThan(chat.lowerBound, note.lowerBound) + } + + func testWritersHaveNoSharePlan() throws { + XCTAssertThrowsError(try plan([try fixtures.batch("group-a.zip")], target(.knowledgeNote))) + } + + func testUniqueName() { + var used: Set = ["a.png", "a (2).png", "b"] + XCTAssertEqual(DeliveryPlanner.uniqueName("a.png", used: &used), "a (3).png") + XCTAssertEqual(DeliveryPlanner.uniqueName("b", used: &used), "b (2)") + XCTAssertEqual(DeliveryPlanner.uniqueName("c.png", used: &used), "c.png") + } +} diff --git a/ios/Tests/FilesExportTests.swift b/ios/Tests/FilesExportTests.swift new file mode 100644 index 0000000..7899b1f --- /dev/null +++ b/ios/Tests/FilesExportTests.swift @@ -0,0 +1,98 @@ +import WeChatBridgeCore +import XCTest +@testable import WeChatBridgeiOS + +final class FilesExportTests: XCTestCase { + private var root: URL! + private var fixtures: FixtureBatches! + + override func setUpWithError() throws { + fixtures = try FixtureBatches() + root = FileManager.default.temporaryDirectory.appendingPathComponent("files-export-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + + override func tearDown() { + try? FileManager.default.removeItem(at: root) + fixtures = nil + } + + func testExportsImagesAndAttachmentsButNotTheTranscript() throws { + let folder = try XCTUnwrap(FilesExport.export(try fixtures.batch("group-a.zip"), name: "甲等3人的聊天", into: root).folder) + let names = try FileManager.default.contentsOfDirectory(atPath: folder.path).sorted() + XCTAssertEqual(names, ["录屏_1.mp4", "微信图片_20261020_1.png", "需求文档.pdf"].sorted()) + } + + func testMediaGoesApartForPhotos() throws { + let media = root.appendingPathComponent("media", isDirectory: true) + let exported = try FilesExport.export(try fixtures.batch("group-a.zip"), name: "聊天", into: root, mediaInto: media) + XCTAssertEqual(exported.media.map(\.lastPathComponent).sorted(), ["录屏_1.mp4", "微信图片_20261020_1.png"].sorted()) + let folder = try XCTUnwrap(exported.folder) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: folder.path), ["需求文档.pdf"]) + } + + func testImagesInThePDFAreLeftOut() throws { + let media = root.appendingPathComponent("media", isDirectory: true) + let exported = try FilesExport.export(try fixtures.batch("group-a.zip"), name: "聊天", into: root, mediaInto: media, inPDF: ["微信图片_20261020_1.png"]) + XCTAssertEqual(exported.media.map(\.lastPathComponent), ["录屏_1.mp4"]) + } + + func testMergedChatsKeepSameNamedMediaApart() throws { + let media = root.appendingPathComponent("media", isDirectory: true) + let jobs = [ + FilesExport.Job(batch: try fixtures.batch("group-a.zip"), name: "聊天"), + FilesExport.Job(batch: try fixtures.batch("group-a-later.zip"), name: "聊天"), + ] + let staged = try FilesExport.stage(jobs, into: root, mediaRoot: media) + XCTAssertEqual(staged.names, ["聊天", "聊天 (2)"]) + XCTAssertEqual(staged.media.map { $0.map(\.lastPathComponent).sorted() }, [["录屏_1.mp4", "微信图片_20261020_1.png"].sorted(), ["微信图片_20261020_1.png"]]) + } + + func testMediaPhotosDidNotTakeGoIntoTheFolder() throws { + let media = root.appendingPathComponent("media", isDirectory: true) + let exported = try FilesExport.export(try fixtures.batch("group-a.zip"), name: "聊天", into: root, mediaInto: media) + try FilesExport.keep(exported.media, in: "聊天", root: root) + let names = try FileManager.default.contentsOfDirectory(atPath: root.appendingPathComponent("聊天").path).sorted() + XCTAssertEqual(names, ["录屏_1.mp4", "微信图片_20261020_1.png", "需求文档.pdf"].sorted()) + } + + func testFailedExportKeepsTheOldFolder() throws { + let batch = try fixtures.batch("group-a.zip") + let folder = try XCTUnwrap(FilesExport.export(batch, name: "聊天", into: root).folder) + try FileManager.default.removeItem(at: batch.items[0].url) + XCTAssertThrowsError(try FilesExport.export(batch, name: "聊天", into: root)) + XCTAssertTrue(FileManager.default.fileExists(atPath: folder.appendingPathComponent("需求文档.pdf").path)) + } + + func testSideNoteSaysWhereEachGoes() { + XCTAssertEqual( + DeliverySheet.sideNote(["a.png", "b.mp4", "c.docx"]), + "发送时图片和视频存到「照片」:a.png、b.mp4;附件放到「我的iPhone › 微信流」:c.docx" + ) + } + + func testTextOnlyChatMakesNoFolder() throws { + XCTAssertNil(try FilesExport.export(try fixtures.batch("text-note.zip"), name: "资料", into: root).folder) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: root.path), []) + } + + func testExportingAgainReplacesTheFolder() throws { + let batch = try fixtures.batch("group-a.zip") + let folder = try XCTUnwrap(FilesExport.export(batch, name: "聊天", into: root).folder) + try Data("旧".utf8).write(to: folder.appendingPathComponent("stale.txt")) + _ = try FilesExport.export(batch, name: "聊天", into: root) + XCTAssertFalse(FileManager.default.fileExists(atPath: folder.appendingPathComponent("stale.txt").path)) + } + + func testGuideKeepsTheFolderVisibleBeforeAnyExport() throws { + FilesExport.placeGuide(in: root) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: root.path), ["使用说明.txt"]) + } + + func testFolderNameDropsCharactersFilesRejects() { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = .current + let date = calendar.date(from: DateComponents(year: 2026, month: 10, day: 20, hour: 9, minute: 0))! + XCTAssertEqual(FilesExport.folderName(title: "A/B:C", date: date), "A-B-C 10-20 09.00") + } +} diff --git a/ios/Tests/Fixtures.swift b/ios/Tests/Fixtures.swift new file mode 100644 index 0000000..9d05493 --- /dev/null +++ b/ios/Tests/Fixtures.swift @@ -0,0 +1,47 @@ +import Foundation +import WeChatBridgeCore +import XCTest + +/// Builds `ReadyBatch` values from the committed fixture ZIPs, each in its +/// own temporary batch directory, the way `InboxReader` would hand them out. +final class FixtureBatches { + let root: URL + + init() throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent("FixtureBatches-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + + deinit { + try? FileManager.default.removeItem(at: root) + } + + static func url(_ name: String) throws -> URL { + let bundle = Bundle(for: FixtureBatches.self) + let url = try XCTUnwrap(bundle.resourceURL).appendingPathComponent("Fixtures/\(name)") + guard FileManager.default.fileExists(atPath: url.path) else { + throw CocoaError(.fileNoSuchFile, userInfo: [NSFilePathErrorKey: url.path]) + } + return url + } + + func batch(_ names: String..., chatName: String? = nil) throws -> ReadyBatch { + let id = UUID() + let directory = root.appendingPathComponent(id.uuidString, isDirectory: true) + let files = directory.appendingPathComponent("files", isDirectory: true) + try FileManager.default.createDirectory(at: files, withIntermediateDirectories: true) + let items = try names.map { name -> ReadyItem in + let destination = files.appendingPathComponent(name) + try FileManager.default.copyItem(at: Self.url(name), to: destination) + let size = try FileManager.default.attributesOfItem(atPath: destination.path)[.size] as? Int64 ?? 0 + return ReadyItem( + id: UUID(), batchID: id, displayName: name, url: destination, + byteCount: size, contentType: "public.zip-archive", createdAt: Date(), action: .collect + ) + } + return ReadyBatch( + id: id, directory: directory, createdAt: Date(), action: .collect, + items: items, outcome: nil, chatName: chatName, isFirstSeen: false + ) + } +} diff --git a/ios/Tests/Fixtures/files-only.zip b/ios/Tests/Fixtures/files-only.zip new file mode 100644 index 0000000..41fa009 Binary files /dev/null and b/ios/Tests/Fixtures/files-only.zip differ diff --git a/ios/Tests/Fixtures/group-a-later.zip b/ios/Tests/Fixtures/group-a-later.zip new file mode 100644 index 0000000..4fd730e Binary files /dev/null and b/ios/Tests/Fixtures/group-a-later.zip differ diff --git a/ios/Tests/Fixtures/group-a.zip b/ios/Tests/Fixtures/group-a.zip new file mode 100644 index 0000000..2fc1e6c Binary files /dev/null and b/ios/Tests/Fixtures/group-a.zip differ diff --git a/ios/Tests/Fixtures/interleave.zip b/ios/Tests/Fixtures/interleave.zip new file mode 100644 index 0000000..14f99a9 Binary files /dev/null and b/ios/Tests/Fixtures/interleave.zip differ diff --git a/ios/Tests/Fixtures/not-wechat.zip b/ios/Tests/Fixtures/not-wechat.zip new file mode 100644 index 0000000..8e1fbfe Binary files /dev/null and b/ios/Tests/Fixtures/not-wechat.zip differ diff --git a/ios/Tests/Fixtures/text-note.zip b/ios/Tests/Fixtures/text-note.zip new file mode 100644 index 0000000..40f6976 Binary files /dev/null and b/ios/Tests/Fixtures/text-note.zip differ diff --git a/ios/Tests/MessageTokenTests.swift b/ios/Tests/MessageTokenTests.swift new file mode 100644 index 0000000..212ada0 --- /dev/null +++ b/ios/Tests/MessageTokenTests.swift @@ -0,0 +1,39 @@ +import XCTest +@testable import WeChatBridgeiOS + +final class MessageTokenTests: XCTestCase { + func testPlainTextStaysOneToken() { + XCTAssertEqual(MessageToken.tokenize("第一行\n第二行"), [.text("第一行\n第二行")]) + } + + func testMediaPlaceholders() { + XCTAssertEqual(MessageToken.tokenize("[图片] 微信图片_1.jpg"), [.image(name: "微信图片_1.jpg")]) + XCTAssertEqual(MessageToken.tokenize("[视频] 录屏 1.mp4"), [.video(name: "录屏 1.mp4")]) + XCTAssertEqual(MessageToken.tokenize("[文件] 需求文档.pdf"), [.file(name: "需求文档.pdf")]) + } + + func testLinkTakesLastURLAndTitleWithSpaces() { + let url = URL(string: "https://mp.weixin.qq.com/s/abc123")! + XCTAssertEqual(MessageToken.tokenize("[链接] 发布 清单 模板 https://mp.weixin.qq.com/s/abc123"), [.link(title: "发布 清单 模板", url: url)]) + } + + func testChannels() { + let url = URL(string: "https://weixin.qq.com/sph/xyz789")! + XCTAssertEqual(MessageToken.tokenize("[视频号] 产品演示 https://weixin.qq.com/sph/xyz789"), [.channels(title: "产品演示", url: url)]) + } + + func testLinkWithoutURLStaysText() { + XCTAssertEqual(MessageToken.tokenize("[链接] 没有地址"), [.text("[链接] 没有地址")]) + } + + func testUnknownBracketsAndEmojiStayText() { + XCTAssertEqual(MessageToken.tokenize("[破涕为笑]"), [.text("[破涕为笑]")]) + XCTAssertEqual(MessageToken.tokenize("[语音] 3秒"), [.text("[语音] 3秒")]) + XCTAssertEqual(MessageToken.tokenize("[图片]"), [.text("[图片]")]) + } + + func testMixedLinesKeepOrder() { + let tokens = MessageToken.tokenize("看这个\n[图片] a.png\n再说") + XCTAssertEqual(tokens, [.text("看这个"), .image(name: "a.png"), .text("再说")]) + } +} diff --git a/ios/Tests/QuickDeliverTests.swift b/ios/Tests/QuickDeliverTests.swift new file mode 100644 index 0000000..c1d90f3 --- /dev/null +++ b/ios/Tests/QuickDeliverTests.swift @@ -0,0 +1,42 @@ +import XCTest +@testable import WeChatBridgeiOS + +final class QuickDeliverTests: XCTestCase { + private func makeDefaults() -> UserDefaults { + let name = "QuickDeliverTests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: name)! + addTeardownBlock { defaults.removePersistentDomain(forName: name) } + return defaults + } + + func testOnByDefaultAndKeepsThreeTargets() { + let defaults = makeDefaults() + XCTAssertTrue(QuickDeliver.isEnabled(defaults)) + QuickDeliver.store((1...5).map { QuickDeliver.Target(id: "t\($0)", name: "目标\($0)") }, in: defaults) + XCTAssertEqual(QuickDeliver.targets(defaults).map(\.id), ["t1", "t2", "t3"]) + } + + func testContentPointsAtTheFirstTarget() { + let id = UUID() + let content = QuickDeliver.content(batchID: id, head: "group-a.zip", targets: [.init(id: "doubao", name: "豆包"), .init(id: "chatgpt", name: "ChatGPT")]) + XCTAssertEqual(content.body, "group-a.zip · 点一下投递到「豆包」,长按换目标") + XCTAssertEqual(content.userInfo[QuickDeliver.batchKey] as? String, id.uuidString) + XCTAssertEqual(content.userInfo[QuickDeliver.targetKey] as? String, "doubao") + let category = QuickDeliver.makeCategory(targets: [.init(id: "doubao", name: "豆包"), .init(id: "chatgpt", name: "ChatGPT")]) + XCTAssertEqual(category.actions.map(\.identifier), ["deliver.doubao", "deliver.chatgpt"]) + } + + func testWithoutTargetsTheTapOpensThePanel() { + let content = QuickDeliver.content(batchID: UUID(), head: "2 个文件", targets: []) + XCTAssertEqual(content.body, "2 个文件 · 点一下去投递") + XCTAssertEqual(content.userInfo[QuickDeliver.targetKey] as? String, "") + } + + @MainActor + func testPreferencesPublishTheArrangedTargets() { + let defaults = makeDefaults() + let preferences = Preferences(defaults: defaults) + preferences.lastTarget = "qwen" + XCTAssertEqual(QuickDeliver.targets(defaults).map(\.id), ["qwen", "chatgpt", "doubao"]) + } +} diff --git a/ios/Tests/RelaySummaryTests.swift b/ios/Tests/RelaySummaryTests.swift new file mode 100644 index 0000000..e10dbee --- /dev/null +++ b/ios/Tests/RelaySummaryTests.swift @@ -0,0 +1,111 @@ +import WeChatBridgeCore +import XCTest +@testable import WeChatBridgeiOS + +final class RelaySummaryTests: XCTestCase { + private var fixtures: FixtureBatches! + + override func setUpWithError() throws { + fixtures = try FixtureBatches() + } + + override func tearDown() { + fixtures = nil + } + + func testGroupSummary() throws { + let batch = try fixtures.batch("group-a.zip") + defer { RelayFiles.remove(batchID: batch.id) } + let summary = RelaySummary.make(for: batch) + XCTAssertFalse(summary.parseFailed) + XCTAssertEqual(summary.messageCount, 8) + XCTAssertEqual(summary.senders, ["甲", "乙", "丙"]) + XCTAssertEqual(summary.mediaCount, 3) + XCTAssertEqual(summary.preview.count, 2) + XCTAssertEqual(summary.preview[0], "甲:早上好,今天讨论发布计划") + XCTAssertNotNil(summary.start) + XCTAssertEqual(summary.end!.timeIntervalSince(summary.start!), 7 * 60) + XCTAssertEqual(summary.archiveItemID, batch.items[0].id) + // The last message is a sticker; search needs the last typed words. + XCTAssertEqual(summary.anchor, "第一行") + XCTAssertEqual(summary.last?.sender, "甲") + XCTAssertFalse(summary.hitsForwardLimit) + } + + func testZipWithoutTextIsParseFailed() throws { + let batch = try fixtures.batch("files-only.zip") + defer { RelayFiles.remove(batchID: batch.id) } + let summary = RelaySummary.make(for: batch) + XCTAssertEqual(summary.kind, .files) + XCTAssertTrue(summary.parseFailed) + XCTAssertNil(summary.messageCount) + XCTAssertEqual(summary.title, "files-only.zip") + XCTAssertEqual(RelayCardView.counts(summary), "1 个附件") + } + + /// A single exported message: `·` heading, then lines, but no timestamps. + func testTextInAnotherLayoutIsReadAsText() throws { + let batch = try fixtures.batch("text-note.zip") + defer { RelayFiles.remove(batchID: batch.id) } + let summary = RelaySummary.make(for: batch) + XCTAssertEqual(summary.kind, .text) + XCTAssertFalse(summary.parseFailed) + XCTAssertEqual(summary.title, "示例收藏 - 资料合集 第一期 10月23日更新") + XCTAssertEqual(summary.preview, ["公开课讲义合集", "https://example.com/s/a1"]) + XCTAssertNil(summary.messageCount) + XCTAssertEqual(summary.mediaCount, 0) + XCTAssertEqual(RelayCardView.counts(summary), "文本") + + guard case .success(let loaded) = LoadedTranscript.load(batch) else { return XCTFail("text did not load") } + XCTAssertTrue(loaded.records.isEmpty) + XCTAssertEqual(loaded.text?.hasPrefix("·示例收藏"), true) + } + + func testChatExportWinsOverPlainText() throws { + let batch = try fixtures.batch("text-note.zip", "group-a.zip") + defer { RelayFiles.remove(batchID: batch.id) } + let summary = RelaySummary.make(for: batch) + XCTAssertEqual(summary.kind, .chat) + XCTAssertEqual(summary.archiveItemID, batch.items[1].id) + XCTAssertEqual(RelayCardView.counts(summary), "8 条消息 · 4 个附件") + } + + func testPlainTextLinksAreLive() { + let text = PlainTextView.linked("工具清单\nhttps://example.com/s/c3") + XCTAssertEqual(text.runs.compactMap(\.link), [URL(string: "https://example.com/s/c3")!]) + } + + func testCacheRoundTrip() throws { + let batch = try fixtures.batch("interleave.zip") + defer { RelayFiles.remove(batchID: batch.id) } + let summary = RelaySummary.make(for: batch) + summary.store(in: batch.directory) + XCTAssertEqual(RelaySummary.cached(in: batch.directory), summary) + } + + func testExtractionIsReused() throws { + let batch = try fixtures.batch("group-a.zip") + defer { RelayFiles.remove(batchID: batch.id) } + let data = try Data(contentsOf: batch.items[0].url) + let first = try RelayFiles.extract(data, batchID: batch.id) + let second = try RelayFiles.extract(data, batchID: batch.id) + XCTAssertEqual(first.names, second.names) + XCTAssertTrue(FileManager.default.fileExists(atPath: first.directory.appendingPathComponent("聊天记录.txt").path)) + } + + func testRangeFormatting() { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = .current + let start = calendar.date(from: DateComponents(year: 2026, month: 10, day: 20, hour: 9, minute: 0))! + XCTAssertEqual(RelayFormat.range(start, start.addingTimeInterval(420), calendar: calendar), "10月20日 09:00–09:07") + XCTAssertEqual(RelayFormat.range(start, start.addingTimeInterval(86_400), calendar: calendar), "10月20日 09:00–10月21日 09:00") + XCTAssertNil(RelayFormat.range(nil, nil)) + } + + func testTextCardShowsOneLinkAsItsDomain() { + let summary = RelaySummary.make(text: "合集\n讲义\nhttps://example.com/s/a1", archiveName: "a.txt", mediaCount: 0, archiveItemID: nil) + XCTAssertEqual(RelayCardView.previewLines(summary), ["讲义", "🔗 example.com"]) + let twoLinks = RelaySummary.make(text: "合集\nhttps://example.com/1\nhttps://example.org/2", archiveName: "a.txt", mediaCount: 0, archiveItemID: nil) + XCTAssertEqual(RelayCardView.previewLines(twoLinks), ["🔗 example.com"]) + } +} diff --git a/ios/Tests/TargetProfileTests.swift b/ios/Tests/TargetProfileTests.swift new file mode 100644 index 0000000..4f6ed9c --- /dev/null +++ b/ios/Tests/TargetProfileTests.swift @@ -0,0 +1,54 @@ +import XCTest +@testable import WeChatBridgeiOS + +final class TargetProfileTests: XCTestCase { + func testBuiltInTable() { + let formats = Dictionary(uniqueKeysWithValues: TargetProfile.builtIn.map { ($0.id, $0.format) }) + XCTAssertEqual(TargetProfile.builtIn.map(\.id), ["chatgpt", "doubao", "qwen", "workbuddy", "claude", "deepseek", "obsidian", "folder", "other"]) + XCTAssertEqual(formats["chatgpt"], .archive) + XCTAssertEqual(formats["doubao"], .transcriptAndImages) + XCTAssertEqual(formats["qwen"], .transcriptAndImages) + XCTAssertEqual(formats["workbuddy"], .archive) + XCTAssertEqual(formats["obsidian"], .knowledgeNote) + XCTAssertEqual(formats["folder"], .folder) + XCTAssertEqual(formats["other"], .archive) + } + + func testLogoForTargetsTheProjectShipsArtFor() { + XCTAssertEqual(TargetProfile.builtIn.compactMap(\.logo), ["Logo-chatgpt", "Logo-doubao", "Logo-qwen", "Logo-workbuddy", "Logo-claude", "Logo-obsidian"]) + } + + func testHint() { + XCTAssertEqual(TargetProfile.builtIn[1].hint, "请在下一屏选择「豆包」") + XCTAssertEqual(TargetProfile.builtIn.first { $0.id == "obsidian" }?.hint, "") + } + + func testPasteHintOnlyForTextDroppersWithPrompt() throws { + let doubao = try XCTUnwrap(TargetProfile.builtIn.first { $0.id == "doubao" }) + XCTAssertEqual(doubao.sendHint(hasPrompt: true), "请在下一屏选择「豆包」\n提示词已复制,在输入框长按粘贴") + XCTAssertEqual(doubao.sendHint(hasPrompt: false), "请在下一屏选择「豆包」") + let chatgpt = try XCTUnwrap(TargetProfile.builtIn.first { $0.id == "chatgpt" }) + XCTAssertEqual(chatgpt.sendHint(hasPrompt: true), chatgpt.hint) + } + + func testArrangedAppliesOrderHiddenOverridesAndLastUsed() { + let arranged = TargetProfile.arranged( + TargetProfile.builtIn, + order: ["qwen", "chatgpt"], + hidden: ["deepseek", "other"], + overrides: ["chatgpt": "transcriptAndImages", "obsidian": "archive", "qwen": "bogus"], + lastUsed: "folder" + ) + XCTAssertEqual(arranged.map(\.id), ["folder", "qwen", "chatgpt", "doubao", "workbuddy", "claude", "obsidian"]) + XCTAssertEqual(arranged.first { $0.id == "chatgpt" }?.format, .transcriptAndImages) + // Writers keep their format; unknown values are ignored. + XCTAssertEqual(arranged.first { $0.id == "obsidian" }?.format, .knowledgeNote) + XCTAssertEqual(arranged.first { $0.id == "qwen" }?.format, .transcriptAndImages) + } + + func testUnknownIDsInOrderAreSkipped() { + let arranged = TargetProfile.arranged(TargetProfile.builtIn, order: ["gone", "other"], hidden: [], overrides: [:], lastUsed: "gone") + XCTAssertEqual(arranged.first?.id, "other") + XCTAssertEqual(arranged.count, TargetProfile.builtIn.count) + } +} diff --git a/ios/Tests/TranscriptMergeTests.swift b/ios/Tests/TranscriptMergeTests.swift new file mode 100644 index 0000000..93630fe --- /dev/null +++ b/ios/Tests/TranscriptMergeTests.swift @@ -0,0 +1,41 @@ +import WeChatBridgeCore +import XCTest +@testable import WeChatBridgeiOS + +final class TranscriptMergeTests: XCTestCase { + private let shanghai = TimeZone(identifier: "Asia/Shanghai")! + + private func body(_ fixture: String) throws -> String { + let data = try Data(contentsOf: FixtureBatches.url(fixture)) + return try XCTUnwrap(WeChatNativeArchive.transcript(data)).body + } + + func testRenderRoundTrips() throws { + let records = try WeChatTranscriptRecord.parse(body("group-a.zip"), timeZone: shanghai) + XCTAssertEqual(records.count, 8) + let rendered = TranscriptMerge.render(records, timeZone: shanghai) + XCTAssertEqual(try WeChatTranscriptRecord.parse(rendered, timeZone: shanghai), records) + } + + func testRenderMatchesWeChatLayout() throws { + let records = try WeChatTranscriptRecord.parse("·甲\n2026年10月20日 09:00\n你好\n\n·乙\n2026年10月20日 09:01\n好\n", timeZone: shanghai) + XCTAssertEqual(TranscriptMerge.render(records, timeZone: shanghai), "·甲\n2026年10月20日 09:00\n你好\n\n·乙\n2026年10月20日 09:01\n好\n") + } + + func testInterleavedMergeIsTimeOrderedAndStable() throws { + let merged = try TranscriptMerge.mergedRecords([body("group-a.zip"), body("interleave.zip")], timeZone: shanghai) + XCTAssertEqual(merged.count, 10) + XCTAssertEqual(merged.map(\.date), merged.map(\.date).sorted()) + // Same minute: the first export's message stays first. + XCTAssertEqual(merged[0].sender, "甲") + XCTAssertEqual(merged[1].text, "插在第一条之后") + XCTAssertEqual(merged[4].sender, "甲") + XCTAssertEqual(merged[5].text, "插在中间") + } + + func testDuplicateExportMergesToSameCount() throws { + let once = try body("group-a.zip") + let merged = try TranscriptMerge.mergedRecords([once, once], timeZone: shanghai) + XCTAssertEqual(merged, try WeChatTranscriptRecord.parse(once, timeZone: shanghai)) + } +} diff --git a/ios/Widget/DeliveryLiveActivity.swift b/ios/Widget/DeliveryLiveActivity.swift new file mode 100644 index 0000000..45cc698 --- /dev/null +++ b/ios/Widget/DeliveryLiveActivity.swift @@ -0,0 +1,147 @@ +import ActivityKit +import AppIntents +import SwiftUI +import WidgetKit + +@main +struct WeChatBridgeWidgets: WidgetBundle { + var body: some Widget { + DeliveryLiveActivity() + } +} + +struct DeliveryLiveActivity: Widget { + var body: some WidgetConfiguration { + ActivityConfiguration(for: DeliveryActivityAttributes.self) { context in + LockScreenView(context: context) + .activityBackgroundTint(Color(.systemBackground).opacity(0.85)) + .widgetURL(context.attributes.detailURL) + } dynamicIsland: { context in + DynamicIsland { + DynamicIslandExpandedRegion(.leading) { + AppGlyph(size: 40).padding(.leading, 4) + } + DynamicIslandExpandedRegion(.trailing) { + TargetGlyph(attributes: context.attributes, size: 40).padding(.trailing, 4) + } + DynamicIslandExpandedRegion(.center) { + VStack(spacing: 2) { + Text(context.attributes.title).font(.headline).lineLimit(1) + Text("投递到「\(context.attributes.targetName)」· \(context.state.status)") + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + DynamicIslandExpandedRegion(.bottom) { + ActionRow(context: context).padding(.top, 6) + } + } compactLeading: { + AppGlyph(size: 22) + } compactTrailing: { + TargetGlyph(attributes: context.attributes, size: 22) + } minimal: { + AppGlyph(size: 22) + } + .widgetURL(context.attributes.detailURL) + .keylineTint(Color("AccentColor")) + } + } +} + +private struct LockScreenView: View { + let context: ActivityViewContext + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 12) { + AppGlyph(size: 44) + VStack(alignment: .leading, spacing: 2) { + Text(context.attributes.title).font(.headline).lineLimit(1) + Text(context.attributes.detail.isEmpty ? context.state.status : "\(context.attributes.detail) · \(context.state.status)") + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer(minLength: 0) + TargetGlyph(attributes: context.attributes, size: 36) + } + ActionRow(context: context) + } + .padding(16) + } +} + +private struct ActionRow: View { + let context: ActivityViewContext + + var body: some View { + HStack(spacing: 8) { + Link(destination: context.attributes.detailURL) { + Label("回到微信流", systemImage: "arrow.uturn.backward") + .frame(maxWidth: .infinity) + } + .buttonStyle(ActionStyle(prominent: true)) + if context.state.hasPrompt { + Button(intent: CopyDeliveryPromptIntent()) { + Label("复制提示词", systemImage: "doc.on.doc") + .frame(maxWidth: .infinity) + } + .buttonStyle(ActionStyle(prominent: false)) + } + Button(intent: EndDeliveryActivityIntent()) { + Image(systemName: "xmark") + } + .buttonStyle(ActionStyle(prominent: false)) + .accessibilityLabel("结束") + } + .font(.footnote.weight(.semibold)) + .labelStyle(.titleAndIcon) + } +} + +private struct ActionStyle: ButtonStyle { + let prominent: Bool + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .padding(.vertical, 9) + .padding(.horizontal, 12) + .foregroundStyle(prominent ? Color.white : Color.primary) + .background(prominent ? Color("AccentColor") : Color.secondary.opacity(0.25), in: Capsule()) + .opacity(configuration.isPressed ? 0.7 : 1) + } +} + +private struct AppGlyph: View { + let size: CGFloat + + var body: some View { + Image("AppGlyph") + .resizable() + .scaledToFit() + .frame(width: size, height: size) + .clipShape(RoundedRectangle(cornerRadius: size * 0.225, style: .continuous)) + } +} + +private struct TargetGlyph: View { + let attributes: DeliveryActivityAttributes + let size: CGFloat + + var body: some View { + Group { + if let logo = attributes.targetLogo { + Image(logo).resizable().scaledToFit() + } else { + Image(systemName: "square.and.arrow.up") + .font(.system(size: size * 0.5, weight: .semibold)) + .foregroundStyle(Color("AccentColor")) + .frame(width: size, height: size) + .background(Color("AccentColor").opacity(0.18)) + } + } + .frame(width: size, height: size) + .clipShape(RoundedRectangle(cornerRadius: size * 0.225, style: .continuous)) + } +} diff --git a/ios/project.yml b/ios/project.yml new file mode 100644 index 0000000..bc9c917 --- /dev/null +++ b/ios/project.yml @@ -0,0 +1,137 @@ +# Generated project: run `xcodegen generate` in this folder. The .xcodeproj is +# not committed, so two branches never conflict over pbxproj. +name: WeChatBridge +options: + bundleIdPrefix: com.xiangming + deploymentTarget: + iOS: "17.0" + createIntermediateGroups: true +# The app and its extensions must carry the same version; TestFlight needs a +# higher CURRENT_PROJECT_VERSION on every upload. +settings: + base: + MARKETING_VERSION: "0.1.0" + CURRENT_PROJECT_VERSION: "1" +configFiles: + Debug: Config/Signing.xcconfig + Release: Config/Signing.xcconfig +packages: + WeChatBridgeKit: + path: ../macos +targets: + WeChatBridgeiOS: + type: application + platform: iOS + sources: + - App + - Shared + - LiveActivity + - Resources + - path: Config/PrivacyInfo.xcprivacy + buildPhase: resources + dependencies: + - package: WeChatBridgeKit + product: WeChatBridgeCore + - target: WeChatBridgeiOSShare + - target: WeChatBridgeiOSCollect + - target: WeChatBridgeiOSWidget + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: $(APP_BUNDLE_ID) + INFOPLIST_FILE: Config/App-Info.plist + CODE_SIGN_ENTITLEMENTS: Config/App.entitlements + SWIFT_VERSION: "5.0" + TARGETED_DEVICE_FAMILY: "1" + ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME: AccentColor + WeChatBridgeiOSShare: + type: app-extension + platform: iOS + sources: + - ShareExtension + - Shared + - path: Config/PrivacyInfo.xcprivacy + buildPhase: resources + dependencies: + - package: WeChatBridgeKit + product: WeChatBridgeCore + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: $(APP_BUNDLE_ID).share + INFOPLIST_FILE: Config/Share-Info.plist + CODE_SIGN_ENTITLEMENTS: Config/Share.entitlements + SWIFT_VERSION: "5.0" + TARGETED_DEVICE_FAMILY: "1" + APPLICATION_EXTENSION_API_ONLY: YES + # 「分批收集到微信流」 in the share sheet's action list: the same import, + # each batch added to the open collection (see Shared/CollectMarker.swift). + WeChatBridgeiOSCollect: + type: app-extension + platform: iOS + sources: + - ShareExtension + - Shared + # The action list draws this icon as a template: a transparent glyph. + - CollectExtension + - path: Config/PrivacyInfo.xcprivacy + buildPhase: resources + dependencies: + - package: WeChatBridgeKit + product: WeChatBridgeCore + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: $(APP_BUNDLE_ID).collect + ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon + INFOPLIST_FILE: Config/Collect-Info.plist + CODE_SIGN_ENTITLEMENTS: Config/Share.entitlements + SWIFT_VERSION: "5.0" + TARGETED_DEVICE_FAMILY: "1" + APPLICATION_EXTENSION_API_ONLY: YES + WeChatBridgeiOSWidget: + type: app-extension + platform: iOS + sources: + - Widget + - LiveActivity + # Shared with the app for the target logos, the app glyph and the accent. + - path: Resources/Assets.xcassets + # The Live Activity code it compiles reads UserDefaults. + - path: Config/PrivacyInfo.xcprivacy + buildPhase: resources + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: $(APP_BUNDLE_ID).widget + INFOPLIST_FILE: Config/Widget-Info.plist + SWIFT_VERSION: "5.0" + TARGETED_DEVICE_FAMILY: "1" + APPLICATION_EXTENSION_API_ONLY: YES + WeChatBridgeiOSTests: + type: bundle.unit-test + platform: iOS + sources: + - path: Tests + excludes: + - "Fixtures/**" + - path: Tests/Fixtures + type: folder + buildPhase: resources + dependencies: + - target: WeChatBridgeiOS + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: $(APP_BUNDLE_ID).tests + GENERATE_INFOPLIST_FILE: YES + SWIFT_VERSION: "5.0" + TEST_HOST: "$(BUILT_PRODUCTS_DIR)/WeChatBridgeiOS.app/WeChatBridgeiOS" + BUNDLE_LOADER: "$(TEST_HOST)" +schemes: + WeChatBridgeiOS: + build: + targets: + WeChatBridgeiOS: all + WeChatBridgeiOSShare: all + WeChatBridgeiOSCollect: all + WeChatBridgeiOSWidget: all + test: + targets: + - WeChatBridgeiOSTests diff --git a/macos/Package.swift b/macos/Package.swift index e7651c8..2aded52 100644 --- a/macos/Package.swift +++ b/macos/Package.swift @@ -7,7 +7,7 @@ import PackageDescription // `Scripts/make-app.sh` assembles and signs the bundle around them. let package = Package( name: "WeChatBridge", - platforms: [.macOS(.v14)], + platforms: [.macOS(.v14), .iOS(.v17)], products: [ .executable(name: "WeChatBridge", targets: ["WeChatBridgeApp"]), .executable(name: "WeChatBridgeShare", targets: ["WeChatBridgeShare"]), diff --git a/macos/Resources/Localizations/en.lproj/Localizable.strings b/macos/Resources/Localizations/en.lproj/Localizable.strings index 02b1b15..48e20b4 100644 --- a/macos/Resources/Localizations/en.lproj/Localizable.strings +++ b/macos/Resources/Localizations/en.lproj/Localizable.strings @@ -226,6 +226,22 @@ /* Software updates — About pane and status menu */ "检查更新…" = "Check for Updates…"; +"软件更新" = "Software Update"; +"自动检查并安装新版本。" = "Checks for and installs new versions automatically."; +"从蓝奏云分享页检查新版本。" = "Checks the Lanzou share folder for new builds."; +"尚未检查更新。" = "No update check has run yet."; +"正在检查更新…" = "Checking for updates…"; +"已是最新版本 %@ (%@)。" = "%@ (%@) is up to date."; +"发现新版本 %@ (%@),大小 %@。" = "New version %@ (%@) is available — %@."; +"检查更新失败:%@" = "Update check failed: %@"; +"前往下载" = "Download"; +"网盘密码:%@" = "Share password: %@"; +"下载新版本 %@…" = "Download %@…"; +"蓝奏云返回 HTTP %d" = "Lanzou returned HTTP %d"; +"无法解析蓝奏云分享页" = "Could not parse the Lanzou share page"; +"蓝奏云拒绝了文件列表请求" = "The Lanzou share rejected the listing request"; +"蓝奏云:%@" = "Lanzou: %@"; +"分享文件夹里没有可识别的安装包" = "No installer found in the share folder"; /* Software updates — General pane */ "自动检查更新" = "Check for updates automatically"; diff --git a/macos/Resources/Localizations/zh-Hans.lproj/Localizable.strings b/macos/Resources/Localizations/zh-Hans.lproj/Localizable.strings index c05c775..9399d8d 100644 --- a/macos/Resources/Localizations/zh-Hans.lproj/Localizable.strings +++ b/macos/Resources/Localizations/zh-Hans.lproj/Localizable.strings @@ -226,6 +226,22 @@ /* 软件更新 — 关于页与状态菜单 */ "检查更新…" = "检查更新…"; +"软件更新" = "软件更新"; +"自动检查并安装新版本。" = "自动检查并安装新版本。"; +"从蓝奏云分享页检查新版本。" = "从蓝奏云分享页检查新版本。"; +"尚未检查更新。" = "尚未检查更新。"; +"正在检查更新…" = "正在检查更新…"; +"已是最新版本 %@ (%@)。" = "已是最新版本 %@ (%@)。"; +"发现新版本 %@ (%@),大小 %@。" = "发现新版本 %@ (%@),大小 %@。"; +"检查更新失败:%@" = "检查更新失败:%@"; +"前往下载" = "前往下载"; +"网盘密码:%@" = "网盘密码:%@"; +"下载新版本 %@…" = "下载新版本 %@…"; +"蓝奏云返回 HTTP %d" = "蓝奏云返回 HTTP %d"; +"无法解析蓝奏云分享页" = "无法解析蓝奏云分享页"; +"蓝奏云拒绝了文件列表请求" = "蓝奏云拒绝了文件列表请求"; +"蓝奏云:%@" = "蓝奏云:%@"; +"分享文件夹里没有可识别的安装包" = "分享文件夹里没有可识别的安装包"; /* 软件更新 — 通用页 */ diff --git a/macos/Sources/WeChatBridgeApp/App.swift b/macos/Sources/WeChatBridgeApp/App.swift index be45958..baae5e5 100644 --- a/macos/Sources/WeChatBridgeApp/App.swift +++ b/macos/Sources/WeChatBridgeApp/App.swift @@ -217,6 +217,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { model: model, updater: updater, openSettings: { [weak self] tab in self?.openMainWindow(tab) } ) + updater.showUpdatePane = { [weak self] in self?.openMainWindow(.about) } + updater.checkForUpdatesInBackgroundIfDue() model.start() model.reload() if let tab = pendingSettingsTab { diff --git a/macos/Sources/WeChatBridgeApp/AppUpdater.swift b/macos/Sources/WeChatBridgeApp/AppUpdater.swift index c28c6bb..b02ed49 100644 --- a/macos/Sources/WeChatBridgeApp/AppUpdater.swift +++ b/macos/Sources/WeChatBridgeApp/AppUpdater.swift @@ -2,16 +2,23 @@ import Combine import Foundation import Sparkle -/// Owns Sparkle for the status menu and the 关于 pane. +/// Owns update checking for the status menu and the 关于 pane. /// -/// `swift run WeChatBridge` has no assembled Info.plist and therefore no `SUFeedURL`, -/// so starting Sparkle there would only produce an updater error during -/// development. The release bundle carries the feed and starts normally. +/// Two channels share this front. A distribution build carries `SUFeedURL` +/// and Sparkle runs — its own scheduler, its own UI. A build without a feed +/// falls back to `LanzouUpdateChecker`, the 蓝奏云 share folder the project +/// actually ships through today; its results surface in the 关于 pane, which +/// `checkForUpdates()` opens on the way. +/// +/// `swift run WeChatBridge` has no assembled Info.plist and therefore no +/// `SUFeedURL` either, so the 蓝奏云 fallback is what a development build +/// exercises. /// /// Automatic checks are switched on in Info.plist rather than asked for: the -/// share extension starts this app in the background over WeChat, and -/// Sparkle's permission prompt would otherwise be the first window a new user -/// ever saw from WeChatBridge. +/// share extension starts this app in the background over WeChat, and a +/// permission prompt would otherwise be the first window a new user ever saw +/// from WeChatBridge. The fallback keeps that contract — its daily check is +/// silent too. @MainActor final class AppUpdater: ObservableObject { @Published private(set) var canCheckForUpdates = false @@ -19,36 +26,80 @@ final class AppUpdater: ObservableObject { private let controller: SPUStandardUpdaterController private let isConfigured: Bool private var canCheckObserver: AnyCancellable? + private var stateObserver: AnyCancellable? + + /// The 蓝奏云 folder check. Always present; only consulted when this build + /// carries no Sparkle feed. + let lanzou: LanzouUpdateChecker + + /// Where a manual fallback check shows its progress and result: the 关于 + /// pane. The app delegate points this at `openMainWindow(.about)`. + var showUpdatePane: (() -> Void)? + + private let defaults: UserDefaults + static let automaticCheckKey = "UpdateCheckAutomatically" + static let lastAutomaticCheckKey = "UpdateLastCheckAt" - init(bundle: Bundle = .main) { + init( + bundle: Bundle = .main, + defaults: UserDefaults = .standard, + lanzou: LanzouUpdateChecker? = nil + ) { + self.defaults = defaults + self.lanzou = lanzou ?? LanzouUpdateChecker() isConfigured = bundle.object(forInfoDictionaryKey: "SUFeedURL") != nil controller = SPUStandardUpdaterController( startingUpdater: isConfigured, updaterDelegate: nil, userDriverDelegate: nil ) + defaults.register(defaults: [Self.automaticCheckKey: true]) - guard isConfigured else { return } - canCheckForUpdates = controller.updater.canCheckForUpdates - canCheckObserver = controller.updater - .publisher(for: \.canCheckForUpdates) - .receive(on: RunLoop.main) - .removeDuplicates() - .sink { [weak self] canCheck in - self?.canCheckForUpdates = canCheck - } + if isConfigured { + canCheckForUpdates = controller.updater.canCheckForUpdates + canCheckObserver = controller.updater + .publisher(for: \.canCheckForUpdates) + .receive(on: RunLoop.main) + .removeDuplicates() + .sink { [weak self] canCheck in + self?.canCheckForUpdates = canCheck + } + } else { + canCheckForUpdates = true + stateObserver = self.lanzou.$state + .receive(on: RunLoop.main) + .sink { [weak self] state in + self?.canCheckForUpdates = state != .checking + self?.objectWillChange.send() + } + } + } + + /// Sparkle shows its own dialogs; the fallback's status lives in the 关于 + /// pane, which reads this. + var usesSparkleFeed: Bool { isConfigured } + var updateState: LanzouUpdateChecker.State { lanzou.state } + var availableUpdate: LanzouUpdateChecker.Release? { + isConfigured ? nil : lanzou.availableUpdate } /// The daily check, as the 通用 pane's switch. Reads false and ignores /// writes in an unconfigured build, which is the honest state of a - /// `swift run` binary with no feed to check. + /// `swift run` binary with no feed to check. The fallback persists the + /// same switch for its own once-a-day pass. var automaticallyChecksForUpdates: Bool { get { - guard isConfigured else { return false } + guard isConfigured else { + return defaults.bool(forKey: Self.automaticCheckKey) + } return controller.updater.automaticallyChecksForUpdates } set { - guard isConfigured else { return } + guard isConfigured else { + defaults.set(newValue, forKey: Self.automaticCheckKey) + objectWillChange.send() + return + } // Sparkle owns the value; the view only needs to know it moved. objectWillChange.send() controller.updater.automaticallyChecksForUpdates = newValue @@ -56,7 +107,30 @@ final class AppUpdater: ObservableObject { } func checkForUpdates() { - guard isConfigured else { return } + guard isConfigured else { + showUpdatePane?() + Task { await lanzou.check() } + return + } controller.checkForUpdates(nil) } + + /// The 关于 pane asks once per run — an idle state means this launch has + /// not checked yet, while a settled state simply displays again. + func checkForUpdatesIfIdle() { + guard !isConfigured, lanzou.state == .idle else { return } + Task { await lanzou.check() } + } + + /// The once-a-day quiet check, called at launch. Sparkle schedules its own + /// when a feed exists; the 蓝奏云 channel needs this loop instead. A hit + /// stays silent — the status menu's 检查更新 item turns into a download + /// link, but no window appears over WeChat uninvited. + func checkForUpdatesInBackgroundIfDue() { + guard !isConfigured, automaticallyChecksForUpdates, !lanzou.isChecking else { return } + let lastCheck = defaults.object(forKey: Self.lastAutomaticCheckKey) as? Date ?? .distantPast + guard Date().timeIntervalSince(lastCheck) >= 24 * 60 * 60 else { return } + defaults.set(Date(), forKey: Self.lastAutomaticCheckKey) + Task { await lanzou.check() } + } } diff --git a/macos/Sources/WeChatBridgeApp/LanzouUpdateChecker.swift b/macos/Sources/WeChatBridgeApp/LanzouUpdateChecker.swift new file mode 100644 index 0000000..2b3483c --- /dev/null +++ b/macos/Sources/WeChatBridgeApp/LanzouUpdateChecker.swift @@ -0,0 +1,304 @@ +import Foundation +import WeChatBridgeCore + +/// Watches the 蓝奏云 share folder that carries 微信流's downloads and reports +/// when a build newer than the running one appears. +/// +/// This channel exists because the app ships through 蓝奏云 rather than a +/// Sparkle appcast: a password-protected folder page exposes its listing over +/// one AJAX endpoint, so "is there an update" is a page fetch, a form POST +/// carrying the share password, and a filename comparison. What a hit offers +/// is the file's own page URL — 前往下载 opens it in the browser and the +/// install stays the user's drag-to-Applications on the mounted DMG, rather +/// than an in-app download fighting 蓝奏云's anti-leech chain. +@MainActor +final class LanzouUpdateChecker: ObservableObject { + /// The share everyone opens to download 微信流, and its password. The + /// password is public — it rides along in every release announcement — + /// so hardcoding it only saves the user typing it. + nonisolated static let sharePage = URL(string: "https://wwbsr.lanzout.com/b0umjur8h")! + nonisolated static let sharePassword = "向明" + + /// One downloadable file in the share, reduced to what an update decision + /// and a 前往下载 button need. + struct Release: Equatable { + let fileName: String + let version: [Int] + let build: Int + let size: String + /// The file's own 蓝奏云 page — `id` in the listing already carries + /// the `?webpage=` token that opens it without the share password. + let pageURL: URL + + var versionLabel: String { version.map(String.init).joined(separator: ".") } + } + + enum State: Equatable { + case idle + case checking + case upToDate + case updateAvailable(Release) + case failed(String) + } + + enum CheckError: LocalizedError { + case badResponse(Int) + case malformedFolderPage + case shareRejected(String) + case emptyShare + + var errorDescription: String? { + switch self { + case .badResponse(let code): + L10n.format("蓝奏云返回 HTTP %d", code) + case .malformedFolderPage: + L10n.text("无法解析蓝奏云分享页") + case .shareRejected(let info): + info.isEmpty + ? L10n.text("蓝奏云拒绝了文件列表请求") + : L10n.format("蓝奏云:%@", info) + case .emptyShare: + L10n.text("分享文件夹里没有可识别的安装包") + } + } + } + + @Published private(set) var state: State = .idle + + var isChecking: Bool { state == .checking } + var availableUpdate: Release? { + if case .updateAvailable(let release) = state { return release } + return nil + } + + private let folderURL: URL + private let password: String + private let session: URLSession + private let currentVersion: [Int] + private let currentBuild: Int + + init( + folderURL: URL = LanzouUpdateChecker.sharePage, + password: String = LanzouUpdateChecker.sharePassword, + session: URLSession = .shared, + currentVersion: [Int] = AppVersion.components, + currentBuild: Int = AppVersion.buildNumber + ) { + self.folderURL = folderURL + self.password = password + self.session = session + self.currentVersion = currentVersion + self.currentBuild = currentBuild + } + + func check() async { + guard !isChecking else { return } + state = .checking + do { + let html = try await folderPage() + let form = try listingForm(in: html) + let files = try await listing(form: form) + let releases = files.compactMap { Self.release(from: $0, base: folderURL) } + guard let latest = releases.max(by: Self.outranks) else { + throw CheckError.emptyShare + } + if Self.newer(latest.version, latest.build, than: currentVersion, currentBuild) { + state = .updateAvailable(latest) + } else { + state = .upToDate + } + } catch let error as CheckError { + state = .failed(error.localizedDescription) + } catch { + state = .failed(error.localizedDescription) + } + } + + /// Ordering for the listing: higher version wins, then higher build, then + /// a .dmg beats a .zip of the same numbers — the disk image is what the + /// download button should land the user on. + private static func outranks(_ a: Release, _ b: Release) -> Bool { + func rank(_ r: Release) -> [Int] { + r.version + [r.build, r.fileName.hasSuffix(".dmg") ? 1 : 0] + } + return rank(a).lexicographicallyPrecedes(rank(b)) + } + + private static func newer( + _ lhsVersion: [Int], _ lhsBuild: Int, + than rhsVersion: [Int], _ rhsBuild: Int + ) -> Bool { + for index in 0.. rhs } + } + return lhsBuild > rhsBuild + } + + // MARK: - 蓝奏云 wire format + + private static let userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " + + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36" + + private func folderPage() async throws -> String { + var request = URLRequest(url: folderURL, timeoutInterval: 20) + request.setValue(Self.userAgent, forHTTPHeaderField: "User-Agent") + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse, http.statusCode == 200 else { + throw CheckError.badResponse((response as? HTTPURLResponse)?.statusCode ?? -1) + } + guard let html = String(data: data, encoding: .utf8) else { + throw CheckError.malformedFolderPage + } + return html + } + + /// The folder page embeds its listing POST's fields in a jQuery block. + /// Values come in three spellings — `'fid':14056937`, `'uid':'1915864'`, + /// and `'t':iay0sp` where the token hides behind a randomly named `var` + /// declared earlier in the page — so each key resolves literal first, + /// then chases the variable. + private func listingForm(in html: String) throws -> [(String, String)] { + func param(_ key: String) throws -> String { + let pattern = "'\(key)'\\s*:\\s*(?:'([^']*)'|([A-Za-z0-9_$]+))" + guard let match = Self.firstMatch(pattern, in: html) else { + throw CheckError.malformedFolderPage + } + if let literal = Self.group(1, of: match, in: html), !literal.isEmpty { + return literal + } + guard let token = Self.group(2, of: match, in: html) else { + throw CheckError.malformedFolderPage + } + if token.allSatisfy(\.isNumber) { return token } + let varPattern = "\\b\(NSRegularExpression.escapedPattern(for: token))\\s*=\\s*'([^']*)'" + guard let varMatch = Self.firstMatch(varPattern, in: html), + let value = Self.group(1, of: varMatch, in: html) else { + throw CheckError.malformedFolderPage + } + return value + } + + return [ + ("lx", "2"), + ("fid", try param("fid")), + ("uid", try param("uid")), + ("puid", try param("puid")), + ("pg", "1"), + ("rep", "0"), + ("t", try param("t")), + ("k", try param("k")), + ("up", "1"), + ("ls", "1"), + ("pwd", password), + ] + } + + private struct ListedFile: Decodable { + let name_all: String + let id: String + let size: String + } + + /// `zt` is 蓝奏云's status field: 1 is success, 3 means the share password + /// was wrong, the rest are opaque refusals whose `info` — when it is a + /// string — is the only explanation the API gives. + private struct ListingResponse: Decodable { + let zt: Int + let infoText: String? + let text: [ListedFile]? + + enum CodingKeys: String, CodingKey { case zt, info, text } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + zt = try container.decode(Int.self, forKey: .zt) + infoText = try? container.decode(String.self, forKey: .info) + text = try? container.decode([ListedFile].self, forKey: .text) + } + } + + private func listing(form: [(String, String)]) async throws -> [ListedFile] { + let fid = form.first { $0.0 == "fid" }?.1 ?? "" + guard let ajaxURL = URL(string: "/filemoreajax.php?file=\(fid)", relativeTo: folderURL) else { + throw CheckError.malformedFolderPage + } + var request = URLRequest(url: ajaxURL.absoluteURL, timeoutInterval: 20) + request.httpMethod = "POST" + request.setValue(Self.userAgent, forHTTPHeaderField: "User-Agent") + request.setValue(folderURL.absoluteString, forHTTPHeaderField: "Referer") + request.setValue("XMLHttpRequest", forHTTPHeaderField: "X-Requested-With") + request.setValue( + "application/x-www-form-urlencoded; charset=UTF-8", + forHTTPHeaderField: "Content-Type" + ) + request.httpBody = Data(Self.formEncode(form).utf8) + + let (data, response) = try await session.data(for: request) + guard let http = response as? HTTPURLResponse, http.statusCode == 200 else { + throw CheckError.badResponse((response as? HTTPURLResponse)?.statusCode ?? -1) + } + guard let listing = try? JSONDecoder().decode(ListingResponse.self, from: data) else { + throw CheckError.malformedFolderPage + } + guard listing.zt == 1, let files = listing.text else { + throw CheckError.shareRejected(listing.infoText ?? "") + } + return files + } + + /// Filenames on the share look like `微信流-0.1.15-b22-universal.dmg` or + /// `WeChatBridge-0.1.15-build21-macOS-universal.zip`: a three-part version, + /// then a build number behind `-b` or `-build`. Anything that is not a + /// .dmg/.zip with both pieces is not a release. + private static func release(from file: ListedFile, base: URL) -> Release? { + let name = file.name_all + guard name.range(of: #"\.(dmg|zip)$"#, options: [.regularExpression, .caseInsensitive]) != nil, + let versionRange = name.range(of: #"\d+\.\d+\.\d+"#, options: .regularExpression) + else { return nil } + + let version = name[versionRange].split(separator: ".").compactMap { Int($0) } + guard version.count == 3 else { return nil } + + var build = 0 + let suffix = name[versionRange.upperBound...] + if let buildRange = suffix.range( + of: #"-(?:b|build)(\d+)"#, + options: [.regularExpression, .caseInsensitive] + ), let digits = suffix[buildRange].range(of: #"\d+"#, options: .regularExpression) { + build = Int(suffix[digits]) ?? 0 + } + + // `id` is a path, sometimes already carrying the `?webpage=` token the + // file page needs to open without the share password. + guard let pageURL = URL(string: "/" + file.id, relativeTo: base)?.absoluteURL else { + return nil + } + return Release( + fileName: name, + version: version, + build: build, + size: file.size, + pageURL: pageURL + ) + } + + private static func formEncode(_ fields: [(String, String)]) -> String { + let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~")) + return fields.map { key, value in + let escaped = value.addingPercentEncoding(withAllowedCharacters: allowed) ?? value + return "\(key)=\(escaped)" + }.joined(separator: "&") + } + + private static func firstMatch(_ pattern: String, in text: String) -> NSTextCheckingResult? { + try? NSRegularExpression(pattern: pattern) + .firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) + } + + private static func group(_ index: Int, of match: NSTextCheckingResult, in text: String) -> String? { + guard let range = Range(match.range(at: index), in: text) else { return nil } + return String(text[range]) + } +} diff --git a/macos/Sources/WeChatBridgeApp/StatusItemController.swift b/macos/Sources/WeChatBridgeApp/StatusItemController.swift index e3b263b..9a42d76 100644 --- a/macos/Sources/WeChatBridgeApp/StatusItemController.swift +++ b/macos/Sources/WeChatBridgeApp/StatusItemController.swift @@ -80,9 +80,15 @@ final class StatusItemController: NSObject, NSMenuDelegate { menu.addItem(item(L10n.text("关于 WeChatBridge…")) { [weak self] in self?.openSettings(.about) }) // Where a regular app keeps it: under the About item. A menu bar app // has no application menu, so the status menu is the only one it has. - menu.addItem(item(L10n.text("检查更新…"), enabled: updater.canCheckForUpdates) { [weak self] in - self?.updater.checkForUpdates() - }) + if let release = updater.availableUpdate { + menu.addItem(item(L10n.format("下载新版本 %@…", release.versionLabel)) { + AppLinks.open(release.pageURL.absoluteString) + }) + } else { + menu.addItem(item(L10n.text("检查更新…"), enabled: updater.canCheckForUpdates) { [weak self] in + self?.updater.checkForUpdates() + }) + } menu.addItem(.separator()) menu.addItem(item(L10n.text("退出 WeChatBridge"), key: "q") { NSApp.terminate(nil) }) } diff --git a/macos/Sources/WeChatBridgeApp/Views/Settings/AboutPane.swift b/macos/Sources/WeChatBridgeApp/Views/Settings/AboutPane.swift index 68e0764..52a5444 100644 --- a/macos/Sources/WeChatBridgeApp/Views/Settings/AboutPane.swift +++ b/macos/Sources/WeChatBridgeApp/Views/Settings/AboutPane.swift @@ -12,6 +12,15 @@ enum AppVersion { static var build: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "—" } + + /// The same two values as numbers, for the update checker's comparison. + static var components: [Int] { + short.split(separator: ".").compactMap { Int($0) } + } + + static var buildNumber: Int { + Int(build) ?? 0 + } } struct AboutPane: View { @@ -24,6 +33,33 @@ struct AboutPane: View { appHeader divider + aboutSection(title: L10n.text("软件更新"), systemImage: "arrow.triangle.2.circlepath") { + if updater.usesSparkleFeed { + paragraph(L10n.text("自动检查并安装新版本。")) + } else { + paragraph(L10n.text("从蓝奏云分享页检查新版本。")) + updateStatus + } + HStack(spacing: Space.m) { + Button(L10n.text("检查更新…")) { updater.checkForUpdates() } + .buttonStyle(SettingsActionButtonStyle(width: 150)) + .disabled(!updater.canCheckForUpdates) + if let release = updater.availableUpdate { + Button(L10n.text("前往下载")) { + AppLinks.open(release.pageURL.absoluteString) + } + .buttonStyle(SettingsActionButtonStyle(width: 150)) + } + } + if updater.availableUpdate != nil { + paragraph(L10n.format("网盘密码:%@", LanzouUpdateChecker.sharePassword)) + } + } + .padding(.vertical, Space.xl) + .task { updater.checkForUpdatesIfIdle() } + + divider + aboutSection(title: L10n.text("WeChatBridge 做什么"), systemImage: "info.circle") { paragraph(L10n.text("在微信的转发菜单里,直接把聊天记录送到你要用的地方。")) } @@ -155,6 +191,31 @@ struct AboutPane: View { .buttonStyle(SettingsActionButtonStyle(width: 150)) } + @ViewBuilder + private var updateStatus: some View { + switch updater.updateState { + case .idle: + paragraph(L10n.text("尚未检查更新。")) + case .checking: + HStack(spacing: 10) { + ProgressView() + .controlSize(.small) + Text(L10n.text("正在检查更新…")) + .font(.system(size: 14)) + .foregroundStyle(Theme.inkSecondary) + } + case .upToDate: + paragraph(L10n.format("已是最新版本 %@ (%@)。", AppVersion.short, AppVersion.build)) + case .updateAvailable(let release): + paragraph(L10n.format( + "发现新版本 %@ (%@),大小 %@。", + release.versionLabel, String(release.build), release.size + )) + case .failed(let message): + paragraph(L10n.format("检查更新失败:%@", message)) + } + } + private func paragraph(_ text: String) -> some View { Text(text) .font(.system(size: 14)) diff --git a/macos/Sources/WeChatBridgeCore/AppGroup.swift b/macos/Sources/WeChatBridgeCore/AppGroup.swift index 5511c92..3a82d7e 100644 --- a/macos/Sources/WeChatBridgeCore/AppGroup.swift +++ b/macos/Sources/WeChatBridgeCore/AppGroup.swift @@ -38,13 +38,22 @@ public enum AppGroup { } /// The real account home, not the sandbox container home. + /// + /// On iOS there is no account home to reach, and each process gets its + /// own container: this is only a scratch root for tests and previews. + /// iOS bundles must declare `.appGroup`, or the app and its extension + /// would each read a different inbox. public static var sharedRoot: URL { + #if os(macOS) guard let entry = getpwuid(getuid()), let path = entry.pointee.pw_dir else { return FileManager.default.homeDirectoryForCurrentUser .appendingPathComponent("Library/Application Support/WeChatBridge", isDirectory: true) } return URL(fileURLWithPath: String(cString: path), isDirectory: true) .appendingPathComponent("Library/Application Support/WeChatBridge", isDirectory: true) + #else + return URL.applicationSupportDirectory.appendingPathComponent("WeChatBridge", isDirectory: true) + #endif } } } diff --git a/macos/Sources/WeChatBridgeShare/AttachmentImporter.swift b/macos/Sources/WeChatBridgeCore/AttachmentImporter.swift similarity index 92% rename from macos/Sources/WeChatBridgeShare/AttachmentImporter.swift rename to macos/Sources/WeChatBridgeCore/AttachmentImporter.swift index 8f51791..484334d 100644 --- a/macos/Sources/WeChatBridgeShare/AttachmentImporter.swift +++ b/macos/Sources/WeChatBridgeCore/AttachmentImporter.swift @@ -1,16 +1,21 @@ -import WeChatBridgeCore import Foundation import UniformTypeIdentifiers -struct AttachmentSource { - let provider: NSItemProvider - let itemIndex: Int - let attachmentIndex: Int +public struct AttachmentSource { + public let provider: NSItemProvider + public let itemIndex: Int + public let attachmentIndex: Int + + public init(provider: NSItemProvider, itemIndex: Int, attachmentIndex: Int) { + self.provider = provider + self.itemIndex = itemIndex + self.attachmentIndex = attachmentIndex + } } -struct ImportedAttachment { - let manifestItem: ManifestItem - let diagnostic: AttachmentDiagnostic +public struct ImportedAttachment: Sendable { + public let manifestItem: ManifestItem + public let diagnostic: AttachmentDiagnostic } /// Copies one shared attachment into a staging batch. @@ -19,7 +24,7 @@ struct ImportedAttachment { /// to `loadFileRepresentation` is deleted the moment that completion handler /// returns. The copy therefore happens *inside* the callback, and the only /// things crossing the queue boundary are value types. -enum AttachmentImporter { +public enum AttachmentImporter { private struct CopiedFile: Sendable { let displayName: String let byteCount: Int64 @@ -35,7 +40,7 @@ enum AttachmentImporter { } } - static func importAttachment( + public static func importAttachment( _ source: AttachmentSource, into staging: BatchStaging, itemID: UUID = UUID() @@ -259,11 +264,11 @@ enum AttachmentImporter { /// Carries the redacted diagnostic alongside the failure so a rejected batch /// still explains itself in the P0 report. -struct ImportRejection: Error, LocalizedError { - let error: Error - let diagnostic: AttachmentDiagnostic +public struct ImportRejection: Error, LocalizedError { + public let error: Error + public let diagnostic: AttachmentDiagnostic - var errorDescription: String? { + public var errorDescription: String? { (error as? LocalizedError)?.errorDescription ?? error.localizedDescription } } diff --git a/macos/Sources/WeChatBridgeCore/FilePasteboard.swift b/macos/Sources/WeChatBridgeCore/FilePasteboard.swift index bf3f9f3..b4e1f83 100644 --- a/macos/Sources/WeChatBridgeCore/FilePasteboard.swift +++ b/macos/Sources/WeChatBridgeCore/FilePasteboard.swift @@ -1,4 +1,6 @@ +#if canImport(AppKit) import AppKit +#endif import Foundation /// Puts staged files on the general pasteboard as real file URLs. @@ -11,6 +13,8 @@ import Foundation /// The targets WeChatBridge pastes into are not sandboxed, so a plain file URL pointing /// into the group container is readable by them as-is. public enum FilePasteboard { + // iOS has no NSPasteboard; only the shell quoting below is shared there. + #if canImport(AppKit) @discardableResult public static func write(_ urls: [URL], to pasteboard: NSPasteboard = .general) -> Bool { guard !urls.isEmpty else { return false } @@ -45,6 +49,7 @@ public enum FilePasteboard { case .text(let text): return writeText(text, to: pasteboard) } } + #endif /// What dropping the same files on a terminal window would have typed. /// diff --git a/macos/Sources/WeChatBridgeApp/FolderDelivery.swift b/macos/Sources/WeChatBridgeCore/FolderDelivery.swift similarity index 95% rename from macos/Sources/WeChatBridgeApp/FolderDelivery.swift rename to macos/Sources/WeChatBridgeCore/FolderDelivery.swift index d66ae64..12b2871 100644 --- a/macos/Sources/WeChatBridgeApp/FolderDelivery.swift +++ b/macos/Sources/WeChatBridgeCore/FolderDelivery.swift @@ -1,13 +1,12 @@ import Darwin -import WeChatBridgeCore import Foundation -enum FolderDelivery { - enum Failure: LocalizedError { +public enum FolderDelivery { + public enum Failure: LocalizedError { case invalidFolder, invalidSource case cleanupFailed(Error) - var errorDescription: String? { + public var errorDescription: String? { switch self { case .invalidFolder: return L10n.text("请选择一个可写入的文件夹。") case .invalidSource: return L10n.text("待保存的文件无法读取,请重新导出。") @@ -16,7 +15,7 @@ enum FolderDelivery { } } - static func validateFolder(_ folder: URL) throws { + public static func validateFolder(_ folder: URL) throws { guard folder.isFileURL else { throw Failure.invalidFolder } let resolved = folder.resolvingSymlinksInPath() let values = try resolved.resourceValues(forKeys: [.isDirectoryKey]) @@ -28,7 +27,7 @@ enum FolderDelivery { /// Copy first, then publish complete files with exclusive renames. On /// cancellation or failure only this call's files are rolled back; inbox /// originals and every pre-existing destination remain untouched. - static func save(_ urls: [URL], to folder: URL, checkCancellation: () throws -> Void) throws -> [URL] { + public static func save(_ urls: [URL], to folder: URL, checkCancellation: () throws -> Void) throws -> [URL] { try checkCancellation() let scoped = folder.startAccessingSecurityScopedResource() defer { if scoped { folder.stopAccessingSecurityScopedResource() } } diff --git a/macos/Sources/WeChatBridgeCore/InboxSignal.swift b/macos/Sources/WeChatBridgeCore/InboxSignal.swift index 9a9aa96..b6e369f 100644 --- a/macos/Sources/WeChatBridgeCore/InboxSignal.swift +++ b/macos/Sources/WeChatBridgeCore/InboxSignal.swift @@ -9,12 +9,24 @@ import Foundation public enum InboxSignal { public static let didChange = Notification.Name("com.xiangming.wechatbridge.inbox.didChange") + /// iOS has no distributed notifications; the Darwin notify center is the + /// payload-free equivalent there, and it reaches across the app group too. public static func post() { + #if os(macOS) DistributedNotificationCenter.default().postNotificationName( didChange, object: nil, userInfo: nil, deliverImmediately: true ) + #else + CFNotificationCenterPostNotification( + CFNotificationCenterGetDarwinNotifyCenter(), + CFNotificationName(didChange.rawValue as CFString), + nil, + nil, + true + ) + #endif } } diff --git a/macos/Sources/WeChatBridgeApp/KnowledgeDelivery.swift b/macos/Sources/WeChatBridgeCore/KnowledgeDelivery.swift similarity index 97% rename from macos/Sources/WeChatBridgeApp/KnowledgeDelivery.swift rename to macos/Sources/WeChatBridgeCore/KnowledgeDelivery.swift index 4ba2cad..40ad851 100644 --- a/macos/Sources/WeChatBridgeApp/KnowledgeDelivery.swift +++ b/macos/Sources/WeChatBridgeCore/KnowledgeDelivery.swift @@ -1,4 +1,3 @@ -import WeChatBridgeCore import Foundation /// Writes a WeChat archive into a folder as Markdown plus a durable copy of @@ -9,12 +8,12 @@ import Foundation /// a subfolder of the user's vault, and 「沉淀到文件夹」 lands it in a subfolder /// of the folder the user picked — the same shape either way. The note shape — /// `聊天名.md` plus `附件/` — is the same too. -enum KnowledgeDelivery { - enum Failure: LocalizedError { +public enum KnowledgeDelivery { + public enum Failure: LocalizedError { case notConfigured case unreadableArchive - var errorDescription: String? { + public var errorDescription: String? { switch self { case .notConfigured: return L10n.text("还没有选择 Obsidian 知识库文件夹。") case .unreadableArchive: return L10n.text("微信导出的文件无法读取,原始文件已保留。") @@ -25,7 +24,7 @@ enum KnowledgeDelivery { /// The Obsidian entry: the vault is what the user configured, and the note /// goes into a `微信流` (or named) subfolder of it. @discardableResult - static func deliver( + public static func deliver( urls: [URL], vaultPath: String, subfolder: String, @@ -49,7 +48,7 @@ enum KnowledgeDelivery { /// goes into a `微信流` (or named) subfolder of it — the same landing /// shape the Obsidian entry writes inside its vault. @discardableResult - static func deliver( + public static func deliver( urls: [URL], folderPath: String, subfolder: String, diff --git a/macos/Sources/WeChatBridgeCore/PointerPlacement.swift b/macos/Sources/WeChatBridgeCore/PointerPlacement.swift index 59059e5..b3b7a8a 100644 --- a/macos/Sources/WeChatBridgeCore/PointerPlacement.swift +++ b/macos/Sources/WeChatBridgeCore/PointerPlacement.swift @@ -1,3 +1,4 @@ +import CoreGraphics import Foundation /// Where a panel that answers a click belongs on screen. diff --git a/macos/Tests/FolderDeliveryTests.swift b/macos/Tests/FolderDeliveryTests.swift index 7dd85cf..de12d51 100644 --- a/macos/Tests/FolderDeliveryTests.swift +++ b/macos/Tests/FolderDeliveryTests.swift @@ -8,7 +8,7 @@ // -Xlinker -rpath -Xlinker "$folder_test_sdk/Library/PrivateFrameworks" \ // -Xlinker -rpath -Xlinker "$folder_test_sdk/usr/lib" \ // .build/debug/WeChatBridgeCore.build/DisplayName.swift.o .build/debug/WeChatBridgeCore.build/L10n.swift.o \ -// Sources/WeChatBridgeApp/FolderDelivery.swift Tests/FolderDeliveryTests.swift \ +// Sources/WeChatBridgeCore/FolderDelivery.swift Tests/FolderDeliveryTests.swift \ // -o "$folder_test_output/runner" // "$folder_test_output/runner" import Foundation diff --git a/shared/AppLogos/README.md b/shared/AppLogos/README.md index a9c0936..205d24e 100644 --- a/shared/AppLogos/README.md +++ b/shared/AppLogos/README.md @@ -18,3 +18,7 @@ international artwork is used. Extension. The settings pane uses the same files when the destination app is not installed. On Windows they are published to `Resources/AppLogos` and used by the Entries pane and target pickers. + +On iOS, `ios/Resources/Assets.xcassets/Logo-*.imageset` holds 180 px copies +for the delivery panel's target grid; regenerate them with `sips -Z 180` when +these change.