diff --git a/mobile/.gitignore b/mobile/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/mobile/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/mobile/.metadata b/mobile/.metadata new file mode 100644 index 0000000..9470a44 --- /dev/null +++ b/mobile/.metadata @@ -0,0 +1,33 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "44a626f4f0027bc38a46dc68aed5964b05a83c18" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 44a626f4f0027bc38a46dc68aed5964b05a83c18 + base_revision: 44a626f4f0027bc38a46dc68aed5964b05a83c18 + - platform: android + create_revision: 44a626f4f0027bc38a46dc68aed5964b05a83c18 + base_revision: 44a626f4f0027bc38a46dc68aed5964b05a83c18 + - platform: ios + create_revision: 44a626f4f0027bc38a46dc68aed5964b05a83c18 + base_revision: 44a626f4f0027bc38a46dc68aed5964b05a83c18 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/mobile/README.md b/mobile/README.md new file mode 100644 index 0000000..3715a24 --- /dev/null +++ b/mobile/README.md @@ -0,0 +1,33 @@ +# ImageFind Mobile + +ImageFind 的 Flutter Android / iOS 客户端。客户端只连接后端 `/api/v1`,不依赖或复用 Web 前端代码。 + +## 本地运行 + +```powershell +C:\Users\nanxun\Documents\flutter\bin\flutter.bat --no-version-check pub get +C:\Users\nanxun\Documents\flutter\bin\flutter.bat --no-version-check run +``` + +首次启动后填写已开启“直接 Web/API 访问”的 ImageFind 地址。局域网地址可以使用 HTTP,公网地址必须使用 HTTPS。 + +## 已实现 + +- 安全会话:服务发现、首次设置、登录、CSRF、加密凭据存储 +- 自适应界面:手机底栏、平板导航 Rail、宽屏双栏 +- 首页、搜索、资料库、人物、合集、个人与服务工作台 +- 文字搜索和图片 multipart 搜索 +- 原始 Range 播放、HLS 回退、进度同步、逐字稿和收藏时刻 +- 设备视频分块上传及已接收分块续传 +- 本机 `.part` Range 续传下载、Drift 状态持久化和离线播放 +- SSE 断线重连及核心 Riverpod 数据刷新 + +## 验证 + +```powershell +C:\Users\nanxun\Documents\flutter\bin\flutter.bat --no-version-check analyze +C:\Users\nanxun\Documents\flutter\bin\flutter.bat --no-version-check test +C:\Users\nanxun\Documents\flutter\bin\flutter.bat --no-version-check build apk --debug +``` + +Android APK 输出到 `build/app/outputs/flutter-apk/app-debug.apk`。iOS 编译、Simulator 截图与签名必须在 macOS 上完成。 diff --git a/mobile/analysis_options.yaml b/mobile/analysis_options.yaml new file mode 100644 index 0000000..2fbb46c --- /dev/null +++ b/mobile/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + curly_braces_in_flow_control_structures: false + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/mobile/android/.gitignore b/mobile/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/mobile/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/mobile/android/app/build.gradle.kts b/mobile/android/app/build.gradle.kts new file mode 100644 index 0000000..411d3ee --- /dev/null +++ b/mobile/android/app/build.gradle.kts @@ -0,0 +1,47 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.imagefind.mobile" + // Flutter 3.41 defaults to API 37, while the stable Android SDK installed + // for this project is API 36. Keep the app on the stable platform until + // Android's API 37 package leaves the `android-37.0` preview naming scheme. + compileSdk = 36 + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.imagefind.mobile" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = 36 + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/mobile/android/app/src/debug/AndroidManifest.xml b/mobile/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/mobile/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..1bc4170 --- /dev/null +++ b/mobile/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/android/app/src/main/kotlin/com/imagefind/imagefind_mobile/MainActivity.kt b/mobile/android/app/src/main/kotlin/com/imagefind/imagefind_mobile/MainActivity.kt new file mode 100644 index 0000000..f1dc8be --- /dev/null +++ b/mobile/android/app/src/main/kotlin/com/imagefind/imagefind_mobile/MainActivity.kt @@ -0,0 +1,5 @@ +package com.imagefind.mobile + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/mobile/android/app/src/main/res/drawable-v21/launch_background.xml b/mobile/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/mobile/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/mobile/android/app/src/main/res/drawable/launch_background.xml b/mobile/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/mobile/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/mobile/android/app/src/main/res/values-night/styles.xml b/mobile/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/mobile/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/mobile/android/app/src/main/res/values/styles.xml b/mobile/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/mobile/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/mobile/android/app/src/profile/AndroidManifest.xml b/mobile/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/mobile/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/mobile/android/build.gradle.kts b/mobile/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/mobile/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/mobile/android/gradle.properties b/mobile/android/gradle.properties new file mode 100644 index 0000000..fbee1d8 --- /dev/null +++ b/mobile/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/mobile/android/gradle/wrapper/gradle-wrapper.properties b/mobile/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e4ef43f --- /dev/null +++ b/mobile/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/mobile/android/settings.gradle.kts b/mobile/android/settings.gradle.kts new file mode 100644 index 0000000..ca7fe06 --- /dev/null +++ b/mobile/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/mobile/ios/.gitignore b/mobile/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/mobile/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/mobile/ios/Flutter/AppFrameworkInfo.plist b/mobile/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..391a902 --- /dev/null +++ b/mobile/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/mobile/ios/Flutter/Debug.xcconfig b/mobile/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/mobile/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/mobile/ios/Flutter/Release.xcconfig b/mobile/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/mobile/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..8c53216 --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,620 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.imagefind.mobile; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.imagefind.mobile.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.imagefind.mobile.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.imagefind.mobile.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.imagefind.mobile; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.imagefind.mobile; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/mobile/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/mobile/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/mobile/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/mobile/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/mobile/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/ios/Runner.xcworkspace/contents.xcworkspacedata b/mobile/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/mobile/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/mobile/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/mobile/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/mobile/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/mobile/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/mobile/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/mobile/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..c30b367 --- /dev/null +++ b/mobile/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard b/mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/ios/Runner/Base.lproj/Main.storyboard b/mobile/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/mobile/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plist new file mode 100644 index 0000000..1c3a626 --- /dev/null +++ b/mobile/ios/Runner/Info.plist @@ -0,0 +1,81 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + ImageFind + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ImageFind + NSLocalNetworkUsageDescription + ImageFind 需要连接你在局域网中的私人媒体服务器。 + NSPhotoLibraryUsageDescription + 用于选择查询图片或上传到你的私人媒体库。 + NSCameraUsageDescription + 用于拍摄查询图片,在自己的媒体库中查找相似画面。 + NSAppTransportSecurity + + NSAllowsLocalNetworking + + + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/mobile/ios/Runner/Runner-Bridging-Header.h b/mobile/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/mobile/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/mobile/ios/Runner/SceneDelegate.swift b/mobile/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/mobile/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/mobile/ios/RunnerTests/RunnerTests.swift b/mobile/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/mobile/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart new file mode 100644 index 0000000..96f7be7 --- /dev/null +++ b/mobile/lib/main.dart @@ -0,0 +1,11 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:media_kit/media_kit.dart'; + +import 'src/app.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + MediaKit.ensureInitialized(); + runApp(const ProviderScope(child: ImageFindApp())); +} diff --git a/mobile/lib/src/api.dart b/mobile/lib/src/api.dart new file mode 100644 index 0000000..e6f4fa8 --- /dev/null +++ b/mobile/lib/src/api.dart @@ -0,0 +1,638 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +import 'models.dart'; + +class ApiException implements Exception { + const ApiException(this.message, {this.statusCode}); + final String message; + final int? statusCode; + @override + String toString() => message; +} + +class UploadChunkSlice { + const UploadChunkSlice(this.index, this.offset, this.length); + final int index; + final int offset; + final int length; +} + +List pendingUploadChunks({ + required int sizeBytes, + required int chunkSize, + Set received = const {}, +}) { + if (sizeBytes <= 0 || chunkSize <= 0) return const []; + final total = (sizeBytes / chunkSize).ceil(); + return [ + for (var index = 0; index < total; index++) + if (!received.contains(index)) + UploadChunkSlice( + index, + index * chunkSize, + (sizeBytes - index * chunkSize).clamp(0, chunkSize), + ), + ]; +} + +Stream> decodeServerEvents( + Stream> bytes, +) async* { + final lines = bytes.transform(utf8.decoder).transform(const LineSplitter()); + await for (final line in lines) { + if (!line.startsWith('data:')) continue; + final raw = line.substring(5).trim(); + if (raw.isEmpty) continue; + final decoded = jsonDecode(raw); + if (decoded is Map) yield Map.from(decoded); + } +} + +class ImageFindApi { + ImageFindApi(this._storage) { + _dio.interceptors.add( + InterceptorsWrapper( + onRequest: (options, handler) { + if (_cookie?.isNotEmpty == true) + options.headers[HttpHeaders.cookieHeader] = _cookie; + if (!{ + 'GET', + 'HEAD', + 'OPTIONS', + }.contains(options.method.toUpperCase()) && + _csrf?.isNotEmpty == true) { + options.headers['X-CSRF-Token'] = _csrf; + } + handler.next(options); + }, + onError: (error, handler) => handler.next(error), + ), + ); + } + + static const _serverKey = 'imagefind.server'; + static const _cookieKey = 'imagefind.session.cookie'; + static const _csrfKey = 'imagefind.session.csrf'; + final FlutterSecureStorage _storage; + final Dio _dio = Dio( + BaseOptions( + connectTimeout: const Duration(seconds: 10), + receiveTimeout: const Duration(seconds: 30), + sendTimeout: const Duration(seconds: 30), + responseType: ResponseType.json, + headers: {HttpHeaders.acceptHeader: 'application/json'}, + ), + ); + String? _apiRoot; + String? _serverRoot; + String? _cookie; + String? _csrf; + + String? get serverRoot => _serverRoot; + bool get isConfigured => _apiRoot != null; + Map get mediaHeaders => _cookie?.isNotEmpty == true + ? {HttpHeaders.cookieHeader: _cookie!} + : const {}; + + Future restore() async { + final server = await _storage.read(key: _serverKey); + if (server == null || server.isEmpty) return false; + _configure(server); + _cookie = await _storage.read(key: _cookieKey); + _csrf = await _storage.read(key: _csrfKey); + return _cookie?.isNotEmpty == true; + } + + Future connect(String rawUrl) async { + final uri = _validateServer(rawUrl); + _configure(uri.toString()); + try { + final response = await _dio.get>('$_apiRoot/status'); + final status = ServerStatus.fromJson(response.data ?? const {}); + if (status.accessMode != 'direct') { + throw const ApiException( + '这是 fnOS 网关专属地址。请在 ImageFind 设置中开启直接 Web/API 访问后,填写直连地址。', + ); + } + await _storage.write(key: _serverKey, value: _serverRoot); + return status; + } on DioException catch (error) { + throw _mapError(error, connection: true); + } + } + + Future login( + String password, { + bool setup = false, + bool remember = true, + }) async { + _requireConfigured(); + try { + final response = await _dio.post>( + '$_apiRoot/${setup ? 'setup' : 'auth/login'}', + data: {'password': password, 'remember_device': remember}, + ); + final data = response.data ?? const {}; + _csrf = data['csrf_token']?.toString(); + _cookie = _extractCookie(response.headers.map['set-cookie']); + if (_cookie == null || _csrf == null) + throw const ApiException('服务器未返回有效会话,请检查反向代理 Cookie 配置。'); + await _storage.write(key: _cookieKey, value: _cookie); + await _storage.write(key: _csrfKey, value: _csrf); + } on DioException catch (error) { + throw _mapError(error); + } + } + + Future verifySession() async { + if (_apiRoot == null || _cookie == null) return false; + try { + final response = await _dio.get>( + '$_apiRoot/auth/me', + ); + final csrf = response.data?['csrf']?.toString(); + if (csrf?.isNotEmpty == true) { + _csrf = csrf; + await _storage.write(key: _csrfKey, value: csrf); + } + return response.data?['authenticated'] == true; + } catch (_) { + return false; + } + } + + Future logout() async { + try { + if (_apiRoot != null && _cookie != null) + await _dio.post('$_apiRoot/auth/logout'); + } catch (_) { + // Local session must still be cleared if the server is unavailable. + } + _cookie = null; + _csrf = null; + await _storage.delete(key: _cookieKey); + await _storage.delete(key: _csrfKey); + } + + Future home() async => HomeFeed.fromJson(await getMap('home')); + Future> videos({Map? query}) async => + (await getList( + 'videos', + query: query, + )).map(VideoRecord.fromJson).toList(); + Future> collections() async => + (await getList('collections')).map(CollectionRecord.fromJson).toList(); + Future> people() async => + (await getList('people')).map(PersonRecord.fromJson).toList(); + + Future> search(String text, {String? imageId}) async { + final data = await postMap( + 'search', + data: { + 'text': text.trim().isEmpty ? null : text.trim(), + 'image_id': imageId, + 'limit': 60, + }, + ); + final raw = data['items'] ?? data['results'] ?? data['hits'] ?? const []; + return asJsonList(raw).map(SearchHit.fromJson).toList(); + } + + Future uploadQueryImage(String path) async { + _requireConfigured(); + final extension = path.split('.').last.toLowerCase(); + final mime = switch (extension) { + 'png' => 'image/png', + 'webp' => 'image/webp', + 'gif' => 'image/gif', + 'bmp' => 'image/bmp', + _ => 'image/jpeg', + }; + try { + final response = await _dio.post>( + '$_apiRoot/query-images', + data: FormData.fromMap({ + 'file': await MultipartFile.fromFile( + path, + filename: path.split(Platform.pathSeparator).last, + contentType: DioMediaType.parse(mime), + ), + }), + options: Options(sendTimeout: const Duration(minutes: 2)), + ); + final id = response.data?['id']?.toString(); + if (id == null || id.isEmpty) { + throw const ApiException('服务器未返回查询图片编号。'); + } + return id; + } on DioException catch (error) { + throw _mapError(error); + } + } + + Future>> writableSources() async => + (await getList('sources')) + .where( + (item) => item['writable'] == true || item['read_only'] != true, + ) + .toList(); + + Future uploadVideoFile({ + required String path, + required String filename, + required int sizeBytes, + required String sourceId, + String relativePath = '', + void Function(String uploadId)? onCreated, + void Function(int sent, int total)? onProgress, + }) async { + final created = await postMap( + 'uploads', + data: { + 'source_id': sourceId, + 'relative_path': relativePath, + 'filename': filename, + 'size_bytes': sizeBytes, + 'conflict': 'rename', + }, + ); + final uploadId = '${created['id'] ?? ''}'; + if (uploadId.isEmpty) throw const ApiException('服务器未能创建上传任务。'); + onCreated?.call(uploadId); + await _sendUploadChunks( + uploadId: uploadId, + path: path, + sizeBytes: sizeBytes, + chunkSize: _asPositiveInt(created['chunk_size'], 4 * 1024 * 1024), + received: _intSet(created['received_chunks']), + onProgress: onProgress, + ); + return uploadId; + } + + Future resumeVideoUpload({ + required String uploadId, + required String path, + required int sizeBytes, + void Function(int sent, int total)? onProgress, + }) async { + final rows = await getList('uploads'); + final upload = rows + .where((item) => '${item['id']}' == uploadId) + .firstOrNull; + if (upload == null) { + throw const ApiException('服务器上的上传任务已过期,请重新选择视频。'); + } + if ('${upload['status']}' != 'receiving') { + throw ApiException('当前任务状态为 ${upload['status']},不能继续上传分块。'); + } + await _sendUploadChunks( + uploadId: uploadId, + path: path, + sizeBytes: sizeBytes, + chunkSize: _asPositiveInt(upload['chunk_size'], 4 * 1024 * 1024), + received: _intSet(upload['received_chunks']), + onProgress: onProgress, + ); + } + + Future _sendUploadChunks({ + required String uploadId, + required String path, + required int sizeBytes, + required int chunkSize, + required Set received, + void Function(int sent, int total)? onProgress, + }) async { + _requireConfigured(); + final file = File(path); + if (!await file.exists() || await file.length() != sizeBytes) { + throw const ApiException('所选视频已移动或大小发生变化,请重新选择。'); + } + var sent = received.fold(0, (sum, index) { + final start = index * chunkSize; + return sum + (sizeBytes - start).clamp(0, chunkSize); + }); + onProgress?.call(sent, sizeBytes); + final handle = await file.open(); + try { + for (final chunk in pendingUploadChunks( + sizeBytes: sizeBytes, + chunkSize: chunkSize, + received: received, + )) { + await handle.setPosition(chunk.offset); + final bytes = await handle.read(chunk.length); + if (bytes.length != chunk.length) { + throw const ApiException('读取视频分块失败。'); + } + try { + await _dio.put>( + '$_apiRoot/uploads/$uploadId/chunks/${chunk.index}', + data: Stream.value(Uint8List.fromList(bytes)), + options: Options( + contentType: 'application/octet-stream', + headers: {HttpHeaders.contentLengthHeader: chunk.length}, + sendTimeout: const Duration(minutes: 10), + ), + ); + } on DioException catch (error) { + throw _mapError(error); + } + sent += chunk.length; + onProgress?.call(sent, sizeBytes); + } + final completed = await postMap('uploads/$uploadId/complete'); + final missing = _intSet(completed['missing_chunks']); + if (missing.isNotEmpty) { + throw ApiException('仍有 ${missing.length} 个分块未上传,请重试。'); + } + } finally { + await handle.close(); + } + } + + Future downloadVideoToFile({ + required VideoRecord video, + required String partialPath, + required int offset, + void Function(int received, int? total)? onProgress, + }) async { + _requireConfigured(); + final path = video.downloadUrl?.isNotEmpty == true + ? video.downloadUrl! + : '/api/v1/videos/${video.id}/download'; + final uri = absoluteUri(path); + try { + final response = await _dio.get( + uri.toString(), + options: Options( + responseType: ResponseType.stream, + headers: offset > 0 + ? {HttpHeaders.rangeHeader: 'bytes=$offset-'} + : null, + receiveTimeout: const Duration(hours: 6), + ), + ); + final append = + offset > 0 && response.statusCode == HttpStatus.partialContent; + final start = append ? offset : 0; + final contentRange = response.headers.value( + HttpHeaders.contentRangeHeader, + ); + final rangeTotal = contentRange?.split('/').last; + final contentLength = int.tryParse( + response.headers.value(HttpHeaders.contentLengthHeader) ?? '', + ); + final total = + int.tryParse(rangeTotal ?? '') ?? + (contentLength == null ? null : start + contentLength); + final sink = File( + partialPath, + ).openWrite(mode: append ? FileMode.append : FileMode.write); + var received = start; + try { + await for (final chunk in response.data!.stream) { + sink.add(chunk); + received += chunk.length; + onProgress?.call(received, total); + } + } finally { + await sink.flush(); + await sink.close(); + } + if (total != null && received < total) { + throw ApiException('下载中断:已接收 $received / $total 字节。'); + } + } on DioException catch (error) { + throw _mapError(error); + } + } + + Stream> events() async* { + _requireConfigured(); + try { + final response = await _dio.get( + '$_apiRoot/events', + options: Options( + responseType: ResponseType.stream, + receiveTimeout: Duration.zero, + headers: {HttpHeaders.acceptHeader: 'text/event-stream'}, + ), + ); + yield* decodeServerEvents(response.data!.stream.cast>()); + } on DioException catch (error) { + throw _mapError(error); + } + } + + Future> transcript(String videoId) async { + final data = await getDynamic('videos/$videoId/transcript'); + final raw = data is Map ? data['segments'] ?? data['items'] : data; + return asJsonList(raw).map(TranscriptLine.fromJson).toList(); + } + + Future> markers(String videoId) async => (await getList( + 'videos/$videoId/markers', + )).map(MarkerRecord.fromJson).toList(); + Future addMarker(String videoId, int positionMs, {String? title}) => + postMap( + 'videos/$videoId/markers', + data: {'position_ms': positionMs, 'title': title}, + ); + Future deleteMarker(String videoId, String markerId) => + delete('videos/$videoId/markers/$markerId'); + Future updateVideoState(String videoId, Map data) => + patchMap('videos/$videoId/state', data: data); + Future updatePreferences(Map data) => + patchMap('preferences', data: data); + + Uri absoluteUri(String? path) { + if (path == null || path.isEmpty) return Uri(); + final parsed = Uri.tryParse(path); + if (parsed?.hasScheme == true) return parsed!; + return Uri.parse( + _serverRoot!, + ).resolve(path.startsWith('/') ? path.substring(1) : path); + } + + Uri streamUri(VideoRecord video, {bool proxy = false}) { + final path = video.playbackUrl?.isNotEmpty == true + ? video.playbackUrl! + : '/api/v1/videos/${video.id}/stream'; + final uri = absoluteUri(path); + return proxy + ? uri.replace( + queryParameters: {...uri.queryParameters, 'mode': 'proxy'}, + ) + : uri; + } + + Uri thumbnailUri(String? path) => absoluteUri(path); + + Future getDynamic(String path, {Map? query}) async { + _requireConfigured(); + try { + final response = await _dio.get( + '$_apiRoot/$path', + queryParameters: query, + ); + return response.data; + } on DioException catch (error) { + throw _mapError(error); + } + } + + Future> getMap( + String path, { + Map? query, + }) async => asJsonMap(await getDynamic(path, query: query)); + Future>> getList( + String path, { + Map? query, + }) async => asJsonList(await getDynamic(path, query: query)); + + Future> postMap(String path, {Object? data}) => + _write('POST', path, data); + Future> patchMap(String path, {Object? data}) => + _write('PATCH', path, data); + Future> putMap(String path, {Object? data}) => + _write('PUT', path, data); + + Future> _write( + String method, + String path, + Object? data, + ) async { + _requireConfigured(); + try { + final response = await _dio.request( + '$_apiRoot/$path', + data: data, + options: Options(method: method), + ); + return asJsonMap(response.data); + } on DioException catch (error) { + throw _mapError(error); + } + } + + Future delete(String path) async { + _requireConfigured(); + try { + await _dio.delete('$_apiRoot/$path'); + } on DioException catch (error) { + throw _mapError(error); + } + } + + Uri _validateServer(String raw) { + var value = raw.trim(); + if (!value.contains('://')) value = 'http://$value'; + final uri = Uri.tryParse(value); + if (uri == null || + !{'http', 'https'}.contains(uri.scheme) || + uri.host.isEmpty || + uri.userInfo.isNotEmpty) { + throw const ApiException('请输入有效的 ImageFind 服务器地址。'); + } + if (uri.scheme == 'http' && !_isPrivateHost(uri.host)) { + throw const ApiException( + '公网地址必须使用 HTTPS;HTTP 只允许局域网、localhost 或 .local 地址。', + ); + } + return _cleanUri(uri); + } + + void _configure(String raw) { + final uri = _cleanUri(Uri.parse(raw)); + var path = uri.path.replaceAll(RegExp(r'/+$'), ''); + if (path.endsWith('/api/v1')) path = path.substring(0, path.length - 7); + if (path.endsWith('/api')) path = path.substring(0, path.length - 4); + _serverRoot = _cleanUri( + uri.replace(path: path.isEmpty ? '/' : '$path/'), + ).toString(); + _apiRoot = Uri.parse( + _serverRoot!, + ).resolve('api/v1').toString().replaceAll(RegExp(r'/+$'), ''); + } + + void _requireConfigured() { + if (_apiRoot == null) throw const ApiException('尚未连接 ImageFind 服务器。'); + } + + String? _extractCookie(List? values) { + if (values == null) return null; + for (final value in values) { + final first = value.split(';').first.trim(); + if (first.startsWith('imagefind_session=')) return first; + } + return null; + } + + ApiException _mapError(DioException error, {bool connection = false}) { + final status = error.response?.statusCode; + final data = error.response?.data; + String? detail; + if (data is Map) { + final raw = data['detail'] ?? data['message']; + detail = raw is Map + ? raw['message']?.toString() ?? jsonEncode(raw) + : raw?.toString(); + } + if (detail?.isNotEmpty == true) + return ApiException(detail!, statusCode: status); + if (status == 401) + return const ApiException('登录已失效,请重新登录。', statusCode: 401); + if (status == 403) + return const ApiException('当前操作未通过安全校验,请重新登录后再试。', statusCode: 403); + if (status == 429) + return const ApiException('登录尝试过于频繁,请稍后再试。', statusCode: 429); + if (error.type == DioExceptionType.connectionTimeout || + error.type == DioExceptionType.receiveTimeout) { + return const ApiException('连接超时,请确认 NAS 在线且地址可从当前网络访问。'); + } + if (connection || error.type == DioExceptionType.connectionError) { + return const ApiException('无法连接服务器,请检查地址、网络和 HTTPS 证书。'); + } + return ApiException( + '请求失败${status == null ? '' : '(HTTP $status)'},请稍后重试。', + statusCode: status, + ); + } + + bool _isPrivateHost(String host) { + final lower = host.toLowerCase(); + if (lower == 'localhost' || lower.endsWith('.local')) return true; + final ip = InternetAddress.tryParse(host); + if (ip == null || ip.type != InternetAddressType.IPv4) return false; + final parts = host.split('.').map(int.parse).toList(); + return parts[0] == 10 || + parts[0] == 127 || + (parts[0] == 192 && parts[1] == 168) || + (parts[0] == 172 && parts[1] >= 16 && parts[1] <= 31); + } + + static int _asPositiveInt(dynamic value, int fallback) { + final parsed = value is int ? value : int.tryParse('$value'); + return parsed != null && parsed > 0 ? parsed : fallback; + } + + static Set _intSet(dynamic value) => value is List + ? value.map((item) => int.tryParse('$item')).whereType().toSet() + : {}; + + static Uri _cleanUri(Uri uri) => Uri( + scheme: uri.scheme, + userInfo: uri.userInfo, + host: uri.host, + port: uri.hasPort ? uri.port : null, + path: uri.path, + ); +} diff --git a/mobile/lib/src/app.dart b/mobile/lib/src/app.dart new file mode 100644 index 0000000..c970c0d --- /dev/null +++ b/mobile/lib/src/app.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import 'models.dart'; +import 'screens/auth_screens.dart'; +import 'screens/core_screens.dart'; +import 'screens/player_screen.dart'; +import 'screens/shell.dart'; +import 'screens/workbench_screens.dart'; +import 'state.dart'; +import 'theme.dart'; + +class ImageFindApp extends ConsumerStatefulWidget { + const ImageFindApp({super.key}); + @override + ConsumerState createState() => _ImageFindAppState(); +} + +class _ImageFindAppState extends ConsumerState { + late final GoRouter _router = GoRouter( + initialLocation: '/splash', + routes: [ + GoRoute(path: '/splash', builder: (_, _) => const SplashScreen()), + GoRoute(path: '/connect', builder: (_, _) => const ConnectScreen()), + GoRoute(path: '/login', builder: (_, _) => const LoginScreen()), + GoRoute( + path: '/home', + builder: (_, _) => const AppShell(index: 0, child: HomeScreen()), + ), + GoRoute( + path: '/search', + builder: (_, _) => const AppShell(index: 1, child: SearchScreen()), + ), + GoRoute( + path: '/library', + builder: (_, _) => const AppShell(index: 2, child: LibraryScreen()), + ), + GoRoute( + path: '/profile', + builder: (_, _) => const AppShell(index: 3, child: ProfileScreen()), + ), + GoRoute( + path: '/player/:id', + builder: (_, state) => PlayerScreen( + videoId: state.pathParameters['id']!, + initialVideo: state.extra is VideoRecord + ? state.extra! as VideoRecord + : null, + startMs: int.tryParse(state.uri.queryParameters['t'] ?? '') ?? 0, + ), + ), + GoRoute(path: '/workbench', builder: (_, _) => const WorkbenchScreen()), + GoRoute( + path: '/manage/:section', + builder: (_, state) => + ManagementSectionScreen(section: state.pathParameters['section']!), + ), + GoRoute( + path: '/collection/:id', + builder: (_, state) => CollectionDetailScreen( + id: state.pathParameters['id']!, + initial: state.extra is CollectionRecord + ? state.extra! as CollectionRecord + : null, + ), + ), + GoRoute( + path: '/person/:id', + builder: (_, state) => PersonDetailScreen( + id: state.pathParameters['id']!, + initial: state.extra is PersonRecord + ? state.extra! as PersonRecord + : null, + ), + ), + ], + redirect: (context, state) { + final session = ref.read(sessionProvider); + final path = state.matchedLocation; + final authPath = + path == '/splash' || path == '/connect' || path == '/login'; + switch (session.stage) { + case SessionStage.booting: + return path == '/splash' ? null : '/splash'; + case SessionStage.disconnected: + return path == '/connect' ? null : '/connect'; + case SessionStage.login: + case SessionStage.setup: + return path == '/login' ? null : '/login'; + case SessionStage.authenticated: + return authPath ? '/home' : null; + } + }, + ); + + @override + Widget build(BuildContext context) { + ref.listen(sessionProvider, (_, _) => _router.refresh()); + ref.watch(eventSyncProvider); + final themeMode = ref.watch(themeModeProvider); + return MaterialApp.router( + title: 'ImageFind', + debugShowCheckedModeBanner: false, + themeMode: themeMode, + theme: buildTheme(Brightness.light, TargetPlatform.android), + darkTheme: buildTheme(Brightness.dark, TargetPlatform.android), + routerConfig: _router, + builder: (context, child) { + final platform = Theme.of(context).platform; + final brightness = Theme.of(context).brightness; + return Theme( + data: buildTheme(brightness, platform), + child: child ?? const SizedBox.shrink(), + ); + }, + ); + } +} diff --git a/mobile/lib/src/models.dart b/mobile/lib/src/models.dart new file mode 100644 index 0000000..6571bba --- /dev/null +++ b/mobile/lib/src/models.dart @@ -0,0 +1,291 @@ +import 'dart:convert'; + +class ServerStatus { + const ServerStatus({ + required this.configured, + required this.version, + required this.accessMode, + }); + final bool configured; + final String version; + final String accessMode; + + factory ServerStatus.fromJson(Map json) => ServerStatus( + configured: json['configured'] == true, + version: '${json['version'] ?? ''}', + accessMode: '${json['access_mode'] ?? 'direct'}', + ); +} + +class VideoRecord { + const VideoRecord({ + required this.id, + required this.title, + required this.durationMs, + this.width = 0, + this.height = 0, + this.series = '', + this.sourceName = '', + this.thumbnailUrl, + this.playbackUrl, + this.downloadUrl, + this.progressMs = 0, + this.favorited = false, + this.completed = false, + this.tags = const [], + }); + + final String id; + final String title; + final int durationMs; + final int width; + final int height; + final String series; + final String sourceName; + final String? thumbnailUrl; + final String? playbackUrl; + final String? downloadUrl; + final int progressMs; + final bool favorited; + final bool completed; + final List tags; + + factory VideoRecord.fromJson(Map json) { + final metadata = json['metadata'] is Map + ? Map.from(json['metadata'] as Map) + : const {}; + final rawTags = json['tags'] ?? metadata['tags']; + return VideoRecord( + id: '${json['id'] ?? ''}', + title: + '${json['title'] ?? metadata['title'] ?? json['display_name'] ?? '未命名视频'}', + durationMs: _asInt(json['duration_ms']), + width: _asInt(json['width']), + height: _asInt(json['height']), + series: + '${json['series'] ?? metadata['series'] ?? json['collection_name'] ?? ''}', + sourceName: '${json['source_name'] ?? json['source_label'] ?? ''}', + thumbnailUrl: json['thumbnail_url']?.toString(), + playbackUrl: json['playback_url']?.toString(), + downloadUrl: json['download_url']?.toString(), + progressMs: _asInt(json['progress_ms']), + favorited: json['favorited'] == true || json['favorite'] == true, + completed: json['completed'] == true, + tags: rawTags is List + ? rawTags + .map((e) => e is Map ? '${e['name'] ?? ''}' : '$e') + .where((e) => e.isNotEmpty) + .toList() + : const [], + ); + } + + String get durationLabel => formatDuration(durationMs); + String get resolutionLabel => width >= 3840 + ? '4K' + : width >= 1920 + ? '1080p' + : width > 0 + ? '${width}p' + : '未知画质'; + + VideoRecord copyWith({bool? favorited, int? progressMs, bool? completed}) => + VideoRecord( + id: id, + title: title, + durationMs: durationMs, + width: width, + height: height, + series: series, + sourceName: sourceName, + thumbnailUrl: thumbnailUrl, + playbackUrl: playbackUrl, + downloadUrl: downloadUrl, + progressMs: progressMs ?? this.progressMs, + favorited: favorited ?? this.favorited, + completed: completed ?? this.completed, + tags: tags, + ); +} + +class CollectionRecord { + const CollectionRecord({ + required this.id, + required this.name, + this.description = '', + this.videoCount = 0, + this.thumbnailUrl, + }); + final String id; + final String name; + final String description; + final int videoCount; + final String? thumbnailUrl; + factory CollectionRecord.fromJson(Map json) => + CollectionRecord( + id: '${json['id'] ?? ''}', + name: '${json['name'] ?? '未命名合集'}', + description: '${json['description'] ?? ''}', + videoCount: _asInt(json['video_count']), + thumbnailUrl: json['thumbnail_url']?.toString(), + ); +} + +class PersonRecord { + const PersonRecord({ + required this.id, + required this.name, + this.faceCount = 0, + this.isNamed = false, + this.thumbnailUrl, + }); + final String id; + final String name; + final int faceCount; + final bool isNamed; + final String? thumbnailUrl; + factory PersonRecord.fromJson(Map json) => PersonRecord( + id: '${json['id'] ?? ''}', + name: '${json['name'] ?? '待命名人物'}', + faceCount: _asInt(json['face_count'] ?? json['video_count']), + isNamed: json['is_named'] == true, + thumbnailUrl: json['thumbnail_url']?.toString(), + ); +} + +class SearchHit { + const SearchHit({ + required this.video, + required this.positionMs, + required this.evidence, + required this.kind, + this.thumbnailUrl, + }); + final VideoRecord video; + final int positionMs; + final String evidence; + final String kind; + final String? thumbnailUrl; + + factory SearchHit.fromJson(Map json) { + final videoJson = json['video'] is Map + ? Map.from(json['video'] as Map) + : json; + return SearchHit( + video: VideoRecord.fromJson(videoJson), + positionMs: _asInt( + json['timestamp_ms'] ?? json['position_ms'] ?? json['start_ms'], + ), + evidence: + '${json['evidence'] ?? json['text'] ?? json['raw_text'] ?? json['matched_text'] ?? ''}', + kind: + '${json['recognition_type'] ?? json['kind'] ?? json['match_type'] ?? 'metadata'}', + thumbnailUrl: (json['thumbnail_url'] ?? videoJson['thumbnail_url']) + ?.toString(), + ); + } +} + +class TranscriptLine { + const TranscriptLine({ + required this.startMs, + required this.endMs, + required this.text, + }); + final int startMs; + final int endMs; + final String text; + factory TranscriptLine.fromJson(Map json) => TranscriptLine( + startMs: _asInt(json['start_ms']), + endMs: _asInt(json['end_ms']), + text: '${json['raw_text'] ?? json['text'] ?? ''}', + ); +} + +class MarkerRecord { + const MarkerRecord({ + required this.id, + required this.positionMs, + required this.title, + }); + final String id; + final int positionMs; + final String title; + factory MarkerRecord.fromJson(Map json) => MarkerRecord( + id: '${json['id'] ?? ''}', + positionMs: _asInt(json['position_ms']), + title: '${json['title'] ?? '收藏时刻'}', + ); +} + +class HomeFeed { + const HomeFeed({ + this.recent = const [], + this.continueWatching = const [], + this.collections = const [], + this.people = const [], + this.unorganized = const [], + }); + final List recent; + final List continueWatching; + final List collections; + final List people; + final List unorganized; + + factory HomeFeed.fromJson(Map json) { + List> items(dynamic value) { + final raw = value is Map ? value['items'] : value; + return raw is List + ? raw + .whereType() + .map((e) => Map.from(e)) + .toList() + : const []; + } + + return HomeFeed( + recent: items(json['recent']).map(VideoRecord.fromJson).toList(), + continueWatching: items( + json['continue_watching'] ?? json['continue'], + ).map(VideoRecord.fromJson).toList(), + collections: items( + json['collections'], + ).map(CollectionRecord.fromJson).toList(), + people: items(json['people']).map(PersonRecord.fromJson).toList(), + unorganized: items( + json['unorganized'], + ).map(VideoRecord.fromJson).toList(), + ); + } +} + +int _asInt(dynamic value) => value is int + ? value + : value is num + ? value.round() + : int.tryParse('$value') ?? 0; + +String formatDuration(int milliseconds) { + final total = (milliseconds / 1000).floor().clamp(0, 359999); + final hours = total ~/ 3600; + final minutes = (total % 3600) ~/ 60; + final seconds = total % 60; + if (hours > 0) + return '$hours:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}'; + return '$minutes:${seconds.toString().padLeft(2, '0')}'; +} + +Map asJsonMap(dynamic value) { + if (value is Map) return value; + if (value is Map) return Map.from(value); + if (value is String && value.isNotEmpty) + return Map.from(jsonDecode(value) as Map); + return {}; +} + +List> asJsonList(dynamic value) { + final raw = value is Map && value['items'] is List ? value['items'] : value; + return raw is List + ? raw.whereType().map((e) => Map.from(e)).toList() + : const []; +} diff --git a/mobile/lib/src/offline_database.dart b/mobile/lib/src/offline_database.dart new file mode 100644 index 0000000..5ac97a8 --- /dev/null +++ b/mobile/lib/src/offline_database.dart @@ -0,0 +1,43 @@ +import 'package:drift/drift.dart'; +import 'package:drift_flutter/drift_flutter.dart'; + +part 'offline_database.g.dart'; + +class OfflineEntries extends Table { + TextColumn get videoId => text()(); + TextColumn get title => text()(); + TextColumn get localPath => text()(); + TextColumn get partialPath => text().nullable()(); + IntColumn get bytesDownloaded => integer().withDefault(const Constant(0))(); + IntColumn get totalBytes => integer().nullable()(); + TextColumn get status => text().withDefault(const Constant('queued'))(); + TextColumn get error => text().nullable()(); + DateTimeColumn get updatedAt => dateTime().withDefault(currentDateAndTime)(); + + @override + Set> get primaryKey => {videoId}; +} + +@DriftDatabase(tables: [OfflineEntries]) +final class OfflineDatabase extends _$OfflineDatabase { + OfflineDatabase([QueryExecutor? executor]) + : super(executor ?? driftDatabase(name: 'imagefind_offline')); + + @override + int get schemaVersion => 1; + + Stream> watchDownloads() => (select( + offlineEntries, + )..orderBy([(row) => OrderingTerm.desc(row.updatedAt)])).watch(); + + Future saveDownload(OfflineEntriesCompanion value) => + into(offlineEntries).insertOnConflictUpdate(value); + + Future removeDownload(String videoId) => (delete( + offlineEntries, + )..where((row) => row.videoId.equals(videoId))).go(); + + Future downloadFor(String videoId) => (select( + offlineEntries, + )..where((row) => row.videoId.equals(videoId))).getSingleOrNull(); +} diff --git a/mobile/lib/src/offline_database.g.dart b/mobile/lib/src/offline_database.g.dart new file mode 100644 index 0000000..a008d2d --- /dev/null +++ b/mobile/lib/src/offline_database.g.dart @@ -0,0 +1,879 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'offline_database.dart'; + +// ignore_for_file: type=lint +class $OfflineEntriesTable extends OfflineEntries + with TableInfo<$OfflineEntriesTable, OfflineEntry> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $OfflineEntriesTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _videoIdMeta = const VerificationMeta( + 'videoId', + ); + @override + late final GeneratedColumn videoId = GeneratedColumn( + 'video_id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _titleMeta = const VerificationMeta('title'); + @override + late final GeneratedColumn title = GeneratedColumn( + 'title', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _localPathMeta = const VerificationMeta( + 'localPath', + ); + @override + late final GeneratedColumn localPath = GeneratedColumn( + 'local_path', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _partialPathMeta = const VerificationMeta( + 'partialPath', + ); + @override + late final GeneratedColumn partialPath = GeneratedColumn( + 'partial_path', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); + static const VerificationMeta _bytesDownloadedMeta = const VerificationMeta( + 'bytesDownloaded', + ); + @override + late final GeneratedColumn bytesDownloaded = GeneratedColumn( + 'bytes_downloaded', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + defaultValue: const Constant(0), + ); + static const VerificationMeta _totalBytesMeta = const VerificationMeta( + 'totalBytes', + ); + @override + late final GeneratedColumn totalBytes = GeneratedColumn( + 'total_bytes', + aliasedName, + true, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _statusMeta = const VerificationMeta('status'); + @override + late final GeneratedColumn status = GeneratedColumn( + 'status', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: false, + defaultValue: const Constant('queued'), + ); + static const VerificationMeta _errorMeta = const VerificationMeta('error'); + @override + late final GeneratedColumn error = GeneratedColumn( + 'error', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); + static const VerificationMeta _updatedAtMeta = const VerificationMeta( + 'updatedAt', + ); + @override + late final GeneratedColumn updatedAt = GeneratedColumn( + 'updated_at', + aliasedName, + false, + type: DriftSqlType.dateTime, + requiredDuringInsert: false, + defaultValue: currentDateAndTime, + ); + @override + List get $columns => [ + videoId, + title, + localPath, + partialPath, + bytesDownloaded, + totalBytes, + status, + error, + updatedAt, + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'offline_entries'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('video_id')) { + context.handle( + _videoIdMeta, + videoId.isAcceptableOrUnknown(data['video_id']!, _videoIdMeta), + ); + } else if (isInserting) { + context.missing(_videoIdMeta); + } + if (data.containsKey('title')) { + context.handle( + _titleMeta, + title.isAcceptableOrUnknown(data['title']!, _titleMeta), + ); + } else if (isInserting) { + context.missing(_titleMeta); + } + if (data.containsKey('local_path')) { + context.handle( + _localPathMeta, + localPath.isAcceptableOrUnknown(data['local_path']!, _localPathMeta), + ); + } else if (isInserting) { + context.missing(_localPathMeta); + } + if (data.containsKey('partial_path')) { + context.handle( + _partialPathMeta, + partialPath.isAcceptableOrUnknown( + data['partial_path']!, + _partialPathMeta, + ), + ); + } + if (data.containsKey('bytes_downloaded')) { + context.handle( + _bytesDownloadedMeta, + bytesDownloaded.isAcceptableOrUnknown( + data['bytes_downloaded']!, + _bytesDownloadedMeta, + ), + ); + } + if (data.containsKey('total_bytes')) { + context.handle( + _totalBytesMeta, + totalBytes.isAcceptableOrUnknown(data['total_bytes']!, _totalBytesMeta), + ); + } + if (data.containsKey('status')) { + context.handle( + _statusMeta, + status.isAcceptableOrUnknown(data['status']!, _statusMeta), + ); + } + if (data.containsKey('error')) { + context.handle( + _errorMeta, + error.isAcceptableOrUnknown(data['error']!, _errorMeta), + ); + } + if (data.containsKey('updated_at')) { + context.handle( + _updatedAtMeta, + updatedAt.isAcceptableOrUnknown(data['updated_at']!, _updatedAtMeta), + ); + } + return context; + } + + @override + Set get $primaryKey => {videoId}; + @override + OfflineEntry map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return OfflineEntry( + videoId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}video_id'], + )!, + title: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}title'], + )!, + localPath: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}local_path'], + )!, + partialPath: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}partial_path'], + ), + bytesDownloaded: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}bytes_downloaded'], + )!, + totalBytes: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}total_bytes'], + ), + status: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}status'], + )!, + error: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}error'], + ), + updatedAt: attachedDatabase.typeMapping.read( + DriftSqlType.dateTime, + data['${effectivePrefix}updated_at'], + )!, + ); + } + + @override + $OfflineEntriesTable createAlias(String alias) { + return $OfflineEntriesTable(attachedDatabase, alias); + } +} + +class OfflineEntry extends DataClass implements Insertable { + final String videoId; + final String title; + final String localPath; + final String? partialPath; + final int bytesDownloaded; + final int? totalBytes; + final String status; + final String? error; + final DateTime updatedAt; + const OfflineEntry({ + required this.videoId, + required this.title, + required this.localPath, + this.partialPath, + required this.bytesDownloaded, + this.totalBytes, + required this.status, + this.error, + required this.updatedAt, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['video_id'] = Variable(videoId); + map['title'] = Variable(title); + map['local_path'] = Variable(localPath); + if (!nullToAbsent || partialPath != null) { + map['partial_path'] = Variable(partialPath); + } + map['bytes_downloaded'] = Variable(bytesDownloaded); + if (!nullToAbsent || totalBytes != null) { + map['total_bytes'] = Variable(totalBytes); + } + map['status'] = Variable(status); + if (!nullToAbsent || error != null) { + map['error'] = Variable(error); + } + map['updated_at'] = Variable(updatedAt); + return map; + } + + OfflineEntriesCompanion toCompanion(bool nullToAbsent) { + return OfflineEntriesCompanion( + videoId: Value(videoId), + title: Value(title), + localPath: Value(localPath), + partialPath: partialPath == null && nullToAbsent + ? const Value.absent() + : Value(partialPath), + bytesDownloaded: Value(bytesDownloaded), + totalBytes: totalBytes == null && nullToAbsent + ? const Value.absent() + : Value(totalBytes), + status: Value(status), + error: error == null && nullToAbsent + ? const Value.absent() + : Value(error), + updatedAt: Value(updatedAt), + ); + } + + factory OfflineEntry.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return OfflineEntry( + videoId: serializer.fromJson(json['videoId']), + title: serializer.fromJson(json['title']), + localPath: serializer.fromJson(json['localPath']), + partialPath: serializer.fromJson(json['partialPath']), + bytesDownloaded: serializer.fromJson(json['bytesDownloaded']), + totalBytes: serializer.fromJson(json['totalBytes']), + status: serializer.fromJson(json['status']), + error: serializer.fromJson(json['error']), + updatedAt: serializer.fromJson(json['updatedAt']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'videoId': serializer.toJson(videoId), + 'title': serializer.toJson(title), + 'localPath': serializer.toJson(localPath), + 'partialPath': serializer.toJson(partialPath), + 'bytesDownloaded': serializer.toJson(bytesDownloaded), + 'totalBytes': serializer.toJson(totalBytes), + 'status': serializer.toJson(status), + 'error': serializer.toJson(error), + 'updatedAt': serializer.toJson(updatedAt), + }; + } + + OfflineEntry copyWith({ + String? videoId, + String? title, + String? localPath, + Value partialPath = const Value.absent(), + int? bytesDownloaded, + Value totalBytes = const Value.absent(), + String? status, + Value error = const Value.absent(), + DateTime? updatedAt, + }) => OfflineEntry( + videoId: videoId ?? this.videoId, + title: title ?? this.title, + localPath: localPath ?? this.localPath, + partialPath: partialPath.present ? partialPath.value : this.partialPath, + bytesDownloaded: bytesDownloaded ?? this.bytesDownloaded, + totalBytes: totalBytes.present ? totalBytes.value : this.totalBytes, + status: status ?? this.status, + error: error.present ? error.value : this.error, + updatedAt: updatedAt ?? this.updatedAt, + ); + OfflineEntry copyWithCompanion(OfflineEntriesCompanion data) { + return OfflineEntry( + videoId: data.videoId.present ? data.videoId.value : this.videoId, + title: data.title.present ? data.title.value : this.title, + localPath: data.localPath.present ? data.localPath.value : this.localPath, + partialPath: data.partialPath.present + ? data.partialPath.value + : this.partialPath, + bytesDownloaded: data.bytesDownloaded.present + ? data.bytesDownloaded.value + : this.bytesDownloaded, + totalBytes: data.totalBytes.present + ? data.totalBytes.value + : this.totalBytes, + status: data.status.present ? data.status.value : this.status, + error: data.error.present ? data.error.value : this.error, + updatedAt: data.updatedAt.present ? data.updatedAt.value : this.updatedAt, + ); + } + + @override + String toString() { + return (StringBuffer('OfflineEntry(') + ..write('videoId: $videoId, ') + ..write('title: $title, ') + ..write('localPath: $localPath, ') + ..write('partialPath: $partialPath, ') + ..write('bytesDownloaded: $bytesDownloaded, ') + ..write('totalBytes: $totalBytes, ') + ..write('status: $status, ') + ..write('error: $error, ') + ..write('updatedAt: $updatedAt') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash( + videoId, + title, + localPath, + partialPath, + bytesDownloaded, + totalBytes, + status, + error, + updatedAt, + ); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is OfflineEntry && + other.videoId == this.videoId && + other.title == this.title && + other.localPath == this.localPath && + other.partialPath == this.partialPath && + other.bytesDownloaded == this.bytesDownloaded && + other.totalBytes == this.totalBytes && + other.status == this.status && + other.error == this.error && + other.updatedAt == this.updatedAt); +} + +class OfflineEntriesCompanion extends UpdateCompanion { + final Value videoId; + final Value title; + final Value localPath; + final Value partialPath; + final Value bytesDownloaded; + final Value totalBytes; + final Value status; + final Value error; + final Value updatedAt; + final Value rowid; + const OfflineEntriesCompanion({ + this.videoId = const Value.absent(), + this.title = const Value.absent(), + this.localPath = const Value.absent(), + this.partialPath = const Value.absent(), + this.bytesDownloaded = const Value.absent(), + this.totalBytes = const Value.absent(), + this.status = const Value.absent(), + this.error = const Value.absent(), + this.updatedAt = const Value.absent(), + this.rowid = const Value.absent(), + }); + OfflineEntriesCompanion.insert({ + required String videoId, + required String title, + required String localPath, + this.partialPath = const Value.absent(), + this.bytesDownloaded = const Value.absent(), + this.totalBytes = const Value.absent(), + this.status = const Value.absent(), + this.error = const Value.absent(), + this.updatedAt = const Value.absent(), + this.rowid = const Value.absent(), + }) : videoId = Value(videoId), + title = Value(title), + localPath = Value(localPath); + static Insertable custom({ + Expression? videoId, + Expression? title, + Expression? localPath, + Expression? partialPath, + Expression? bytesDownloaded, + Expression? totalBytes, + Expression? status, + Expression? error, + Expression? updatedAt, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (videoId != null) 'video_id': videoId, + if (title != null) 'title': title, + if (localPath != null) 'local_path': localPath, + if (partialPath != null) 'partial_path': partialPath, + if (bytesDownloaded != null) 'bytes_downloaded': bytesDownloaded, + if (totalBytes != null) 'total_bytes': totalBytes, + if (status != null) 'status': status, + if (error != null) 'error': error, + if (updatedAt != null) 'updated_at': updatedAt, + if (rowid != null) 'rowid': rowid, + }); + } + + OfflineEntriesCompanion copyWith({ + Value? videoId, + Value? title, + Value? localPath, + Value? partialPath, + Value? bytesDownloaded, + Value? totalBytes, + Value? status, + Value? error, + Value? updatedAt, + Value? rowid, + }) { + return OfflineEntriesCompanion( + videoId: videoId ?? this.videoId, + title: title ?? this.title, + localPath: localPath ?? this.localPath, + partialPath: partialPath ?? this.partialPath, + bytesDownloaded: bytesDownloaded ?? this.bytesDownloaded, + totalBytes: totalBytes ?? this.totalBytes, + status: status ?? this.status, + error: error ?? this.error, + updatedAt: updatedAt ?? this.updatedAt, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (videoId.present) { + map['video_id'] = Variable(videoId.value); + } + if (title.present) { + map['title'] = Variable(title.value); + } + if (localPath.present) { + map['local_path'] = Variable(localPath.value); + } + if (partialPath.present) { + map['partial_path'] = Variable(partialPath.value); + } + if (bytesDownloaded.present) { + map['bytes_downloaded'] = Variable(bytesDownloaded.value); + } + if (totalBytes.present) { + map['total_bytes'] = Variable(totalBytes.value); + } + if (status.present) { + map['status'] = Variable(status.value); + } + if (error.present) { + map['error'] = Variable(error.value); + } + if (updatedAt.present) { + map['updated_at'] = Variable(updatedAt.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('OfflineEntriesCompanion(') + ..write('videoId: $videoId, ') + ..write('title: $title, ') + ..write('localPath: $localPath, ') + ..write('partialPath: $partialPath, ') + ..write('bytesDownloaded: $bytesDownloaded, ') + ..write('totalBytes: $totalBytes, ') + ..write('status: $status, ') + ..write('error: $error, ') + ..write('updatedAt: $updatedAt, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +abstract class _$OfflineDatabase extends GeneratedDatabase { + _$OfflineDatabase(QueryExecutor e) : super(e); + $OfflineDatabaseManager get managers => $OfflineDatabaseManager(this); + late final $OfflineEntriesTable offlineEntries = $OfflineEntriesTable(this); + @override + Iterable> get allTables => + allSchemaEntities.whereType>(); + @override + List get allSchemaEntities => [offlineEntries]; +} + +typedef $$OfflineEntriesTableCreateCompanionBuilder = + OfflineEntriesCompanion Function({ + required String videoId, + required String title, + required String localPath, + Value partialPath, + Value bytesDownloaded, + Value totalBytes, + Value status, + Value error, + Value updatedAt, + Value rowid, + }); +typedef $$OfflineEntriesTableUpdateCompanionBuilder = + OfflineEntriesCompanion Function({ + Value videoId, + Value title, + Value localPath, + Value partialPath, + Value bytesDownloaded, + Value totalBytes, + Value status, + Value error, + Value updatedAt, + Value rowid, + }); + +class $$OfflineEntriesTableFilterComposer + extends Composer<_$OfflineDatabase, $OfflineEntriesTable> { + $$OfflineEntriesTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get videoId => $composableBuilder( + column: $table.videoId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get title => $composableBuilder( + column: $table.title, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get localPath => $composableBuilder( + column: $table.localPath, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get partialPath => $composableBuilder( + column: $table.partialPath, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get bytesDownloaded => $composableBuilder( + column: $table.bytesDownloaded, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get totalBytes => $composableBuilder( + column: $table.totalBytes, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get status => $composableBuilder( + column: $table.status, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get error => $composableBuilder( + column: $table.error, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get updatedAt => $composableBuilder( + column: $table.updatedAt, + builder: (column) => ColumnFilters(column), + ); +} + +class $$OfflineEntriesTableOrderingComposer + extends Composer<_$OfflineDatabase, $OfflineEntriesTable> { + $$OfflineEntriesTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get videoId => $composableBuilder( + column: $table.videoId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get title => $composableBuilder( + column: $table.title, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get localPath => $composableBuilder( + column: $table.localPath, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get partialPath => $composableBuilder( + column: $table.partialPath, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get bytesDownloaded => $composableBuilder( + column: $table.bytesDownloaded, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get totalBytes => $composableBuilder( + column: $table.totalBytes, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get status => $composableBuilder( + column: $table.status, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get error => $composableBuilder( + column: $table.error, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get updatedAt => $composableBuilder( + column: $table.updatedAt, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$OfflineEntriesTableAnnotationComposer + extends Composer<_$OfflineDatabase, $OfflineEntriesTable> { + $$OfflineEntriesTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get videoId => + $composableBuilder(column: $table.videoId, builder: (column) => column); + + GeneratedColumn get title => + $composableBuilder(column: $table.title, builder: (column) => column); + + GeneratedColumn get localPath => + $composableBuilder(column: $table.localPath, builder: (column) => column); + + GeneratedColumn get partialPath => $composableBuilder( + column: $table.partialPath, + builder: (column) => column, + ); + + GeneratedColumn get bytesDownloaded => $composableBuilder( + column: $table.bytesDownloaded, + builder: (column) => column, + ); + + GeneratedColumn get totalBytes => $composableBuilder( + column: $table.totalBytes, + builder: (column) => column, + ); + + GeneratedColumn get status => + $composableBuilder(column: $table.status, builder: (column) => column); + + GeneratedColumn get error => + $composableBuilder(column: $table.error, builder: (column) => column); + + GeneratedColumn get updatedAt => + $composableBuilder(column: $table.updatedAt, builder: (column) => column); +} + +class $$OfflineEntriesTableTableManager + extends + RootTableManager< + _$OfflineDatabase, + $OfflineEntriesTable, + OfflineEntry, + $$OfflineEntriesTableFilterComposer, + $$OfflineEntriesTableOrderingComposer, + $$OfflineEntriesTableAnnotationComposer, + $$OfflineEntriesTableCreateCompanionBuilder, + $$OfflineEntriesTableUpdateCompanionBuilder, + ( + OfflineEntry, + BaseReferences< + _$OfflineDatabase, + $OfflineEntriesTable, + OfflineEntry + >, + ), + OfflineEntry, + PrefetchHooks Function() + > { + $$OfflineEntriesTableTableManager( + _$OfflineDatabase db, + $OfflineEntriesTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$OfflineEntriesTableFilterComposer($db: db, $table: table), + createOrderingComposer: () => + $$OfflineEntriesTableOrderingComposer($db: db, $table: table), + createComputedFieldComposer: () => + $$OfflineEntriesTableAnnotationComposer($db: db, $table: table), + updateCompanionCallback: + ({ + Value videoId = const Value.absent(), + Value title = const Value.absent(), + Value localPath = const Value.absent(), + Value partialPath = const Value.absent(), + Value bytesDownloaded = const Value.absent(), + Value totalBytes = const Value.absent(), + Value status = const Value.absent(), + Value error = const Value.absent(), + Value updatedAt = const Value.absent(), + Value rowid = const Value.absent(), + }) => OfflineEntriesCompanion( + videoId: videoId, + title: title, + localPath: localPath, + partialPath: partialPath, + bytesDownloaded: bytesDownloaded, + totalBytes: totalBytes, + status: status, + error: error, + updatedAt: updatedAt, + rowid: rowid, + ), + createCompanionCallback: + ({ + required String videoId, + required String title, + required String localPath, + Value partialPath = const Value.absent(), + Value bytesDownloaded = const Value.absent(), + Value totalBytes = const Value.absent(), + Value status = const Value.absent(), + Value error = const Value.absent(), + Value updatedAt = const Value.absent(), + Value rowid = const Value.absent(), + }) => OfflineEntriesCompanion.insert( + videoId: videoId, + title: title, + localPath: localPath, + partialPath: partialPath, + bytesDownloaded: bytesDownloaded, + totalBytes: totalBytes, + status: status, + error: error, + updatedAt: updatedAt, + rowid: rowid, + ), + withReferenceMapper: (p0) => p0 + .map((e) => (e.readTable(table), BaseReferences(db, table, e))) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$OfflineEntriesTableProcessedTableManager = + ProcessedTableManager< + _$OfflineDatabase, + $OfflineEntriesTable, + OfflineEntry, + $$OfflineEntriesTableFilterComposer, + $$OfflineEntriesTableOrderingComposer, + $$OfflineEntriesTableAnnotationComposer, + $$OfflineEntriesTableCreateCompanionBuilder, + $$OfflineEntriesTableUpdateCompanionBuilder, + ( + OfflineEntry, + BaseReferences<_$OfflineDatabase, $OfflineEntriesTable, OfflineEntry>, + ), + OfflineEntry, + PrefetchHooks Function() + >; + +class $OfflineDatabaseManager { + final _$OfflineDatabase _db; + $OfflineDatabaseManager(this._db); + $$OfflineEntriesTableTableManager get offlineEntries => + $$OfflineEntriesTableTableManager(_db, _db.offlineEntries); +} diff --git a/mobile/lib/src/screens/auth_screens.dart b/mobile/lib/src/screens/auth_screens.dart new file mode 100644 index 0000000..710ccc2 --- /dev/null +++ b/mobile/lib/src/screens/auth_screens.dart @@ -0,0 +1,356 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../state.dart'; +import '../theme.dart'; + +class SplashScreen extends StatelessWidget { + const SplashScreen({super.key}); + @override + Widget build(BuildContext context) => Scaffold( + body: SafeArea( + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const _AppMark(size: 58), + const SizedBox(height: 18), + Text('ImageFind', style: context.text.titleLarge), + const SizedBox(height: 18), + const SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2.4), + ), + ], + ), + ), + ), + ); +} + +class ConnectScreen extends ConsumerStatefulWidget { + const ConnectScreen({super.key}); + @override + ConsumerState createState() => _ConnectScreenState(); +} + +class _ConnectScreenState extends ConsumerState { + final _controller = TextEditingController( + text: 'http://imagefind.local:8765', + ); + final _formKey = GlobalKey(); + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final session = ref.watch(sessionProvider); + return Scaffold( + body: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 28), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 430), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Align( + alignment: Alignment.centerLeft, + child: _AppMark(size: 52), + ), + const SizedBox(height: 32), + Text('连接你的媒体库', style: context.text.headlineMedium), + const SizedBox(height: 9), + Text( + '输入 ImageFind 的直连地址。你的密码和媒体都不会离开自己的服务。', + style: context.text.bodyMedium?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + const SizedBox(height: 28), + TextFormField( + controller: _controller, + keyboardType: TextInputType.url, + textInputAction: TextInputAction.done, + autocorrect: false, + decoration: const InputDecoration( + labelText: '服务器地址', + hintText: 'http://192.168.1.10:8765', + prefixIcon: Icon(Icons.dns_outlined), + ), + validator: (value) => + value == null || value.trim().isEmpty + ? '请输入服务器地址' + : null, + onFieldSubmitted: (_) => _connect(), + ), + if (session.error != null) ...[ + const SizedBox(height: 12), + _InlineError(message: session.error!), + ], + const SizedBox(height: 18), + FilledButton( + onPressed: session.busy ? null : _connect, + child: session.busy + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : const Text('检查并继续'), + ), + const SizedBox(height: 22), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + Icons.shield_outlined, + size: 20, + color: context.colors.primary, + ), + const SizedBox(width: 9), + Expanded( + child: Text( + '支持局域网 HTTP;公网地址必须使用有效的 HTTPS 证书。', + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ), + ], + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + Future _connect() async { + if (!_formKey.currentState!.validate()) return; + FocusScope.of(context).unfocus(); + await ref.read(sessionProvider.notifier).connect(_controller.text); + } +} + +class LoginScreen extends ConsumerStatefulWidget { + const LoginScreen({super.key}); + @override + ConsumerState createState() => _LoginScreenState(); +} + +class _LoginScreenState extends ConsumerState { + final _password = TextEditingController(); + final _confirm = TextEditingController(); + final _formKey = GlobalKey(); + bool _remember = true; + bool _obscure = true; + @override + void dispose() { + _password.dispose(); + _confirm.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final session = ref.watch(sessionProvider); + final setup = session.stage == SessionStage.setup; + return Scaffold( + body: SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 28), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 430), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + IconButton( + onPressed: () => + ref.read(sessionProvider.notifier).logout(), + tooltip: '返回服务器设置', + icon: const Icon(Icons.arrow_back_ios_new_rounded), + ), + const Spacer(), + if (session.status?.version.isNotEmpty == true) + Text( + 'ImageFind ${session.status!.version}', + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 46), + Text( + setup ? '创建管理员密码' : '欢迎回来', + style: context.text.headlineMedium, + ), + const SizedBox(height: 9), + Text( + setup + ? '首次连接需要设置至少 10 个字符的管理员密码。' + : '使用 ImageFind 管理员密码继续。', + style: context.text.bodyMedium?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + const SizedBox(height: 26), + TextFormField( + controller: _password, + obscureText: _obscure, + autofocus: true, + textInputAction: setup + ? TextInputAction.next + : TextInputAction.done, + decoration: InputDecoration( + labelText: '管理员密码', + prefixIcon: const Icon(Icons.lock_outline_rounded), + suffixIcon: IconButton( + onPressed: () => setState(() => _obscure = !_obscure), + tooltip: _obscure ? '显示密码' : '隐藏密码', + icon: Icon( + _obscure + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + ), + ), + ), + validator: (value) => value == null || value.isEmpty + ? '请输入密码' + : setup && value.length < 10 + ? '密码至少需要 10 个字符' + : null, + onFieldSubmitted: setup ? null : (_) => _authenticate(), + ), + if (setup) ...[ + const SizedBox(height: 12), + TextFormField( + controller: _confirm, + obscureText: _obscure, + textInputAction: TextInputAction.done, + decoration: const InputDecoration( + labelText: '再次输入密码', + prefixIcon: Icon(Icons.verified_user_outlined), + ), + validator: (value) => + value != _password.text ? '两次输入的密码不一致' : null, + onFieldSubmitted: (_) => _authenticate(), + ), + ], + const SizedBox(height: 10), + SwitchListTile.adaptive( + contentPadding: EdgeInsets.zero, + title: const Text('记住此设备'), + subtitle: const Text('只保存加密会话,不保存密码'), + value: _remember, + onChanged: (value) => setState(() => _remember = value), + ), + if (session.error != null) + _InlineError(message: session.error!), + const SizedBox(height: 16), + FilledButton( + onPressed: session.busy ? null : _authenticate, + child: session.busy + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : Text(setup ? '创建并进入' : '安全登录'), + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + Future _authenticate() async { + if (!_formKey.currentState!.validate()) return; + FocusScope.of(context).unfocus(); + await ref + .read(sessionProvider.notifier) + .authenticate(_password.text, remember: _remember); + } +} + +class _InlineError extends StatelessWidget { + const _InlineError({required this.message}); + final String message; + @override + Widget build(BuildContext context) => Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: context.colors.errorContainer, + borderRadius: BorderRadius.circular(12), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon( + Icons.error_outline_rounded, + size: 20, + color: context.colors.onErrorContainer, + ), + const SizedBox(width: 9), + Expanded( + child: Text( + message, + style: context.text.bodySmall?.copyWith( + color: context.colors.onErrorContainer, + ), + ), + ), + ], + ), + ); +} + +class _AppMark extends StatelessWidget { + const _AppMark({required this.size}); + final double size; + @override + Widget build(BuildContext context) => Container( + width: size, + height: size, + decoration: BoxDecoration( + color: context.colors.primary, + borderRadius: BorderRadius.circular(size * .28), + ), + alignment: Alignment.center, + child: Text( + 'IF', + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.w800, + fontSize: size * .28, + letterSpacing: -.4, + ), + ), + ); +} diff --git a/mobile/lib/src/screens/core_screens.dart b/mobile/lib/src/screens/core_screens.dart new file mode 100644 index 0000000..2248ec3 --- /dev/null +++ b/mobile/lib/src/screens/core_screens.dart @@ -0,0 +1,1426 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:image_picker/image_picker.dart'; + +import '../api.dart'; +import '../models.dart'; +import '../state.dart'; +import '../theme.dart'; +import '../widgets.dart'; + +class HomeScreen extends ConsumerWidget { + const HomeScreen({super.key}); + @override + Widget build(BuildContext context, WidgetRef ref) { + final feed = ref.watch(homeProvider); + final api = ref.watch(apiProvider); + return Scaffold( + body: RefreshIndicator( + onRefresh: () => ref.refresh(homeProvider.future), + child: CustomScrollView( + physics: const AlwaysScrollableScrollPhysics(), + slivers: [ + SliverAppBar( + pinned: true, + floating: true, + toolbarHeight: 62, + titleSpacing: 6, + title: Row( + children: [ + Semantics( + button: true, + label: '我的', + child: InkWell( + onTap: () => context.go('/profile'), + borderRadius: BorderRadius.circular(14), + child: Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: context.colors.primary, + borderRadius: BorderRadius.circular(14), + ), + alignment: Alignment.center, + child: const Text( + '南', + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.w700, + ), + ), + ), + ), + ), + const SizedBox(width: 9), + Expanded( + child: InkWell( + onTap: () => context.go('/search'), + borderRadius: BorderRadius.circular(14), + child: Container( + height: 44, + padding: const EdgeInsets.symmetric(horizontal: 12), + decoration: BoxDecoration( + color: context.colors.surface, + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: Theme.of(context).dividerColor, + ), + ), + child: Row( + children: [ + Icon( + Icons.search_rounded, + size: 21, + color: context.colors.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + '搜画面、对白或人物', + overflow: TextOverflow.ellipsis, + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ), + ], + ), + ), + ), + ), + const SizedBox(width: 3), + IconButton( + onPressed: () => context.push('/manage/activity'), + tooltip: '资料库活动', + icon: const Icon(Icons.notifications_none_rounded), + ), + ], + ), + bottom: PreferredSize( + preferredSize: const Size.fromHeight(46), + child: _HomeChannels( + onSelected: (value) { + if (value == 2) context.go('/library?tab=collections'); + if (value == 3) context.go('/library?tab=people'); + if (value == 4) context.go('/library?tab=videos'); + }, + ), + ), + ), + SliverToBoxAdapter( + child: Padding( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 0, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 22, + ), + child: AsyncPane( + value: feed, + onRetry: () => ref.invalidate(homeProvider), + data: (value) { + if (value.recent.isEmpty && + value.continueWatching.isEmpty) { + return EmptyState( + icon: Icons.video_library_outlined, + title: '资料库还是空的', + message: '添加本地目录、WebDAV 或 AList,扫描完成后就能浏览和搜索自己的影像。', + action: FilledButton( + onPressed: () => context.push('/manage/sources'), + child: const Text('添加第一个数据源'), + ), + ); + } + return Column( + children: [ + if (value.continueWatching.isNotEmpty) ...[ + SectionHeading( + title: '继续观看', + subtitle: + '${value.continueWatching.length} 个未看完的视频', + ), + MediaGrid( + items: value.continueWatching, + api: api, + maxItems: 6, + ), + ], + SectionHeading( + title: '最近加入', + subtitle: '你的私人媒体库', + action: '查看全部', + onAction: () => context.go('/library'), + ), + MediaGrid(items: value.recent, api: api, maxItems: 10), + if (value.collections.isNotEmpty) ...[ + const SectionHeading(title: '合集'), + _CollectionStrip(items: value.collections, api: api), + ], + if (value.people.isNotEmpty) ...[ + const SectionHeading(title: '人物'), + _PeopleStrip(items: value.people, api: api), + ], + if (value.unorganized.isNotEmpty) ...[ + const SectionHeading( + title: '待整理', + subtitle: '还没有系列、人物或标签的信息', + ), + MediaGrid( + items: value.unorganized, + api: api, + maxItems: 6, + ), + ], + ], + ); + }, + ), + ), + ), + ], + ), + ), + ); + } +} + +class _HomeChannels extends StatefulWidget { + const _HomeChannels({required this.onSelected}); + final ValueChanged onSelected; + @override + State<_HomeChannels> createState() => _HomeChannelsState(); +} + +class _HomeChannelsState extends State<_HomeChannels> { + int selected = 0; + @override + Widget build(BuildContext context) => SizedBox( + height: 46, + child: Row( + children: ['推荐', '最近', '合集', '人物', '待整理'].asMap().entries.map((entry) { + final active = selected == entry.key; + return Expanded( + child: InkWell( + onTap: () { + setState(() => selected = entry.key); + widget.onSelected(entry.key); + }, + child: Container( + alignment: Alignment.center, + decoration: BoxDecoration( + border: Border( + bottom: BorderSide( + color: active ? context.colors.primary : Colors.transparent, + width: 2, + ), + ), + ), + child: Text( + entry.value, + style: context.text.bodySmall?.copyWith( + fontWeight: active ? FontWeight.w700 : FontWeight.w500, + color: active + ? context.colors.onSurface + : context.colors.onSurfaceVariant, + ), + ), + ), + ), + ); + }).toList(), + ), + ); +} + +class SearchScreen extends ConsumerStatefulWidget { + const SearchScreen({super.key}); + @override + ConsumerState createState() => _SearchScreenState(); +} + +class _SearchScreenState extends ConsumerState { + final _query = TextEditingController(); + bool _loading = false; + bool _searched = false; + String? _error; + List _hits = const []; + String _type = 'all'; + @override + void dispose() { + _query.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final api = ref.watch(apiProvider); + final filtered = _type == 'all' + ? _hits + : _hits + .where( + (hit) => + _type == 'videos' ? hit.positionMs == 0 : hit.kind == _type, + ) + .toList(); + final searchPane = Column( + children: [ + SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(6, 6, 6, 4), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _query, + autofocus: false, + textInputAction: TextInputAction.search, + decoration: InputDecoration( + hintText: '搜视频、对白或画面', + prefixIcon: const Icon(Icons.search_rounded), + suffixIcon: IconButton( + onPressed: _pickImage, + tooltip: '以图搜图', + icon: const Icon(Icons.image_search_outlined), + ), + ), + onSubmitted: (_) => _search(), + ), + ), + const SizedBox(width: 4), + TextButton( + onPressed: _loading ? null : _search, + child: const Text('搜索'), + ), + ], + ), + ), + ), + SizedBox( + height: 48, + child: ListView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 5), + children: [ + for (final item in const [ + ('all', '综合'), + ('videos', '视频'), + ('visual', '画面'), + ('audio', '对白'), + ('ocr', '文字'), + ('person', '人物'), + ]) + Padding( + padding: const EdgeInsets.only(right: 6), + child: ChoiceChip( + label: Text(item.$2), + selected: _type == item.$1, + onSelected: (_) => setState(() => _type = item.$1), + ), + ), + ], + ), + ), + Expanded( + child: _loading + ? const Center(child: CircularProgressIndicator()) + : _error != null + ? EmptyState( + icon: Icons.search_off_rounded, + title: '搜索没有完成', + message: _error!, + action: FilledButton.tonal( + onPressed: _search, + child: const Text('重试'), + ), + ) + : !_searched + ? const EmptyState( + icon: Icons.manage_search_rounded, + title: '找到记忆里的那一刻', + message: '可以描述画面、输入对白、人物或片名;结果会告诉你为什么命中。', + ) + : filtered.isEmpty + ? const EmptyState( + icon: Icons.search_off_rounded, + title: '没有找到相关内容', + message: '换一个更完整的描述,或减少筛选条件再试。', + ) + : ListView.separated( + padding: const EdgeInsets.fromLTRB(6, 4, 6, 22), + itemCount: filtered.length, + separatorBuilder: (_, _) => const SizedBox(height: 8), + itemBuilder: (context, index) => + _SearchHitCard(hit: filtered[index], api: api), + ), + ), + ], + ); + if (MediaQuery.sizeOf(context).width < 840 || filtered.isEmpty) + return Scaffold(body: searchPane); + return Scaffold( + body: Row( + children: [ + SizedBox(width: 470, child: searchPane), + VerticalDivider(width: 1, color: Theme.of(context).dividerColor), + Expanded( + child: _SearchPreview(hit: filtered.first, api: api), + ), + ], + ), + ); + } + + Future _search({String? imageId}) async { + FocusScope.of(context).unfocus(); + if (_query.text.trim().isEmpty && imageId == null) return; + setState(() { + _loading = true; + _error = null; + }); + try { + final results = await ref + .read(apiProvider) + .search(_query.text, imageId: imageId); + if (mounted) + setState(() { + _hits = results; + _searched = true; + _loading = false; + }); + } on ApiException catch (error) { + if (mounted) + setState(() { + _error = error.message; + _loading = false; + _searched = true; + }); + } + } + + Future _pickImage() async { + final source = await showModalBottomSheet( + context: context, + builder: (context) => SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + AppListTile( + icon: Icons.photo_library_outlined, + title: '从照片中选择', + onTap: () => Navigator.pop(context, ImageSource.gallery), + ), + AppListTile( + icon: Icons.camera_alt_outlined, + title: '拍摄一张照片', + onTap: () => Navigator.pop(context, ImageSource.camera), + ), + ], + ), + ), + ), + ); + if (source == null) return; + final image = await ImagePicker().pickImage( + source: source, + maxWidth: 2048, + imageQuality: 92, + ); + if (image == null || !mounted) return; + setState(() { + _loading = true; + _error = null; + }); + try { + final imageId = await ref.read(apiProvider).uploadQueryImage(image.path); + if (!mounted) return; + await _search(imageId: imageId); + } on ApiException catch (error) { + if (!mounted) return; + setState(() { + _loading = false; + _searched = true; + _error = error.message; + }); + } + } +} + +class _SearchHitCard extends StatelessWidget { + const _SearchHitCard({required this.hit, required this.api}); + final SearchHit hit; + final ImageFindApi api; + @override + Widget build(BuildContext context) => Material( + color: context.colors.surface, + borderRadius: BorderRadius.circular(14), + child: InkWell( + borderRadius: BorderRadius.circular(14), + onTap: () => context.push( + '/player/${hit.video.id}?t=${hit.positionMs}', + extra: hit.video, + ), + child: Padding( + padding: const EdgeInsets.all(8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 142, + child: AspectRatio( + aspectRatio: 16 / 9, + child: MediaCover( + api: api, + url: hit.thumbnailUrl, + treatment: hit.video.id.hashCode.isEven ? 0 : 1, + duration: formatDuration(hit.positionMs), + ), + ), + ), + const SizedBox(width: 11), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + hit.video.title, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: context.text.bodyMedium?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 7), + if (hit.evidence.isNotEmpty) + Text( + '“${hit.evidence}”', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + height: 1.45, + ), + ), + const SizedBox(height: 7), + Row( + children: [ + Icon( + Icons.auto_awesome_outlined, + size: 15, + color: context.colors.primary, + ), + const SizedBox(width: 5), + Expanded( + child: Text( + _kindLabel(hit.kind), + style: context.text.bodySmall?.copyWith( + color: context.colors.primary, + ), + ), + ), + const Icon(Icons.chevron_right_rounded, size: 19), + ], + ), + ], + ), + ), + ], + ), + ), + ), + ); +} + +class _SearchPreview extends StatelessWidget { + const _SearchPreview({required this.hit, required this.api}); + final SearchHit hit; + final ImageFindApi api; + @override + Widget build(BuildContext context) => SafeArea( + child: Padding( + padding: const EdgeInsets.all(28), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 720), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + AspectRatio( + aspectRatio: 16 / 9, + child: MediaCover( + api: api, + url: hit.thumbnailUrl, + treatment: 0, + duration: formatDuration(hit.positionMs), + borderRadius: 18, + ), + ), + const SizedBox(height: 22), + Text(hit.video.title, style: context.text.headlineMedium), + if (hit.evidence.isNotEmpty) ...[ + const SizedBox(height: 9), + Text( + '“${hit.evidence}”', + style: context.text.bodyLarge?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + const SizedBox(height: 18), + FilledButton.icon( + onPressed: () => context.push( + '/player/${hit.video.id}?t=${hit.positionMs}', + extra: hit.video, + ), + icon: const Icon(Icons.play_arrow_rounded), + label: Text('从 ${formatDuration(hit.positionMs)} 播放'), + ), + ], + ), + ), + ), + ), + ); +} + +String _kindLabel(String kind) => switch (kind) { + 'visual' => '画面语义', + 'audio' => '对白', + 'subtitle' => '字幕', + 'ocr' => '画面文字', + 'person' => '人物', + _ => '标题与资料', +}; + +class LibraryScreen extends ConsumerStatefulWidget { + const LibraryScreen({super.key}); + @override + ConsumerState createState() => _LibraryScreenState(); +} + +class _LibraryScreenState extends ConsumerState { + String tab = 'videos'; + @override + Widget build(BuildContext context) { + final api = ref.watch(apiProvider); + final Widget body = switch (tab) { + 'collections' => AsyncPane>( + value: ref.watch(collectionsProvider), + onRetry: () => ref.invalidate(collectionsProvider), + data: (items) => items.isEmpty + ? const EmptyState( + icon: Icons.collections_bookmark_outlined, + title: '还没有合集', + message: '可以把相关视频整理到同一个合集中。', + ) + : _CollectionGrid(items: items, api: api), + ), + 'people' => AsyncPane>( + value: ref.watch(peopleProvider), + onRetry: () => ref.invalidate(peopleProvider), + data: (items) => items.isEmpty + ? const EmptyState( + icon: Icons.people_outline_rounded, + title: '还没有识别到人物', + message: '人物模型完成索引后会显示在这里。', + ) + : _PeopleGrid(items: items, api: api), + ), + 'series' => _GenericApiList(path: 'series', emptyTitle: '还没有系列'), + 'tags' => _GenericApiList(path: 'tag-groups', emptyTitle: '还没有标签组'), + _ => AsyncPane>( + value: ref.watch(videosProvider), + onRetry: () => ref.invalidate(videosProvider), + data: (items) => items.isEmpty + ? const EmptyState( + icon: Icons.video_library_outlined, + title: '资料库还是空的', + message: '先添加数据源并完成一次扫描。', + ) + : MediaGrid(items: items, api: api), + ), + }; + return Scaffold( + body: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(10, 10, 6, 2), + child: Row( + children: [ + Expanded( + child: Text('资料库', style: context.text.headlineMedium), + ), + IconButton( + onPressed: () => showMessage(context, '排序和批量整理入口'), + tooltip: '资料库菜单', + icon: const Icon(Icons.more_horiz_rounded), + ), + ], + ), + ), + SizedBox( + height: 48, + child: ListView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 5), + children: [ + for (final item in const [ + ('videos', '视频'), + ('collections', '合集'), + ('series', '系列'), + ('people', '人物'), + ('tags', '标签'), + ]) + Padding( + padding: const EdgeInsets.only(right: 6), + child: ChoiceChip( + label: Text(item.$2), + selected: tab == item.$1, + onSelected: (_) => setState(() => tab = item.$1), + ), + ), + ], + ), + ), + Expanded( + child: SingleChildScrollView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 7, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 24, + ), + child: body, + ), + ), + ], + ), + ), + ); + } +} + +class ProfileScreen extends ConsumerWidget { + const ProfileScreen({super.key}); + @override + Widget build(BuildContext context, WidgetRef ref) { + final themeMode = ref.watch(themeModeProvider); + return Scaffold( + body: SafeArea( + child: ListView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 14, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 28, + ), + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 6), + child: Row( + children: [ + Container( + width: 66, + height: 66, + decoration: BoxDecoration( + color: context.colors.primary, + borderRadius: BorderRadius.circular(20), + ), + alignment: Alignment.center, + child: const Text( + '南', + style: TextStyle( + color: Colors.white, + fontSize: 22, + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('管理员', style: context.text.titleLarge), + const SizedBox(height: 4), + Text( + '仅私人可见', + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + const SizedBox(height: 5), + Row( + children: [ + Container( + width: 7, + height: 7, + decoration: const BoxDecoration( + color: AppColors.success, + shape: BoxShape.circle, + ), + ), + const SizedBox(width: 6), + Expanded( + child: Text( + ref.watch(apiProvider).serverRoot ?? + 'ImageFind', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ), + ], + ), + ], + ), + ), + IconButton( + onPressed: () => _themeSheet(context, ref, themeMode), + tooltip: '外观设置', + icon: const Icon(Icons.settings_outlined), + ), + ], + ), + ), + const SizedBox(height: 22), + Row( + children: [ + Expanded( + child: _ProfileShortcut( + icon: Icons.history_rounded, + label: '观看历史', + onTap: () => context.push('/manage/history'), + ), + ), + const SizedBox(width: 7), + Expanded( + child: _ProfileShortcut( + icon: Icons.star_outline_rounded, + label: '我的收藏', + onTap: () => context.go('/library'), + ), + ), + const SizedBox(width: 7), + Expanded( + child: _ProfileShortcut( + icon: Icons.download_for_offline_outlined, + label: '离线内容', + onTap: () => context.push('/manage/transfers'), + ), + ), + ], + ), + const SizedBox(height: 14), + Material( + color: context.colors.primaryContainer, + borderRadius: BorderRadius.circular(16), + child: InkWell( + borderRadius: BorderRadius.circular(16), + onTap: () => context.push('/workbench'), + child: Padding( + padding: const EdgeInsets.all(16), + child: Row( + children: [ + Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: context.colors.primary, + borderRadius: BorderRadius.circular(13), + ), + child: Icon( + Icons.build_outlined, + color: context.colors.onPrimary, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('服务工作台', style: context.text.titleMedium), + const SizedBox(height: 3), + Text( + '数据源、传输、索引和系统维护', + style: context.text.bodySmall?.copyWith( + color: context.colors.onPrimaryContainer, + ), + ), + ], + ), + ), + const Icon(Icons.chevron_right_rounded), + ], + ), + ), + ), + ), + const SectionHeading(title: '播放与外观'), + GroupSurface( + children: [ + AppListTile( + icon: Icons.play_circle_outline_rounded, + title: '自动连播', + subtitle: '播完后继续相关内容', + trailing: Switch.adaptive( + value: true, + onChanged: (value) => ref + .read(apiProvider) + .updatePreferences({'autoplay': value}) + .catchError((_) {}), + ), + ), + AppListTile( + icon: Icons.visibility_off_outlined, + title: '隐私遮罩', + subtitle: '浏览时模糊所有封面', + trailing: Switch.adaptive( + value: false, + onChanged: (value) => ref + .read(apiProvider) + .updatePreferences({'mask_covers': value}) + .catchError((_) {}), + ), + ), + AppListTile( + icon: Icons.dark_mode_outlined, + title: '外观', + subtitle: switch (themeMode) { + ThemeMode.dark => '深色', + ThemeMode.light => '浅色', + _ => '跟随系统', + }, + onTap: () => _themeSheet(context, ref, themeMode), + ), + ], + ), + const SectionHeading(title: '账户与服务'), + GroupSurface( + children: [ + AppListTile( + icon: Icons.dns_outlined, + title: ref.watch(apiProvider).serverRoot ?? '服务器', + subtitle: 'ImageFind 直连模式', + onTap: () => showMessage(context, '服务器连接正常'), + ), + AppListTile( + icon: Icons.password_rounded, + title: '安全与密码', + subtitle: '更新管理员凭据', + onTap: () => context.push('/manage/security'), + ), + AppListTile( + icon: Icons.key_outlined, + title: 'API Token', + subtitle: '管理外部访问凭证', + onTap: () => context.push('/manage/tokens'), + ), + ], + ), + const SizedBox(height: 16), + OutlinedButton.icon( + onPressed: () => ref.read(sessionProvider.notifier).logout(), + icon: Icon(Icons.logout_rounded, color: context.colors.error), + label: Text( + '退出登录', + style: TextStyle(color: context.colors.error), + ), + ), + ], + ), + ), + ); + } +} + +Future _themeSheet( + BuildContext context, + WidgetRef ref, + ThemeMode current, +) => showModalBottomSheet( + context: context, + builder: (context) => SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 18), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.all(12), + child: Text('外观', style: context.text.titleLarge), + ), + for (final item in const [ + (ThemeMode.system, '跟随系统', Icons.brightness_auto_outlined), + (ThemeMode.light, '浅色', Icons.light_mode_outlined), + (ThemeMode.dark, '深色', Icons.dark_mode_outlined), + ]) + ListTile( + minTileHeight: context.minTouch, + leading: Icon(item.$3), + title: Text(item.$2), + trailing: current == item.$1 + ? Icon(Icons.check_rounded, color: context.colors.primary) + : null, + onTap: () { + ref.read(themeModeProvider.notifier).set(item.$1); + Navigator.pop(context); + }, + ), + ], + ), + ), + ), +); + +class _ProfileShortcut extends StatelessWidget { + const _ProfileShortcut({ + required this.icon, + required this.label, + required this.onTap, + }); + final IconData icon; + final String label; + final VoidCallback onTap; + @override + Widget build(BuildContext context) => Material( + color: context.colors.surface, + borderRadius: BorderRadius.circular(14), + child: InkWell( + borderRadius: BorderRadius.circular(14), + onTap: onTap, + child: ConstrainedBox( + constraints: BoxConstraints(minHeight: context.minTouch + 32), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, color: context.colors.primary), + const SizedBox(height: 6), + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: context.text.bodySmall?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ), + ); +} + +class _CollectionStrip extends StatelessWidget { + const _CollectionStrip({required this.items, required this.api}); + final List items; + final ImageFindApi api; + @override + Widget build(BuildContext context) => SizedBox( + height: 154, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: items.length, + separatorBuilder: (_, _) => const SizedBox(width: 8), + itemBuilder: (context, index) => SizedBox( + width: 194, + child: InkWell( + onTap: () => context.push( + '/collection/${items[index].id}', + extra: items[index], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + AspectRatio( + aspectRatio: 16 / 9, + child: MediaCover( + api: api, + url: items[index].thumbnailUrl, + treatment: index % 2, + ), + ), + const SizedBox(height: 7), + Text( + items[index].name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: context.text.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ), + ), + ); +} + +class _PeopleStrip extends StatelessWidget { + const _PeopleStrip({required this.items, required this.api}); + final List items; + final ImageFindApi api; + @override + Widget build(BuildContext context) => SizedBox( + height: 112, + child: ListView.separated( + scrollDirection: Axis.horizontal, + itemCount: items.length, + separatorBuilder: (_, _) => const SizedBox(width: 12), + itemBuilder: (context, index) => SizedBox( + width: 78, + child: InkWell( + onTap: () => + context.push('/person/${items[index].id}', extra: items[index]), + child: Column( + children: [ + ClipOval( + child: SizedBox( + width: 70, + height: 70, + child: MediaCover( + api: api, + url: items[index].thumbnailUrl, + treatment: index % 2, + borderRadius: 0, + ), + ), + ), + const SizedBox(height: 7), + Text( + items[index].name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: context.text.bodySmall?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ), + ), + ); +} + +class _CollectionGrid extends StatelessWidget { + const _CollectionGrid({required this.items, required this.api}); + final List items; + final ImageFindApi api; + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final count = constraints.maxWidth >= 900 + ? 4 + : constraints.maxWidth >= 620 + ? 3 + : 2; + return GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: items.length, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: count, + crossAxisSpacing: 8, + mainAxisSpacing: 15, + childAspectRatio: 1.28, + ), + itemBuilder: (context, index) => InkWell( + onTap: () => context.push( + '/collection/${items[index].id}', + extra: items[index], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + AspectRatio( + aspectRatio: 16 / 9, + child: MediaCover( + api: api, + url: items[index].thumbnailUrl, + treatment: index % 2, + ), + ), + const SizedBox(height: 7), + Text( + items[index].name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: context.text.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + Text( + '${items[index].videoCount} 个视频', + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + ), + ), + ); + }, + ); +} + +class _PeopleGrid extends StatelessWidget { + const _PeopleGrid({required this.items, required this.api}); + final List items; + final ImageFindApi api; + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final count = constraints.maxWidth >= 900 + ? 6 + : constraints.maxWidth >= 620 + ? 4 + : 3; + return GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: items.length, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: count, + crossAxisSpacing: 9, + mainAxisSpacing: 15, + childAspectRatio: .83, + ), + itemBuilder: (context, index) => InkWell( + onTap: () => + context.push('/person/${items[index].id}', extra: items[index]), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + AspectRatio( + aspectRatio: 1, + child: MediaCover( + api: api, + url: items[index].thumbnailUrl, + treatment: index % 2, + ), + ), + const SizedBox(height: 7), + Text( + items[index].name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: context.text.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + Text( + '${items[index].faceCount} 张人脸', + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + ), + ), + ); + }, + ); +} + +class _GenericApiList extends ConsumerWidget { + const _GenericApiList({required this.path, required this.emptyTitle}); + final String path; + final String emptyTitle; + @override + Widget build(BuildContext context, WidgetRef ref) => + FutureBuilder>>( + future: ref.read(apiProvider).getList(path), + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) + return const Center( + child: Padding( + padding: EdgeInsets.all(36), + child: CircularProgressIndicator(), + ), + ); + if (snapshot.hasError) + return EmptyState( + icon: Icons.cloud_off_outlined, + title: '暂时无法载入', + message: '${snapshot.error}', + ); + final items = snapshot.data ?? const []; + if (items.isEmpty) + return EmptyState( + icon: Icons.inventory_2_outlined, + title: emptyTitle, + message: '创建或整理后会显示在这里。', + ); + return GroupSurface( + children: items + .map( + (item) => AppListTile( + icon: path == 'series' + ? Icons.collections_bookmark_outlined + : Icons.tag_outlined, + title: '${item['name'] ?? '未命名'}', + subtitle: + '${item['video_count'] ?? item['tags']?.length ?? 0} 项', + onTap: () {}, + ), + ) + .toList(), + ); + }, + ); +} + +class CollectionDetailScreen extends ConsumerWidget { + const CollectionDetailScreen({super.key, required this.id, this.initial}); + final String id; + final CollectionRecord? initial; + @override + Widget build(BuildContext context, WidgetRef ref) => Scaffold( + appBar: InlinePageHeader( + title: initial?.name ?? '合集', + actions: [ + IconButton( + onPressed: () => showMessage(context, '合集操作'), + icon: const Icon(Icons.more_horiz_rounded), + ), + ], + ), + body: FutureBuilder>( + future: ref.read(apiProvider).getMap('collections/$id'), + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) + return const Center(child: CircularProgressIndicator()); + if (snapshot.hasError) + return EmptyState( + icon: Icons.cloud_off_outlined, + title: '无法载入合集', + message: '${snapshot.error}', + ); + final data = snapshot.data ?? const {}; + final collection = CollectionRecord.fromJson(data); + final videos = asJsonList( + data['videos'], + ).map(VideoRecord.fromJson).toList(); + return ListView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 12, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 24, + ), + children: [ + Text(collection.name, style: context.text.headlineMedium), + if (collection.description.isNotEmpty) ...[ + const SizedBox(height: 8), + Text( + collection.description, + style: context.text.bodyMedium?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + const SizedBox(height: 18), + MediaGrid(items: videos, api: ref.read(apiProvider)), + ], + ); + }, + ), + ); +} + +class PersonDetailScreen extends ConsumerWidget { + const PersonDetailScreen({super.key, required this.id, this.initial}); + final String id; + final PersonRecord? initial; + @override + Widget build(BuildContext context, WidgetRef ref) => Scaffold( + appBar: InlinePageHeader( + title: initial?.name ?? '人物', + actions: [ + IconButton( + onPressed: () => showMessage(context, '人物编辑入口'), + icon: const Icon(Icons.more_horiz_rounded), + ), + ], + ), + body: FutureBuilder>( + future: ref.read(apiProvider).videos(query: {'has_people': true}), + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) + return const Center(child: CircularProgressIndicator()); + if (snapshot.hasError) + return EmptyState( + icon: Icons.cloud_off_outlined, + title: '无法载入人物', + message: '${snapshot.error}', + ); + return ListView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 12, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 24, + ), + children: [ + Row( + children: [ + ClipOval( + child: SizedBox( + width: 72, + height: 72, + child: MediaCover( + api: ref.read(apiProvider), + url: initial?.thumbnailUrl, + treatment: 1, + borderRadius: 0, + ), + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + initial?.name ?? '待命名人物', + style: context.text.titleLarge, + ), + Text( + '${initial?.faceCount ?? 0} 张人脸', + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + ), + ), + OutlinedButton( + onPressed: () => showMessage(context, '人物重命名'), + child: const Text('编辑'), + ), + ], + ), + const SectionHeading(title: '出现的视频'), + MediaGrid( + items: snapshot.data ?? const [], + api: ref.read(apiProvider), + ), + ], + ); + }, + ), + ); +} diff --git a/mobile/lib/src/screens/player_screen.dart b/mobile/lib/src/screens/player_screen.dart new file mode 100644 index 0000000..fd195a9 --- /dev/null +++ b/mobile/lib/src/screens/player_screen.dart @@ -0,0 +1,756 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:media_kit/media_kit.dart'; +import 'package:media_kit_video/media_kit_video.dart'; + +import '../api.dart'; +import '../models.dart'; +import '../state.dart'; +import '../theme.dart'; +import '../transfer_services.dart'; +import '../widgets.dart'; + +class PlayerScreen extends ConsumerStatefulWidget { + const PlayerScreen({ + super.key, + required this.videoId, + this.initialVideo, + this.startMs = 0, + }); + final String videoId; + final VideoRecord? initialVideo; + final int startMs; + @override + ConsumerState createState() => _PlayerScreenState(); +} + +class _PlayerScreenState extends ConsumerState + with WidgetsBindingObserver { + late final Player _player; + late final VideoController _controller; + StreamSubscription? _errorSubscription; + Timer? _progressTimer; + VideoRecord? _video; + bool _loading = true; + bool _fallbackAttempted = false; + bool _favorited = false; + int _tab = 0; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _player = Player(); + _controller = VideoController(_player); + _video = widget.initialVideo; + _favorited = _video?.favorited ?? false; + WidgetsBinding.instance.addPostFrameCallback((_) => _initialize()); + } + + Future _initialize() async { + final api = ref.read(apiProvider); + if (_video == null) { + try { + final videos = await api.videos(); + _video = videos.where((item) => item.id == widget.videoId).firstOrNull; + } catch (_) {} + } + _video ??= VideoRecord(id: widget.videoId, title: '视频详情', durationMs: 0); + _errorSubscription = _player.stream.error.listen((message) { + if (message.isNotEmpty && !_fallbackAttempted) _openHlsFallback(); + }); + final offline = await ref + .read(offlineDatabaseProvider) + .downloadFor(widget.videoId); + final useOffline = + offline?.status == 'completed' && + offline != null && + await File(offline.localPath).exists(); + await _player.open( + useOffline + ? Media(offline.localPath) + : Media( + api.streamUri(_video!).toString(), + httpHeaders: api.mediaHeaders, + ), + play: true, + ); + if (widget.startMs > 0) + await _player.seek(Duration(milliseconds: widget.startMs)); + _progressTimer = Timer.periodic( + const Duration(seconds: 15), + (_) => _saveProgress(), + ); + if (mounted) setState(() => _loading = false); + } + + Future _openHlsFallback() async { + _fallbackAttempted = true; + final api = ref.read(apiProvider); + try { + final result = await api.postMap( + 'videos/${widget.videoId}/preview', + data: {'start_ms': _player.state.position.inMilliseconds}, + ); + final playlist = api.absoluteUri(result['playlist_url']?.toString()); + if (playlist.hasScheme) + await _player.open( + Media(playlist.toString(), httpHeaders: api.mediaHeaders), + play: true, + ); + } on ApiException catch (error) { + if (mounted) + showMessage(context, '播放器无法打开此视频:${error.message}', error: true); + } + } + + Future _saveProgress({bool completed = false}) async { + if (_video == null) return; + try { + await ref.read(apiProvider).updateVideoState(widget.videoId, { + 'progress_ms': _player.state.position.inMilliseconds, + if (completed) 'completed': true, + }); + } catch (_) {} + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.paused || + state == AppLifecycleState.inactive || + state == AppLifecycleState.detached) + _saveProgress(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _progressTimer?.cancel(); + _errorSubscription?.cancel(); + _saveProgress(); + _player.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final video = + _video ?? + widget.initialVideo ?? + VideoRecord(id: widget.videoId, title: '视频详情', durationMs: 0); + final player = _PlayerPane( + player: _player, + controller: _controller, + loading: _loading, + onBack: () => Navigator.of(context).maybePop(), + ); + final detail = _DetailPane( + video: video, + player: _player, + tab: _tab, + favorited: _favorited, + onTab: (value) => setState(() => _tab = value), + onFavorite: _toggleFavorite, + onMarker: _addMarker, + onOffline: _downloadOffline, + ); + return Scaffold( + backgroundColor: context.isDark + ? AppColors.darkCanvas + : AppColors.lightCanvas, + body: LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth >= 840) { + return SafeArea( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + flex: 6, + child: ColoredBox( + color: Colors.black, + child: Align( + alignment: Alignment.topCenter, + child: player, + ), + ), + ), + VerticalDivider( + width: 1, + color: Theme.of(context).dividerColor, + ), + Expanded(flex: 5, child: detail), + ], + ), + ); + } + return CustomScrollView( + slivers: [ + SliverToBoxAdapter(child: player), + SliverToBoxAdapter(child: detail), + ], + ); + }, + ), + ); + } + + Future _toggleFavorite() async { + final next = !_favorited; + setState(() => _favorited = next); + try { + await ref.read(apiProvider).updateVideoState(widget.videoId, { + 'favorited': next, + }); + } on ApiException catch (error) { + if (mounted) { + setState(() => _favorited = !next); + showMessage(context, error.message, error: true); + } + } + } + + Future _addMarker() async { + try { + await ref + .read(apiProvider) + .addMarker(widget.videoId, _player.state.position.inMilliseconds); + if (mounted) { + showMessage( + context, + '已记住 ${formatDuration(_player.state.position.inMilliseconds)}', + ); + setState(() => _tab = 1); + } + } on ApiException catch (error) { + if (mounted) showMessage(context, error.message, error: true); + } + } + + Future _downloadOffline() async { + final video = _video; + if (video == null) return; + if (ref.read(offlineDownloadControllerProvider).contains(video.id)) { + showMessage(context, '正在下载,可在传输中心查看进度'); + return; + } + showMessage(context, '已开始离线下载'); + try { + await ref + .read(offlineDownloadControllerProvider.notifier) + .download(video); + if (mounted) showMessage(context, '已保存到本机离线内容'); + } catch (error) { + if (mounted) { + showMessage( + context, + error is ApiException ? error.message : '离线下载失败,请稍后重试。', + error: true, + ); + } + } + } +} + +class _PlayerPane extends StatelessWidget { + const _PlayerPane({ + required this.player, + required this.controller, + required this.loading, + required this.onBack, + }); + final Player player; + final VideoController controller; + final bool loading; + final VoidCallback onBack; + @override + Widget build(BuildContext context) => AspectRatio( + aspectRatio: 16 / 9, + child: ColoredBox( + color: Colors.black, + child: Stack( + fit: StackFit.expand, + children: [ + Video( + controller: controller, + fit: BoxFit.contain, + controls: NoVideoControls, + ), + if (loading) + const Center(child: CircularProgressIndicator(color: Colors.white)), + Align( + alignment: Alignment.topCenter, + child: SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2), + child: Row( + children: [ + IconButton( + onPressed: onBack, + tooltip: '返回', + icon: const Icon( + Icons.arrow_back_ios_new_rounded, + color: Colors.white, + ), + ), + const Spacer(), + IconButton( + onPressed: () {}, + tooltip: '更多播放选项', + icon: const Icon( + Icons.more_horiz_rounded, + color: Colors.white, + ), + ), + ], + ), + ), + ), + ), + Center( + child: StreamBuilder( + stream: player.stream.playing, + initialData: player.state.playing, + builder: (context, snapshot) => IconButton.filled( + style: IconButton.styleFrom( + backgroundColor: Colors.black.withValues(alpha: .58), + foregroundColor: Colors.white, + minimumSize: const Size(58, 58), + ), + onPressed: () => + snapshot.data == true ? player.pause() : player.play(), + tooltip: snapshot.data == true ? '暂停' : '播放', + icon: Icon( + snapshot.data == true + ? Icons.pause_rounded + : Icons.play_arrow_rounded, + size: 34, + ), + ), + ), + ), + Align( + alignment: Alignment.bottomCenter, + child: SafeArea( + top: false, + child: Container( + padding: const EdgeInsets.fromLTRB(8, 20, 8, 4), + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Colors.transparent, + Colors.black.withValues(alpha: .72), + ], + ), + ), + child: StreamBuilder( + stream: player.stream.position, + initialData: player.state.position, + builder: (context, snapshot) { + final position = snapshot.data ?? Duration.zero; + final duration = player.state.duration; + final max = duration.inMilliseconds <= 0 + ? 1.0 + : duration.inMilliseconds.toDouble(); + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Slider( + value: position.inMilliseconds + .clamp(0, max.toInt()) + .toDouble(), + max: max, + onChanged: (value) => player.seek( + Duration(milliseconds: value.round()), + ), + ), + Row( + children: [ + Text( + formatDuration(position.inMilliseconds), + style: const TextStyle( + color: Colors.white, + fontSize: 11, + fontFeatures: [FontFeature.tabularFigures()], + ), + ), + const Spacer(), + Text( + formatDuration(duration.inMilliseconds), + style: const TextStyle( + color: Colors.white, + fontSize: 11, + fontFeatures: [FontFeature.tabularFigures()], + ), + ), + ], + ), + ], + ); + }, + ), + ), + ), + ), + ], + ), + ), + ); +} + +class _DetailPane extends ConsumerWidget { + const _DetailPane({ + required this.video, + required this.player, + required this.tab, + required this.favorited, + required this.onTab, + required this.onFavorite, + required this.onMarker, + required this.onOffline, + }); + final VideoRecord video; + final Player player; + final int tab; + final bool favorited; + final ValueChanged onTab; + final VoidCallback onFavorite; + final VoidCallback onMarker; + final VoidCallback onOffline; + @override + Widget build(BuildContext context, WidgetRef ref) => Padding( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 17, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 28, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + video.title, + style: context.text.titleLarge, + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 5, + children: [ + if (video.series.isNotEmpty) + _Meta( + text: video.series, + icon: Icons.collections_bookmark_outlined, + ), + if (video.sourceName.isNotEmpty) + _Meta(text: video.sourceName, icon: Icons.dns_outlined), + _Meta( + text: video.resolutionLabel, + icon: Icons.high_quality_outlined, + ), + _Meta(text: video.durationLabel, icon: Icons.schedule_rounded), + ], + ), + const SizedBox(height: 15), + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + _PlayerAction( + icon: favorited ? Icons.star_rounded : Icons.star_outline_rounded, + label: '收藏', + active: favorited, + onTap: onFavorite, + ), + _PlayerAction( + icon: Icons.bookmark_add_outlined, + label: '记住此刻', + onTap: onMarker, + ), + _PlayerAction( + icon: Icons.download_for_offline_outlined, + label: '离线缓存', + onTap: onOffline, + ), + _PlayerAction( + icon: Icons.more_horiz_rounded, + label: '更多', + onTap: () => showMessage(context, '更多播放选项'), + ), + ], + ), + const SizedBox(height: 10), + Container( + padding: const EdgeInsets.symmetric(horizontal: 11, vertical: 9), + decoration: BoxDecoration( + color: context.colors.primaryContainer.withValues(alpha: .55), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + children: [ + Icon( + Icons.lock_outline_rounded, + size: 17, + color: context.colors.primary, + ), + const SizedBox(width: 7), + Expanded( + child: Text( + '仅保存在你的 ImageFind 服务中', + style: context.text.bodySmall?.copyWith( + color: context.colors.onPrimaryContainer, + ), + ), + ), + ], + ), + ), + const SizedBox(height: 12), + SegmentedButton( + segments: const [ + ButtonSegment(value: 0, label: Text('逐字稿')), + ButtonSegment(value: 1, label: Text('收藏时刻')), + ButtonSegment(value: 2, label: Text('详情')), + ], + selected: {tab}, + onSelectionChanged: (value) => onTab(value.first), + showSelectedIcon: false, + ), + const SizedBox(height: 14), + if (tab == 0) _TranscriptTab(videoId: video.id, player: player), + if (tab == 1) _MarkersTab(videoId: video.id, player: player), + if (tab == 2) _InfoTab(video: video), + ], + ), + ); +} + +class _Meta extends StatelessWidget { + const _Meta({required this.text, required this.icon}); + final String text; + final IconData icon; + @override + Widget build(BuildContext context) => Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 15, color: context.colors.onSurfaceVariant), + const SizedBox(width: 4), + Text( + text, + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + ); +} + +class _PlayerAction extends StatelessWidget { + const _PlayerAction({ + required this.icon, + required this.label, + required this.onTap, + this.active = false, + }); + final IconData icon; + final String label; + final VoidCallback onTap; + final bool active; + @override + Widget build(BuildContext context) => InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: ConstrainedBox( + constraints: BoxConstraints( + minWidth: 66, + minHeight: context.minTouch + 16, + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + icon, + color: active + ? context.colors.primary + : context.colors.onSurfaceVariant, + ), + const SizedBox(height: 4), + Text( + label, + style: context.text.bodySmall?.copyWith( + color: active + ? context.colors.primary + : context.colors.onSurfaceVariant, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ), + ); +} + +class _TranscriptTab extends ConsumerWidget { + const _TranscriptTab({required this.videoId, required this.player}); + final String videoId; + final Player player; + @override + Widget build(BuildContext context, WidgetRef ref) => + FutureBuilder>( + future: ref.read(apiProvider).transcript(videoId), + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) + return const Center( + child: Padding( + padding: EdgeInsets.all(28), + child: CircularProgressIndicator(), + ), + ); + if (snapshot.hasError) + return EmptyState( + icon: Icons.subtitles_off_outlined, + title: '逐字稿暂不可用', + message: '${snapshot.error}', + ); + final lines = snapshot.data ?? const []; + if (lines.isEmpty) + return const EmptyState( + icon: Icons.subtitles_outlined, + title: '还没有逐字稿', + message: '语音索引完成后会显示在这里。', + ); + return GroupSurface( + children: lines + .map( + (line) => ListTile( + minTileHeight: context.minTouch, + leading: Text( + formatDuration(line.startMs), + style: context.text.bodySmall?.copyWith( + color: context.colors.primary, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + title: Text(line.text, style: context.text.bodyMedium), + onTap: () => + player.seek(Duration(milliseconds: line.startMs)), + ), + ) + .toList(), + ); + }, + ); +} + +class _MarkersTab extends ConsumerStatefulWidget { + const _MarkersTab({required this.videoId, required this.player}); + final String videoId; + final Player player; + @override + ConsumerState<_MarkersTab> createState() => _MarkersTabState(); +} + +class _MarkersTabState extends ConsumerState<_MarkersTab> { + late Future> future = ref + .read(apiProvider) + .markers(widget.videoId); + @override + Widget build(BuildContext context) => FutureBuilder>( + future: future, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) + return const Center( + child: Padding( + padding: EdgeInsets.all(28), + child: CircularProgressIndicator(), + ), + ); + if (snapshot.hasError) + return EmptyState( + icon: Icons.bookmark_border_rounded, + title: '无法载入收藏时刻', + message: '${snapshot.error}', + ); + final items = snapshot.data ?? const []; + if (items.isEmpty) + return const EmptyState( + icon: Icons.bookmark_add_outlined, + title: '还没有收藏时刻', + message: '播放到想记住的位置,再点击“记住此刻”。', + ); + return GroupSurface( + children: items + .map( + (item) => ListTile( + minTileHeight: context.minTouch, + title: Text(item.title), + subtitle: Text( + formatDuration(item.positionMs), + style: const TextStyle( + fontFeatures: [FontFeature.tabularFigures()], + ), + ), + trailing: IconButton( + onPressed: () async { + await ref + .read(apiProvider) + .deleteMarker(widget.videoId, item.id); + setState( + () => future = ref + .read(apiProvider) + .markers(widget.videoId), + ); + }, + tooltip: '删除', + icon: const Icon(Icons.delete_outline_rounded), + ), + onTap: () => + widget.player.seek(Duration(milliseconds: item.positionMs)), + ), + ) + .toList(), + ); + }, + ); +} + +class _InfoTab extends StatelessWidget { + const _InfoTab({required this.video}); + final VideoRecord video; + @override + Widget build(BuildContext context) => GroupSurface( + children: [ + AppListTile( + icon: Icons.title_rounded, + title: '标题', + subtitle: video.title, + onTap: () => showMessage(context, '编辑视频标题'), + ), + AppListTile( + icon: Icons.collections_bookmark_outlined, + title: '系列', + subtitle: video.series.isEmpty ? '未整理' : video.series, + onTap: () => showMessage(context, '编辑视频系列'), + ), + AppListTile( + icon: Icons.dns_outlined, + title: '来源', + subtitle: + '${video.sourceName.isEmpty ? '未知来源' : video.sourceName} · ${video.width}×${video.height}', + ), + AppListTile( + icon: Icons.tag_outlined, + title: '标签', + subtitle: video.tags.isEmpty ? '暂无标签' : video.tags.join(' · '), + onTap: () => showMessage(context, '编辑视频标签'), + ), + ], + ); +} diff --git a/mobile/lib/src/screens/shell.dart b/mobile/lib/src/screens/shell.dart new file mode 100644 index 0000000..87be7c3 --- /dev/null +++ b/mobile/lib/src/screens/shell.dart @@ -0,0 +1,267 @@ +import 'dart:async'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../theme.dart'; +import '../api.dart'; +import '../state.dart'; +import '../transfer_services.dart'; +import '../widgets.dart'; + +class AppShell extends ConsumerWidget { + const AppShell({super.key, required this.index, required this.child}); + final int index; + final Widget child; + + static const _paths = ['/home', '/search', '/library', '/profile']; + @override + Widget build(BuildContext context, WidgetRef ref) { + final expanded = MediaQuery.sizeOf(context).width >= 600; + if (expanded) { + return Scaffold( + body: SafeArea( + child: Row( + children: [ + NavigationRail( + selectedIndex: index, + labelType: NavigationRailLabelType.all, + leading: Padding( + padding: const EdgeInsets.only(bottom: 18), + child: Column( + children: [ + Container( + width: 46, + height: 46, + decoration: BoxDecoration( + color: context.colors.primary, + borderRadius: BorderRadius.circular(14), + ), + alignment: Alignment.center, + child: const Text( + 'IF', + style: TextStyle( + color: Colors.white, + fontWeight: FontWeight.w800, + ), + ), + ), + const SizedBox(height: 14), + IconButton.filled( + style: IconButton.styleFrom( + backgroundColor: AppColors.coral, + foregroundColor: Colors.white, + minimumSize: const Size(48, 48), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(13), + ), + ), + onPressed: () => _showAddSheet(context, ref), + tooltip: '添加', + icon: const Icon(Icons.add_rounded), + ), + ], + ), + ), + destinations: const [ + NavigationRailDestination( + icon: Icon(Icons.home_outlined), + selectedIcon: Icon(Icons.home_rounded), + label: Text('首页'), + ), + NavigationRailDestination( + icon: Icon(Icons.search_rounded), + label: Text('搜索'), + ), + NavigationRailDestination( + icon: Icon(Icons.video_library_outlined), + selectedIcon: Icon(Icons.video_library_rounded), + label: Text('资料库'), + ), + NavigationRailDestination( + icon: Icon(Icons.person_outline_rounded), + selectedIcon: Icon(Icons.person_rounded), + label: Text('我的'), + ), + ], + onDestinationSelected: (value) => context.go(_paths[value]), + ), + VerticalDivider(width: 1, color: Theme.of(context).dividerColor), + Expanded(child: child), + ], + ), + ), + ); + } + final selected = index >= 2 ? index + 1 : index; + return Scaffold( + body: child, + bottomNavigationBar: NavigationBar( + selectedIndex: selected, + onDestinationSelected: (value) { + if (value == 2) { + _showAddSheet(context, ref); + return; + } + context.go(_paths[value > 2 ? value - 1 : value]); + }, + destinations: [ + const NavigationDestination( + icon: Icon(Icons.home_outlined), + selectedIcon: Icon(Icons.home_rounded), + label: '首页', + ), + const NavigationDestination( + icon: Icon(Icons.search_rounded), + label: '搜索', + ), + NavigationDestination( + icon: Container( + width: 50, + height: 38, + margin: const EdgeInsets.only(top: 2), + decoration: BoxDecoration( + color: AppColors.coral, + borderRadius: BorderRadius.circular(12), + ), + child: const Icon(Icons.add_rounded, color: Colors.white), + ), + label: '添加', + ), + const NavigationDestination( + icon: Icon(Icons.video_library_outlined), + selectedIcon: Icon(Icons.video_library_rounded), + label: '资料库', + ), + const NavigationDestination( + icon: Icon(Icons.person_outline_rounded), + selectedIcon: Icon(Icons.person_rounded), + label: '我的', + ), + ], + ), + ); + } +} + +Future _showAddSheet(BuildContext context, WidgetRef ref) async { + await showModalBottomSheet( + context: context, + useSafeArea: true, + isScrollControlled: true, + builder: (sheetContext) => Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 22), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('添加到 ImageFind', style: sheetContext.text.titleLarge), + const SizedBox(height: 6), + Text( + '选择视频文件、创建服务器下载,或管理媒体来源。', + style: sheetContext.text.bodyMedium?.copyWith( + color: sheetContext.colors.onSurfaceVariant, + ), + ), + const SizedBox(height: 18), + GroupSurface( + children: [ + AppListTile( + icon: Icons.upload_file_outlined, + title: '从此设备上传', + subtitle: '选择视频后创建可恢复的分块上传', + onTap: () async { + Navigator.pop(sheetContext); + final result = await FilePicker.pickFile( + type: FileType.video, + ); + if (result != null && context.mounted) { + try { + final sources = await ref + .read(apiProvider) + .writableSources(); + if (!context.mounted) return; + if (sources.isEmpty) { + showMessage( + context, + '没有可写的数据源,请先在服务工作台中配置。', + error: true, + ); + context.push('/manage/sources'); + return; + } + final sourceId = sources.length == 1 + ? '${sources.first['id']}' + : await _chooseUploadSource(context, sources); + if (sourceId == null || !context.mounted) return; + unawaited( + ref + .read(deviceUploadProvider.notifier) + .start(result, sourceId) + .catchError((_) {}), + ); + showMessage(context, '${result.name} 已开始上传'); + context.push('/manage/transfers'); + } on ApiException catch (error) { + if (context.mounted) { + showMessage(context, error.message, error: true); + } + } + } + }, + ), + AppListTile( + icon: Icons.link_rounded, + title: '从链接下载', + subtitle: '让 NAS 在后台下载远程视频', + onTap: () { + Navigator.pop(sheetContext); + context.push('/manage/transfers'); + }, + ), + AppListTile( + icon: Icons.dns_outlined, + title: '管理数据源', + subtitle: '本地目录、WebDAV 与 AList', + onTap: () { + Navigator.pop(sheetContext); + context.push('/manage/sources'); + }, + ), + ], + ), + ], + ), + ), + ); +} + +Future _chooseUploadSource( + BuildContext context, + List> sources, +) => showModalBottomSheet( + context: context, + useSafeArea: true, + builder: (context) => Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 18), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(6, 2, 6, 12), + child: Text('上传到', style: context.text.titleLarge), + ), + for (final source in sources) + AppListTile( + icon: Icons.dns_outlined, + title: '${source['name'] ?? '数据源'}', + subtitle: '${source['kind'] ?? source['driver'] ?? ''}', + onTap: () => Navigator.pop(context, '${source['id']}'), + ), + ], + ), + ), +); diff --git a/mobile/lib/src/screens/workbench_screens.dart b/mobile/lib/src/screens/workbench_screens.dart new file mode 100644 index 0000000..145a967 --- /dev/null +++ b/mobile/lib/src/screens/workbench_screens.dart @@ -0,0 +1,1154 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../api.dart'; +import '../models.dart'; +import '../state.dart'; +import '../theme.dart'; +import '../transfer_services.dart'; +import '../widgets.dart'; + +class WorkbenchScreen extends ConsumerWidget { + const WorkbenchScreen({super.key}); + static const sections = [ + _Section('transfers', '传输', '上传、服务器下载与离线内容', Icons.swap_vert_rounded), + _Section('files', '文件', '浏览媒体来源中的文件', Icons.folder_outlined), + _Section('sources', '数据源', '本地目录、WebDAV 与 AList', Icons.dns_outlined), + _Section('jobs', '后台任务', '扫描、索引和维护任务', Icons.schedule_rounded), + _Section('models', 'AI 模型', '画面、文字、人物和语音模型', Icons.memory_rounded), + _Section('speech', '语音与诊断', '逐字稿覆盖与识别策略', Icons.graphic_eq_rounded), + _Section('resources', '资源控制', '性能档位、缓存与后台服务', Icons.speed_rounded), + _Section( + 'diagnostics', + '系统诊断', + '数据库、推理与存储状态', + Icons.health_and_safety_outlined, + ), + _Section('backups', '备份与恢复', '导出配置与恢复资料', Icons.backup_outlined), + _Section('trash', '回收站', '恢复或永久删除文件', Icons.delete_outline_rounded), + _Section('tokens', 'API Token', '外部访问凭证', Icons.key_outlined), + _Section( + 'tag-suggestions', + '标签建议', + '审核 AI 整理结果', + Icons.auto_awesome_outlined, + ), + ]; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final wide = MediaQuery.sizeOf(context).width >= 840; + final navigation = ListView( + padding: const EdgeInsets.fromLTRB(10, 12, 10, 24), + children: [ + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: context.colors.primaryContainer, + borderRadius: BorderRadius.circular(16), + ), + child: Row( + children: [ + Container( + width: 44, + height: 44, + decoration: BoxDecoration( + color: AppColors.success.withValues(alpha: .13), + borderRadius: BorderRadius.circular(14), + ), + child: const Icon( + Icons.check_rounded, + color: AppColors.success, + ), + ), + const SizedBox(width: 11), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '服务运行正常', + style: context.text.bodyMedium?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + Text( + '状态来自 ImageFind 实时接口', + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + ), + const SizedBox(height: 14), + for (final section in sections) + ListTile( + minTileHeight: context.minTouch, + leading: Icon(section.icon, color: context.colors.primary), + title: Text(section.title), + subtitle: Text( + section.subtitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + trailing: const Icon(Icons.chevron_right_rounded, size: 20), + onTap: () => context.push('/manage/${section.id}'), + ), + ], + ); + return Scaffold( + appBar: InlinePageHeader( + title: '服务工作台', + actions: [ + IconButton( + onPressed: () => showMessage(context, '状态已刷新'), + tooltip: '刷新', + icon: const Icon(Icons.refresh_rounded), + ), + ], + ), + body: wide + ? Row( + children: [ + SizedBox(width: 360, child: navigation), + VerticalDivider( + width: 1, + color: Theme.of(context).dividerColor, + ), + const Expanded(child: _WorkbenchOverview()), + ], + ) + : navigation, + ); + } +} + +class _WorkbenchOverview extends ConsumerWidget { + const _WorkbenchOverview(); + @override + Widget build(BuildContext context, WidgetRef ref) => + FutureBuilder>( + future: ref.read(apiProvider).getMap('system/diagnostics'), + builder: (context, snapshot) => ListView( + padding: const EdgeInsets.all(24), + children: [ + Text('服务概览', style: context.text.headlineMedium), + const SizedBox(height: 7), + Text( + '管理数据源、索引任务和设备资源。', + style: context.text.bodyMedium?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + const SizedBox(height: 22), + Wrap( + spacing: 10, + runSpacing: 10, + children: [ + _Metric( + label: '诊断状态', + value: snapshot.hasError + ? '需检查' + : snapshot.connectionState == ConnectionState.done + ? '正常' + : '读取中', + ), + const _Metric(label: '访问模式', value: '直连'), + _Metric( + label: '服务器', + value: + Uri.tryParse( + ref.read(apiProvider).serverRoot ?? '', + )?.host ?? + 'ImageFind', + ), + ], + ), + const SectionHeading(title: '常用维护'), + GroupSurface( + children: [ + AppListTile( + icon: Icons.schedule_rounded, + title: '正在处理', + subtitle: '查看后台任务和失败项', + onTap: () => context.push('/manage/jobs'), + ), + AppListTile( + icon: Icons.backup_outlined, + title: '数据保护', + subtitle: '创建完整备份或恢复', + onTap: () => context.push('/manage/backups'), + ), + AppListTile( + icon: Icons.health_and_safety_outlined, + title: '系统诊断', + subtitle: '检查数据库、推理和存储', + onTap: () => context.push('/manage/diagnostics'), + ), + ], + ), + ], + ), + ); +} + +class _Metric extends StatelessWidget { + const _Metric({required this.label, required this.value}); + final String label; + final String value; + @override + Widget build(BuildContext context) => Container( + width: 168, + padding: const EdgeInsets.all(15), + decoration: BoxDecoration( + color: context.colors.surface, + border: Border.all(color: Theme.of(context).dividerColor), + borderRadius: BorderRadius.circular(15), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(value, style: context.text.titleLarge), + const SizedBox(height: 4), + Text( + label, + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + ), + ); +} + +class ManagementSectionScreen extends ConsumerStatefulWidget { + const ManagementSectionScreen({super.key, required this.section}); + final String section; + @override + ConsumerState createState() => + _ManagementSectionScreenState(); +} + +class _ManagementSectionScreenState + extends ConsumerState { + late Future _future = _load(); + _Section get spec => + WorkbenchScreen.sections + .where((item) => item.id == widget.section) + .firstOrNull ?? + _Section( + widget.section, + _fallbackTitle(widget.section), + '', + Icons.settings_outlined, + ); + + Future _load() { + final api = ref.read(apiProvider); + return switch (widget.section) { + 'transfers' => Future.wait([ + api.getDynamic('uploads'), + api.getDynamic('downloads'), + ]), + 'files' => api.getDynamic('files'), + 'trash' => api.getDynamic('trash'), + 'sources' => api.getDynamic('sources'), + 'jobs' => api.getDynamic('jobs'), + 'models' => api.getDynamic('models'), + 'speech' => Future.wait([ + api.getDynamic('speech/config'), + api.getDynamic('search/coverage'), + ]), + 'resources' => api.getDynamic('system/resources'), + 'diagnostics' => api.getDynamic('system/diagnostics'), + 'backups' => Future.wait([ + api.getDynamic('backups/status'), + api.getDynamic('backups'), + ]), + 'tokens' => api.getDynamic('tokens'), + 'tag-suggestions' => api.getDynamic('tag-suggestions'), + 'activity' => api.getDynamic('activity'), + 'history' => api.getDynamic( + 'videos', + query: {'played_only': true, 'sort': 'last_played'}, + ), + _ => Future.value({}), + }; + } + + @override + Widget build(BuildContext context) => Scaffold( + appBar: InlinePageHeader(title: spec.title, actions: _actions(context)), + body: FutureBuilder( + future: _future, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) + return const Center(child: CircularProgressIndicator()); + if (snapshot.hasError) + return EmptyState( + icon: Icons.cloud_off_outlined, + title: '暂时无法载入', + message: '${snapshot.error}', + action: FilledButton.tonal( + onPressed: _reload, + child: const Text('重试'), + ), + ); + return _body(context, snapshot.data); + }, + ), + ); + + List _actions(BuildContext context) => switch (widget.section) { + 'sources' => [ + IconButton( + onPressed: _newSource, + tooltip: '添加数据源', + icon: const Icon(Icons.add_rounded), + ), + ], + 'tokens' => [ + IconButton( + onPressed: _newToken, + tooltip: '创建 Token', + icon: const Icon(Icons.add_rounded), + ), + ], + 'jobs' => [TextButton(onPressed: _retryFailed, child: const Text('重试失败项'))], + 'activity' => [TextButton(onPressed: _markRead, child: const Text('全部已读'))], + 'tag-suggestions' => [ + TextButton(onPressed: _analyzeTags, child: const Text('重新分析')), + ], + _ => [ + IconButton( + onPressed: _reload, + tooltip: '刷新', + icon: const Icon(Icons.refresh_rounded), + ), + ], + }; + + Widget _body(BuildContext context, dynamic data) { + if (widget.section == 'history') { + final videos = asJsonList(data).map(VideoRecord.fromJson).toList(); + return ListView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 12, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 24, + ), + children: [ + Text( + '只记录在你的 ImageFind 服务中', + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + const SizedBox(height: 14), + if (videos.isEmpty) + const EmptyState( + icon: Icons.history_rounded, + title: '还没有观看记录', + message: '播放过的视频会出现在这里。', + ) + else + MediaGrid(items: videos, api: ref.read(apiProvider)), + ], + ); + } + if (widget.section == 'resources') + return _ResourceBody(data: asJsonMap(data), onChanged: _updateResources); + if (widget.section == 'speech') + return _SpeechBody(data: data is List ? data : const []); + if (widget.section == 'diagnostics') + return _DiagnosticsBody(data: asJsonMap(data)); + if (widget.section == 'backups') + return _BackupsBody( + data: data is List ? data : const [], + onCreate: _newBackup, + ); + final rows = [..._flattenRows(data)]; + if (widget.section == 'transfers') { + rows.insertAll( + 0, + ref.watch(deviceUploadProvider).map((item) => item.toJson()), + ); + final offline = + ref.watch(offlineDownloadsProvider).valueOrNull ?? const []; + rows.addAll( + offline.map( + (item) => { + 'id': item.videoId, + 'type': 'offline_download', + 'name': item.title, + 'status': item.status, + 'progress': item.totalBytes == null || item.totalBytes == 0 + ? 0.0 + : item.bytesDownloaded / item.totalBytes!, + 'error': item.error, + }, + ), + ); + } + if (rows.isEmpty) + return EmptyState( + icon: spec.icon, + title: _emptyTitle(widget.section), + message: '当前没有需要显示的项目。', + ); + return ListView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 12, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 24, + ), + children: [ + if (spec.subtitle.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(6, 2, 6, 14), + child: Text( + spec.subtitle, + style: context.text.bodyMedium?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ), + GroupSurface(children: rows.map((row) => _rowTile(row)).toList()), + ], + ); + } + + List> _flattenRows(dynamic data) { + if (data is List && data.isNotEmpty && data.first is Future) + return const []; + if (data is List && + data.isNotEmpty && + data.every((item) => item is List || item is Map)) { + final result = >[]; + for (final item in data) { + result.addAll(asJsonList(item)); + if (item is Map && asJsonList(item).isEmpty) + result.add(asJsonMap(item)); + } + return result.where((item) => item.isNotEmpty).toList(); + } + return asJsonList(data); + } + + Widget _rowTile(Map row) { + final status = '${row['status'] ?? row['phase'] ?? ''}'; + final error = status == 'failed' || status == 'error'; + final success = { + 'completed', + 'ready', + 'online', + 'accepted', + }.contains(status); + final title = + '${row['name'] ?? row['label'] ?? row['filename'] ?? row['display_name'] ?? row['message'] ?? row['kind'] ?? '项目'}'; + final subtitle = _subtitle(row); + return AppListTile( + icon: _iconFor(widget.section, row), + iconColor: error + ? context.colors.error + : success + ? AppColors.success + : null, + title: title, + subtitle: subtitle, + trailing: status.isEmpty + ? null + : _Status(text: _statusLabel(status), error: error, success: success), + onTap: () => _rowAction(row), + ); + } + + String _subtitle(Map row) { + final parts = + [ + row['path'], + row['source_name'], + row['description'], + row['error'], + row['scope'], + row['progress'] is num + ? '${((row['progress'] as num) * 100).round()}%' + : null, + ] + .where((value) => value != null && '$value'.isNotEmpty) + .map((value) => '$value') + .toList(); + return parts.isEmpty ? '点击查看详情与可用操作' : parts.join(' · '); + } + + void _rowAction(Map row) { + if (widget.section == 'tag-suggestions') { + _decideSuggestion(row, true); + return; + } + showModalBottomSheet( + context: context, + builder: (context) => SafeArea( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 18), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + AppListTile( + icon: Icons.info_outline_rounded, + title: + '${row['name'] ?? row['label'] ?? row['filename'] ?? '项目详情'}', + subtitle: _subtitle(row), + ), + if (widget.section == 'trash') + AppListTile( + icon: Icons.restore_rounded, + title: '恢复', + onTap: () { + Navigator.pop(context); + _restore(row); + }, + ), + if (widget.section == 'jobs' && row['status'] == 'failed') + AppListTile( + icon: Icons.refresh_rounded, + title: '重试任务', + onTap: () { + Navigator.pop(context); + _retryJob(row); + }, + ), + if (widget.section == 'transfers' && + row['type'] == 'device_upload' && + row['can_retry'] == true) + AppListTile( + icon: Icons.restart_alt_rounded, + title: '继续上传', + subtitle: '跳过服务器已经收到的分块', + onTap: () { + Navigator.pop(context); + _retryDeviceUpload('${row['local_key']}'); + }, + ), + if (widget.section == 'tokens') + AppListTile( + icon: Icons.delete_outline_rounded, + iconColor: context.colors.error, + title: '撤销 Token', + onTap: () { + Navigator.pop(context); + _deleteToken(row); + }, + ), + ], + ), + ), + ), + ); + } + + void _reload() => setState(() => _future = _load()); + Future _call(Future request, String success) async { + try { + await request; + if (mounted) { + showMessage(context, success); + _reload(); + } + } on ApiException catch (error) { + if (mounted) showMessage(context, error.message, error: true); + } + } + + Future _retryFailed() => + _call(ref.read(apiProvider).postMap('jobs/retry-failed'), '已重新排队失败任务'); + Future _markRead() => + _call(ref.read(apiProvider).postMap('activity/read'), '活动已全部标为已读'); + Future _analyzeTags() => _call( + ref + .read(apiProvider) + .postMap( + 'tag-suggestions/analyze', + data: {'video_ids': [], 'force': true}, + ), + '已开始重新分析', + ); + Future _retryJob(Map row) => _call( + ref.read(apiProvider).postMap('jobs/${row['id']}/retry'), + '任务已重新排队', + ); + Future _retryDeviceUpload(String key) => + _call(ref.read(deviceUploadProvider.notifier).retry(key), '上传已继续'); + Future _restore(Map row) => _call( + ref.read(apiProvider).postMap('trash/${row['id']}/restore'), + '项目已恢复', + ); + Future _deleteToken(Map row) => + _call(ref.read(apiProvider).delete('tokens/${row['id']}'), 'Token 已撤销'); + Future _decideSuggestion(Map row, bool accept) => + _call( + ref + .read(apiProvider) + .postMap( + 'tag-suggestions/decide', + data: { + 'suggestion_ids': [row['id']], + 'action': accept ? 'accept' : 'reject', + }, + ), + accept ? '标签建议已接受' : '标签建议已拒绝', + ); + Future _updateResources(Map values) => _call( + ref.read(apiProvider).patchMap('system/resources', data: values), + '资源策略已更新', + ); + + Future _newSource() async { + final name = TextEditingController(); + final path = TextEditingController(); + final result = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('添加本地数据源'), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + TextField( + controller: name, + decoration: const InputDecoration(labelText: '名称'), + ), + const SizedBox(height: 10), + TextField( + controller: path, + decoration: const InputDecoration(labelText: 'NAS 绝对路径'), + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('取消'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('添加'), + ), + ], + ), + ); + if (result == true) + await _call( + ref + .read(apiProvider) + .postMap( + 'sources/local', + data: {'name': name.text, 'path': path.text}, + ), + '数据源已添加', + ); + name.dispose(); + path.dispose(); + } + + Future _newToken() async { + final name = TextEditingController(text: '移动端访问'); + final result = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('创建 API Token'), + content: TextField( + controller: name, + decoration: const InputDecoration(labelText: '名称'), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('取消'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('创建'), + ), + ], + ), + ); + if (result == true) { + try { + final token = await ref + .read(apiProvider) + .postMap( + 'tokens', + data: { + 'name': name.text, + 'scopes': ['admin'], + }, + ); + if (mounted) + await showDialog( + context: context, + barrierDismissible: false, + builder: (context) => AlertDialog( + title: const Text('Token 仅显示一次'), + content: SelectableText('${token['token'] ?? ''}'), + actions: [ + FilledButton( + onPressed: () => Navigator.pop(context), + child: const Text('我已保存'), + ), + ], + ), + ); + _reload(); + } on ApiException catch (error) { + if (mounted) showMessage(context, error.message, error: true); + } + } + name.dispose(); + } + + Future _newBackup() async { + final password = TextEditingController(); + final result = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('创建完整备份'), + content: TextField( + controller: password, + obscureText: true, + decoration: const InputDecoration(labelText: '备份密码(至少 10 个字符)'), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('取消'), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: const Text('创建'), + ), + ], + ), + ); + if (result == true) + await _call( + ref + .read(apiProvider) + .postMap( + 'backups', + data: {'scope': 'full', 'password': password.text}, + ), + '备份任务已创建', + ); + password.dispose(); + } +} + +class _ResourceBody extends StatelessWidget { + const _ResourceBody({required this.data, required this.onChanged}); + final Map data; + final Future Function(Map) onChanged; + @override + Widget build(BuildContext context) => ListView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 12, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 24, + ), + children: [ + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: context.colors.primaryContainer, + borderRadius: BorderRadius.circular(16), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('设备资源', style: context.text.titleLarge), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: _MiniMetric( + label: 'CPU', + value: '${data['cpu_percent'] ?? data['cpu'] ?? 0}%', + ), + ), + Expanded( + child: _MiniMetric( + label: '内存', + value: '${data['memory_percent'] ?? data['memory'] ?? 0}%', + ), + ), + Expanded( + child: _MiniMetric( + label: 'GPU', + value: '${data['gpu_percent'] ?? data['gpu'] ?? 0}%', + ), + ), + ], + ), + ], + ), + ), + const SectionHeading(title: '性能档位'), + SegmentedButton( + segments: const [ + ButtonSegment(value: 'quiet', label: Text('安静')), + ButtonSegment(value: 'balanced', label: Text('均衡')), + ButtonSegment(value: 'turbo', label: Text('极速')), + ], + selected: {'${data['profile'] ?? 'balanced'}'}, + onSelectionChanged: (value) => onChanged({'profile': value.first}), + showSelectedIcon: false, + ), + const SizedBox(height: 16), + GroupSurface( + children: [ + AppListTile( + icon: Icons.pause_circle_outline_rounded, + title: 'AI 后台任务', + subtitle: data['manual_pause'] == true ? '已暂停' : '运行中', + trailing: Switch.adaptive( + value: data['manual_pause'] != true, + onChanged: (value) => onChanged({'manual_pause': !value}), + ), + ), + AppListTile( + icon: Icons.cleaning_services_outlined, + title: '清理远程缓存', + subtitle: '${data['remote_cache_bytes'] ?? '检查可释放空间'}', + onTap: () {}, + ), + AppListTile( + icon: Icons.dns_outlined, + title: 'Rclone 后台进程', + subtitle: '${data['rclone'] ?? '由 ImageFind 管理'}', + onTap: () {}, + ), + ], + ), + ], + ); +} + +class _MiniMetric extends StatelessWidget { + const _MiniMetric({required this.label, required this.value}); + final String label; + final String value; + @override + Widget build(BuildContext context) => Column( + children: [ + Text(value, style: context.text.titleLarge), + Text( + label, + style: context.text.bodySmall?.copyWith( + color: context.colors.onPrimaryContainer, + ), + ), + ], + ); +} + +class _SpeechBody extends StatelessWidget { + const _SpeechBody({required this.data}); + final List data; + @override + Widget build(BuildContext context) { + final config = data.isNotEmpty + ? asJsonMap(data[0]) + : const {}; + final coverage = data.length > 1 + ? asJsonMap(data[1]) + : const {}; + return ListView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 12, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 24, + ), + children: [ + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: context.colors.primaryContainer, + borderRadius: BorderRadius.circular(16), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '语音搜索覆盖 ${coverage['coverage_percent'] ?? coverage['percent'] ?? 0}%', + style: context.text.titleLarge, + ), + const SizedBox(height: 5), + Text( + '${coverage['ready'] ?? 0} / ${coverage['total'] ?? 0} 个视频可搜索', + style: context.text.bodySmall?.copyWith( + color: context.colors.onPrimaryContainer, + ), + ), + ], + ), + ), + const SectionHeading(title: '识别策略'), + GroupSurface( + children: [ + AppListTile( + icon: Icons.language_rounded, + title: '语言策略', + subtitle: '${config['language_policy'] ?? 'zh_priority'}', + onTap: () {}, + ), + AppListTile( + icon: Icons.tune_rounded, + title: '质量档位', + subtitle: '${config['quality_profile'] ?? 'balanced'}', + onTap: () {}, + ), + AppListTile( + icon: Icons.refresh_rounded, + title: '修复低质量逐字稿', + subtitle: '重新处理风险视频', + onTap: () {}, + ), + ], + ), + ], + ); + } +} + +class _DiagnosticsBody extends StatelessWidget { + const _DiagnosticsBody({required this.data}); + final Map data; + @override + Widget build(BuildContext context) { + final rows = data.entries + .where((entry) => entry.value is! Map && entry.value is! List) + .toList(); + return ListView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 12, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 24, + ), + children: [ + Container( + padding: const EdgeInsets.all(13), + decoration: BoxDecoration( + color: AppColors.success.withValues(alpha: .1), + borderRadius: BorderRadius.circular(14), + ), + child: const Row( + children: [ + Icon(Icons.health_and_safety_outlined, color: AppColors.success), + SizedBox(width: 10), + Expanded(child: Text('诊断数据只显示在当前设备。')), + ], + ), + ), + const SectionHeading(title: '核心服务'), + GroupSurface( + children: rows.isEmpty + ? [ + const AppListTile( + icon: Icons.check_circle_outline_rounded, + title: '未发现严重问题', + subtitle: '服务返回的诊断状态正常', + ), + ] + : rows + .map( + (entry) => AppListTile( + icon: Icons.check_circle_outline_rounded, + iconColor: AppColors.success, + title: entry.key.replaceAll('_', ' '), + subtitle: '${entry.value}', + ), + ) + .toList(), + ), + ], + ); + } +} + +class _BackupsBody extends StatelessWidget { + const _BackupsBody({required this.data, required this.onCreate}); + final List data; + final VoidCallback onCreate; + @override + Widget build(BuildContext context) { + final status = data.isNotEmpty + ? asJsonMap(data[0]) + : const {}; + final backups = data.length > 1 + ? asJsonList(data[1]) + : const >[]; + return ListView( + padding: EdgeInsets.fromLTRB( + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 12, + MediaQuery.sizeOf(context).width < 600 ? 6 : 22, + 24, + ), + children: [ + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: context.colors.primaryContainer, + borderRadius: BorderRadius.circular(16), + ), + child: Row( + children: [ + Icon(Icons.verified_user_outlined, color: context.colors.primary), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '备份状态${status['status'] == 'failed' ? '需检查' : '良好'}', + style: context.text.titleMedium, + ), + Text( + '${status['last_completed_at'] ?? '尚未完成备份'}', + style: context.text.bodySmall?.copyWith( + color: context.colors.onPrimaryContainer, + ), + ), + ], + ), + ), + ], + ), + ), + const SizedBox(height: 14), + FilledButton.icon( + onPressed: onCreate, + icon: const Icon(Icons.add_rounded), + label: const Text('创建完整备份'), + ), + const SectionHeading(title: '备份记录'), + if (backups.isEmpty) + const EmptyState( + icon: Icons.backup_outlined, + title: '还没有备份', + message: '创建后会显示可下载的备份文件。', + ) + else + GroupSurface( + children: backups + .map( + (row) => AppListTile( + icon: Icons.description_outlined, + title: '${row['filename'] ?? row['id']}', + subtitle: + '${row['scope'] ?? 'full'} · ${row['size_bytes'] ?? ''}', + onTap: () {}, + ), + ) + .toList(), + ), + ], + ); + } +} + +class _Status extends StatelessWidget { + const _Status({required this.text, this.error = false, this.success = false}); + final String text; + final bool error; + final bool success; + @override + Widget build(BuildContext context) { + final color = error + ? context.colors.error + : success + ? AppColors.success + : context.colors.onSurfaceVariant; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 4), + decoration: BoxDecoration( + color: color.withValues(alpha: .1), + borderRadius: BorderRadius.circular(7), + ), + child: Text( + text, + style: context.text.bodySmall?.copyWith( + color: color, + fontWeight: FontWeight.w600, + ), + ), + ); + } +} + +class _Section { + const _Section(this.id, this.title, this.subtitle, this.icon); + final String id; + final String title; + final String subtitle; + final IconData icon; +} + +String _fallbackTitle(String section) => switch (section) { + 'activity' => '活动', + 'history' => '观看历史', + 'security' => '安全与密码', + _ => '服务管理', +}; +String _emptyTitle(String section) => switch (section) { + 'transfers' => '没有传输任务', + 'files' => '目录是空的', + 'trash' => '回收站是空的', + 'jobs' => '没有后台任务', + 'tokens' => '还没有 API Token', + 'tag-suggestions' => '没有待审核建议', + 'activity' => '没有新活动', + _ => '这里还没有项目', +}; +String _statusLabel(String value) => switch (value) { + 'running' => '进行中', + 'queued' => '排队中', + 'completed' => '已完成', + 'failed' => '失败', + 'ready' => '可用', + 'online' => '在线', + 'receiving' => '接收中', + 'accepted' => '已接受', + 'rejected' => '已拒绝', + _ => value, +}; +IconData _iconFor(String section, Map row) => + switch (section) { + 'transfers' => + row['type'] == 'download' || row['type'] == 'offline_download' + ? Icons.download_rounded + : Icons.upload_rounded, + 'files' => + row['type'] == 'directory' + ? Icons.folder_outlined + : Icons.insert_drive_file_outlined, + 'trash' => Icons.delete_outline_rounded, + 'sources' => Icons.dns_outlined, + 'jobs' => Icons.schedule_rounded, + 'models' => Icons.memory_rounded, + 'tokens' => Icons.key_outlined, + 'tag-suggestions' => Icons.auto_awesome_outlined, + 'activity' => Icons.notifications_none_rounded, + _ => Icons.settings_outlined, + }; diff --git a/mobile/lib/src/state.dart b/mobile/lib/src/state.dart new file mode 100644 index 0000000..2e0d76c --- /dev/null +++ b/mobile/lib/src/state.dart @@ -0,0 +1,174 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + +import 'api.dart'; +import 'models.dart'; +import 'offline_database.dart'; + +final secureStorageProvider = Provider( + (ref) => const FlutterSecureStorage(), +); + +final apiProvider = Provider( + (ref) => ImageFindApi(ref.watch(secureStorageProvider)), +); +final offlineDatabaseProvider = Provider((ref) { + final database = OfflineDatabase(); + ref.onDispose(database.close); + return database; +}); + +enum SessionStage { booting, disconnected, login, setup, authenticated } + +class SessionState { + const SessionState({ + this.stage = SessionStage.booting, + this.status, + this.error, + this.busy = false, + }); + final SessionStage stage; + final ServerStatus? status; + final String? error; + final bool busy; + SessionState copyWith({ + SessionStage? stage, + ServerStatus? status, + String? error, + bool? busy, + bool clearError = false, + }) => SessionState( + stage: stage ?? this.stage, + status: status ?? this.status, + error: clearError ? null : error ?? this.error, + busy: busy ?? this.busy, + ); +} + +class SessionController extends StateNotifier { + SessionController(this.api) : super(const SessionState()) { + bootstrap(); + } + final ImageFindApi api; + + Future bootstrap() async { + final hadSession = await api.restore(); + if (hadSession && await api.verifySession()) { + state = const SessionState(stage: SessionStage.authenticated); + } else { + state = const SessionState(stage: SessionStage.disconnected); + } + } + + Future connect(String url) async { + state = state.copyWith(busy: true, clearError: true); + try { + final status = await api.connect(url); + state = SessionState( + stage: status.configured ? SessionStage.login : SessionStage.setup, + status: status, + ); + return true; + } on ApiException catch (error) { + state = SessionState( + stage: SessionStage.disconnected, + error: error.message, + ); + return false; + } + } + + Future authenticate(String password, {required bool remember}) async { + state = state.copyWith(busy: true, clearError: true); + try { + await api.login( + password, + setup: state.stage == SessionStage.setup, + remember: remember, + ); + state = const SessionState(stage: SessionStage.authenticated); + return true; + } on ApiException catch (error) { + state = state.copyWith(busy: false, error: error.message); + return false; + } + } + + Future logout() async { + await api.logout(); + state = const SessionState(stage: SessionStage.disconnected); + } +} + +final sessionProvider = StateNotifierProvider( + (ref) => SessionController(ref.watch(apiProvider)), +); +final homeProvider = FutureProvider( + (ref) => ref.watch(apiProvider).home(), +); +final videosProvider = FutureProvider>( + (ref) => ref.watch(apiProvider).videos(), +); +final collectionsProvider = FutureProvider>( + (ref) => ref.watch(apiProvider).collections(), +); +final peopleProvider = FutureProvider>( + (ref) => ref.watch(apiProvider).people(), +); + +final eventRevisionProvider = StateProvider((ref) => 0); + +final eventSyncProvider = Provider((ref) { + if (ref.watch(sessionProvider).stage != SessionStage.authenticated) return; + var stopped = false; + StreamSubscription>? subscription; + Timer? reconnect; + var attempts = 0; + + void connect() { + if (stopped) return; + subscription = ref + .read(apiProvider) + .events() + .listen( + (_) { + attempts = 0; + ref.read(eventRevisionProvider.notifier).state++; + ref.invalidate(homeProvider); + ref.invalidate(videosProvider); + ref.invalidate(collectionsProvider); + ref.invalidate(peopleProvider); + }, + onError: (_) { + if (stopped) return; + attempts++; + final seconds = (1 << attempts.clamp(0, 5)).clamp(2, 30); + reconnect = Timer(Duration(seconds: seconds), connect); + }, + onDone: () { + if (!stopped) + reconnect = Timer(const Duration(seconds: 2), connect); + }, + cancelOnError: true, + ); + } + + connect(); + ref.onDispose(() { + stopped = true; + reconnect?.cancel(); + subscription?.cancel(); + }); +}); + +class ThemeModeController extends StateNotifier { + ThemeModeController() : super(ThemeMode.system); + void set(ThemeMode value) => state = value; +} + +final themeModeProvider = StateNotifierProvider( + (ref) => ThemeModeController(), +); diff --git a/mobile/lib/src/theme.dart b/mobile/lib/src/theme.dart new file mode 100644 index 0000000..d84cd8b --- /dev/null +++ b/mobile/lib/src/theme.dart @@ -0,0 +1,175 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +abstract final class AppColors { + static const blue = Color(0xFF176FE8); + static const blueDark = Color(0xFF76A5FF); + static const coral = Color(0xFFF06478); + static const lightCanvas = Color(0xFFF7F7F4); + static const darkCanvas = Color(0xFF111318); + static const darkSurface = Color(0xFF191C22); + static const success = Color(0xFF18815A); + static const warning = Color(0xFF9A5D10); + static const danger = Color(0xFFCC3F4D); +} + +ThemeData buildTheme(Brightness brightness, TargetPlatform platform) { + final dark = brightness == Brightness.dark; + final scheme = + ColorScheme.fromSeed( + seedColor: dark ? AppColors.blueDark : AppColors.blue, + brightness: brightness, + surface: dark ? AppColors.darkSurface : Colors.white, + ).copyWith( + primary: dark ? AppColors.blueDark : AppColors.blue, + error: dark ? const Color(0xFFFF7B86) : AppColors.danger, + surface: dark ? AppColors.darkSurface : Colors.white, + surfaceContainerLowest: dark + ? AppColors.darkCanvas + : AppColors.lightCanvas, + ); + final isIos = + platform == TargetPlatform.iOS || platform == TargetPlatform.macOS; + final base = ThemeData( + useMaterial3: true, + brightness: brightness, + colorScheme: scheme, + scaffoldBackgroundColor: dark + ? AppColors.darkCanvas + : AppColors.lightCanvas, + platform: platform, + splashFactory: isIos ? NoSplash.splashFactory : InkSparkle.splashFactory, + visualDensity: VisualDensity.standard, + ); + final text = base.textTheme.copyWith( + headlineMedium: base.textTheme.headlineMedium?.copyWith( + fontSize: 25, + height: 1.12, + fontWeight: FontWeight.w700, + letterSpacing: -0.5, + ), + titleLarge: base.textTheme.titleLarge?.copyWith( + fontSize: 20, + height: 1.2, + fontWeight: FontWeight.w700, + letterSpacing: -0.25, + ), + titleMedium: base.textTheme.titleMedium?.copyWith( + fontSize: 16, + height: 1.3, + fontWeight: FontWeight.w600, + ), + bodyLarge: base.textTheme.bodyLarge?.copyWith(fontSize: 16, height: 1.5), + bodyMedium: base.textTheme.bodyMedium?.copyWith(fontSize: 14, height: 1.45), + bodySmall: base.textTheme.bodySmall?.copyWith(fontSize: 12, height: 1.4), + labelLarge: base.textTheme.labelLarge?.copyWith( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ); + return base.copyWith( + textTheme: text, + cupertinoOverrideTheme: CupertinoThemeData( + brightness: brightness, + primaryColor: scheme.primary, + scaffoldBackgroundColor: base.scaffoldBackgroundColor, + ), + dividerColor: dark + ? Colors.white.withValues(alpha: 0.09) + : const Color(0x1813171E), + cardTheme: CardThemeData( + elevation: 0, + margin: EdgeInsets.zero, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + color: scheme.surface, + ), + appBarTheme: AppBarTheme( + elevation: 0, + scrolledUnderElevation: 0, + centerTitle: isIos, + backgroundColor: base.scaffoldBackgroundColor, + surfaceTintColor: Colors.transparent, + titleTextStyle: text.titleMedium?.copyWith(color: scheme.onSurface), + ), + navigationBarTheme: NavigationBarThemeData( + height: 68, + elevation: 0, + backgroundColor: dark ? AppColors.darkSurface : Colors.white, + indicatorColor: Colors.transparent, + labelTextStyle: WidgetStateProperty.resolveWith( + (states) => text.bodySmall?.copyWith( + fontWeight: states.contains(WidgetState.selected) + ? FontWeight.w700 + : FontWeight.w500, + color: states.contains(WidgetState.selected) + ? scheme.primary + : scheme.onSurfaceVariant, + ), + ), + iconTheme: WidgetStateProperty.resolveWith( + (states) => IconThemeData( + size: 23, + color: states.contains(WidgetState.selected) + ? scheme.primary + : scheme.onSurfaceVariant, + ), + ), + ), + navigationRailTheme: NavigationRailThemeData( + backgroundColor: scheme.surface, + indicatorColor: Colors.transparent, + selectedIconTheme: IconThemeData(color: scheme.primary), + selectedLabelTextStyle: text.bodySmall?.copyWith( + color: scheme.primary, + fontWeight: FontWeight.w700, + ), + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: dark ? const Color(0xFF21252D) : Colors.white, + contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 13), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + borderSide: BorderSide.none, + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + borderSide: BorderSide(color: base.dividerColor), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + borderSide: BorderSide(color: scheme.primary, width: 1.5), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + minimumSize: Size(48, isIos ? 44 : 48), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + textStyle: text.labelLarge, + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + minimumSize: Size(48, isIos ? 44 : 48), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), + side: BorderSide(color: base.dividerColor), + ), + ), + bottomSheetTheme: BottomSheetThemeData( + backgroundColor: scheme.surface, + surfaceTintColor: Colors.transparent, + showDragHandle: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(22)), + ), + ), + ); +} + +extension ThemeX on BuildContext { + ColorScheme get colors => Theme.of(this).colorScheme; + TextTheme get text => Theme.of(this).textTheme; + bool get isDark => Theme.of(this).brightness == Brightness.dark; + bool get isIos => Theme.of(this).platform == TargetPlatform.iOS; + double get minTouch => isIos ? 44 : 48; +} diff --git a/mobile/lib/src/transfer_services.dart b/mobile/lib/src/transfer_services.dart new file mode 100644 index 0000000..49c3c09 --- /dev/null +++ b/mobile/lib/src/transfer_services.dart @@ -0,0 +1,360 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:drift/drift.dart' show Value; +import 'package:file_picker/file_picker.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:path_provider/path_provider.dart'; + +import 'api.dart'; +import 'models.dart'; +import 'offline_database.dart'; +import 'state.dart'; + +class DeviceUploadTask { + const DeviceUploadTask({ + required this.key, + required this.filename, + this.progress = 0, + this.status = 'queued', + this.uploadId, + this.error, + this.canRetry = false, + }); + + final String key; + final String filename; + final double progress; + final String status; + final String? uploadId; + final String? error; + final bool canRetry; + + DeviceUploadTask copyWith({ + double? progress, + String? status, + String? uploadId, + String? error, + bool? canRetry, + }) => DeviceUploadTask( + key: key, + filename: filename, + progress: progress ?? this.progress, + status: status ?? this.status, + uploadId: uploadId ?? this.uploadId, + error: error, + canRetry: canRetry ?? this.canRetry, + ); + + Map toJson() => { + 'id': uploadId ?? key, + 'type': 'device_upload', + 'filename': filename, + 'progress': progress, + 'status': status, + 'error': error, + 'can_retry': canRetry, + 'local_key': key, + }; +} + +class DeviceUploadController extends StateNotifier> { + DeviceUploadController(this._api) : super(const []); + final ImageFindApi _api; + final Map _payloads = {}; + + Future start(PlatformFile file, String sourceId) async { + var path = file.path; + final size = await file.length(); + File? temporary; + if (size <= 0) { + throw const ApiException('无法读取所选视频,请重新选择。'); + } + if (path == null || path.isEmpty) { + final cache = await getTemporaryDirectory(); + temporary = File( + '${cache.path}${Platform.pathSeparator}upload-${DateTime.now().microsecondsSinceEpoch}-${_safeFileName(file.name)}', + ); + final sink = temporary.openWrite(); + try { + await for (final chunk in file.readAsByteStream()) { + sink.add(chunk); + } + } finally { + await sink.flush(); + await sink.close(); + } + path = temporary.path; + } + final key = '${DateTime.now().microsecondsSinceEpoch}-${file.name}'; + _payloads[key] = (path: path, size: size, temporary: temporary); + state = [ + DeviceUploadTask(key: key, filename: file.name), + ...state.where((item) => item.status != 'completed').take(9), + ]; + try { + _replace(key, (task) => task.copyWith(status: 'receiving')); + final id = await _api.uploadVideoFile( + path: path, + filename: file.name, + sizeBytes: size, + sourceId: sourceId, + onCreated: (id) => _replace( + key, + (task) => task.copyWith(uploadId: id, canRetry: true), + ), + onProgress: (sent, total) => _replace( + key, + (task) => task.copyWith( + status: 'receiving', + progress: total <= 0 ? 0 : sent / total, + ), + ), + ); + _replace( + key, + (task) => task.copyWith( + status: 'completed', + progress: 1, + uploadId: id, + canRetry: false, + ), + ); + } on ApiException catch (error) { + _replace( + key, + (task) => task.copyWith( + status: 'failed', + error: error.message, + canRetry: task.uploadId != null, + ), + ); + rethrow; + } catch (error) { + _replace( + key, + (task) => task.copyWith( + status: 'failed', + error: '$error', + canRetry: task.uploadId != null, + ), + ); + rethrow; + } finally { + final current = state.where((task) => task.key == key).firstOrNull; + final completed = state + .where((task) => task.key == key) + .any((task) => task.status == 'completed'); + if (completed || current?.canRetry != true) { + if (temporary != null && await temporary.exists()) { + await temporary.delete(); + } + _payloads.remove(key); + } + } + } + + Future retry(String key) async { + final task = state.where((item) => item.key == key).firstOrNull; + final payload = _payloads[key]; + if (task?.uploadId == null || payload == null) { + throw const ApiException('原视频已不可用,请重新选择文件。'); + } + _replace( + key, + (item) => + item.copyWith(status: 'receiving', error: null, canRetry: false), + ); + try { + await _api.resumeVideoUpload( + uploadId: task!.uploadId!, + path: payload.path, + sizeBytes: payload.size, + onProgress: (sent, total) => _replace( + key, + (item) => item.copyWith( + progress: total <= 0 ? 0 : sent / total, + status: 'receiving', + ), + ), + ); + _replace( + key, + (item) => + item.copyWith(status: 'completed', progress: 1, canRetry: false), + ); + if (payload.temporary case final temporary?) { + if (await temporary.exists()) await temporary.delete(); + } + _payloads.remove(key); + } on ApiException catch (error) { + _replace( + key, + (item) => item.copyWith( + status: 'failed', + error: error.message, + canRetry: true, + ), + ); + rethrow; + } + } + + static String _safeFileName(String input) => + input.replaceAll(RegExp(r'[^A-Za-z0-9._-]'), '_'); + + void _replace( + String key, + DeviceUploadTask Function(DeviceUploadTask task) update, + ) { + state = [for (final task in state) task.key == key ? update(task) : task]; + } +} + +final deviceUploadProvider = + StateNotifierProvider>( + (ref) => DeviceUploadController(ref.watch(apiProvider)), + ); + +class OfflineDownloadController extends StateNotifier> { + OfflineDownloadController(this._api, this._database) : super(const {}); + final ImageFindApi _api; + final OfflineDatabase _database; + + Future download(VideoRecord video) async { + if (state.contains(video.id)) return; + state = {...state, video.id}; + var progressWrite = Future.value(); + try { + final root = await getApplicationDocumentsDirectory(); + final directory = Directory( + '${root.path}${Platform.pathSeparator}offline', + ); + await directory.create(recursive: true); + final extension = _extension(video.downloadUrl ?? video.playbackUrl); + final base = _safeName(video.title).isEmpty + ? video.id + : _safeName(video.title); + final suffix = video.id.length <= 8 ? video.id : video.id.substring(0, 8); + final localPath = + '${directory.path}${Platform.pathSeparator}$base-$suffix$extension'; + final partialPath = '$localPath.part'; + final partial = File(partialPath); + final offset = await partial.exists() ? await partial.length() : 0; + await _database.saveDownload( + OfflineEntriesCompanion.insert( + videoId: video.id, + title: video.title, + localPath: localPath, + partialPath: Value(partialPath), + bytesDownloaded: Value(offset), + status: const Value('downloading'), + error: const Value(null), + updatedAt: Value(DateTime.now()), + ), + ); + void onProgress(int received, int? total) { + progressWrite = progressWrite.then( + (_) => _database.saveDownload( + OfflineEntriesCompanion.insert( + videoId: video.id, + title: video.title, + localPath: localPath, + partialPath: Value(partialPath), + bytesDownloaded: Value(received), + totalBytes: Value(total), + status: const Value('downloading'), + error: const Value(null), + updatedAt: Value(DateTime.now()), + ), + ), + ); + } + + try { + await _api.downloadVideoToFile( + video: video, + partialPath: partialPath, + offset: offset, + onProgress: onProgress, + ); + } on ApiException catch (error) { + if (offset <= 0 || + error.statusCode != HttpStatus.requestedRangeNotSatisfiable) { + rethrow; + } + await partial.writeAsBytes(const []); + await _api.downloadVideoToFile( + video: video, + partialPath: partialPath, + offset: 0, + onProgress: onProgress, + ); + } + await progressWrite; + final target = File(localPath); + if (await target.exists()) await target.delete(); + await partial.rename(localPath); + final total = await target.length(); + await _database.saveDownload( + OfflineEntriesCompanion.insert( + videoId: video.id, + title: video.title, + localPath: localPath, + partialPath: const Value(null), + bytesDownloaded: Value(total), + totalBytes: Value(total), + status: const Value('completed'), + error: const Value(null), + updatedAt: Value(DateTime.now()), + ), + ); + } catch (error) { + await progressWrite.catchError((_) {}); + final existing = await _database.downloadFor(video.id); + await _database.saveDownload( + OfflineEntriesCompanion.insert( + videoId: video.id, + title: video.title, + localPath: existing?.localPath ?? '', + partialPath: Value(existing?.partialPath), + bytesDownloaded: Value(existing?.bytesDownloaded ?? 0), + totalBytes: Value(existing?.totalBytes), + status: const Value('failed'), + error: Value(error is ApiException ? error.message : '$error'), + updatedAt: Value(DateTime.now()), + ), + ); + rethrow; + } finally { + state = {...state}..remove(video.id); + } + } + + static String _safeName(String input) { + final safe = input + .replaceAll(RegExp(r'[<>:"/\\|?*\x00-\x1F]'), '_') + .trim() + .replaceAll(RegExp(r'[. ]+$'), ''); + return safe.length <= 72 ? safe : safe.substring(0, 72); + } + + static String _extension(String? url) { + final path = Uri.tryParse(url ?? '')?.path ?? ''; + final dot = path.lastIndexOf('.'); + if (dot < 0 || path.length - dot > 7) return '.mp4'; + return path.substring(dot).toLowerCase(); + } +} + +final offlineDownloadControllerProvider = + StateNotifierProvider>( + (ref) => OfflineDownloadController( + ref.watch(apiProvider), + ref.watch(offlineDatabaseProvider), + ), + ); + +final offlineDownloadsProvider = StreamProvider>( + (ref) => ref.watch(offlineDatabaseProvider).watchDownloads(), +); diff --git a/mobile/lib/src/widgets.dart b/mobile/lib/src/widgets.dart new file mode 100644 index 0000000..0faab2d --- /dev/null +++ b/mobile/lib/src/widgets.dart @@ -0,0 +1,585 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import 'api.dart'; +import 'models.dart'; +import 'theme.dart'; + +abstract final class AppSpacing { + static const phoneGutter = 6.0; + static const tabletGutter = 22.0; +} + +class ResponsiveValue extends StatelessWidget { + const ResponsiveValue({ + super.key, + required this.compact, + this.medium, + required this.expanded, + }); + final Widget compact; + final Widget? medium; + final Widget expanded; + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) => constraints.maxWidth >= 840 + ? expanded + : constraints.maxWidth >= 600 + ? medium ?? expanded + : compact, + ); +} + +class AppPage extends StatelessWidget { + const AppPage({ + super.key, + required this.child, + this.paddingTop = 0, + this.safeBottom = true, + this.scrollable = true, + }); + final Widget child; + final double paddingTop; + final bool safeBottom; + final bool scrollable; + + @override + Widget build(BuildContext context) { + final width = MediaQuery.sizeOf(context).width; + final gutter = width < 600 + ? AppSpacing.phoneGutter + : AppSpacing.tabletGutter; + final content = Padding( + padding: EdgeInsets.fromLTRB( + gutter, + paddingTop, + gutter, + safeBottom ? 18 : 0, + ), + child: child, + ); + return SafeArea( + top: false, + bottom: safeBottom, + child: scrollable + ? CustomScrollView(slivers: [SliverToBoxAdapter(child: content)]) + : content, + ); + } +} + +class InlinePageHeader extends StatelessWidget implements PreferredSizeWidget { + const InlinePageHeader({ + super.key, + required this.title, + this.actions = const [], + this.showBack = true, + }); + final String title; + final List actions; + final bool showBack; + @override + Size get preferredSize => const Size.fromHeight(52); + + @override + Widget build(BuildContext context) => AppBar( + toolbarHeight: 52, + automaticallyImplyLeading: showBack, + leadingWidth: 50, + titleSpacing: showBack ? 0 : 12, + title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis), + actions: actions, + ); +} + +class SectionHeading extends StatelessWidget { + const SectionHeading({ + super.key, + required this.title, + this.subtitle, + this.action, + this.onAction, + }); + final String title; + final String? subtitle; + final String? action; + final VoidCallback? onAction; + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.fromLTRB(6, 22, 6, 9), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(title, style: context.text.titleLarge), + if (subtitle != null) ...[ + const SizedBox(height: 3), + Text( + subtitle!, + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ], + ], + ), + ), + if (action != null) + TextButton(onPressed: onAction, child: Text(action!)), + ], + ), + ); +} + +class MediaGrid extends StatelessWidget { + const MediaGrid({ + super.key, + required this.items, + required this.api, + this.maxItems, + this.onTap, + }); + final List items; + final ImageFindApi api; + final int? maxItems; + final void Function(VideoRecord video)? onTap; + + @override + Widget build(BuildContext context) { + final values = maxItems == null ? items : items.take(maxItems!).toList(); + return LayoutBuilder( + builder: (context, constraints) { + final width = constraints.maxWidth; + final columns = width >= 1100 + ? 4 + : width >= 720 + ? 3 + : 2; + return GridView.builder( + padding: EdgeInsets.zero, + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: values.length, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: columns, + crossAxisSpacing: 8, + mainAxisSpacing: 15, + childAspectRatio: columns >= 3 ? 1.42 : 1.31, + ), + itemBuilder: (context, index) => MediaCard( + video: values[index], + api: api, + treatment: index.isEven ? 0 : 1, + onTap: () { + if (onTap != null) { + onTap!(values[index]); + } else { + context.push( + '/player/${values[index].id}', + extra: values[index], + ); + } + }, + ), + ); + }, + ); + } +} + +class MediaCard extends StatelessWidget { + const MediaCard({ + super.key, + required this.video, + required this.api, + required this.treatment, + this.onTap, + }); + final VideoRecord video; + final ImageFindApi api; + final int treatment; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) => Semantics( + button: true, + label: '播放 ${video.title}', + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + AspectRatio( + aspectRatio: 16 / 9, + child: MediaCover( + api: api, + url: video.thumbnailUrl, + treatment: treatment, + duration: video.durationLabel, + progress: video.durationMs <= 0 + ? 0 + : video.progressMs / video.durationMs, + tags: video.tags.take(2).toList(), + ), + ), + const SizedBox(height: 7), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 2), + child: Text( + video.title, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: context.text.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + height: 1.36, + ), + ), + ), + ], + ), + ), + ); +} + +class MediaCover extends StatelessWidget { + const MediaCover({ + super.key, + required this.api, + this.url, + this.treatment = 0, + this.duration, + this.progress = 0, + this.tags = const [], + this.borderRadius = 12, + }); + final ImageFindApi api; + final String? url; + final int treatment; + final String? duration; + final double progress; + final List tags; + final double borderRadius; + + @override + Widget build(BuildContext context) { + final uri = api.thumbnailUri(url); + return ClipRRect( + borderRadius: BorderRadius.circular(borderRadius), + child: Stack( + fit: StackFit.expand, + children: [ + ColoredBox( + color: context.isDark + ? const Color(0xFF202632) + : const Color(0xFFDDE4EF), + child: uri.hasScheme + ? Image.network( + uri.toString(), + headers: api.mediaHeaders, + fit: BoxFit.cover, + errorBuilder: (_, _, _) => CustomPaint( + painter: _CoverPainter(treatment, context.isDark), + ), + ) + : CustomPaint( + painter: _CoverPainter(treatment, context.isDark), + ), + ), + if (tags.isNotEmpty) + Positioned( + top: 6, + left: 6, + child: Wrap( + spacing: 4, + children: tags + .map( + (tag) => Container( + constraints: const BoxConstraints(maxWidth: 76), + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 4, + ), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.62), + borderRadius: BorderRadius.circular(5), + ), + child: Text( + tag, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.w600, + ), + ), + ), + ) + .toList(), + ), + ), + if (duration != null) + Positioned( + right: 6, + bottom: 6, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3), + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: 0.72), + borderRadius: BorderRadius.circular(5), + ), + child: Text( + duration!, + style: const TextStyle( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.w700, + fontFeatures: [FontFeature.tabularFigures()], + ), + ), + ), + ), + if (progress > 0) + Align( + alignment: Alignment.bottomLeft, + child: FractionallySizedBox( + widthFactor: progress.clamp(0, 1), + child: Container(height: 3, color: context.colors.primary), + ), + ), + ], + ), + ); + } +} + +class _CoverPainter extends CustomPainter { + const _CoverPainter(this.treatment, this.dark); + final int treatment; + final bool dark; + @override + void paint(Canvas canvas, Size size) { + final base = Paint() + ..color = treatment == 0 + ? (dark ? const Color(0xFF25324A) : const Color(0xFFCBD7EA)) + : (dark ? const Color(0xFF3B2C43) : const Color(0xFFE6D6E2)); + canvas.drawRect(Offset.zero & size, base); + if (treatment == 0) { + canvas.drawCircle( + Offset(size.width * .78, size.height * .72), + size.height * .34, + Paint() + ..color = dark ? const Color(0xFF6081A8) : const Color(0xFF7896BC), + ); + final path = Path() + ..moveTo(0, size.height) + ..lineTo(size.width * .54, size.height * .32) + ..lineTo(size.width, size.height) + ..close(); + canvas.drawPath( + path, + Paint() + ..color = dark ? const Color(0xFF172033) : const Color(0xFFA7B8D1), + ); + } else { + canvas.drawRRect( + RRect.fromRectAndRadius( + Rect.fromLTWH( + size.width * .1, + size.height * .18, + size.width * .42, + size.height * .64, + ), + const Radius.circular(18), + ), + Paint() + ..color = dark ? const Color(0xFF71516B) : const Color(0xFFB47B9A), + ); + canvas.drawOval( + Rect.fromCenter( + center: Offset(size.width * .73, size.height * .48), + width: size.width * .43, + height: size.height * .36, + ), + Paint() + ..color = dark ? const Color(0xFFB87968) : const Color(0xFFD8A189), + ); + } + } + + @override + bool shouldRepaint(covariant _CoverPainter oldDelegate) => + oldDelegate.treatment != treatment || oldDelegate.dark != dark; +} + +class AsyncPane extends StatelessWidget { + const AsyncPane({ + super.key, + required this.value, + required this.data, + this.onRetry, + this.emptyMessage = '这里还没有内容', + }); + final AsyncValue value; + final Widget Function(T value) data; + final VoidCallback? onRetry; + final String emptyMessage; + + @override + Widget build(BuildContext context) => value.when( + loading: () => const Padding( + padding: EdgeInsets.all(36), + child: Center(child: CircularProgressIndicator()), + ), + error: (error, _) => EmptyState( + icon: Icons.cloud_off_outlined, + title: '暂时无法载入', + message: '$error', + action: onRetry == null + ? null + : FilledButton.tonal(onPressed: onRetry, child: const Text('重试')), + ), + data: data, + ); +} + +class EmptyState extends StatelessWidget { + const EmptyState({ + super.key, + required this.icon, + required this.title, + required this.message, + this.action, + }); + final IconData icon; + final String title; + final String message; + final Widget? action; + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 46), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 420), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 42, color: context.colors.primary), + const SizedBox(height: 16), + Text( + title, + textAlign: TextAlign.center, + style: context.text.titleLarge, + ), + const SizedBox(height: 8), + Text( + message, + textAlign: TextAlign.center, + style: context.text.bodyMedium?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + if (action != null) ...[const SizedBox(height: 20), action!], + ], + ), + ), + ), + ); +} + +class GroupSurface extends StatelessWidget { + const GroupSurface({super.key, required this.children}); + final List children; + @override + Widget build(BuildContext context) => Container( + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + color: context.colors.surface, + borderRadius: BorderRadius.circular(16), + border: Border.all(color: Theme.of(context).dividerColor), + ), + child: Column( + children: [ + for (var i = 0; i < children.length; i++) ...[ + children[i], + if (i < children.length - 1) + Divider( + height: 1, + indent: 62, + color: Theme.of(context).dividerColor, + ), + ], + ], + ), + ); +} + +class AppListTile extends StatelessWidget { + const AppListTile({ + super.key, + required this.icon, + required this.title, + this.subtitle, + this.trailing, + this.onTap, + this.iconColor, + }); + final IconData icon; + final String title; + final String? subtitle; + final Widget? trailing; + final VoidCallback? onTap; + final Color? iconColor; + @override + Widget build(BuildContext context) => ListTile( + minTileHeight: context.minTouch + 16, + contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 3), + leading: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: (iconColor ?? context.colors.primary).withValues(alpha: .11), + borderRadius: BorderRadius.circular(12), + ), + child: Icon(icon, color: iconColor ?? context.colors.primary, size: 21), + ), + title: Text( + title, + style: context.text.bodyMedium?.copyWith(fontWeight: FontWeight.w600), + ), + subtitle: subtitle == null + ? null + : Text( + subtitle!, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: context.text.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + trailing: + trailing ?? + (onTap == null + ? null + : const Icon(Icons.chevron_right_rounded, size: 21)), + onTap: onTap, + ); +} + +void showMessage(BuildContext context, String message, {bool error = false}) { + final messenger = ScaffoldMessenger.of(context); + messenger.clearSnackBars(); + messenger.showSnackBar( + SnackBar( + content: Text(message), + backgroundColor: error ? context.colors.error : null, + behavior: SnackBarBehavior.floating, + ), + ); +} diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock new file mode 100644 index 0000000..d5a2cba --- /dev/null +++ b/mobile/pubspec.lock @@ -0,0 +1,1346 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: "8d7ff3948166b8ec5da0fbb5962000926b8e02f2ed9b3e51d1738905fbd4c98d" + url: "https://pub.flutter-io.cn" + source: hosted + version: "93.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: de7148ed2fcec579b19f122c1800933dfa028f6d9fd38a152b04b1516cec120b + url: "https://pub.flutter-io.cn" + source: hosted + version: "10.0.1" + android_file_picker: + dependency: transitive + description: + name: android_file_picker + sha256: "665a5a57dfca27f91a715d300e4852a784f9f98e503dcff281bec9afb55767be" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.1" + archive: + dependency: transitive + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.0.9" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.2" + build: + dependency: transitive + description: + name: build + sha256: "45d14a0fb23e018d8287c32fc98d726ce466b231928ed9b9200f29bd3ccd39ae" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.0.7" + build_config: + dependency: transitive + description: + name: build_config + sha256: "94eaf6708fe64408c632ef2689ca3777b112f9421306ccf4f8c84d7c5c9f83f8" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.3.2" + build_daemon: + dependency: transitive + description: + name: build_daemon + sha256: "79e05eaf15a48d7230b053a4363b8eaac0cc234bbd0134c3229455481f55cbc6" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.1.5" + build_runner: + dependency: "direct dev" + description: + name: build_runner + sha256: "5367e521935b102bdf1e735d2aab461e36b2edca6517662d088dd04cc39f8d16" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.15.1" + built_collection: + dependency: transitive + description: + name: built_collection + sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + url: "https://pub.flutter-io.cn" + source: hosted + version: "5.1.1" + built_value: + dependency: transitive + description: + name: built_value + sha256: "31b24be6615ec7fcf70b3aa5a7469fe35826485e639a16dd7eb83ba30e4cc6a8" + url: "https://pub.flutter-io.cn" + source: hosted + version: "8.12.7" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.1" + charcode: + dependency: transitive + description: + name: charcode + sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.0.4" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: ff6785f7e9e3c38ac98b2fb035701789de90154024a75b6cb926445e83197d1c + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.4.2" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.2.1" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.19.1" + connectivity_plus: + dependency: "direct main" + description: + name: connectivity_plus + sha256: "762c99f890ca8bf87f7337236f99edd42793843bc6c3631da294a76653a54bd0" + url: "https://pub.flutter-io.cn" + source: hosted + version: "7.3.1" + connectivity_plus_platform_interface: + dependency: transitive + description: + name: connectivity_plus_platform_interface + sha256: "3c09627c536d22fd24691a905cdd8b14520de69da52c7a97499c8be5284a32ed" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.0" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.1.2" + cookie_jar: + dependency: "direct main" + description: + name: cookie_jar + sha256: "963da02c1ef64cb5ac20de948c9e5940aa351f1e34a12b1d327c83d85b7e8fff" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.0.9" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: "92c9c43c383bfa1c32079d3bc492d55d6d4318044b7b47edaff8971cbb555c51" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.3.5+4" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.7" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.9" + dart_style: + dependency: transitive + description: + name: dart_style + sha256: "29f7ecc274a86d32920b1d9cfc7502fa87220da41ec60b55f329559d5732e2b2" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.1.7" + dbus: + dependency: transitive + description: + name: dbus + sha256: "0ce9b0a839e6dee59a37a623d2fc26a35bbbe6404213e419b0d6411023d62645" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.7.14" + dio: + dependency: "direct main" + description: + name: dio + sha256: "0df44ebba85e503958eb75d07eedd3c86275a58c1d3eda2f2ce8f0a2c3abbb3c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "5.11.0" + dio_cookie_manager: + dependency: "direct main" + description: + name: dio_cookie_manager + sha256: "4ed4669cacb11931517c1158876a2189f19386674b9dab498abcca063dbe4c61" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.5.0" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "0786d0b7295a373de356fc0af4f6f1d0ab2844ed31b19dfc5e7556b70e24212c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.1" + drift: + dependency: "direct main" + description: + name: drift + sha256: "3a3f1f6f905037d7426e4c445854139fd6a3d592135f7c96d7931682b73d16f4" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.34.3" + drift_dev: + dependency: "direct dev" + description: + name: drift_dev + sha256: "9cfff1576b49725da0d32c040651a41ae195e8c4af8d8da301593e41d7abc2f7" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.34.0" + drift_flutter: + dependency: "direct main" + description: + name: drift_flutter + sha256: "91acf4bee7c3c84467cba46455aa70e5292a3b889f4582645d74f2e5a8c106f2" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.3.1" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.1.2" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.flutter-io.cn" + source: hosted + version: "7.0.1" + file_picker: + dependency: "direct main" + description: + name: file_picker + sha256: afbaa8015d9efabd224f41084ed9fdeddfa65389ebd7cd3a9eb1476aca66b46d + url: "https://pub.flutter-io.cn" + source: hosted + version: "12.0.0" + file_picker_darwin: + dependency: transitive + description: + name: file_picker_darwin + sha256: "5d87d156c1d63920447a662b7117d3498c67e3444a44d2cb01ed955d6efa62ef" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.1" + file_picker_linux: + dependency: transitive + description: + name: file_picker_linux + sha256: "93d3f62f97c657053e7b184fe0f5e22347d85067c053640a30b1ac8ad7844e3b" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.1" + file_picker_platform_interface: + dependency: transitive + description: + name: file_picker_platform_interface + sha256: "9e7a7e01e179929241f0afeb2c8c69ac95e29e17c0abea36ed193881c6bef90c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.1" + file_picker_web: + dependency: transitive + description: + name: file_picker_web + sha256: f1af38b3c91fafe0ca97f659b5c6818a057473ef09bb8b722f9f3f5364aa7eed + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.1" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "2567f398e06ac72dcf2e98a0c95df2a9edd03c2c2e0cacd4780f20cdf56263a0" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.9.4" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "5e0bbe9c312416f1787a68259ea1505b52f258c587f12920422671807c4d618a" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.9.5" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "62197474ae75893a62df75939c777763d39c2bc5f73ce5b88497208bc269abfd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.9.3+5" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.0.35" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "9532ee6db4a943a1ed8383072a2e3eeda041db5657cdf6d2acecf3c21ecbe7e1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.6.1" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: da922f2aab2d733db7e011a6bcc4a825b844892d4edd6df83ff156b09a9b2e40 + url: "https://pub.flutter-io.cn" + source: hosted + version: "10.0.0" + flutter_secure_storage_darwin: + dependency: transitive + description: + name: flutter_secure_storage_darwin + sha256: "8878c25136a79def1668c75985e8e193d9d7d095453ec28730da0315dc69aee3" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.2.0" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: "76fa9c841b3b1619fc5b5bc36efc7d158fa2356f223b6caeb1d0c80a54168546" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.2" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: "788060052712555182aba55ecb5f8b6e5cb9cfe8f776c83249a61fe3ce877db4" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.0.3" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.2.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + freezed_annotation: + dependency: "direct main" + description: + name: freezed_annotation + sha256: "7294967ff0a6d98638e7acb774aac3af2550777accd8149c90af5b014e6d44d8" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.1.0" + glob: + dependency: transitive + description: + name: glob + sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.3" + go_router: + dependency: "direct main" + description: + name: go_router + sha256: d7a3576cb312649eaa51f2356450aed686085fb58fcdebda5b359aa951eef7ea + url: "https://pub.flutter-io.cn" + source: hosted + version: "17.5.0" + graphs: + dependency: transitive + description: + name: graphs + sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.3.2" + hooks: + dependency: transitive + description: + name: hooks + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.0.2" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.6.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: f9881ff4998044947ec38d098bc7c8316ae1186fa786eddffdb867b9bc94dfce + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.8.0" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: d8402284df184bc05f4a2210c6c23983b0720f4cd87cbd05c5390a78af602667 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.2.3" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: d5b3e1774af29c9ab00103afb0d4614070f924d2e0057ac867ec98800114793f + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.8.13+17" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: b9c4a438a9ff4f60808c9cf0039b93a42bb6c2211ef6ebb647394b2b3fa84588 + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.8.13+6" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.2.2" + io: + dependency: transitive + description: + name: io + sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.5" + jni: + dependency: transitive + description: + name: jni + sha256: f038e58b4dc2c9037f50e233175086337e0b305e356d28211bf55f21c504cbd3 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.3" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "7b717011ea40d04fd47c2731d3d1d36eb99eba3435c2753d62489e8c3c9991d5" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.2" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.0" + json_annotation: + dependency: "direct main" + description: + name: json_annotation + sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.12.0" + json_serializable: + dependency: "direct dev" + description: + name: json_serializable + sha256: e45aefa0324f08c683caafbb94b72837aa6193c61822799c916e45f4a263113d + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.14.1" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.flutter-io.cn" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.12.18" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.13.0" + media_kit: + dependency: "direct main" + description: + name: media_kit + sha256: ae9e79597500c7ad6083a3c7b7b7544ddabfceacce7ae5c9709b0ec16a5d6643 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.2.6" + media_kit_libs_android_video: + dependency: transitive + description: + name: media_kit_libs_android_video + sha256: "3f6274e5ab2de512c286a25c327288601ee445ed8ac319e0ef0b66148bd8f76c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.3.8" + media_kit_libs_ios_video: + dependency: transitive + description: + name: media_kit_libs_ios_video + sha256: b5382994eb37a4564c368386c154ad70ba0cc78dacdd3fb0cd9f30db6d837991 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.4" + media_kit_libs_linux: + dependency: transitive + description: + name: media_kit_libs_linux + sha256: "2b473399a49ec94452c4d4ae51cfc0f6585074398d74216092bf3d54aac37ecf" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.2.1" + media_kit_libs_macos_video: + dependency: transitive + description: + name: media_kit_libs_macos_video + sha256: f26aa1452b665df288e360393758f84b911f70ffb3878032e1aabba23aa1032d + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.4" + media_kit_libs_video: + dependency: "direct main" + description: + name: media_kit_libs_video + sha256: "2b235b5dac79c6020e01eef5022c6cc85fedc0df1738aadc6ea489daa12a92a9" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.7" + media_kit_libs_windows_video: + dependency: transitive + description: + name: media_kit_libs_windows_video + sha256: dff76da2778729ab650229e6b4ec6ec111eb5151431002cbd7ea304ff1f112ab + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.11" + media_kit_video: + dependency: "direct main" + description: + name: media_kit_video + sha256: afaa509e7b7e0bf247557a3a740cde903a52c34ace9810f94500e127bd7b043d + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.0.1" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.17.0" + mime: + dependency: transitive + description: + name: mime + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.0.0" + mocktail: + dependency: "direct dev" + description: + name: mocktail + sha256: "5e1bf53cc7baa8062a33b84424deb61513858ea05c601b8509e683815b5914aa" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.5" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: f9c168717100ae6d9fee9ffb0be379bf1f8b26b0f6bcbd4fdddcd931993a6a72 + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.19.2" + nm: + dependency: transitive + description: + name: nm + sha256: "2c9aae4127bdc8993206464fcc063611e0e36e72018696cd9631023a31b24254" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.5.0" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e + url: "https://pub.flutter-io.cn" + source: hosted + version: "9.5.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.0" + package_info_plus: + dependency: transitive + description: + name: package_info_plus + sha256: "127e1751e37ffb2ff4658beeaca77bad0c27bf5f932bd3a501c2296926d4b481" + url: "https://pub.flutter-io.cn" + source: hosted + version: "10.2.1" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.1.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675" + url: "https://pub.flutter-io.cn" + source: hosted + version: "7.0.2" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.5.2" + posix: + dependency: transitive + description: + name: posix + sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.5.2" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.0" + pubspec_parse: + dependency: transitive + description: + name: pubspec_parse + sha256: "0560ba233314abbed0a48a2956f7f022cce7c3e1e73df540277da7544cad4082" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.5.0" + recase: + dependency: transitive + description: + name: recase + sha256: e4eb4ec2dcdee52dcf99cb4ceabaffc631d7424ee55e56f280bc039737f89213 + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.1.0" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.6.0" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "59062512288d3056b2321804332a13ffdd1bf16df70dcc8e506e411280a72959" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.6.1" + safe_local_storage: + dependency: transitive + description: + name: safe_local_storage + sha256: "494b982d5edb71030650ea463d939670e91b232b588323dc75229d2c5f23e7b7" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.0.6" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: c3025c5534b01739267eb7d76959bbc25a6d10f6988e1c2a3036940133dd10bf + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.5.5" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: e8d4762b1e2e8578fc4d0fd548cebf24afd24f49719c08974df92834565e2c53 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.23" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.5.6" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.4.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.2" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_gen: + dependency: transitive + description: + name: source_gen + sha256: a603f1fb984a7391ae5978d1b92bfaaa08b350dca5c825256f925818f7943bf5 + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.2.4" + source_helper: + dependency: transitive + description: + name: source_helper + sha256: "5e6f216fdf6376c9f3852381ae037499797a3385377d388b011dac98d303c67c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.3.13" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.10.2" + sqlcipher_flutter_libs: + dependency: transitive + description: + name: sqlcipher_flutter_libs + sha256: "38d62d659d2fb8739bf25a42c9a350d1fdd6c29a5a61f13a946778ec75d27929" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.7.0+eol" + sqlite3: + dependency: transitive + description: + name: sqlite3 + sha256: "64b2c63c8232dd20d14b34105a81ebfd74320442e8451f836179ec89986aa478" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.5.1" + sqlite3_flutter_libs: + dependency: "direct main" + description: + name: sqlite3_flutter_libs + sha256: "3ed7553eee7bb368f8950f58ba29f634e06e813c029aff6a0d60862b96de8454" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.6.0+eol" + sqlparser: + dependency: "direct dev" + description: + name: sqlparser + sha256: "40bdddb306a727be9ce510bd2d2b9a6c9db6c586d846ef7b22e3990a2b24f02d" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.44.5" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.12.1" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.4" + stream_transform: + dependency: transitive + description: + name: stream_transform + sha256: ad47125e588cfd37a9a7f86c7d6356dde8dfe89d071d293f80ca9e9273a33871 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.1.1" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.1" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: "63896c27e81b28f8cb4e69ead0d3e8f03f1d1e5fc531a3e579cabed6a2c7c9e5" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.4.0+1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "19a78f63e83d3a61f00826d09bc2f60e191bf3504183c001262be6ac75589fb8" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.7.8" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.4.0" + universal_io: + dependency: transitive + description: + name: universal_io + sha256: f63cbc48103236abf48e345e07a03ce5757ea86285ed313a6a032596ed9301e2 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.3.1" + universal_platform: + dependency: transitive + description: + name: universal_platform + sha256: "64e16458a0ea9b99260ceb5467a214c1f298d647c659af1bff6d3bf82536b1ec" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.0" + uri_parser: + dependency: transitive + description: + name: uri_parser + sha256: "051c62e5f693de98ca9f130ee707f8916e2266945565926be3ff20659f7853ce" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.2" + uuid: + dependency: transitive + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.6.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" + url: "https://pub.flutter-io.cn" + source: hosted + version: "15.2.0" + wakelock_plus: + dependency: transitive + description: + name: wakelock_plus + sha256: "7253bca0fcf40d8413ddfcf4d2a1fa0a82475e79be25a4f2c564b695c9351486" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.7.0" + wakelock_plus_platform_interface: + dependency: transitive + description: + name: wakelock_plus_platform_interface + sha256: "0618d1799f0b28bcf98255b4ee8313e6fc4d38589dc4ee5fe5840d57d1aff6da" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.6.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.2.1" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.3" + win32: + dependency: transitive + description: + name: win32 + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.4.0" + windows_file_picker: + dependency: transitive + description: + name: windows_file_picker + sha256: "72cf23466e146f2c0f19e1d78be97ff6409dc15b0c090f8eb284f94f4a33de26" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025" + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.6.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.1.3" +sdks: + dart: ">=3.11.0 <4.0.0" + flutter: ">=3.41.0" diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml new file mode 100644 index 0000000..0742501 --- /dev/null +++ b/mobile/pubspec.yaml @@ -0,0 +1,113 @@ +name: imagefind_mobile +description: "ImageFind private media library for iOS and Android." +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: ^3.11.0 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + flutter_riverpod: ^2.6.1 + go_router: ^17.5.0 + dio: ^5.11.0 + cookie_jar: ^4.0.9 + dio_cookie_manager: ^3.5.0 + flutter_secure_storage: 10.0.0 + shared_preferences: ^2.5.5 + media_kit: ^1.2.6 + media_kit_video: ^2.0.1 + media_kit_libs_video: ^1.0.7 + path_provider: ^2.1.6 + file_picker: ^12.0.0 + image_picker: ^1.2.3 + connectivity_plus: ^7.3.1 + drift: ^2.34.3 + drift_flutter: ^0.3.1 + sqlite3_flutter_libs: ^0.6.0+eol + freezed_annotation: ^3.1.0 + json_annotation: ^4.12.0 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + build_runner: ^2.15.1 + json_serializable: ^6.14.1 + drift_dev: ^2.34.0 + mocktail: ^1.0.5 + sqlparser: 0.44.5 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/mobile/test/api_contract_test.dart b/mobile/test/api_contract_test.dart new file mode 100644 index 0000000..199082e --- /dev/null +++ b/mobile/test/api_contract_test.dart @@ -0,0 +1,43 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:imagefind_mobile/src/api.dart'; +import 'package:imagefind_mobile/src/models.dart'; + +void main() { + test('resume plan skips received chunks and keeps the short final chunk', () { + final chunks = pendingUploadChunks( + sizeBytes: 10, + chunkSize: 4, + received: {1}, + ); + + expect(chunks.map((item) => item.index), [0, 2]); + expect(chunks.map((item) => item.offset), [0, 8]); + expect(chunks.map((item) => item.length), [4, 2]); + }); + + test('SSE decoder ignores keep-alives and accepts split packets', () async { + final bytes = Stream>.fromIterable([ + utf8.encode(': keep-alive\n\ndata: {"type":"upload"'), + utf8.encode(',"id":"42"}\n\n'), + ]); + + final events = await decodeServerEvents(bytes).toList(); + + expect(events, [ + {'type': 'upload', 'id': '42'}, + ]); + }); + + test('video payload keeps the dedicated download endpoint', () { + final video = VideoRecord.fromJson({ + 'id': 'video-1', + 'title': '片段', + 'duration_ms': 1000, + 'download_url': '/api/v1/videos/video-1/download', + }); + + expect(video.downloadUrl, '/api/v1/videos/video-1/download'); + }); +} diff --git a/mobile/test/offline_database_test.dart b/mobile/test/offline_database_test.dart new file mode 100644 index 0000000..20899b0 --- /dev/null +++ b/mobile/test/offline_database_test.dart @@ -0,0 +1,44 @@ +import 'package:drift/drift.dart'; +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:imagefind_mobile/src/offline_database.dart'; + +void main() { + late OfflineDatabase database; + + setUp(() => database = OfflineDatabase(NativeDatabase.memory())); + tearDown(() => database.close()); + + test( + 'offline progress survives an upsert and can become completed', + () async { + await database.saveDownload( + OfflineEntriesCompanion.insert( + videoId: 'v1', + title: '测试视频', + localPath: 'video.mp4', + partialPath: const Value('video.mp4.part'), + bytesDownloaded: const Value(512), + totalBytes: const Value(1024), + status: const Value('downloading'), + ), + ); + await database.saveDownload( + OfflineEntriesCompanion.insert( + videoId: 'v1', + title: '测试视频', + localPath: 'video.mp4', + partialPath: const Value(null), + bytesDownloaded: const Value(1024), + totalBytes: const Value(1024), + status: const Value('completed'), + ), + ); + + final entry = await database.downloadFor('v1'); + expect(entry?.status, 'completed'); + expect(entry?.partialPath, null); + expect(entry?.bytesDownloaded, 1024); + }, + ); +} diff --git a/mobile/test/widget_test.dart b/mobile/test/widget_test.dart new file mode 100644 index 0000000..f010655 --- /dev/null +++ b/mobile/test/widget_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:imagefind_mobile/src/models.dart'; +import 'package:imagefind_mobile/src/screens/core_screens.dart'; +import 'package:imagefind_mobile/src/screens/shell.dart'; +import 'package:imagefind_mobile/src/theme.dart'; + +void main() { + test('formats media duration', () { + expect(formatDuration(1845000), '30:45'); + expect(formatDuration(3723000), '1:02:03'); + }); + + testWidgets('selected navigation has no bubble', (tester) async { + await tester.pumpWidget( + MaterialApp( + theme: buildTheme(Brightness.light, TargetPlatform.android), + home: Scaffold( + bottomNavigationBar: NavigationBar( + selectedIndex: 0, + destinations: const [ + NavigationDestination( + icon: Icon(Icons.home_outlined), + label: '首页', + ), + NavigationDestination(icon: Icon(Icons.search), label: '搜索'), + ], + ), + ), + ), + ); + final theme = NavigationBarTheme.of( + tester.element(find.byType(NavigationBar)), + ); + expect(theme.indicatorColor, Colors.transparent); + }); + + testWidgets('phone shell and search fit a 390dp viewport', (tester) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + theme: buildTheme(Brightness.light, TargetPlatform.android), + home: const AppShell(index: 1, child: SearchScreen()), + ), + ), + ); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(find.byType(NavigationBar), findsOneWidget); + final field = tester.getRect(find.byType(TextField)); + expect(field.left, greaterThanOrEqualTo(6)); + expect(field.right, lessThan(340)); + final navigation = tester.getRect(find.byType(NavigationBar)); + expect(navigation.left, 0); + expect(navigation.right, 390); + }); +}