From ed875ef2e1f706d1b280191f3cceeb627ca23b57 Mon Sep 17 00:00:00 2001 From: TongTongStudio Date: Sat, 14 Nov 2026 22:46:43 +0800 Subject: [PATCH] feat: add local file management and incoming share support --- AGENTS.md | 17 + android/app/src/main/AndroidManifest.xml | 22 + .../com/ttstd/familycare/MainActivity.java | 31 ++ android/app/src/main/res/xml/file_paths.xml | 5 + ios/Runner.xcodeproj/project.pbxproj | 28 + ios/Runner/AppDelegate.swift | 207 +++++++- ios/Runner/Info.plist | 16 +- ios/Runner/Runner.entitlements | 8 +- ios/ShareExtension/Info.plist | 47 ++ .../ShareExtension.entitlements | 10 + ios/ShareExtension/ShareViewController.swift | 8 + lib/app/app.dart | 14 +- lib/app/router/app_router.dart | 90 +++- lib/features/files/data/file_repository.dart | 92 ++++ .../files/presentation/files_page.dart | 234 +++++++++ .../messages/presentation/messages_tab.dart | 6 +- .../sharing/data/clipboard_history.dart | 2 + .../sharing/data/clipboard_history_io.dart | 23 + .../sharing/data/clipboard_history_stub.dart | 2 + .../sharing/data/clipboard_repository.dart | 10 + lib/features/sharing/data/share_storage.dart | 1 + .../sharing/data/share_storage_io.dart | 89 ++++ .../sharing/data/share_storage_stub.dart | 7 + lib/features/sharing/domain/douyin_share.dart | 18 + lib/features/sharing/domain/shared_inbox.dart | 28 + .../sharing/domain/shared_inbox.freezed.dart | 496 ++++++++++++++++++ .../sharing/domain/shared_inbox.g.dart | 45 ++ .../presentation/received_share_page.dart | 100 ++++ .../sharing/presentation/share_receiver.dart | 152 ++++++ .../sharing/presentation/share_thumbnail.dart | 2 + .../presentation/share_thumbnail_io.dart | 10 + .../presentation/share_thumbnail_stub.dart | 3 + .../presentation/sharing_controller.dart | 190 +++++++ lib/l10n/app_localizations.dart | 102 ++++ lib/l10n/app_localizations_en.dart | 58 ++ lib/l10n/app_localizations_zh.dart | 52 ++ lib/l10n/intl_en.arb | 19 +- lib/l10n/intl_zh.arb | 19 +- pubspec.lock | 8 + pubspec.yaml | 4 + test/clipboard_prompt_test.dart | 130 +++++ test/clipboard_share_test.dart | 187 +++++++ test/sharing_test.dart | 118 +++++ 43 files changed, 2674 insertions(+), 36 deletions(-) create mode 100644 android/app/src/main/res/xml/file_paths.xml create mode 100644 ios/ShareExtension/Info.plist create mode 100644 ios/ShareExtension/ShareExtension.entitlements create mode 100644 ios/ShareExtension/ShareViewController.swift create mode 100644 lib/features/files/data/file_repository.dart create mode 100644 lib/features/files/presentation/files_page.dart create mode 100644 lib/features/sharing/data/clipboard_history.dart create mode 100644 lib/features/sharing/data/clipboard_history_io.dart create mode 100644 lib/features/sharing/data/clipboard_history_stub.dart create mode 100644 lib/features/sharing/data/clipboard_repository.dart create mode 100644 lib/features/sharing/data/share_storage.dart create mode 100644 lib/features/sharing/data/share_storage_io.dart create mode 100644 lib/features/sharing/data/share_storage_stub.dart create mode 100644 lib/features/sharing/domain/douyin_share.dart create mode 100644 lib/features/sharing/domain/shared_inbox.dart create mode 100644 lib/features/sharing/domain/shared_inbox.freezed.dart create mode 100644 lib/features/sharing/domain/shared_inbox.g.dart create mode 100644 lib/features/sharing/presentation/received_share_page.dart create mode 100644 lib/features/sharing/presentation/share_receiver.dart create mode 100644 lib/features/sharing/presentation/share_thumbnail.dart create mode 100644 lib/features/sharing/presentation/share_thumbnail_io.dart create mode 100644 lib/features/sharing/presentation/share_thumbnail_stub.dart create mode 100644 lib/features/sharing/presentation/sharing_controller.dart create mode 100644 test/clipboard_prompt_test.dart create mode 100644 test/clipboard_share_test.dart create mode 100644 test/sharing_test.dart diff --git a/AGENTS.md b/AGENTS.md index 3c77f86..82100fe 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -414,3 +414,20 @@ static const String kBaseUrl = 'http://:/api/v1/open/'; - Web 兼容修改至少执行 `flutter build web`、`flutter analyze` 和 `flutter test`,并明确区分发布构建、宿主测试与真实浏览器验证。 - 本次适配已通过 Web 发布构建及 24 项宿主测试;静态分析仍有 13 项未涉及本次改动的 warning/info。Chrome 首屏测试停留在加载阶段后终止,尚未完成浏览器首屏及真实登录/接口联调验证,不得表述为所有 Web 功能已验证通过。 + + +## 20. 系统分享接收(receive_sharing_intent) + +- Android / iOS 接收系统分享使用 `receive_sharing_intent 1.9.0`。当前固定版本,因为 iOS ShareExtension 的本地 Swift Package 路径带版本号;升级依赖须同步更新 `ios/Runner.xcodeproj/project.pbxproj` 中该路径。 +- Android 保留 MainActivity 的 `singleTask` 和 Flutter 默认 `onNewIntent` 转发;SEND / SEND_MULTIPLE 接收任意文件、媒体、文字和链接。接收文件不申请整个存储权限。 +- 接收入口在账号 ProviderScope 外监听;分享模块有独立 ProviderContainer,不能把账号 ProviderScope 嵌进共享父 ProviderScope,否则账号切换后的缓存隔离会失效。应用根组件销毁时释放分享容器。 +- 分享内容属于本机收件箱,不自动上传、发送给设备或执行网址。文件复制到 ApplicationSupport/Received,每批写 items.json;文件页右上角收件箱可重新查看。文字、链接也持久保存,卸载 App 会清除应用内收件箱。 +- 状态模型用 freezed,`SharingController` 暂用手动声明的 Riverpod NotifierProvider:当前 analyzer 7.6 / riverpod_generator 与 SDK 的 dot shorthand 解析不兼容。新增纯 Dart 模型可用精确 build-filter 生成;不要运行全量生成并遗留原有生成文件被删除的状态。待统一升级生成工具后可迁回注解控制器。 +- iOS 新增 ShareExtension target,App Group 为 `group.com.ttstd.familycare`,回调 scheme 为 `ShareMedia-com.ttstd.familycare`;pubspec 按项目启用 Swift Package Manager,保留现有其他插件的构建配置。 +- Mac 首次构建前需在开发者账号为 Runner 与 ShareExtension 配置同一个 App Group 和有效签名,再执行 flutter pub get / flutter build ios,让 Flutter 生成 Swift Package 链接并迁移 Runner。禁止把 Windows 上 Swift 语法解析通过表述为 Xcode 编译或真机验证通过。 +- 微信、抖音的自有分享面板和传出内容由来源应用决定;本功能仅注册系统分享目标,不保证拿到原视频。 + +- 剪贴板抖音识别:仅原生 Android / iOS 启动或恢复前台时读一次文字,不在后台轮询;按严格域名和视频/图文路径识别,先确认,再作为 URL(附原始文案)进入本机收件箱。取消不导入,不清空剪贴板,不自动请求抖音网页。 +- 处理过的链接以规范化 URL 的 SHA-256 去重:本次进程最多保留 64 个哈希,最后处理的哈希通过 MMKV 跨启动保存;已导入链接也不重复询问。只持久化哈希,不持久化未确认的剪贴板原文;Android 不用 SharedPreferences。 +- iOS 主动读剪贴板可能触发系统粘贴授权弹窗;拒绝时静默跳过。当前没有 iOS 编译及真机验证条件,不能承诺与 Android 完全一致。 +- 抖音封面尚未接入:示例短链接可跳转并取得作品 ID,但普通 HTTP 请求返回的页面没有封面元数据。官方视频数据接口有 cover 字段,但需要权限和用户授权;不能承诺任意链接都能免授权解析封面。 diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 1630107..33bc318 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -23,6 +23,7 @@ + @@ -38,6 +39,7 @@ + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index 69e6b64..1be6412 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -5,6 +5,28 @@ }; objectVersion = 54; objects = { + FA2026111400000000000001 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = ""; }; + FA2026111400000000000002 = { isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + FA2026111400000000000003 = { isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = ShareExtension.entitlements; sourceTree = ""; }; + FA2026111400000000000004 = { isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; path = ShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + FA2026111400000000000005 = { isa = PBXBuildFile; fileRef = FA2026111400000000000001; }; + FA2026111400000000000006 = { isa = PBXBuildFile; fileRef = FA2026111400000000000004; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + FA2026111400000000000007 = { isa = PBXBuildFile; productRef = FA2026111400000000000014; }; + FA2026111400000000000008 = { isa = PBXGroup; children = (FA2026111400000000000001, FA2026111400000000000002, FA2026111400000000000003, ); path = ShareExtension; sourceTree = ""; }; + FA2026111400000000000009 = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (FA2026111400000000000005, ); runOnlyForDeploymentPostprocessing = 0; }; + FA202611140000000000000A = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (FA2026111400000000000007, ); runOnlyForDeploymentPostprocessing = 0; }; + FA202611140000000000000B = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; }; + FA202611140000000000000C = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 13; files = (FA2026111400000000000006, ); name = "Embed Share Extension"; runOnlyForDeploymentPostprocessing = 0; }; + FA202611140000000000000D = { isa = PBXContainerItemProxy; containerPortal = 97C146E61CF9000F007C117D; proxyType = 1; remoteGlobalIDString = FA202611140000000000000F; remoteInfo = ShareExtension; }; + FA202611140000000000000E = { isa = PBXTargetDependency; target = FA202611140000000000000F; targetProxy = FA202611140000000000000D; }; + FA202611140000000000000F = { isa = PBXNativeTarget; buildConfigurationList = FA2026111400000000000010; buildPhases = (FA2026111400000000000009, FA202611140000000000000A, FA202611140000000000000B, ); buildRules = (); dependencies = (); name = ShareExtension; packageProductDependencies = (FA2026111400000000000014, ); productName = ShareExtension; productReference = FA2026111400000000000004; productType = "com.apple.product-type.app-extension"; }; + FA2026111400000000000010 = { isa = XCConfigurationList; buildConfigurations = (FA2026111400000000000011, FA2026111400000000000012, FA2026111400000000000013, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + FA2026111400000000000011 = { isa = XCBuildConfiguration; baseConfigurationReference = 9740EEB21CF90195004384FC; buildSettings = {APPLICATION_EXTENSION_API_ONLY = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_STYLE = Automatic; CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; INFOPLIST_FILE = ShareExtension/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 13.0; LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); PRODUCT_BUNDLE_IDENTIFIER = com.ttstd.familycare.ShareExtension; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; + FA2026111400000000000012 = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E; buildSettings = {APPLICATION_EXTENSION_API_ONLY = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_STYLE = Automatic; CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; INFOPLIST_FILE = ShareExtension/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 13.0; LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); PRODUCT_BUNDLE_IDENTIFIER = com.ttstd.familycare.ShareExtension; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; }; + FA2026111400000000000013 = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E; buildSettings = {APPLICATION_EXTENSION_API_ONLY = YES; CLANG_ENABLE_MODULES = YES; CODE_SIGN_STYLE = Automatic; CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; INFOPLIST_FILE = ShareExtension/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 13.0; LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); PRODUCT_BUNDLE_IDENTIFIER = com.ttstd.familycare.ShareExtension; PRODUCT_NAME = "$(TARGET_NAME)"; SKIP_INSTALL = YES; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Profile; }; + FA2026111400000000000014 = { isa = XCSwiftPackageProductDependency; package = FA2026111400000000000015; productName = "receive-sharing-intent"; }; + FA2026111400000000000015 = { isa = XCLocalSwiftPackageReference; relativePath = "Flutter/ephemeral/Packages/.packages/receive_sharing_intent-1.9.0"; }; + /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; @@ -124,6 +146,7 @@ 97C146E51CF9000F007C117D = { isa = PBXGroup; children = ( + FA2026111400000000000008, 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, @@ -136,6 +159,7 @@ 97C146EF1CF9000F007C117D /* Products */ = { isa = PBXGroup; children = ( + FA2026111400000000000004, 97C146EE1CF9000F007C117D /* Runner.app */, 331C8081294A63A400263BE5 /* RunnerTests.xctest */, ); @@ -199,6 +223,7 @@ 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, + FA202611140000000000000C, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, D19718AED14992F7F2737A53 /* [CP] Embed Pods Frameworks */, 0FF3D9F1AE0B3A7D1337E3E5 /* [CP] Copy Pods Resources */, @@ -206,6 +231,7 @@ buildRules = ( ); dependencies = ( + FA202611140000000000000E, ); name = Runner; productName = Runner; @@ -241,10 +267,12 @@ Base, ); mainGroup = 97C146E51CF9000F007C117D; + packageReferences = (FA2026111400000000000015, ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( + FA202611140000000000000F, 97C146ED1CF9000F007C117D /* Runner */, 331C8080294A63A400263BE5 /* RunnerTests */, ); diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index a472509..2ac1668 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -1,9 +1,16 @@ import Flutter import Photos +import QuickLook import UIKit +import UniformTypeIdentifiers @main -@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate, UIDocumentPickerDelegate, QLPreviewControllerDataSource, QLPreviewControllerDelegate { + private var previewFileURL: URL? + private var previewRoot: URL? + private var fileDirectoryURL: URL? + private var directoryPicker: UIDocumentPickerViewController? + private var directoryPickerResult: FlutterResult? override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? @@ -22,7 +29,29 @@ import UIKit binaryMessenger: registrar.messenger() ) channel.setMethodCallHandler { call, result in - if call.method == "dialPhone" { + if call.method == "openLocalFile" { + guard let path = call.arguments as? String else { + result(false) + return + } + self.openLocalFile(path, result: result) + } else if call.method == "chooseFileDirectory" { + self.chooseFileDirectory(result) + } else if call.method == "listFileDirectory" { + guard let path = call.arguments as? String else { + result(FlutterError(code: "INVALID_PATH", message: "Invalid folder", details: nil)) + return + } + self.listFileDirectory(path, result: result) + } else if call.method == "releaseFileDirectory" { + self.fileDirectoryURL = nil + let pending = self.directoryPickerResult + self.directoryPickerResult = nil + self.directoryPicker?.dismiss(animated: false) + self.directoryPicker = nil + pending?(nil) + result(nil) + } else if call.method == "dialPhone" { guard let args = call.arguments as? [String: Any], let phone = args["phone"] as? String else { result(FlutterError(code: "INVALID_PHONE", message: "电话号码为空", details: nil)) @@ -59,4 +88,178 @@ import UIKit } } } + private func chooseFileDirectory(_ result: @escaping FlutterResult) { + guard directoryPickerResult == nil else { + result(FlutterError(code: "PICKER_BUSY", message: "Folder selection is in progress", details: nil)) + return + } + var presenter = UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene } + .filter { $0.activationState == .foregroundActive } + .flatMap { $0.windows } + .first { $0.isKeyWindow }?.rootViewController + while let presented = presenter?.presentedViewController { + presenter = presented + } + guard let presenter = presenter else { + result(FlutterError(code: "NO_WINDOW", message: "No active window", details: nil)) + return + } + let picker: UIDocumentPickerViewController + if #available(iOS 14.0, *) { + picker = UIDocumentPickerViewController(forOpeningContentTypes: [.folder], asCopy: false) + } else { + picker = UIDocumentPickerViewController(documentTypes: ["public.folder"], in: .open) + } + picker.allowsMultipleSelection = false + picker.delegate = self + directoryPickerResult = result + directoryPicker = picker + presenter.present(picker, animated: true) + } + + func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { + guard controller === directoryPicker else { return } + let callback = directoryPickerResult + directoryPickerResult = nil + directoryPicker = nil + callback?(nil) + } + + func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { + guard controller === directoryPicker else { return } + let callback = directoryPickerResult + directoryPickerResult = nil + directoryPicker = nil + guard let url = urls.first, url.startAccessingSecurityScopedResource() else { + callback?(FlutterError(code: "DIRECTORY_DENIED", message: "Folder access denied", details: nil)) + return + } + defer { url.stopAccessingSecurityScopedResource() } + fileDirectoryURL = url + callback?(url.standardizedFileURL.resolvingSymlinksInPath().path) + } + + private func listFileDirectory(_ path: String, result: @escaping FlutterResult) { + guard let root = fileDirectoryURL else { + result(FlutterError(code: "DIRECTORY_DENIED", message: "Choose a folder first", details: nil)) + return + } + DispatchQueue.global(qos: .userInitiated).async { + guard root.startAccessingSecurityScopedResource() else { + DispatchQueue.main.async { + result(FlutterError(code: "DIRECTORY_DENIED", message: "Folder permission was revoked", details: nil)) + } + return + } + defer { root.stopAccessingSecurityScopedResource() } + let rootPath = root.standardizedFileURL.resolvingSymlinksInPath().path + let directory = URL(fileURLWithPath: path).standardizedFileURL.resolvingSymlinksInPath() + guard directory.path == rootPath || directory.path.hasPrefix(rootPath + "/") else { + DispatchQueue.main.async { + result(FlutterError(code: "INVALID_PATH", message: "Folder is outside the authorized directory", details: nil)) + } + return + } + let coordinator = NSFileCoordinator() + var coordinationError: NSError? + var readError: Error? + var entries: [[String: Any]] = [] + coordinator.coordinate(readingItemAt: directory, options: .withoutChanges, + error: &coordinationError) { coordinatedURL in + do { + let children = try FileManager.default.contentsOfDirectory( + at: coordinatedURL, + includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], + options: [] + ) + entries = try children.compactMap { child -> [String: Any]? in + let values = try child.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + if values.isSymbolicLink == true { return nil } + return ["path": child.path, "directory": values.isDirectory == true] + } + } catch { + readError = error + } + } + let failure = coordinationError ?? (readError as NSError?) + let output = entries + DispatchQueue.main.async { + if let failure = failure { + result(FlutterError(code: "DIRECTORY_READ_FAILED", message: failure.localizedDescription, details: nil)) + } else { + result(output) + } + } + } + } + + private func openLocalFile(_ path: String, result: @escaping FlutterResult) { + guard previewFileURL == nil else { result(false); return } + let file = URL(fileURLWithPath: path).standardizedFileURL.resolvingSymlinksInPath() + let inbox = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! + .appendingPathComponent("Received").standardizedFileURL.resolvingSymlinksInPath() + var scopedRoot: URL? + if !file.path.hasPrefix(inbox.path + "/") { + guard let root = fileDirectoryURL, + file.path.hasPrefix(root.standardizedFileURL.resolvingSymlinksInPath().path + "/"), + root.startAccessingSecurityScopedResource() else { result(false); return } + scopedRoot = root + } + guard FileManager.default.isReadableFile(atPath: file.path) else { + scopedRoot?.stopAccessingSecurityScopedResource() + result(false) + return + } + var presenter = UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene } + .filter { $0.activationState == .foregroundActive } + .flatMap { $0.windows } + .first { $0.isKeyWindow }?.rootViewController + while let presented = presenter?.presentedViewController { + presenter = presented + } + guard let presenter = presenter else { + scopedRoot?.stopAccessingSecurityScopedResource() + result(false) + return + } + previewRoot = scopedRoot + previewFileURL = file + if QLPreviewController.canPreview(file as NSURL) { + let preview = QLPreviewController() + preview.dataSource = self + preview.delegate = self + presenter.present(preview, animated: true) { result(true) } + } else { + let share = UIActivityViewController(activityItems: [file], applicationActivities: nil) + share.completionWithItemsHandler = { [weak self] _, _, _, _ in + self?.releaseFilePreview() + } + share.popoverPresentationController?.sourceView = presenter.view + share.popoverPresentationController?.sourceRect = CGRect( + x: presenter.view.bounds.midX, y: presenter.view.bounds.midY, width: 1, height: 1 + ) + presenter.present(share, animated: true) { result(true) } + } + } + + private func releaseFilePreview() { + previewRoot?.stopAccessingSecurityScopedResource() + previewRoot = nil + previewFileURL = nil + } + + func numberOfPreviewItems(in controller: QLPreviewController) -> Int { + return previewFileURL == nil ? 0 : 1 + } + + func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { + return previewFileURL! as NSURL + } + + func previewControllerDidDismiss(_ controller: QLPreviewController) { + releaseFilePreview() + } + } diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index cd664b7..d18420e 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -70,7 +70,6 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight - NSLocationWhenInUseUsageDescription 用于在地图上展示设备位置 NSLocationAlwaysUsageDescription @@ -98,5 +97,20 @@ 用于将远程屏幕录制保存到系统相册 io.flutter.embedded_views_preview + AppGroupId + group.com.ttstd.familycare + FlutterDeepLinkingEnabled + + CFBundleURLTypes + + + CFBundleTypeRole + Editor + CFBundleURLSchemes + + ShareMedia-$(PRODUCT_BUNDLE_IDENTIFIER) + + + diff --git a/ios/Runner/Runner.entitlements b/ios/Runner/Runner.entitlements index dea0d97..43acd0d 100644 --- a/ios/Runner/Runner.entitlements +++ b/ios/Runner/Runner.entitlements @@ -2,7 +2,11 @@ - keychain-access-groups - + keychain-access-groups + + com.apple.security.application-groups + + group.com.ttstd.familycare + diff --git a/ios/ShareExtension/Info.plist b/ios/ShareExtension/Info.plist new file mode 100644 index 0000000..2cf3681 --- /dev/null +++ b/ios/ShareExtension/Info.plist @@ -0,0 +1,47 @@ + + + + + CFBundleDisplayName + 同同家庭关怀 + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + XPC! + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + AppGroupId + group.com.ttstd.familycare + NSExtension + + NSExtensionPrincipalClass + $(PRODUCT_MODULE_NAME).ShareViewController + NSExtensionPointIdentifier + com.apple.share-services + NSExtensionAttributes + + NSExtensionActivationRule + + NSExtensionActivationSupportsText + + NSExtensionActivationSupportsWebURLWithMaxCount + 10 + NSExtensionActivationSupportsImageWithMaxCount + 100 + NSExtensionActivationSupportsMovieWithMaxCount + 100 + NSExtensionActivationSupportsFileWithMaxCount + 100 + + + + + diff --git a/ios/ShareExtension/ShareExtension.entitlements b/ios/ShareExtension/ShareExtension.entitlements new file mode 100644 index 0000000..1519d41 --- /dev/null +++ b/ios/ShareExtension/ShareExtension.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.application-groups + + group.com.ttstd.familycare + + + diff --git a/ios/ShareExtension/ShareViewController.swift b/ios/ShareExtension/ShareViewController.swift new file mode 100644 index 0000000..4a243fb --- /dev/null +++ b/ios/ShareExtension/ShareViewController.swift @@ -0,0 +1,8 @@ +import receive_sharing_intent + +/// The plugin persists attachments in the shared App Group and delivers them to Flutter. +final class ShareViewController: RSIShareViewController { + override func shouldAutoRedirect() -> Bool { + return true + } +} diff --git a/lib/app/app.dart b/lib/app/app.dart index dbc9093..ada3952 100644 --- a/lib/app/app.dart +++ b/lib/app/app.dart @@ -1,3 +1,4 @@ +import '../features/sharing/presentation/share_receiver.dart'; import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter/gestures.dart' show PointerDeviceKind; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -58,11 +59,14 @@ class App extends StatelessWidget { /// 便于在 main 中统一构建 ProviderScope + App。 Widget buildApp(GoRouter router) { - return ValueListenableBuilder( - valueListenable: TokenStorage.sessionChanges, - builder: (context, version, _) => ProviderScope( - key: ValueKey(version), - child: App(router: router), + return ShareReceiver( + router: router, + child: ValueListenableBuilder( + valueListenable: TokenStorage.sessionChanges, + builder: (context, version, _) => ProviderScope( + key: ValueKey(version), + child: App(router: router), + ), ), ); } diff --git a/lib/app/router/app_router.dart b/lib/app/router/app_router.dart index fae78ed..a6f0548 100644 --- a/lib/app/router/app_router.dart +++ b/lib/app/router/app_router.dart @@ -1,3 +1,6 @@ +import '../../features/sharing/presentation/sharing_controller.dart'; +import '../../features/sharing/presentation/received_share_page.dart'; +import 'package:cupertino_ui/cupertino_ui.dart' show CupertinoPage; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; @@ -26,6 +29,7 @@ import '../../features/contacts/presentation/contacts_page.dart'; import '../../features/contacts/presentation/contact_edit_page.dart'; import '../../features/contacts/domain/contact_models.dart'; import '../../features/apps/presentation/apps_page.dart'; +import '../../features/files/presentation/files_page.dart'; import '../../features/account/presentation/change_mobile_page.dart'; import '../../features/account/presentation/change_password_page.dart'; import '../../features/account/presentation/login_devices_page.dart'; @@ -38,6 +42,22 @@ import '../../features/device/presentation/device_manage_page.dart'; import '../../features/device/presentation/device_scan_page.dart'; import '../../features/connection/presentation/remote_control_page.dart'; +/// 显式使用分包后的 CupertinoPage,避免 go_router 将应用识别为 WidgetsApp。 +GoRoute _cupertinoRoute({ + required String path, + required Widget Function(BuildContext, GoRouterState) builder, +}) { + return GoRoute( + path: path, + pageBuilder: (context, state) => CupertinoPage( + key: state.pageKey, + name: state.name ?? state.path, + restorationId: state.pageKey.value, + child: builder(context, state), + ), + ); +} + /// 应用路由定义(GoRouter)。 /// /// - /splash 启动页,依据登录态决定首跳 @@ -53,6 +73,7 @@ GoRouter buildAppRouter() { redirect: (context, state) { const publicPaths = { '/splash', + '/received-share', '/login', '/register', '/forgot-password', @@ -68,92 +89,115 @@ GoRouter buildAppRouter() { return null; }, routes: [ + _cupertinoRoute( + path: "/received-share", + builder: (context, state) => UncontrolledProviderScope( + container: sharingContainer, + child: const ReceivedSharePage(), + ), + ), GoRoute(path: '/splash', builder: (context, state) => const SplashPage()), GoRoute(path: '/login', builder: (context, state) => const LoginPage()), - GoRoute( + _cupertinoRoute( path: '/register', builder: (context, state) => const RegisterPage(), ), - GoRoute( + _cupertinoRoute( path: '/forgot-password', builder: (context, state) => const ForgotPasswordPage(), ), - GoRoute( + _cupertinoRoute( path: '/legal', builder: (context, state) => LegalDocumentPage.fromExtra(state.extra), ), - GoRoute(path: '/album', builder: (context, state) => const AlbumPage()), - GoRoute(path: '/alarm', builder: (context, state) => const AlarmPage()), - GoRoute( + _cupertinoRoute( + path: '/files', + builder: (context, state) => const FilesPage(), + ), + _cupertinoRoute( + path: '/album', + builder: (context, state) => const AlbumPage(), + ), + _cupertinoRoute( + path: '/alarm', + builder: (context, state) => const AlarmPage(), + ), + _cupertinoRoute( path: '/alarm/edit', builder: (context, state) => AlarmEditPage( alarm: state.extra is AlarmModel ? state.extra as AlarmModel : null, ), ), - GoRoute( + _cupertinoRoute( path: '/contacts', builder: (context, state) => const ContactsPage(), ), - GoRoute( + _cupertinoRoute( path: '/contacts/edit', builder: (context, state) => ContactEditPage( contact: state.extra is Contact ? state.extra as Contact : null, ), ), - GoRoute(path: '/apps', builder: (context, state) => const AppsPage()), - GoRoute( + _cupertinoRoute( + path: '/apps', + builder: (context, state) => const AppsPage(), + ), + _cupertinoRoute( path: '/device/manage', builder: (context, state) => const DeviceManagePage(), ), - GoRoute( + _cupertinoRoute( path: '/device/bind', builder: (context, state) => DeviceBindPage( initialSn: state.extra is String ? state.extra as String : null, ), ), - GoRoute( + _cupertinoRoute( path: '/device/scan', builder: (context, state) => const DeviceScanPage(), ), - GoRoute(path: '/profile/edit', builder: (context, state) => const ProfileEditPage()), - GoRoute( + _cupertinoRoute( + path: '/profile/edit', + builder: (context, state) => const ProfileEditPage(), + ), + _cupertinoRoute( path: '/security', builder: (context, state) => const SecurityPage(), ), - GoRoute( + _cupertinoRoute( path: '/security/login-devices', builder: (context, state) => const LoginDevicesPage(), ), - GoRoute( + _cupertinoRoute( path: '/security/password', builder: (context, state) => const ChangePasswordPage(), ), - GoRoute( + _cupertinoRoute( path: '/security/mobile', builder: (context, state) => ChangeMobilePage( currentMobile: state.extra is String ? state.extra as String : null, ), ), - GoRoute( + _cupertinoRoute( path: '/security/wechat', builder: (context, state) => const WechatBindingPage(), ), - GoRoute(path: '/map', builder: (context, state) => _MapRoute()), - GoRoute( + _cupertinoRoute(path: '/map', builder: (context, state) => _MapRoute()), + _cupertinoRoute( path: '/screenshots', builder: (context, state) => _ScreenshotsRoute( initialIndex: (state.extra is int) ? state.extra as int : 0, ), ), - GoRoute( + _cupertinoRoute( path: '/connection', builder: (context, state) => _RemoteControlRoute(), ), - GoRoute( + _cupertinoRoute( path: '/settings', builder: (context, state) => const SystemSettingsPage(), ), - GoRoute( + _cupertinoRoute( path: '/wallpaper', builder: (context, state) => const WallpaperPage(), ), diff --git a/lib/features/files/data/file_repository.dart b/lib/features/files/data/file_repository.dart new file mode 100644 index 0000000..0bf4f64 --- /dev/null +++ b/lib/features/files/data/file_repository.dart @@ -0,0 +1,92 @@ +import 'dart:io'; + +import 'package:device_info_plus/device_info_plus.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:permission_handler/permission_handler.dart'; + +final fileRepositoryProvider = Provider.autoDispose((ref) { + final repository = FileRepository(); + ref.onDispose(repository.release); + return repository; +}); + +final fileStorageProvider = FutureProvider.autoDispose((ref) { + return ref.watch(fileRepositoryProvider).requestStorage(); +}); + +final directoryEntriesProvider = FutureProvider.autoDispose + .family, String>((ref, path) { + return ref.watch(fileRepositoryProvider).list(path); + }); + +/// 本机共享存储目录。系统保护目录的访问限制由 Android 执行。 +class FileRepository { + static const _channel = MethodChannel('com.ttstd.familycare/app'); + + Future requestStorage() async { + if (Platform.isIOS) { + return _channel.invokeMethod('chooseFileDirectory'); + } + if (!Platform.isAndroid) return null; + final sdk = (await DeviceInfoPlugin().androidInfo).version.sdkInt; + final permission = sdk >= 30 + ? Permission.manageExternalStorage + : Permission.storage; + if (await permission.isPermanentlyDenied) { + await openAppSettings(); + return null; + } + if (!await permission.isGranted && + !(await permission.request()).isGranted) { + return null; + } + return _channel.invokeMethod('externalStorageRoot'); + } + + Future> list(String path) async { + final List entries; + if (Platform.isIOS) { + final data = await _channel.invokeListMethod( + 'listFileDirectory', + path, + ); + entries = (data ?? []).map((item) { + final entry = Map.from(item as Map); + final path = entry['path'] as String; + return entry['directory'] == true ? Directory(path) : File(path); + }).toList(); + } else { + entries = await Directory(path).list(followLinks: false).toList(); + } + // 不跟随符号链接,避免目录导航跳出共享存储。 + entries.removeWhere((entry) => entry is Link); + entries.sort((left, right) { + if (left is Directory && right is! Directory) return -1; + if (left is! Directory && right is Directory) return 1; + return left.uri.pathSegments + .where((s) => s.isNotEmpty) + .last + .toLowerCase() + .compareTo( + right.uri.pathSegments + .where((s) => s.isNotEmpty) + .last + .toLowerCase(), + ); + }); + return entries; + } + + Future open(String path) async { + return await _channel.invokeMethod('openLocalFile', path) ?? false; + } + + void release() { + if (Platform.isIOS) { + _channel + .invokeMethod('releaseFileDirectory') + .catchError((Object _) {}); + } + } +} diff --git a/lib/features/files/presentation/files_page.dart b/lib/features/files/presentation/files_page.dart new file mode 100644 index 0000000..2ec039b --- /dev/null +++ b/lib/features/files/presentation/files_page.dart @@ -0,0 +1,234 @@ +import 'dart:io'; + +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../../../app/theme/dark_mode.dart'; +import '../../../core/widgets/app_page_scaffold.dart'; +import '../../../core/widgets/feature_ui.dart'; +import '../../../l10n/app_localizations.dart'; +import '../data/file_repository.dart'; + +class FilesPage extends ConsumerStatefulWidget { + const FilesPage({super.key}); + + @override + ConsumerState createState() => _FilesPageState(); +} + +class _FilesPageState extends ConsumerState { + String? _path; + + void _back(String? root) { + if (root != null && _path != null && _path != root) { + setState(() => _path = Directory(_path!).parent.path); + } else { + context.pop(); + } + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final storage = ref.watch(fileStorageProvider); + final root = storage.valueOrNull; + final path = root == null + ? null + : _path != null && (_path == root || _path!.startsWith('$root/')) + ? _path + : root; + + return PopScope( + canPop: false, + onPopInvokedWithResult: (didPop, _) { + if (!didPop) _back(root); + }, + child: AppPageScaffold( + navigationBar: CupertinoNavigationBar( + middle: Text(l10n.filesTitle), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () => context.push('/received-share'), + child: const Icon(CupertinoIcons.tray_arrow_down), + ), + if (Platform.isIOS) + CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () { + setState(() => _path = null); + ref.invalidate(fileStorageProvider); + }, + child: Text(l10n.filesChooseFolder), + ), + ], + ), + leading: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () => _back(root), + child: const Icon(CupertinoIcons.back), + ), + ), + child: SafeArea( + child: storage.when( + loading: () => const Center(child: CupertinoActivityIndicator()), + error: (_, _) => _permissionView(l10n), + data: (root) => root == null || path == null + ? _permissionView(l10n) + : Column( + children: [ + Padding( + padding: const EdgeInsets.all(16), + child: Text( + path == root + ? (Platform.isIOS + ? Directory(root).uri.pathSegments + .where((s) => s.isNotEmpty) + .last + : l10n.filesStorage) + : path.substring(root.length), + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: DarkMode.color(context, AppColors.sub), + ), + ), + ), + Expanded(child: _directory(path, l10n)), + ], + ), + ), + ), + ), + ); + } + + Widget _permissionView(AppLocalizations l10n) => Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + Platform.isIOS ? l10n.filesIosPermission : l10n.filesPermission, + textAlign: TextAlign.center, + style: TextStyle(color: DarkMode.color(context, AppColors.ink)), + ), + const SizedBox(height: 16), + CupertinoButton.filled( + onPressed: () { + setState(() => _path = null); + ref.invalidate(fileStorageProvider); + }, + child: Text(l10n.filesAuthorize), + ), + ], + ), + ), + ); + + bool _opening = false; + + Future _openFile(String path, AppLocalizations l10n) async { + if (_opening) return; + _opening = true; + try { + final opened = await ref.read(fileRepositoryProvider).open(path); + if (!opened && mounted) await _openFailed(l10n); + } catch (_) { + if (mounted) await _openFailed(l10n); + } finally { + _opening = false; + } + } + + Future _openFailed(AppLocalizations l10n) => showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + content: Text(l10n.filesOpenFailed), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.of(context).pop(), + child: Text(l10n.confirm), + ), + ], + ), + ); + + Widget _directory(String path, AppLocalizations l10n) { + final provider = directoryEntriesProvider(path); + return CustomScrollView( + physics: const AlwaysScrollableScrollPhysics( + parent: BouncingScrollPhysics(), + ), + slivers: [ + CupertinoSliverRefreshControl( + onRefresh: () async { + ref.invalidate(provider); + try { + await ref.read(provider.future); + } catch (_) { + // 下方 AsyncValue 展示目录读取错误。 + } + }, + ), + ref + .watch(provider) + .when( + loading: () => const SliverFillRemaining( + child: Center(child: CupertinoActivityIndicator()), + ), + error: (_, _) => SliverFillRemaining( + hasScrollBody: false, + child: Center( + child: Text( + l10n.filesUnreadable, + style: TextStyle( + color: DarkMode.color(context, AppColors.sub), + ), + ), + ), + ), + data: (entries) => entries.isEmpty + ? SliverFillRemaining( + hasScrollBody: false, + child: Center(child: Text(l10n.filesEmpty)), + ) + : SliverList.builder( + itemCount: entries.length, + itemBuilder: (context, index) { + final entry = entries[index]; + final folder = entry is Directory; + final name = entry.path + .split(Platform.pathSeparator) + .last; + return CupertinoListTile( + title: Text( + name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: DarkMode.color(context, AppColors.ink), + ), + ), + leading: Icon( + folder ? CupertinoIcons.folder : CupertinoIcons.doc, + color: AppColors.blue, + ), + trailing: folder + ? const CupertinoListTileChevron() + : null, + onTap: folder + ? () => setState(() => _path = entry.path) + : () => _openFile(entry.path, l10n), + ); + }, + ), + ), + ], + ); + } +} diff --git a/lib/features/messages/presentation/messages_tab.dart b/lib/features/messages/presentation/messages_tab.dart index 84c42bc..2967c9c 100644 --- a/lib/features/messages/presentation/messages_tab.dart +++ b/lib/features/messages/presentation/messages_tab.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart' show defaultTargetPlatform, TargetPlatform, kIsWeb; import 'package:cupertino_ui/cupertino_ui.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; @@ -49,7 +50,10 @@ class MessagesTab extends ConsumerWidget { emoji: '📁', color: AppColors.teal, label: l10n.menuFiles, - route: '/apps', + route: '/files', + supported: !kIsWeb && + (defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.iOS), ), _Menu( emoji: '➕', diff --git a/lib/features/sharing/data/clipboard_history.dart b/lib/features/sharing/data/clipboard_history.dart new file mode 100644 index 0000000..7133e67 --- /dev/null +++ b/lib/features/sharing/data/clipboard_history.dart @@ -0,0 +1,2 @@ +export 'clipboard_history_stub.dart' + if (dart.library.io) 'clipboard_history_io.dart'; diff --git a/lib/features/sharing/data/clipboard_history_io.dart b/lib/features/sharing/data/clipboard_history_io.dart new file mode 100644 index 0000000..accbbe1 --- /dev/null +++ b/lib/features/sharing/data/clipboard_history_io.dart @@ -0,0 +1,23 @@ +import 'dart:io'; +import 'package:mmkv/mmkv.dart'; + +const _key = 'sharing.clipboard.last_handled_url_hash'; +String? _memory; +String? readClipboardFingerprint() { + if (!Platform.isAndroid && !Platform.isIOS) return _memory; + try { + return MMKV.defaultMMKV().decodeString(_key) ?? _memory; + } catch (_) { + return _memory; + } +} + +void writeClipboardFingerprint(String value) { + _memory = value; + if (!Platform.isAndroid && !Platform.isIOS) return; + try { + MMKV.defaultMMKV().encodeString(_key, value); + } catch (_) { + /* No SharedPreferences fallback. */ + } +} diff --git a/lib/features/sharing/data/clipboard_history_stub.dart b/lib/features/sharing/data/clipboard_history_stub.dart new file mode 100644 index 0000000..f098345 --- /dev/null +++ b/lib/features/sharing/data/clipboard_history_stub.dart @@ -0,0 +1,2 @@ +String? readClipboardFingerprint() => null; +void writeClipboardFingerprint(String value) {} diff --git a/lib/features/sharing/data/clipboard_repository.dart b/lib/features/sharing/data/clipboard_repository.dart new file mode 100644 index 0000000..089f428 --- /dev/null +++ b/lib/features/sharing/data/clipboard_repository.dart @@ -0,0 +1,10 @@ +import 'package:flutter/services.dart'; +import 'clipboard_history.dart'; + +class ClipboardRepository { + Future readText() async => + (await Clipboard.getData(Clipboard.kTextPlain))?.text; + String? get lastHandledFingerprint => readClipboardFingerprint(); + void markHandled(String fingerprint) => + writeClipboardFingerprint(fingerprint); +} diff --git a/lib/features/sharing/data/share_storage.dart b/lib/features/sharing/data/share_storage.dart new file mode 100644 index 0000000..b6e1c13 --- /dev/null +++ b/lib/features/sharing/data/share_storage.dart @@ -0,0 +1 @@ +export 'share_storage_stub.dart' if (dart.library.io) 'share_storage_io.dart'; diff --git a/lib/features/sharing/data/share_storage_io.dart b/lib/features/sharing/data/share_storage_io.dart new file mode 100644 index 0000000..dbd4bc6 --- /dev/null +++ b/lib/features/sharing/data/share_storage_io.dart @@ -0,0 +1,89 @@ +import 'package:flutter/services.dart'; +import 'dart:io'; +import 'dart:convert'; +import 'package:path_provider/path_provider.dart'; +import 'package:receive_sharing_intent/receive_sharing_intent.dart'; + +/// Keep received files independently of the sender's temporary URI grant. +Future> saveSharedItems( + List items, +) async { + final documents = await getApplicationSupportDirectory(); + final folder = Directory( + '${documents.path}/Received/${DateTime.now().microsecondsSinceEpoch}', + ); + await folder.create(recursive: true); + final saved = []; + try { + for (var i = 0; i < items.length; i++) { + final item = items[i]; + if (item.type == SharedMediaType.text || + item.type == SharedMediaType.url) { + await File('${folder.path}/$i.txt').writeAsString(item.path); + saved.add(item); + } else { + final name = Uri.file(item.path).pathSegments.last; + final target = await File(item.path).copy('${folder.path}/${i}_$name'); + saved.add( + SharedMediaFile( + path: target.path, + type: item.type, + mimeType: item.mimeType, + message: item.message, + duration: item.duration, + ), + ); + } + } + await File( + '${folder.path}/items.json', + ).writeAsString(jsonEncode(saved.map((item) => item.toMap()).toList())); + return saved; + } catch (_) { + await folder.delete(recursive: true); + rethrow; + } +} + +Future> loadSharedItems() async { + final documents = await getApplicationSupportDirectory(); + final root = Directory('${documents.path}/Received'); + if (!await root.exists()) return []; + final result = []; + final folders = await root + .list(followLinks: false) + .where((e) => e is Directory) + .toList(); + folders.sort((a, b) => a.path.compareTo(b.path)); + for (final folder in folders) { + try { + final data = + jsonDecode(await File('${folder.path}/items.json').readAsString()) + as List; + for (final json in data) { + final item = SharedMediaFile.fromMap( + Map.from(json as Map), + ); + if (item.type == SharedMediaType.text || + item.type == SharedMediaType.url || + await File(item.path).exists()) { + result.add(item); + } + } + } catch (_) { + // An interrupted import must not prevent opening previously saved batches. + } + } + return result; +} + +Future openSharedItem(String path) async { + try { + return await const MethodChannel( + 'com.ttstd.familycare/app', + ).invokeMethod('openLocalFile', path) ?? + false; + } catch (_) { + return false; + } +} diff --git a/lib/features/sharing/data/share_storage_stub.dart b/lib/features/sharing/data/share_storage_stub.dart new file mode 100644 index 0000000..a50ae72 --- /dev/null +++ b/lib/features/sharing/data/share_storage_stub.dart @@ -0,0 +1,7 @@ +import 'package:receive_sharing_intent/receive_sharing_intent.dart'; + +Future> saveSharedItems( + List items, +) async => []; +Future> loadSharedItems() async => []; +Future openSharedItem(String path) async => false; diff --git a/lib/features/sharing/domain/douyin_share.dart b/lib/features/sharing/domain/douyin_share.dart new file mode 100644 index 0000000..341b9c0 --- /dev/null +++ b/lib/features/sharing/domain/douyin_share.dart @@ -0,0 +1,18 @@ +/// Extract a canonical Douyin share URL without opening it or making requests. +/// Only supported Douyin hosts and video/note paths are accepted. +String? findDouyinShareUrl(String text) { + final normalized = text.replaceAll(r'\:', ':').replaceAll(r'\/', '/'); + final links = RegExp( + r'https?://(?:v\.douyin\.com/[A-Za-z0-9_-]+|(?:www\.)?douyin\.com/(?:video|note)/[0-9]+|www\.iesdouyin\.com/share/(?:video|note)/[0-9]+)(?=[/\s?&#。,、;!?)】」》"\x27]|$)', + caseSensitive: false, + ); + final match = links.firstMatch(normalized); + if (match == null) return null; + final uri = Uri.tryParse(match.group(0)!); + if (uri == null) return null; + return Uri( + scheme: 'https', + host: uri.host.toLowerCase(), + path: '${uri.path}/', + ).toString(); +} diff --git a/lib/features/sharing/domain/shared_inbox.dart b/lib/features/sharing/domain/shared_inbox.dart new file mode 100644 index 0000000..b8e3087 --- /dev/null +++ b/lib/features/sharing/domain/shared_inbox.dart @@ -0,0 +1,28 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +part 'shared_inbox.freezed.dart'; +part 'shared_inbox.g.dart'; + +@freezed +class SharedItem with _$SharedItem { + const factory SharedItem({ + required String path, + required String type, + String? message, + }) = _SharedItem; + factory SharedItem.fromJson(Map json) => + _$SharedItemFromJson(json); +} + +@freezed +class SharedInbox with _$SharedInbox { + const factory SharedInbox({ + @Default([]) List items, + @Default(false) bool importing, + @Default(false) bool failed, + @Default(0) int delivery, + String? clipboardText, + String? clipboardUrl, + }) = _SharedInbox; + factory SharedInbox.fromJson(Map json) => + _$SharedInboxFromJson(json); +} diff --git a/lib/features/sharing/domain/shared_inbox.freezed.dart b/lib/features/sharing/domain/shared_inbox.freezed.dart new file mode 100644 index 0000000..49d9f01 --- /dev/null +++ b/lib/features/sharing/domain/shared_inbox.freezed.dart @@ -0,0 +1,496 @@ +// coverage:ignore-file +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'shared_inbox.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +T _$identity(T value) => value; + +final _privateConstructorUsedError = UnsupportedError( + 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#adding-getters-and-methods-to-our-models', +); + +SharedItem _$SharedItemFromJson(Map json) { + return _SharedItem.fromJson(json); +} + +/// @nodoc +mixin _$SharedItem { + String get path => throw _privateConstructorUsedError; + String get type => throw _privateConstructorUsedError; + String? get message => throw _privateConstructorUsedError; + + /// Serializes this SharedItem to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of SharedItem + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $SharedItemCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SharedItemCopyWith<$Res> { + factory $SharedItemCopyWith( + SharedItem value, + $Res Function(SharedItem) then, + ) = _$SharedItemCopyWithImpl<$Res, SharedItem>; + @useResult + $Res call({String path, String type, String? message}); +} + +/// @nodoc +class _$SharedItemCopyWithImpl<$Res, $Val extends SharedItem> + implements $SharedItemCopyWith<$Res> { + _$SharedItemCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of SharedItem + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? path = null, + Object? type = null, + Object? message = freezed, + }) { + return _then( + _value.copyWith( + path: null == path + ? _value.path + : path // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + message: freezed == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String?, + ) + as $Val, + ); + } +} + +/// @nodoc +abstract class _$$SharedItemImplCopyWith<$Res> + implements $SharedItemCopyWith<$Res> { + factory _$$SharedItemImplCopyWith( + _$SharedItemImpl value, + $Res Function(_$SharedItemImpl) then, + ) = __$$SharedItemImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({String path, String type, String? message}); +} + +/// @nodoc +class __$$SharedItemImplCopyWithImpl<$Res> + extends _$SharedItemCopyWithImpl<$Res, _$SharedItemImpl> + implements _$$SharedItemImplCopyWith<$Res> { + __$$SharedItemImplCopyWithImpl( + _$SharedItemImpl _value, + $Res Function(_$SharedItemImpl) _then, + ) : super(_value, _then); + + /// Create a copy of SharedItem + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? path = null, + Object? type = null, + Object? message = freezed, + }) { + return _then( + _$SharedItemImpl( + path: null == path + ? _value.path + : path // ignore: cast_nullable_to_non_nullable + as String, + type: null == type + ? _value.type + : type // ignore: cast_nullable_to_non_nullable + as String, + message: freezed == message + ? _value.message + : message // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class _$SharedItemImpl implements _SharedItem { + const _$SharedItemImpl({ + required this.path, + required this.type, + this.message, + }); + + factory _$SharedItemImpl.fromJson(Map json) => + _$$SharedItemImplFromJson(json); + + @override + final String path; + @override + final String type; + @override + final String? message; + + @override + String toString() { + return 'SharedItem(path: $path, type: $type, message: $message)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SharedItemImpl && + (identical(other.path, path) || other.path == path) && + (identical(other.type, type) || other.type == type) && + (identical(other.message, message) || other.message == message)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash(runtimeType, path, type, message); + + /// Create a copy of SharedItem + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SharedItemImplCopyWith<_$SharedItemImpl> get copyWith => + __$$SharedItemImplCopyWithImpl<_$SharedItemImpl>(this, _$identity); + + @override + Map toJson() { + return _$$SharedItemImplToJson(this); + } +} + +abstract class _SharedItem implements SharedItem { + const factory _SharedItem({ + required final String path, + required final String type, + final String? message, + }) = _$SharedItemImpl; + + factory _SharedItem.fromJson(Map json) = + _$SharedItemImpl.fromJson; + + @override + String get path; + @override + String get type; + @override + String? get message; + + /// Create a copy of SharedItem + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SharedItemImplCopyWith<_$SharedItemImpl> get copyWith => + throw _privateConstructorUsedError; +} + +SharedInbox _$SharedInboxFromJson(Map json) { + return _SharedInbox.fromJson(json); +} + +/// @nodoc +mixin _$SharedInbox { + List get items => throw _privateConstructorUsedError; + bool get importing => throw _privateConstructorUsedError; + bool get failed => throw _privateConstructorUsedError; + int get delivery => throw _privateConstructorUsedError; + String? get clipboardText => throw _privateConstructorUsedError; + String? get clipboardUrl => throw _privateConstructorUsedError; + + /// Serializes this SharedInbox to a JSON map. + Map toJson() => throw _privateConstructorUsedError; + + /// Create a copy of SharedInbox + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + $SharedInboxCopyWith get copyWith => + throw _privateConstructorUsedError; +} + +/// @nodoc +abstract class $SharedInboxCopyWith<$Res> { + factory $SharedInboxCopyWith( + SharedInbox value, + $Res Function(SharedInbox) then, + ) = _$SharedInboxCopyWithImpl<$Res, SharedInbox>; + @useResult + $Res call({ + List items, + bool importing, + bool failed, + int delivery, + String? clipboardText, + String? clipboardUrl, + }); +} + +/// @nodoc +class _$SharedInboxCopyWithImpl<$Res, $Val extends SharedInbox> + implements $SharedInboxCopyWith<$Res> { + _$SharedInboxCopyWithImpl(this._value, this._then); + + // ignore: unused_field + final $Val _value; + // ignore: unused_field + final $Res Function($Val) _then; + + /// Create a copy of SharedInbox + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? items = null, + Object? importing = null, + Object? failed = null, + Object? delivery = null, + Object? clipboardText = freezed, + Object? clipboardUrl = freezed, + }) { + return _then( + _value.copyWith( + items: null == items + ? _value.items + : items // ignore: cast_nullable_to_non_nullable + as List, + importing: null == importing + ? _value.importing + : importing // ignore: cast_nullable_to_non_nullable + as bool, + failed: null == failed + ? _value.failed + : failed // ignore: cast_nullable_to_non_nullable + as bool, + delivery: null == delivery + ? _value.delivery + : delivery // ignore: cast_nullable_to_non_nullable + as int, + clipboardText: freezed == clipboardText + ? _value.clipboardText + : clipboardText // ignore: cast_nullable_to_non_nullable + as String?, + clipboardUrl: freezed == clipboardUrl + ? _value.clipboardUrl + : clipboardUrl // ignore: cast_nullable_to_non_nullable + as String?, + ) + as $Val, + ); + } +} + +/// @nodoc +abstract class _$$SharedInboxImplCopyWith<$Res> + implements $SharedInboxCopyWith<$Res> { + factory _$$SharedInboxImplCopyWith( + _$SharedInboxImpl value, + $Res Function(_$SharedInboxImpl) then, + ) = __$$SharedInboxImplCopyWithImpl<$Res>; + @override + @useResult + $Res call({ + List items, + bool importing, + bool failed, + int delivery, + String? clipboardText, + String? clipboardUrl, + }); +} + +/// @nodoc +class __$$SharedInboxImplCopyWithImpl<$Res> + extends _$SharedInboxCopyWithImpl<$Res, _$SharedInboxImpl> + implements _$$SharedInboxImplCopyWith<$Res> { + __$$SharedInboxImplCopyWithImpl( + _$SharedInboxImpl _value, + $Res Function(_$SharedInboxImpl) _then, + ) : super(_value, _then); + + /// Create a copy of SharedInbox + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? items = null, + Object? importing = null, + Object? failed = null, + Object? delivery = null, + Object? clipboardText = freezed, + Object? clipboardUrl = freezed, + }) { + return _then( + _$SharedInboxImpl( + items: null == items + ? _value._items + : items // ignore: cast_nullable_to_non_nullable + as List, + importing: null == importing + ? _value.importing + : importing // ignore: cast_nullable_to_non_nullable + as bool, + failed: null == failed + ? _value.failed + : failed // ignore: cast_nullable_to_non_nullable + as bool, + delivery: null == delivery + ? _value.delivery + : delivery // ignore: cast_nullable_to_non_nullable + as int, + clipboardText: freezed == clipboardText + ? _value.clipboardText + : clipboardText // ignore: cast_nullable_to_non_nullable + as String?, + clipboardUrl: freezed == clipboardUrl + ? _value.clipboardUrl + : clipboardUrl // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class _$SharedInboxImpl implements _SharedInbox { + const _$SharedInboxImpl({ + final List items = const [], + this.importing = false, + this.failed = false, + this.delivery = 0, + this.clipboardText, + this.clipboardUrl, + }) : _items = items; + + factory _$SharedInboxImpl.fromJson(Map json) => + _$$SharedInboxImplFromJson(json); + + final List _items; + @override + @JsonKey() + List get items { + if (_items is EqualUnmodifiableListView) return _items; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_items); + } + + @override + @JsonKey() + final bool importing; + @override + @JsonKey() + final bool failed; + @override + @JsonKey() + final int delivery; + @override + final String? clipboardText; + @override + final String? clipboardUrl; + + @override + String toString() { + return 'SharedInbox(items: $items, importing: $importing, failed: $failed, delivery: $delivery, clipboardText: $clipboardText, clipboardUrl: $clipboardUrl)'; + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _$SharedInboxImpl && + const DeepCollectionEquality().equals(other._items, _items) && + (identical(other.importing, importing) || + other.importing == importing) && + (identical(other.failed, failed) || other.failed == failed) && + (identical(other.delivery, delivery) || + other.delivery == delivery) && + (identical(other.clipboardText, clipboardText) || + other.clipboardText == clipboardText) && + (identical(other.clipboardUrl, clipboardUrl) || + other.clipboardUrl == clipboardUrl)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode => Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_items), + importing, + failed, + delivery, + clipboardText, + clipboardUrl, + ); + + /// Create a copy of SharedInbox + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @override + @pragma('vm:prefer-inline') + _$$SharedInboxImplCopyWith<_$SharedInboxImpl> get copyWith => + __$$SharedInboxImplCopyWithImpl<_$SharedInboxImpl>(this, _$identity); + + @override + Map toJson() { + return _$$SharedInboxImplToJson(this); + } +} + +abstract class _SharedInbox implements SharedInbox { + const factory _SharedInbox({ + final List items, + final bool importing, + final bool failed, + final int delivery, + final String? clipboardText, + final String? clipboardUrl, + }) = _$SharedInboxImpl; + + factory _SharedInbox.fromJson(Map json) = + _$SharedInboxImpl.fromJson; + + @override + List get items; + @override + bool get importing; + @override + bool get failed; + @override + int get delivery; + @override + String? get clipboardText; + @override + String? get clipboardUrl; + + /// Create a copy of SharedInbox + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + _$$SharedInboxImplCopyWith<_$SharedInboxImpl> get copyWith => + throw _privateConstructorUsedError; +} diff --git a/lib/features/sharing/domain/shared_inbox.g.dart b/lib/features/sharing/domain/shared_inbox.g.dart new file mode 100644 index 0000000..47b9413 --- /dev/null +++ b/lib/features/sharing/domain/shared_inbox.g.dart @@ -0,0 +1,45 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'shared_inbox.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_$SharedItemImpl _$$SharedItemImplFromJson(Map json) => + _$SharedItemImpl( + path: json['path'] as String, + type: json['type'] as String, + message: json['message'] as String?, + ); + +Map _$$SharedItemImplToJson(_$SharedItemImpl instance) => + { + 'path': instance.path, + 'type': instance.type, + 'message': instance.message, + }; + +_$SharedInboxImpl _$$SharedInboxImplFromJson(Map json) => + _$SharedInboxImpl( + items: + (json['items'] as List?) + ?.map((e) => SharedItem.fromJson(e as Map)) + .toList() ?? + const [], + importing: json['importing'] as bool? ?? false, + failed: json['failed'] as bool? ?? false, + delivery: (json['delivery'] as num?)?.toInt() ?? 0, + clipboardText: json['clipboardText'] as String?, + clipboardUrl: json['clipboardUrl'] as String?, + ); + +Map _$$SharedInboxImplToJson(_$SharedInboxImpl instance) => + { + 'items': instance.items, + 'importing': instance.importing, + 'failed': instance.failed, + 'delivery': instance.delivery, + 'clipboardText': instance.clipboardText, + 'clipboardUrl': instance.clipboardUrl, + }; diff --git a/lib/features/sharing/presentation/received_share_page.dart b/lib/features/sharing/presentation/received_share_page.dart new file mode 100644 index 0000000..38da686 --- /dev/null +++ b/lib/features/sharing/presentation/received_share_page.dart @@ -0,0 +1,100 @@ +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:flutter/services.dart'; +import 'package:material_ui/material_ui.dart' show SelectableText; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'share_thumbnail.dart'; +import '../../../core/widgets/app_page_scaffold.dart'; +import '../../../l10n/app_localizations.dart'; +import 'sharing_controller.dart'; + +class ReceivedSharePage extends ConsumerWidget { + const ReceivedSharePage({super.key}); + Future _open(BuildContext context, WidgetRef ref, String path) async { + final opened = await ref + .read(sharingControllerProvider.notifier) + .open(path); + if (!opened && context.mounted) { + final l10n = AppLocalizations.of(context); + await showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + content: Text(l10n.filesOpenFailed), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.pop(context), + child: Text(l10n.commonConfirm), + ), + ], + ), + ); + } + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final inbox = ref.watch(sharingControllerProvider); + final l10n = AppLocalizations.of(context); + return AppPageScaffold( + navigationBar: CupertinoNavigationBar( + middle: Text(l10n.shareReceivedTitle), + ), + child: SafeArea( + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + Text(l10n.shareSavedHint), + if (inbox.importing) + const Padding( + padding: EdgeInsets.all(16), + child: CupertinoActivityIndicator(), + ), + if (inbox.failed) + Text( + l10n.shareReceiveFailed, + style: const TextStyle(color: CupertinoColors.systemRed), + ), + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final item in inbox.items.reversed) + Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (item.type == 'image') shareThumbnail(item.path), + if (item.type == 'file' || + item.type == 'video' || + item.type == 'image') + Text( + Uri.file(item.path).pathSegments.last, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + if (item.type == 'text' || item.type == 'url') + SelectableText(item.path), + if (item.type != 'text' && item.type != 'url') + CupertinoButton( + onPressed: () => _open(context, ref, item.path), + child: Text(l10n.shareOpen), + ), + if (item.message?.isNotEmpty == true) + SelectableText(item.message!), + if (item.type == 'text' || item.type == 'url') + CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () => Clipboard.setData( + ClipboardData(text: item.path), + ), + child: Text(l10n.shareCopy), + ), + ], + ), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/sharing/presentation/share_receiver.dart b/lib/features/sharing/presentation/share_receiver.dart new file mode 100644 index 0000000..e4daa83 --- /dev/null +++ b/lib/features/sharing/presentation/share_receiver.dart @@ -0,0 +1,152 @@ +import 'package:cupertino_ui/cupertino_ui.dart'; +import '../../../l10n/app_localizations.dart'; +import 'package:go_router/go_router.dart'; +import 'sharing_controller.dart'; + +class ShareReceiver extends StatefulWidget { + const ShareReceiver({super.key, required this.router, required this.child}); + final GoRouter router; + final Widget child; + @override + State createState() => _ShareReceiverState(); +} + +class _ShareReceiverState extends State + with WidgetsBindingObserver { + String get _currentPath => + widget.router.routerDelegate.currentConfiguration.isEmpty + ? widget.router.routeInformationProvider.value.uri.path + : widget.router.state.uri.path; + bool _navigatePending = false; + bool _clipboardCheckPending = true; + bool _clipboardFrameScheduled = false; + bool _clipboardDialogOpen = false; + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + sharingContainer.listen( + sharingControllerProvider.select((value) => value.delivery), + (previous, next) { + _navigatePending = true; + _navigate(); + }, + ); + sharingContainer.listen( + sharingControllerProvider.select((value) => value.clipboardUrl), + (previous, next) { + if (next != null) _scheduleClipboard(); + }, + ); + widget.router.routerDelegate.addListener(_routeChanged); + _scheduleClipboard(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + _clipboardCheckPending = true; + _scheduleClipboard(); + } + } + + void _routeChanged() { + _navigate(); + _scheduleClipboard(); + } + + void _scheduleClipboard() { + if (_clipboardFrameScheduled || !mounted) return; + _clipboardFrameScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) async { + _clipboardFrameScheduled = false; + if (!mounted || + WidgetsBinding.instance.lifecycleState != AppLifecycleState.resumed || + _currentPath == '/splash') { + return; + } + if (_clipboardCheckPending) { + _clipboardCheckPending = false; + await sharingContainer + .read(sharingControllerProvider.notifier) + .checkClipboard(); + } + if (mounted) _showClipboardPrompt(); + }); + WidgetsBinding.instance.ensureVisualUpdate(); + } + + Future _showClipboardPrompt() async { + if (_clipboardDialogOpen || + !mounted || + WidgetsBinding.instance.lifecycleState != AppLifecycleState.resumed) { + return; + } + final state = sharingContainer.read(sharingControllerProvider); + final url = state.clipboardUrl; + final text = state.clipboardText; + final context = widget.router.routerDelegate.navigatorKey.currentContext; + if (url == null || text == null || context == null) return; + _clipboardDialogOpen = true; + final l10n = AppLocalizations.of(context); + try { + final accepted = await showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + title: Text(l10n.shareClipboardTitle), + content: Column( + children: [ + Text(l10n.shareClipboardQuestion), + const SizedBox(height: 12), + Text(text, maxLines: 5, overflow: TextOverflow.ellipsis), + ], + ), + actions: [ + CupertinoDialogAction( + onPressed: () => Navigator.pop(context, false), + child: Text(l10n.commonCancel), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: () => Navigator.pop(context, true), + child: Text(l10n.shareClipboardConfirm), + ), + ], + ), + ); + if (mounted && + sharingContainer.read(sharingControllerProvider).clipboardUrl == + url) { + sharingContainer + .read(sharingControllerProvider.notifier) + .resolveClipboard(share: accepted == true); + } + } finally { + _clipboardDialogOpen = false; + } + } + + void _navigate() { + if (!_navigatePending || !mounted || _currentPath == '/splash') { + return; + } + _navigatePending = false; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _currentPath != '/received-share') { + widget.router.push('/received-share'); + } + }); + WidgetsBinding.instance.ensureVisualUpdate(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + disposeSharingContainer(); + widget.router.routerDelegate.removeListener(_routeChanged); + super.dispose(); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/lib/features/sharing/presentation/share_thumbnail.dart b/lib/features/sharing/presentation/share_thumbnail.dart new file mode 100644 index 0000000..92b1ce7 --- /dev/null +++ b/lib/features/sharing/presentation/share_thumbnail.dart @@ -0,0 +1,2 @@ +export 'share_thumbnail_stub.dart' + if (dart.library.io) 'share_thumbnail_io.dart'; diff --git a/lib/features/sharing/presentation/share_thumbnail_io.dart b/lib/features/sharing/presentation/share_thumbnail_io.dart new file mode 100644 index 0000000..618b9db --- /dev/null +++ b/lib/features/sharing/presentation/share_thumbnail_io.dart @@ -0,0 +1,10 @@ +import 'dart:io'; +import 'package:flutter/widgets.dart'; + +Widget shareThumbnail(String path) => Image.file( + File(path), + height: 180, + fit: BoxFit.contain, + cacheWidth: 720, + errorBuilder: (_, _, _) => const SizedBox.shrink(), +); diff --git a/lib/features/sharing/presentation/share_thumbnail_stub.dart b/lib/features/sharing/presentation/share_thumbnail_stub.dart new file mode 100644 index 0000000..f8b4af4 --- /dev/null +++ b/lib/features/sharing/presentation/share_thumbnail_stub.dart @@ -0,0 +1,3 @@ +import 'package:flutter/widgets.dart'; + +Widget shareThumbnail(String path) => const SizedBox.shrink(); diff --git a/lib/features/sharing/presentation/sharing_controller.dart b/lib/features/sharing/presentation/sharing_controller.dart new file mode 100644 index 0000000..0d172f1 --- /dev/null +++ b/lib/features/sharing/presentation/sharing_controller.dart @@ -0,0 +1,190 @@ +import 'package:crypto/crypto.dart'; +import '../data/clipboard_repository.dart'; +import '../domain/douyin_share.dart'; +import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:receive_sharing_intent/receive_sharing_intent.dart'; +import '../data/share_storage.dart'; +import '../domain/shared_inbox.dart'; + +ProviderContainer? _sharingContainer; + +/// Local-phone inbox is independent of account caches. +ProviderContainer get sharingContainer => + _sharingContainer ??= ProviderContainer(); +void disposeSharingContainer() { + _sharingContainer?.dispose(); + _sharingContainer = null; +} + +final clipboardRepositoryProvider = Provider((ref) => ClipboardRepository()); + +final sharingControllerProvider = + NotifierProvider.autoDispose( + SharingController.new, + ); + +/// Kept alive by ShareReceiver, independent of account-scoped business providers. +class SharingController extends AutoDisposeNotifier { + Future _pending = Future.value(); + Future _initialShareReady = Future.value(); + String? _lastBatch; + DateTime? _lastReceived; + bool _disposed = false; + bool _opening = false; + bool _checkingClipboard = false; + bool _mobile = false; + final Set _handledClipboard = {}; + + Future checkClipboard() async { + if (!_mobile || + _disposed || + _checkingClipboard || + state.clipboardUrl != null || + state.importing) { + return; + } + _checkingClipboard = true; + try { + // Finish loading saved shares before checking for an already imported URL. + await _initialShareReady; + await _pending; + if (_disposed || state.importing) return; + final text = await ref.read(clipboardRepositoryProvider).readText(); + if (_disposed || text == null || text.length > 20000) return; + final url = findDouyinShareUrl(text); + if (url == null || state.importing || state.clipboardUrl != null) return; + final fingerprint = sha256.convert(utf8.encode(url)).toString(); + final repository = ref.read(clipboardRepositoryProvider); + if (_handledClipboard.contains(fingerprint) || + repository.lastHandledFingerprint == fingerprint || + state.items.any( + (item) => + (item.type == 'url' || item.type == 'text') && + findDouyinShareUrl(item.path) == url, + )) { + return; + } + state = state.copyWith(clipboardText: text.trim(), clipboardUrl: url); + } catch (_) { + // Clipboard denial/unavailability must not interrupt returning to the app. + } finally { + _checkingClipboard = false; + } + } + + void resolveClipboard({required bool share}) { + final url = state.clipboardUrl; + final text = state.clipboardText; + if (url == null || text == null) return; + final fingerprint = sha256.convert(utf8.encode(url)).toString(); + _handledClipboard.add(fingerprint); + // Keep only hashes, never persist unrelated clipboard content. + if (_handledClipboard.length > 64) { + _handledClipboard.remove(_handledClipboard.first); + } + ref.read(clipboardRepositoryProvider).markHandled(fingerprint); + state = state.copyWith(clipboardText: null, clipboardUrl: null); + if (share) { + receive([ + SharedMediaFile(path: url, type: SharedMediaType.url, message: text), + ]); + } + } + + Future open(String path) async { + if (_opening) return true; + _opening = true; + try { + return await openSharedItem(path); + } finally { + _opening = false; + } + } + + @override + SharedInbox build() { + if (kIsWeb || + (defaultTargetPlatform != TargetPlatform.android && + defaultTargetPlatform != TargetPlatform.iOS)) { + return const SharedInbox(); + } + _mobile = true; + _pending = loadSharedItems().then( + (items) { + if (!_disposed) { + state = state.copyWith( + items: items + .map((item) => SharedItem.fromJson(item.toMap())) + .toList(), + ); + } + }, + onError: (Object error) { + if (!_disposed) state = state.copyWith(failed: true); + }, + ); + final subscription = ReceiveSharingIntent.instance.getMediaStream().listen( + receive, + onError: (Object error) => _error(), + ); + _initialShareReady = ReceiveSharingIntent.instance.getInitialMedia().then( + receive, + onError: (Object error) => _error(), + ); + ref.onDispose(() { + _disposed = true; + subscription.cancel(); + }); + return const SharedInbox(); + } + + void _error() { + if (!_disposed) { + state = state.copyWith(failed: true, delivery: state.delivery + 1); + } + } + + void receive(List items) { + if (_disposed || items.isEmpty) return; + final signature = jsonEncode(items.map((item) => item.toMap()).toList()); + final now = DateTime.now(); + if (_lastBatch == signature && + _lastReceived != null && + now.difference(_lastReceived!).inSeconds < 2) { + return; + } + _lastBatch = signature; + _lastReceived = now; + _pending = _pending.then((_) async { + if (_disposed) return; + state = state.copyWith( + importing: true, + failed: false, + delivery: state.delivery + 1, + ); + try { + final saved = await saveSharedItems(items); + if (!_disposed) { + state = state.copyWith( + items: [ + ...state.items, + ...saved.map((item) => SharedItem.fromJson(item.toMap())), + ], + ); + } + } catch (_) { + if (!_disposed) state = state.copyWith(failed: true); + } finally { + if (!_disposed) state = state.copyWith(importing: false); + try { + await ReceiveSharingIntent.instance.reset(); + } catch (_) { + /* Do not block subsequent batches. */ + } + } + }); + } +} diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 0c1be1c..2a91349 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2317,6 +2317,108 @@ abstract class AppLocalizations { /// In zh, this message translates to: /// **'头像仅支持JPEG或PNG图片'** String get profileAvatarUnsupported; + + /// No description provided for @filesTitle. + /// + /// In zh, this message translates to: + /// **'文件管理'** + String get filesTitle; + + /// No description provided for @filesStorage. + /// + /// In zh, this message translates to: + /// **'本机共享存储'** + String get filesStorage; + + /// No description provided for @filesPermission. + /// + /// In zh, this message translates to: + /// **'请允许访问本机共享存储。Android 11 及以上请在系统设置中允许“所有文件访问”。'** + String get filesPermission; + + /// No description provided for @filesAuthorize. + /// + /// In zh, this message translates to: + /// **'授权访问'** + String get filesAuthorize; + + /// No description provided for @filesUnreadable. + /// + /// In zh, this message translates to: + /// **'无法读取此目录,可能受到系统保护。返回上一级或下拉重试。'** + String get filesUnreadable; + + /// No description provided for @filesEmpty. + /// + /// In zh, this message translates to: + /// **'此目录为空'** + String get filesEmpty; + + /// No description provided for @filesChooseFolder. + /// + /// In zh, this message translates to: + /// **'选择目录'** + String get filesChooseFolder; + + /// No description provided for @filesIosPermission. + /// + /// In zh, this message translates to: + /// **'请选择并授权一个文件夹,可访问“我的 iPhone”、iCloud Drive 或其他文件提供方中的目录。'** + String get filesIosPermission; + + /// No description provided for @filesOpenFailed. + /// + /// In zh, this message translates to: + /// **'无法打开文件,请确认访问权限,并安装支持此文件类型的应用。'** + String get filesOpenFailed; + + /// No description provided for @shareReceivedTitle. + /// + /// In zh, this message translates to: + /// **'收到的分享'** + String get shareReceivedTitle; + + /// No description provided for @shareSavedHint. + /// + /// In zh, this message translates to: + /// **'分享内容已保存在本机,可在文件页右上角的收件箱查看。'** + String get shareSavedHint; + + /// No description provided for @shareReceiveFailed. + /// + /// In zh, this message translates to: + /// **'部分内容接收失败,请从来源应用重新分享。'** + String get shareReceiveFailed; + + /// No description provided for @shareCopy. + /// + /// In zh, this message translates to: + /// **'复制'** + String get shareCopy; + + /// No description provided for @shareOpen. + /// + /// In zh, this message translates to: + /// **'打开'** + String get shareOpen; + + /// No description provided for @shareClipboardTitle. + /// + /// In zh, this message translates to: + /// **'发现抖音分享'** + String get shareClipboardTitle; + + /// No description provided for @shareClipboardQuestion. + /// + /// In zh, this message translates to: + /// **'检测到剪贴板中的抖音内容,是否分享到同同家庭关怀?'** + String get shareClipboardQuestion; + + /// No description provided for @shareClipboardConfirm. + /// + /// In zh, this message translates to: + /// **'分享'** + String get shareClipboardConfirm; } class _AppLocalizationsDelegate diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 46e7604..db785c9 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1160,4 +1160,62 @@ class AppLocalizationsEn extends AppLocalizations { @override String get profileAvatarUnsupported => 'Choose a JPEG or PNG image'; + + @override + String get filesTitle => 'Files'; + + @override + String get filesStorage => 'Shared storage on this device'; + + @override + String get filesPermission => + 'Allow access to shared storage on this device. On Android 11 or later, enable all files access in Settings.'; + + @override + String get filesAuthorize => 'Grant access'; + + @override + String get filesUnreadable => + 'Unable to read this folder. It may be protected. Go back or pull down to retry.'; + + @override + String get filesEmpty => 'This folder is empty'; + + @override + String get filesChooseFolder => 'Choose folder'; + + @override + String get filesIosPermission => + 'Choose a folder to grant access. Browse folders in On My iPhone, iCloud Drive, or other file providers.'; + + @override + String get filesOpenFailed => + 'Unable to open this file. Check access permissions and install an app that supports this file type.'; + + @override + String get shareReceivedTitle => 'Received shares'; + + @override + String get shareSavedHint => + 'Shared content is saved on this phone. Open the inbox at the top right of Files to view it again.'; + + @override + String get shareReceiveFailed => + 'Could not receive some content. Please share it again from the source app.'; + + @override + String get shareCopy => 'Copy'; + + @override + String get shareOpen => 'Open'; + + @override + String get shareClipboardTitle => 'Douyin share found'; + + @override + String get shareClipboardQuestion => + 'Share the Douyin content from your clipboard to Family Care?'; + + @override + String get shareClipboardConfirm => 'Share'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index f31bcee..d3003de 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1133,4 +1133,56 @@ class AppLocalizationsZh extends AppLocalizations { @override String get profileAvatarUnsupported => '头像仅支持JPEG或PNG图片'; + + @override + String get filesTitle => '文件管理'; + + @override + String get filesStorage => '本机共享存储'; + + @override + String get filesPermission => '请允许访问本机共享存储。Android 11 及以上请在系统设置中允许“所有文件访问”。'; + + @override + String get filesAuthorize => '授权访问'; + + @override + String get filesUnreadable => '无法读取此目录,可能受到系统保护。返回上一级或下拉重试。'; + + @override + String get filesEmpty => '此目录为空'; + + @override + String get filesChooseFolder => '选择目录'; + + @override + String get filesIosPermission => + '请选择并授权一个文件夹,可访问“我的 iPhone”、iCloud Drive 或其他文件提供方中的目录。'; + + @override + String get filesOpenFailed => '无法打开文件,请确认访问权限,并安装支持此文件类型的应用。'; + + @override + String get shareReceivedTitle => '收到的分享'; + + @override + String get shareSavedHint => '分享内容已保存在本机,可在文件页右上角的收件箱查看。'; + + @override + String get shareReceiveFailed => '部分内容接收失败,请从来源应用重新分享。'; + + @override + String get shareCopy => '复制'; + + @override + String get shareOpen => '打开'; + + @override + String get shareClipboardTitle => '发现抖音分享'; + + @override + String get shareClipboardQuestion => '检测到剪贴板中的抖音内容,是否分享到同同家庭关怀?'; + + @override + String get shareClipboardConfirm => '分享'; } diff --git a/lib/l10n/intl_en.arb b/lib/l10n/intl_en.arb index b629c21..c40a2ba 100644 --- a/lib/l10n/intl_en.arb +++ b/lib/l10n/intl_en.arb @@ -381,5 +381,22 @@ "profileNicknameInvalid": "Enter a nickname with 1–64 characters", "profileSignatureInvalid": "Your signature must be 200 characters or fewer", "profileAvatarTooLarge": "Choose an avatar no larger than 5 MB", - "profileAvatarUnsupported": "Choose a JPEG or PNG image" + "profileAvatarUnsupported": "Choose a JPEG or PNG image", + "filesTitle": "Files", + "filesStorage": "Shared storage on this device", + "filesPermission": "Allow access to shared storage on this device. On Android 11 or later, enable all files access in Settings.", + "filesAuthorize": "Grant access", + "filesUnreadable": "Unable to read this folder. It may be protected. Go back or pull down to retry.", + "filesEmpty": "This folder is empty", + "filesChooseFolder": "Choose folder", + "filesIosPermission": "Choose a folder to grant access. Browse folders in On My iPhone, iCloud Drive, or other file providers.", + "filesOpenFailed": "Unable to open this file. Check access permissions and install an app that supports this file type.", + "shareReceivedTitle": "Received shares", + "shareSavedHint": "Shared content is saved on this phone. Open the inbox at the top right of Files to view it again.", + "shareReceiveFailed": "Could not receive some content. Please share it again from the source app.", + "shareCopy": "Copy", + "shareOpen": "Open", + "shareClipboardTitle": "Douyin share found", + "shareClipboardQuestion": "Share the Douyin content from your clipboard to Family Care?", + "shareClipboardConfirm": "Share" } diff --git a/lib/l10n/intl_zh.arb b/lib/l10n/intl_zh.arb index 941b3ca..f5ec8ba 100644 --- a/lib/l10n/intl_zh.arb +++ b/lib/l10n/intl_zh.arb @@ -1494,5 +1494,22 @@ "profileNicknameInvalid": "昵称须为1至64个字符", "profileSignatureInvalid": "个性签名不能超过200个字符", "profileAvatarTooLarge": "请选择不超过5MB的头像图片", - "profileAvatarUnsupported": "头像仅支持JPEG或PNG图片" + "profileAvatarUnsupported": "头像仅支持JPEG或PNG图片", + "filesTitle": "文件管理", + "filesStorage": "本机共享存储", + "filesPermission": "请允许访问本机共享存储。Android 11 及以上请在系统设置中允许“所有文件访问”。", + "filesAuthorize": "授权访问", + "filesUnreadable": "无法读取此目录,可能受到系统保护。返回上一级或下拉重试。", + "filesEmpty": "此目录为空", + "filesChooseFolder": "选择目录", + "filesIosPermission": "请选择并授权一个文件夹,可访问“我的 iPhone”、iCloud Drive 或其他文件提供方中的目录。", + "filesOpenFailed": "无法打开文件,请确认访问权限,并安装支持此文件类型的应用。", + "shareReceivedTitle": "收到的分享", + "shareSavedHint": "分享内容已保存在本机,可在文件页右上角的收件箱查看。", + "shareReceiveFailed": "部分内容接收失败,请从来源应用重新分享。", + "shareCopy": "复制", + "shareOpen": "打开", + "shareClipboardTitle": "发现抖音分享", + "shareClipboardQuestion": "检测到剪贴板中的抖音内容,是否分享到同同家庭关怀?", + "shareClipboardConfirm": "分享" } diff --git a/pubspec.lock b/pubspec.lock index 85b8ea7..c192dfc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1053,6 +1053,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.6.0" + receive_sharing_intent: + dependency: "direct main" + description: + name: receive_sharing_intent + sha256: "72f229a38f2910029c11d840770c173b27072e348ef3376130b37514bc4556f6" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.9.0" record_use: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 60d4e94..f4396bd 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -123,6 +123,8 @@ dependencies: # 统一处理 Android(6.0~12 READ_EXTERNAL_STORAGE / 13+ READ_MEDIA_IMAGES、READ_MEDIA_VIDEO) # 与 iOS(PhotoKit,含 limited 授权状态)的相册权限与读取。 photo_manager: ^3.6.0 + # Keep in sync with the versioned Swift package reference in the iOS project. + receive_sharing_intent: 1.9.0 dev_dependencies: flutter_test: @@ -145,6 +147,8 @@ dev_dependencies: # The following section is specific to Flutter packages. flutter: + config: + enable-swift-package-manager: true # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in diff --git a/test/clipboard_prompt_test.dart b/test/clipboard_prompt_test.dart new file mode 100644 index 0000000..0abde8d --- /dev/null +++ b/test/clipboard_prompt_test.dart @@ -0,0 +1,130 @@ +import 'dart:io'; +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +// ignore: depend_on_referenced_packages +import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; +import 'package:receive_sharing_intent/receive_sharing_intent.dart'; +import 'package:ttstd_family_care/app/app.dart'; +import 'package:ttstd_family_care/features/sharing/presentation/sharing_controller.dart'; + +class _Paths extends PathProviderPlatform { + _Paths(this.path); + final String path; + @override + Future getApplicationSupportPath() async => path; +} + +void main() { + late Directory temp; + setUp(() async { + temp = await Directory.systemTemp.createTemp('ttstd_prompt_'); + }); + tearDown(() async { + await temp.delete(recursive: true); + }); + for (final accept in [false, true]) { + testWidgets( + 'resume prompts once and ${accept ? 'confirmation navigates' : 'cancel stays on the page'}', + (tester) async { + final directory = temp; + final originalPaths = PathProviderPlatform.instance; + final originalPlugin = ReceiveSharingIntent.instance; + PathProviderPlatform.instance = _Paths(directory.path); + ReceiveSharingIntent.setMockValues( + initialMedia: [], + mediaStream: const Stream.empty(), + ); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + bool offer = false; + final url = + 'https://v.douyin.com/PromptTest${accept ? 'Accept' : 'Cancel'}/'; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.getData') { + return {'text': offer ? '复制打开抖音 $url' : 'ordinary text'}; + } + return null; + }, + ); + final router = GoRouter( + initialLocation: '/home', + routes: [ + GoRoute( + path: '/home', + builder: (_, _) => + const CupertinoPageScaffold(child: Text('Home')), + ), + GoRoute( + path: '/received-share', + builder: (_, _) => + const CupertinoPageScaffold(child: Text('Inbox')), + ), + ], + ); + Future settleNativeWork() async { + await tester.runAsync(() async { + await Future.delayed(const Duration(milliseconds: 100)); + }); + await tester.pumpAndSettle(); + } + + try { + tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.resumed, + ); + await tester.pumpWidget(buildApp(router)); + await settleNativeWork(); + expect(find.byType(CupertinoAlertDialog), findsNothing); + offer = true; + tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.paused, + ); + await tester.pump(); + expect(find.byType(CupertinoAlertDialog), findsNothing); + tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.resumed, + ); + await tester.pump(); + await settleNativeWork(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect( + sharingContainer.read(sharingControllerProvider).items, + isEmpty, + ); + final actions = find.byType(CupertinoDialogAction); + await tester.tap(accept ? actions.last : actions.first); + await tester.pumpAndSettle(); + await settleNativeWork(); + if (accept) { + for (var i = 0; i < 10; i++) { + await settleNativeWork(); + if (!sharingContainer.read(sharingControllerProvider).importing && + router.state.uri.path == '/received-share') { + break; + } + } + } + expect(router.state.uri.path, accept ? '/received-share' : '/home'); + expect( + sharingContainer.read(sharingControllerProvider).items.length, + accept ? 1 : 0, + ); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + router.dispose(); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); + PathProviderPlatform.instance = originalPaths; + ReceiveSharingIntent.instance = originalPlugin; + debugDefaultTargetPlatformOverride = null; + } + }, + ); + } +} diff --git a/test/clipboard_share_test.dart b/test/clipboard_share_test.dart new file mode 100644 index 0000000..bc3a0c5 --- /dev/null +++ b/test/clipboard_share_test.dart @@ -0,0 +1,187 @@ +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +// ignore: depend_on_referenced_packages +import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; +import 'package:receive_sharing_intent/receive_sharing_intent.dart'; +import 'package:ttstd_family_care/features/sharing/data/clipboard_repository.dart'; +import 'package:ttstd_family_care/features/sharing/data/share_storage.dart'; +import 'package:ttstd_family_care/features/sharing/domain/douyin_share.dart'; +import 'package:ttstd_family_care/features/sharing/presentation/sharing_controller.dart'; + +const sample = + r'6.17 复制打开抖音,看看【seo的作品】冒个泡○。○゜。 # 卖萌可耻 https\://v.douyin.com/hurvskFQ1F4/ mQK:/ 11/20 y@g.bN :6pm'; +const canonical = 'https://v.douyin.com/hurvskFQ1F4/'; + +class _Clipboard extends ClipboardRepository { + String? text = sample; + String? handled; + bool denied = false; + @override + Future readText() async { + if (denied) throw StateError('clipboard denied'); + return text; + } + + @override + String? get lastHandledFingerprint => handled; + @override + void markHandled(String fingerprint) => handled = fingerprint; +} + +class _Paths extends PathProviderPlatform { + _Paths(this.path); + final String path; + @override + Future getApplicationSupportPath() async => path; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + test('extracts the supplied share and normalizes escaped URL characters', () { + expect(findDouyinShareUrl(sample), canonical); + expect( + findDouyinShareUrl(r'https:\/\/v.douyin.com/hurvskFQ1F4/'), + canonical, + ); + }); + test('normalizes tracking text, schemes and numeric work links', () { + expect( + findDouyinShareUrl('http://v.douyin.com/Ab-12/?foo=bar。'), + 'https://v.douyin.com/Ab-12/', + ); + expect( + findDouyinShareUrl( + '分享 https://www.douyin.com/video/123456789?tracking=1', + ), + 'https://www.douyin.com/video/123456789/', + ); + expect( + findDouyinShareUrl('https://www.iesdouyin.com/share/video/123456789/'), + 'https://www.iesdouyin.com/share/video/123456789/', + ); + }); + test('rejects ordinary clipboard text and spoofed domains', () { + for (final value in [ + '复制打开抖音,没有网址', + 'https://example.com/video/123', + 'https://v.douyin.com.evil.example/Abc/', + 'https://evil-douyin.com/video/123', + 'https://www.douyin.com/user/123', + 'https://v.douyin.com/Abc中文', + ]) { + expect(findDouyinShareUrl(value), isNull, reason: value); + } + }); + group('clipboard confirmation', () { + late Directory temp; + late PathProviderPlatform originalPaths; + late _Clipboard clipboard; + late ProviderContainer container; + final plugin = ReceiveSharingIntent.instance; + setUp(() async { + temp = await Directory.systemTemp.createTemp('ttstd_clipboard_'); + originalPaths = PathProviderPlatform.instance; + PathProviderPlatform.instance = _Paths(temp.path); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + ReceiveSharingIntent.setMockValues( + initialMedia: [], + mediaStream: const Stream.empty(), + ); + clipboard = _Clipboard(); + container = ProviderContainer( + overrides: [clipboardRepositoryProvider.overrideWithValue(clipboard)], + ); + container.listen(sharingControllerProvider, (_, _) {}); + }); + tearDown(() async { + container.dispose(); + PathProviderPlatform.instance = originalPaths; + ReceiveSharingIntent.instance = plugin; + debugDefaultTargetPlatformOverride = null; + await temp.delete(recursive: true); + }); + test( + 'cancel saves no content and the same URL does not prompt again', + () async { + final controller = container.read(sharingControllerProvider.notifier); + await controller.checkClipboard(); + expect( + container.read(sharingControllerProvider).clipboardUrl, + canonical, + ); + expect(await loadSharedItems(), isEmpty); + controller.resolveClipboard(share: false); + clipboard.text = '不同文案 $canonical?tracking=changed'; + await controller.checkClipboard(); + expect(container.read(sharingControllerProvider).clipboardUrl, isNull); + expect(await loadSharedItems(), isEmpty); + expect(clipboard.handled, isNot(contains('douyin'))); + }, + ); + test( + 'only confirmation imports the link and preserves the share caption', + () async { + final controller = container.read(sharingControllerProvider.notifier); + await controller.checkClipboard(); + controller.resolveClipboard(share: true); + for ( + var i = 0; + i < 200 && container.read(sharingControllerProvider).items.isEmpty; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + final state = container.read(sharingControllerProvider); + expect(state.items.single.path, canonical); + expect(state.items.single.message, sample); + expect(state.clipboardUrl, isNull); + expect((await loadSharedItems()).single.path, canonical); + }, + ); + test( + 'ordinary text, clipboard denial and already imported links stay quiet', + () async { + final controller = container.read(sharingControllerProvider.notifier); + clipboard.text = 'ordinary text'; + await controller.checkClipboard(); + expect(container.read(sharingControllerProvider).clipboardUrl, isNull); + clipboard.denied = true; + await controller.checkClipboard(); + expect(container.read(sharingControllerProvider).failed, isFalse); + clipboard.denied = false; + clipboard.text = sample; + controller.receive([ + SharedMediaFile(path: canonical, type: SharedMediaType.url), + ]); + for ( + var i = 0; + i < 200 && container.read(sharingControllerProvider).items.isEmpty; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + await controller.checkClipboard(); + expect(container.read(sharingControllerProvider).clipboardUrl, isNull); + }, + ); + test( + 'last handled fingerprint suppresses the prompt in a new app session', + () async { + final controller = container.read(sharingControllerProvider.notifier); + await controller.checkClipboard(); + controller.resolveClipboard(share: false); + container.dispose(); + container = ProviderContainer( + overrides: [clipboardRepositoryProvider.overrideWithValue(clipboard)], + ); + container.listen(sharingControllerProvider, (_, _) {}); + await container + .read(sharingControllerProvider.notifier) + .checkClipboard(); + expect(container.read(sharingControllerProvider).clipboardUrl, isNull); + }, + ); + }); +} diff --git a/test/sharing_test.dart b/test/sharing_test.dart new file mode 100644 index 0000000..5caa342 --- /dev/null +++ b/test/sharing_test.dart @@ -0,0 +1,118 @@ +import 'dart:async'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +// The test substitutes the platform interface already supplied by path_provider. +// ignore: depend_on_referenced_packages +import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; +import 'package:receive_sharing_intent/receive_sharing_intent.dart'; +import 'package:ttstd_family_care/features/sharing/data/share_storage.dart'; +import 'package:ttstd_family_care/features/sharing/presentation/sharing_controller.dart'; + +class _Paths extends PathProviderPlatform { + _Paths(this.path); + final String path; + @override + Future getApplicationSupportPath() async => path; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory temp; + late PathProviderPlatform originalPaths; + final originalPlugin = ReceiveSharingIntent.instance; + setUp(() async { + temp = await Directory.systemTemp.createTemp('ttstd_share_'); + originalPaths = PathProviderPlatform.instance; + PathProviderPlatform.instance = _Paths(temp.path); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + }); + tearDown(() async { + debugDefaultTargetPlatformOverride = null; + PathProviderPlatform.instance = originalPaths; + ReceiveSharingIntent.instance = originalPlugin; + await temp.delete(recursive: true); + }); + test( + 'files survive deletion of source and restore together with text', + () async { + final source = await File( + '${temp.path}/source.png', + ).writeAsBytes([1, 2, 3]); + final saved = await saveSharedItems([ + SharedMediaFile(path: source.path, type: SharedMediaType.image), + SharedMediaFile(path: 'https://example.com', type: SharedMediaType.url), + ]); + await source.delete(); + expect(await File(saved.first.path).readAsBytes(), [1, 2, 3]); + final loaded = await loadSharedItems(); + expect(loaded.map((e) => e.type), [ + SharedMediaType.image, + SharedMediaType.url, + ]); + expect(loaded.last.path, 'https://example.com'); + }, + ); + test('failed batch does not leave partial files in the inbox', () async { + final source = await File('${temp.path}/source.txt').writeAsString('test'); + await expectLater( + saveSharedItems([ + SharedMediaFile(path: source.path, type: SharedMediaType.file), + SharedMediaFile( + path: '${temp.path}/missing', + type: SharedMediaType.file, + ), + ]), + throwsA(isA()), + ); + expect(await loadSharedItems(), isEmpty); + expect(await Directory('${temp.path}/Received').list().toList(), isEmpty); + }); + test( + 'cold start, duplicate event and queued warm shares preserve batches', + () async { + final events = StreamController>(); + final cold = [SharedMediaFile(path: 'cold', type: SharedMediaType.text)]; + ReceiveSharingIntent.setMockValues( + initialMedia: cold, + mediaStream: events.stream, + ); + final container = ProviderContainer(); + final listener = container.listen(sharingControllerProvider, (_, _) {}); + Future waitUntil(bool Function() done) async { + for (var i = 0; i < 200 && !done(); i++) { + await Future.delayed(const Duration(milliseconds: 10)); + } + expect(done(), isTrue); + } + + try { + events.add(cold); + await waitUntil( + () => container.read(sharingControllerProvider).items.length == 1, + ); + events.add([ + SharedMediaFile(path: 'warm1', type: SharedMediaType.text), + ]); + events.add([ + SharedMediaFile(path: 'warm2', type: SharedMediaType.text), + ]); + await waitUntil( + () => + container.read(sharingControllerProvider).items.length == 3 && + !container.read(sharingControllerProvider).importing, + ); + expect( + container.read(sharingControllerProvider).items.map((e) => e.path), + ['cold', 'warm1', 'warm2'], + ); + expect(container.read(sharingControllerProvider).failed, isFalse); + } finally { + listener.close(); + container.dispose(); + await events.close(); + } + }, + ); +}