├── .cursorrules ├── .gitignore ├── .metadata ├── .vscode ├── launch.json └── settings.json ├── .windsurf ├── cascade_rules.json └── flutter_rules.md ├── README.md ├── READMEDEV.md ├── analysis_options.yaml ├── android ├── .gitignore ├── app │ ├── build.gradle │ └── src │ │ ├── debug │ │ └── AndroidManifest.xml │ │ ├── main │ │ ├── AndroidManifest.xml │ │ ├── kotlin │ │ │ └── com │ │ │ │ └── example │ │ │ │ └── hapee_next │ │ │ │ └── MainActivity.kt │ │ └── res │ │ │ ├── drawable-v21 │ │ │ └── launch_background.xml │ │ │ ├── drawable │ │ │ └── launch_background.xml │ │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ └── ic_launcher.png │ │ │ ├── values-night │ │ │ └── styles.xml │ │ │ └── values │ │ │ └── styles.xml │ │ └── profile │ │ └── AndroidManifest.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties └── settings.gradle ├── build.yaml ├── docs ├── api_examples.md ├── api_usage.md └── development_guidelines.md ├── import_sorter.yaml ├── l10n.yaml ├── lib ├── app │ ├── app.dart │ ├── core │ │ ├── api │ │ │ └── gopeed_api │ │ │ │ ├── api.dart │ │ │ │ ├── client │ │ │ │ └── api_client.dart │ │ │ │ ├── endpoints │ │ │ │ ├── base_api.dart │ │ │ │ ├── config_api.dart │ │ │ │ ├── info_api.dart │ │ │ │ ├── resolve_api.dart │ │ │ │ └── task_api.dart │ │ │ │ └── exceptions.dart │ │ ├── app_config │ │ │ ├── app_config.dart │ │ │ ├── desktop_config.dart │ │ │ ├── mobile_config.dart │ │ │ └── tracker_config.dart │ │ ├── database │ │ │ ├── database.dart │ │ │ ├── entity.dart │ │ │ └── entity.g.dart │ │ ├── local_storage │ │ │ └── app_storage.dart │ │ ├── models │ │ │ └── gopeed_models │ │ │ │ └── common │ │ │ │ ├── config.dart │ │ │ │ ├── enums.dart │ │ │ │ ├── meta.dart │ │ │ │ ├── models.dart │ │ │ │ ├── options.dart │ │ │ │ ├── progress.dart │ │ │ │ ├── request.dart │ │ │ │ ├── resolve_result.dart │ │ │ │ ├── resource.dart │ │ │ │ ├── result.dart │ │ │ │ ├── result_extension.dart │ │ │ │ ├── server_info.dart │ │ │ │ └── task.dart │ │ ├── router │ │ │ └── router.dart │ │ ├── style │ │ │ └── app_style.dart │ │ ├── theme │ │ │ └── app_theme.dart │ │ ├── utils │ │ │ ├── file_icon_helper.dart │ │ │ ├── file_icons.dart │ │ │ ├── file_utils.dart │ │ │ └── util.dart │ │ └── widgets │ │ │ ├── adaptive_icon.dart │ │ │ └── error_view.dart │ └── features │ │ ├── create │ │ ├── provider │ │ │ └── create_task_provider.dart │ │ ├── view │ │ │ └── create_view.dart │ │ └── widgets │ │ │ ├── resolved_bt_tree_view.dart │ │ │ └── resolved_resource_dialog.dart │ │ ├── main │ │ ├── providers │ │ │ └── main_providers.dart │ │ ├── repository │ │ │ ├── main_repository.dart │ │ │ ├── main_repository_fake.dart │ │ │ └── main_repository_impl.dart │ │ └── view │ │ │ └── main_view.dart │ │ └── sync │ │ ├── extension │ │ └── status_extension.dart │ │ ├── provider │ │ └── sync_providers.dart │ │ ├── view │ │ └── sync_view.dart │ │ └── widgets │ │ ├── sync_grid_view.dart │ │ ├── sync_table_view.dart │ │ └── task_actions.dart ├── baas │ ├── baas.dart │ ├── firebase.dart │ ├── pocketbase.dart │ └── pocketbase_baas.dart ├── gopeed │ ├── common │ │ ├── libgopeed_channel.dart │ │ ├── libgopeed_ffi.dart │ │ ├── libgopeed_interface.dart │ │ ├── start_config.dart │ │ ├── start_config.freezed.dart │ │ └── start_config.g.dart │ ├── entry │ │ ├── libgopeed_boot_browser.dart │ │ └── libgopeed_boot_native.dart │ ├── ffi │ │ └── libgopeed_bind.dart │ ├── libgopeed_boot.dart │ └── libgopeed_boot_stub.dart ├── l10n │ ├── arb │ │ ├── app_ar.arb │ │ ├── app_bg.arb │ │ ├── app_ca.arb │ │ ├── app_de.arb │ │ ├── app_el.arb │ │ ├── app_en.arb │ │ ├── app_es.arb │ │ ├── app_fa.arb │ │ ├── app_fr.arb │ │ ├── app_hu.arb │ │ ├── app_id.arb │ │ ├── app_it.arb │ │ ├── app_ja.arb │ │ ├── app_ko.arb │ │ ├── app_nb.arb │ │ ├── app_nl.arb │ │ ├── app_pl.arb │ │ ├── app_pt.arb │ │ ├── app_ro.arb │ │ ├── app_ru.arb │ │ ├── app_ta.arb │ │ ├── app_tr.arb │ │ ├── app_uk.arb │ │ ├── app_vi.arb │ │ ├── app_zh.arb │ │ └── app_zh_TW.arb │ └── l10n.dart └── main.dart ├── linux ├── .gitignore ├── CMakeLists.txt ├── flutter │ ├── CMakeLists.txt │ ├── generated_plugin_registrant.cc │ ├── generated_plugin_registrant.h │ └── generated_plugins.cmake ├── main.cc ├── my_application.cc └── my_application.h ├── macos ├── .gitignore ├── Flutter │ ├── Flutter-Debug.xcconfig │ ├── Flutter-Release.xcconfig │ └── GeneratedPluginRegistrant.swift ├── Runner.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ └── xcshareddata │ │ └── xcschemes │ │ └── Runner.xcscheme ├── Runner.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist ├── Runner │ ├── AppDelegate.swift │ ├── Assets.xcassets │ │ └── AppIcon.appiconset │ │ │ ├── Contents.json │ │ │ ├── app_icon_1024.png │ │ │ ├── app_icon_128.png │ │ │ ├── app_icon_16.png │ │ │ ├── app_icon_256.png │ │ │ ├── app_icon_32.png │ │ │ ├── app_icon_512.png │ │ │ └── app_icon_64.png │ ├── Base.lproj │ │ └── MainMenu.xib │ ├── Configs │ │ ├── AppInfo.xcconfig │ │ ├── Debug.xcconfig │ │ ├── Release.xcconfig │ │ └── Warnings.xcconfig │ ├── DebugProfile.entitlements │ ├── Info.plist │ ├── MainFlutterWindow.swift │ └── Release.entitlements └── RunnerTests │ └── RunnerTests.swift ├── pubspec.lock ├── pubspec.yaml ├── test ├── api │ ├── api_client_test.dart │ ├── config_api_test.dart │ ├── info_api_test.dart │ ├── performance_test.dart │ ├── resolve_api_test.dart │ └── task_api_test.dart ├── create │ └── view │ │ ├── create_page_test.dart │ │ └── widgets │ │ └── create_body_test.dart ├── edge_cases │ └── api_edge_cases_test.dart ├── integration │ └── download_workflow_test.dart ├── mocks.dart ├── mocks.mocks.dart ├── sync │ └── view │ │ ├── sync_page_test.dart │ │ └── widgets │ │ └── sync_body_test.dart └── widget_test.dart ├── tool.dart ├── web ├── favicon.png ├── icons │ ├── Icon-192.png │ ├── Icon-512.png │ ├── Icon-maskable-192.png │ └── Icon-maskable-512.png ├── index.html └── manifest.json └── windows ├── .gitignore ├── CMakeLists.txt ├── CMakeSettings.json ├── flutter ├── CMakeLists.txt ├── generated_plugin_registrant.cc ├── generated_plugin_registrant.h └── generated_plugins.cmake ├── git_path.cmake ├── libgopeed.dll ├── libgopeed.h └── runner ├── CMakeLists.txt ├── Runner.rc ├── flutter_window.cpp ├── flutter_window.h ├── main.cpp ├── resource.h ├── resources └── app_icon.ico ├── runner.exe.manifest ├── utils.cpp ├── utils.h ├── win32_window.cpp └── win32_window.h /.cursorrules: -------------------------------------------------------------------------------- 1 | You are an expert in Flutter, Dart, Riverpod, Freezed, Flutter Hooks. 2 | 3 | Key Principles 4 | - Use English for all code and documentation. 5 | - Write concise, technical Dart code with accurate examples. 6 | - Use functional and declarative programming patterns where appropriate. 7 | - Prefer composition over inheritance. 8 | - Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError). 9 | - Structure files: exported widget, subwidgets, helpers, static content, types. 10 | 11 | Dart/Flutter 12 | - Use const constructors for immutable widgets. 13 | - Leverage Freezed for immutable state classes and unions. 14 | - Use arrow syntax for simple functions and methods. 15 | - Prefer expression bodies for one-line getters and setters. 16 | - Use trailing commas for better formatting and diffs. 17 | 18 | Error Handling and Validation 19 | - Implement error handling in views using SelectableText.rich instead of SnackBars. 20 | - Display errors in SelectableText.rich with red color for visibility. 21 | - Handle empty states within the displaying screen. 22 | - Use AsyncValue for proper error handling and loading states. 23 | 24 | Riverpod-Specific Guidelines 25 | - Use @riverpod annotation for generating providers. 26 | - Prefer StreamProvider, AsyncNotifierProvider and NotifierProvider over StateProvider. 27 | - Avoid StateProvider, StateNotifierProvider, and ChangeNotifierProvider. 28 | - Use ref.invalidate() for manually triggering provider updates. 29 | - Implement proper cancellation of asynchronous operations when widgets are disposed. 30 | 31 | Performance Optimization 32 | - Use const widgets where possible to optimize rebuilds. 33 | - Implement list view optimizations (e.g., ListView.builder). 34 | - Use AssetImage for static images and cached_network_image for remote images. 35 | - Implement proper error handling for Supabase operations, including network errors. 36 | 37 | Key Conventions 38 | 1. Use GoRouter for navigation and deep linking. 39 | 2. Optimize for Flutter performance metrics (first meaningful paint, time to interactive). 40 | 3. Prefer stateless widgets: 41 | - Use ConsumerWidget with Riverpod for state-dependent widgets. 42 | - Use HookConsumerWidget when combining Riverpod and Flutter Hooks. 43 | 44 | UI and Styling 45 | - Use Flutter's built-in widgets and create custom widgets. 46 | - Implement responsive design using LayoutBuilder or MediaQuery. 47 | - Use themes for consistent styling across the app. 48 | - Use Theme.of(context).textTheme.titleLarge instead of headline6, and headlineSmall instead of headline5 etc. 49 | 50 | Model and Database Conventions 51 | - Include createdAt, updatedAt, and isDeleted fields in database tables. 52 | - Use @JsonSerializable(fieldRename: FieldRename.snake) for models. 53 | - Implement @JsonKey(includeFromJson: true, includeToJson: false) for read-only fields. 54 | 55 | Widgets and UI Components 56 | - Create small, private widget classes instead of methods like Widget _build.... 57 | - Implement RefreshIndicator for pull-to-refresh functionality. 58 | - In TextFields, set appropriate textCapitalization, keyboardType, and textInputAction. 59 | - Always include an errorBuilder when using Image.network. 60 | - Write styling code in style.dart file. 61 | 62 | Miscellaneous 63 | - Use log instead of print for debugging. 64 | - Use Flutter Hooks / Riverpod Hooks where appropriate. 65 | - Keep lines no longer than 80 characters, adding commas before closing brackets for multi-parameter functions. 66 | - Use @JsonValue(int) for enums that go to the database. 67 | 68 | Code Generation 69 | - Utilize build_runner for generating code from annotations (Freezed, Riverpod, JSON serialization). 70 | - Run 'dart run build_runner build --delete-conflicting-outputs' after modifying annotated classes. 71 | 72 | Documentation 73 | - Document complex logic and non-obvious code decisions. 74 | - Follow official Flutter, Riverpod, and Supabase documentation for best practices. 75 | 76 | 77 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | migrate_working_dir/ 12 | 13 | # IntelliJ related 14 | *.iml 15 | *.ipr 16 | *.iws 17 | .idea/ 18 | 19 | # The .vscode folder contains launch configuration and tasks you configure in 20 | # VS Code which you may wish to be included in version control, so this line 21 | # is commented out by default. 22 | #.vscode/ 23 | 24 | # Flutter/Dart/Pub related 25 | **/doc/api/ 26 | **/ios/Flutter/.last_build_id 27 | .dart_tool/ 28 | .flutter-plugins 29 | .flutter-plugins-dependencies 30 | .pub-cache/ 31 | .pub/ 32 | /build/ 33 | 34 | # Symbolication related 35 | app.*.symbols 36 | 37 | # Obfuscation related 38 | app.*.map.json 39 | 40 | # Android Studio will place build artifacts here 41 | /android/app/debug 42 | /android/app/profile 43 | /android/app/release 44 | 45 | # Firebase 46 | lib/firebase_options.dart 47 | android/app/google-services.json 48 | ios/Runner/GoogleService-Info.plist 49 | 50 | 51 | .firebase/ 52 | firebase-debug.log 53 | .firebase-emulator-cache/ 54 | 55 | 56 | .firebaserc 57 | firebase.json 58 | 59 | # Firebase Admin SDK 60 | serviceAccountKey.json 61 | 62 | # tools 63 | tools/ 64 | 65 | # secrets 66 | .gitignore-secrets 67 | push.ps1 68 | env.json 69 | 70 | 71 | # gopeed 72 | gopeedswagger.json 73 | gopeed.db 74 | 75 | # Generated Dart files 76 | *.g.dart 77 | *.freezed.dart 78 | -------------------------------------------------------------------------------- /.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled and should not be manually edited. 5 | 6 | version: 7 | revision: "5874a72aa4c779a02553007c47dacbefba2374dc" 8 | channel: "stable" 9 | 10 | project_type: app 11 | 12 | # Tracks metadata for the flutter migrate command 13 | migration: 14 | platforms: 15 | - platform: root 16 | create_revision: 5874a72aa4c779a02553007c47dacbefba2374dc 17 | base_revision: 5874a72aa4c779a02553007c47dacbefba2374dc 18 | - platform: windows 19 | create_revision: 5874a72aa4c779a02553007c47dacbefba2374dc 20 | base_revision: 5874a72aa4c779a02553007c47dacbefba2374dc 21 | 22 | # User provided section 23 | 24 | # List of Local paths (relative to this file) that should be 25 | # ignored by the migrate tool. 26 | # 27 | # Files that are not part of the templates will be ignored by default. 28 | unmanaged_files: 29 | - 'lib/main.dart' 30 | - 'ios/Runner.xcodeproj/project.pbxproj' 31 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Flutter", 9 | "type": "dart", 10 | "request": "launch", 11 | "args": [ 12 | "--dart-define-from-file=env.json" 13 | ] 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "conventionalCommits.scopes": [ 3 | "hapee" 4 | ], 5 | "cmake.ignoreCMakeListsMissing": true 6 | } 7 | -------------------------------------------------------------------------------- /.windsurf/cascade_rules.json: -------------------------------------------------------------------------------- 1 | { 2 | "global": { 3 | "comments": { 4 | "language": "english", 5 | "description": "All code comments must be written in English" 6 | }, 7 | "naming": { 8 | "conventions": { 9 | "variables": "lowerCamelCase", 10 | "functions": "lowerCamelCase", 11 | "classes": "UpperCamelCase", 12 | "types": "UpperCamelCase", 13 | "files": "lowercase_with_underscores" 14 | } 15 | } 16 | }, 17 | "flutter": { 18 | "stateManagement": { 19 | "hooks": { 20 | "rules": [ 21 | { 22 | "rule": "use_memo_for_persistence", 23 | "description": "Use useMemoized for objects that should persist across rebuilds" 24 | }, 25 | { 26 | "rule": "effect_for_updates", 27 | "description": "Use useEffect for updates instead of recreation" 28 | } 29 | ] 30 | }, 31 | "riverpod": { 32 | "rules": [ 33 | { 34 | "rule": "ref_usage", 35 | "description": "Proper ref method usage", 36 | "methods": { 37 | "watch": "Reactive dependencies in build", 38 | "read": "One-time reads in callbacks" 39 | } 40 | } 41 | ] 42 | } 43 | }, 44 | "performance": { 45 | "rules": [ 46 | { 47 | "rule": "preserve_state", 48 | "description": "Maintain state during updates", 49 | "checks": [ 50 | "Sort state", 51 | "Selection state", 52 | "User customizations" 53 | ] 54 | } 55 | ] 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /.windsurf/flutter_rules.md: -------------------------------------------------------------------------------- 1 | # Flutter Development Rules 2 | 3 | ## State Management with Hooks and Riverpod 4 | 5 | ### Hooks Best Practices 6 | 7 | #### Object Creation and Persistence 8 | 1. Use `useMemoized` for objects that should persist across rebuilds 9 | 2. Always use empty const array for dependencies unless specific dependencies are needed 10 | ```dart 11 | final persistentObject = useMemoized( 12 | () => ComplexObject(), 13 | const [], // Empty dependency array ensures single initialization 14 | ); 15 | ``` 16 | 17 | #### State Updates 18 | 1. Use `useEffect` for handling updates instead of recreating objects 19 | 2. Clearly specify effect dependencies 20 | 3. Return cleanup function when needed 21 | ```dart 22 | useEffect(() { 23 | // Setup 24 | existingObject.update(newData); 25 | 26 | // Cleanup 27 | return () { 28 | existingObject.dispose(); 29 | }; 30 | }, [newData]); // Only update when newData changes 31 | ``` 32 | 33 | #### Hook Selection Guidelines 34 | 1. `useState`: For simple local state 35 | ```dart 36 | final counter = useState(0); 37 | counter.value++; // Triggers rebuild 38 | ``` 39 | 40 | 2. `useMemoized`: For expensive computations or object creation 41 | ```dart 42 | final expensiveValue = useMemoized(() => compute(data), [data]); 43 | ``` 44 | 45 | 3. `useCallback`: For function memoization 46 | ```dart 47 | final handler = useCallback(() { 48 | // Handle event 49 | }, [dependency]); 50 | ``` 51 | 52 | 4. `useFuture`: For Future handling 53 | ```dart 54 | final snapshot = useFuture(fetchData()); 55 | ``` 56 | 57 | 5. `useStream`: For Stream handling 58 | ```dart 59 | final snapshot = useStream(dataStream); 60 | ``` 61 | 62 | ### Riverpod Best Practices 63 | 64 | #### Provider Types 65 | 1. `Provider`: For computed/cached values 66 | ```dart 67 | final computedProvider = Provider((ref) => Complex.compute()); 68 | ``` 69 | 70 | 2. `StateProvider`: For simple state 71 | ```dart 72 | final counterProvider = StateProvider((ref) => 0); 73 | ``` 74 | 75 | 3. `StateNotifierProvider`: For complex state 76 | ```dart 77 | final tasksProvider = StateNotifierProvider>((ref) => TasksNotifier()); 78 | ``` 79 | 80 | 4. `FutureProvider`: For async data 81 | ```dart 82 | final userProvider = FutureProvider((ref) => fetchUser()); 83 | ``` 84 | 85 | 5. `StreamProvider`: For reactive data 86 | ```dart 87 | final updatesProvider = StreamProvider((ref) => getUpdates()); 88 | ``` 89 | 90 | #### Provider Organization 91 | 1. Group related providers in a single file 92 | 2. Use family modifier for parameterized providers 93 | 3. Use autoDispose when appropriate 94 | ```dart 95 | final userProvider = FutureProvider.family.autoDispose((ref, String id) { 96 | return fetchUser(id); 97 | }); 98 | ``` 99 | 100 | #### Ref Usage 101 | 1. Use `watch` for reactive dependencies 102 | 2. Use `read` for one-time reads 103 | 3. Use `listen` for side effects 104 | ```dart 105 | // In build method 106 | final value = ref.watch(myProvider); 107 | 108 | // In callbacks 109 | ref.read(myProvider.notifier).update(); 110 | 111 | // For side effects 112 | ref.listen(myProvider, (previous, next) { 113 | // Handle changes 114 | }); 115 | ``` 116 | 117 | ### DataSource Management 118 | 1. Never recreate DataSource objects on data updates 119 | 2. Maintain sort and selection states within the DataSource 120 | 3. Use update methods instead of reconstruction 121 | ```dart 122 | // Correct 123 | final dataSource = useMemoized(() => MyDataSource(), const []); 124 | useEffect(() { dataSource.updateData(newData); }, [newData]); 125 | 126 | // Incorrect 127 | final dataSource = MyDataSource(data); // Will recreate on every rebuild 128 | ``` 129 | 130 | ### State Preservation 131 | 1. Maintain UI state during data updates: 132 | - Sort order 133 | - Selection state 134 | - Filter criteria 135 | - Scroll position 136 | - Form input values 137 | 138 | 2. Use appropriate storage methods: 139 | - `useMemoized` for complex objects 140 | - Provider state for shared state 141 | - Local state for UI-only state 142 | 143 | ### Error Handling 144 | 1. Use `AsyncValue` for error states 145 | ```dart 146 | final provider = FutureProvider((ref) async { 147 | try { 148 | return await fetchData(); 149 | } catch (e) { 150 | throw CustomError(e); 151 | } 152 | }); 153 | ``` 154 | 155 | 2. Handle loading states appropriately 156 | ```dart 157 | ref.watch(provider).when( 158 | data: (data) => DataWidget(data), 159 | loading: () => LoadingWidget(), 160 | error: (error, stack) => ErrorWidget(error), 161 | ); 162 | ``` 163 | 164 | ## Common Pitfalls to Avoid 165 | 1. Recreating complex objects in build methods 166 | 2. Using useState for persistent objects 167 | 3. Missing effect dependencies 168 | 4. Mixing state management approaches 169 | 5. Forgetting to dispose resources 170 | 6. Watching providers in callbacks 171 | 7. Using BuildContext after dispose 172 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Developing 0.1.0 ... 2 | 3 | 4 | 5 | 这个是我对未来搜索引擎的一个梦想, 6 | 尽量开源,尽量挖掘Dart在前端的潜藏能力,尽量支持所有协议, 7 | 8 | 为什么要起名Hapee? 9 | 因为我觉得人的一生最缺少快乐吧。希望Hapee能带给大家刚第一次接触到搜索引擎时轻易搜到自己喜欢的东西的那种快乐。 10 | 11 | ## TODOS 12 | - 添加Aria2支持 13 | - 为不支持Flutter的操作系统提供Web方案 14 | - CI/CD 15 | - Dart扩展平台 16 | - js扩展平台 17 | 18 | 19 | 20 | 21 | 22 | 23 | ## Hapee理论支持平台 24 | 25 | ### Flutter 平台支持 26 | 27 | 当前 Flutter 版本: 3.24.1 (stable) 28 | 29 | | Target platform | Target architectures | Supported versions | CI-tested versions | Unsupported versions | 30 | | --- | --- | --- | --- | --- | 31 | | Android SDK | x64, Arm32, Arm64 | 21 to 34 | 21 to 34 | 20 and earlier | 32 | | iOS | Arm64 | 12 to 18 | 17 | 11 and earlier | 33 | | macOS | x64, Arm64 | Mojave (10.14) to Sequoia (15) | Ventura (13), Sonoma (14) | High Sierra (10.13) and earlier | 34 | | Windows | x64, Arm64 | 10, 11 | 10 | 8 and earlier | 35 | | Debian (Linux) | x64, Arm64 | 10, 11, 12 | 11, 12 | 9 and earlier | 36 | | Ubuntu (Linux) | x64, Arm64 | 20.04 LTS to 24.04 LTS | 20.04 LTS, 22.04 LTS | 23.10 and earlier non-LTS | 37 | | Chrome (Web) | JavaScript, WebAssembly | Latest 2 | 119, 125 | 95 and earlier | 38 | | Firefox (Web) | JavaScript | 106 and newer | 106 | 98 and earlier | 39 | | Safari (Web) | JavaScript | 15.6 and newer | 15.6 | 15.5 and earlier | 40 | | Edge (Web) | JavaScript, WebAssembly | Latest 2 | 119, 125 | 95 and earlier | 41 | 42 | ## Hapee目前支持平台 43 | -------------------------------------------------------------------------------- /READMEDEV.md: -------------------------------------------------------------------------------- 1 | ## 开发 2 | 开发时 3 | ``` 4 | dart run import_sorter:main 5 | dart run build_runner watch --delete-conflicting-outputs --low-resources-mode 6 | flutter run 7 | ``` 8 | 9 | push前 10 | 11 | ``` 12 | dart run import_sorter:main 13 | ``` 14 | TODO: 15 | 16 | - 所有错误error,和stacktrace会用riverpod显示在右边可选屏幕 17 | 同时会打印在控制台 18 | - 国际化以及长按国际化组件 19 | - gridview 20 | - 设置页面 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | pub points = 160 40 | 41 | popularity > 90% 42 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the analyzer, which statically analyzes Dart code to 2 | # check for errors, warnings, and lints. 3 | # 4 | # The issues identified by the analyzer are surfaced in the UI of Dart-enabled 5 | # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be 6 | # invoked from the command line by running `flutter analyze`. 7 | 8 | # The following line activates a set of recommended lints for Flutter apps, 9 | # packages, and plugins designed to encourage good coding practices. 10 | include: package:flutter_lints/flutter.yaml 11 | # include: package:very_good_analysis/analysis_options.yaml 12 | linter: 13 | # The lint rules applied to this project can be customized in the 14 | # section below to disable rules from the `package:flutter_lints/flutter.yaml` 15 | # included above or to enable additional rules. A list of all available lints 16 | # and their documentation is published at https://dart.dev/lints. 17 | # 18 | # Instead of disabling a lint rule for the entire project in the 19 | # section below, it can also be suppressed for a single line of code 20 | # or a specific dart file by using the `// ignore: name_of_lint` and 21 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file 22 | # producing the lint. 23 | rules: 24 | # avoid_print: false # Uncomment to disable the `avoid_print` rule 25 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule 26 | 27 | # Additional information about this file can be found at 28 | # https://dart.dev/guides/language/analysis-options 29 | 30 | analyzer: 31 | errors: 32 | depend_on_referenced_packages: ignore 33 | plugins: 34 | - custom_lint 35 | -------------------------------------------------------------------------------- /android/.gitignore: -------------------------------------------------------------------------------- 1 | gradle-wrapper.jar 2 | /.gradle 3 | /captures/ 4 | /gradlew 5 | /gradlew.bat 6 | /local.properties 7 | GeneratedPluginRegistrant.java 8 | 9 | # Remember to never publicly share your keystore. 10 | # See https://flutter.dev/to/reference-keystore 11 | key.properties 12 | **/*.keystore 13 | **/*.jks 14 | -------------------------------------------------------------------------------- /android/app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "com.android.application" 3 | id "kotlin-android" 4 | // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. 5 | id "dev.flutter.flutter-gradle-plugin" 6 | } 7 | 8 | android { 9 | namespace = "com.example.hapee" 10 | compileSdk = flutter.compileSdkVersion 11 | ndkVersion = flutter.ndkVersion 12 | 13 | compileOptions { 14 | sourceCompatibility = JavaVersion.VERSION_1_8 15 | targetCompatibility = JavaVersion.VERSION_1_8 16 | } 17 | 18 | kotlinOptions { 19 | jvmTarget = JavaVersion.VERSION_1_8 20 | } 21 | 22 | defaultConfig { 23 | // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). 24 | applicationId = "com.example.hapee" 25 | // You can update the following values to match your application needs. 26 | // For more information, see: https://flutter.dev/to/review-gradle-config. 27 | minSdk = flutter.minSdkVersion 28 | targetSdk = flutter.targetSdkVersion 29 | versionCode = flutter.versionCode 30 | versionName = flutter.versionName 31 | } 32 | 33 | buildTypes { 34 | release { 35 | // TODO: Add your own signing config for the release build. 36 | // Signing with the debug keys for now, so `flutter run --release` works. 37 | signingConfig = signingConfigs.debug 38 | } 39 | } 40 | } 41 | 42 | flutter { 43 | source = "../.." 44 | } 45 | -------------------------------------------------------------------------------- /android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 16 | 20 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 34 | 35 | 37 | 40 | 41 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/example/hapee_next/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.example.hapee 2 | 3 | import io.flutter.embedding.android.FlutterActivity 4 | 5 | class MainActivity: FlutterActivity() 6 | -------------------------------------------------------------------------------- /android/app/src/main/res/drawable-v21/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /android/app/src/main/res/drawable/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/values-night/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /android/app/src/profile/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | allprojects { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | } 6 | } 7 | 8 | rootProject.buildDir = "../build" 9 | subprojects { 10 | project.buildDir = "${rootProject.buildDir}/${project.name}" 11 | } 12 | subprojects { 13 | project.evaluationDependsOn(":app") 14 | } 15 | 16 | tasks.register("clean", Delete) { 17 | delete rootProject.buildDir 18 | } 19 | -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError 2 | android.useAndroidX=true 3 | android.enableJetifier=true 4 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-all.zip 6 | -------------------------------------------------------------------------------- /android/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | def flutterSdkPath = { 3 | def properties = new Properties() 4 | file("local.properties").withInputStream { properties.load(it) } 5 | def flutterSdkPath = properties.getProperty("flutter.sdk") 6 | assert flutterSdkPath != null, "flutter.sdk not set in local.properties" 7 | return flutterSdkPath 8 | }() 9 | 10 | includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") 11 | 12 | repositories { 13 | google() 14 | mavenCentral() 15 | gradlePluginPortal() 16 | } 17 | } 18 | 19 | plugins { 20 | id "dev.flutter.flutter-plugin-loader" version "1.0.0" 21 | id "com.android.application" version "7.3.0" apply false 22 | id "org.jetbrains.kotlin.android" version "1.7.10" apply false 23 | } 24 | 25 | include ":app" 26 | -------------------------------------------------------------------------------- /build.yaml: -------------------------------------------------------------------------------- 1 | targets: 2 | $default: 3 | sources: 4 | exclude: 5 | - lib/**/*.g.dart 6 | - lib/**/*.freezed.dart 7 | builders: 8 | json_serializable: 9 | options: 10 | any_map: true 11 | explicit_to_json: true 12 | -------------------------------------------------------------------------------- /docs/api_examples.md: -------------------------------------------------------------------------------- 1 | # Hapee API 使用示例 2 | 3 | ## 基础用法 4 | 5 | ### 初始化 6 | -------------------------------------------------------------------------------- /docs/api_usage.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/docs/api_usage.md -------------------------------------------------------------------------------- /docs/development_guidelines.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/docs/development_guidelines.md -------------------------------------------------------------------------------- /import_sorter.yaml: -------------------------------------------------------------------------------- 1 | import_sorter: 2 | comments: false # 是否保留注释 3 | ignored_files: # 忽略的文件 4 | - /lib/generated/ 5 | sort_by_type: true # 按类型排序 6 | emojis: false # 不使用表情符号 7 | line_length: 80 # 行长度 8 | always_specify_types: false 9 | use_package_imports: true # 使用 package 导入方式 10 | -------------------------------------------------------------------------------- /l10n.yaml: -------------------------------------------------------------------------------- 1 | arb-dir: lib/l10n/arb 2 | template-arb-file: app_en.arb 3 | output-localization-file: app_localizations.dart -------------------------------------------------------------------------------- /lib/app/app.dart: -------------------------------------------------------------------------------- 1 | // Flutter imports: 2 | import 'package:flutter/material.dart'; 3 | 4 | // Package imports: 5 | import 'package:hooks_riverpod/hooks_riverpod.dart'; 6 | 7 | // Project imports: 8 | import '../l10n/l10n.dart'; 9 | import 'core/router/router.dart'; 10 | import 'core/utils/util.dart'; 11 | 12 | class App extends ConsumerWidget { 13 | /// [App] 14 | const App({super.key}); 15 | 16 | @override 17 | Widget build(BuildContext context, WidgetRef ref) { 18 | final router = ref.read(routerProvider); 19 | 20 | return MaterialApp.router( 21 | title: 'Hapee', 22 | routerConfig: router, 23 | localizationsDelegates: AppLocalizations.localizationsDelegates, 24 | supportedLocales: AppLocalizations.supportedLocales, 25 | themeMode: ThemeMode.system, 26 | theme: ThemeData.light(useMaterial3: true).copyWith( 27 | textTheme: ThemeData.light().textTheme.apply( 28 | fontFamily: Util.isWindows ? 'Microsoft YaHei' : null, 29 | ), 30 | ), 31 | darkTheme: ThemeData.dark(useMaterial3: true).copyWith( 32 | textTheme: ThemeData.dark().textTheme.apply( 33 | fontFamily: Util.isWindows ? 'Microsoft YaHei' : null, 34 | ), 35 | ), 36 | ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /lib/app/core/api/gopeed_api/api.dart: -------------------------------------------------------------------------------- 1 | // Project imports: 2 | import 'client/api_client.dart'; 3 | import 'endpoints/config_api.dart'; 4 | import 'endpoints/info_api.dart'; 5 | import 'endpoints/resolve_api.dart'; 6 | import 'endpoints/task_api.dart'; 7 | 8 | // 导出所有API相关类 9 | export 'client/api_client.dart'; 10 | export 'endpoints/task_api.dart'; 11 | export 'endpoints/config_api.dart'; 12 | export 'endpoints/info_api.dart'; 13 | export 'endpoints/resolve_api.dart'; 14 | 15 | /// API 统一访问入口 16 | class Api { 17 | // 私有构造函数,防止实例化 18 | Api._(); 19 | 20 | // API实例 21 | static final TaskApi taskApi = TaskApi(); 22 | static final ConfigApi configApi = ConfigApi(); 23 | static final InfoApi infoApi = InfoApi(); 24 | static final ResolveApi resolveApi = ResolveApi(); 25 | 26 | /// 初始化API客户端 27 | /// 28 | /// [network] - 网络类型 ('unix' 或 'tcp') 29 | /// [address] - 服务器地址 30 | /// [apiToken] - API访问令牌 31 | static void init(String network, String address, String apiToken) { 32 | ApiClient.instance.initialize( 33 | network: network, 34 | address: address, 35 | apiToken: apiToken, 36 | ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /lib/app/core/api/gopeed_api/client/api_client.dart: -------------------------------------------------------------------------------- 1 | // Dart imports: 2 | import 'dart:io'; 3 | 4 | // Package imports: 5 | import 'package:dio/dio.dart'; 6 | import 'package:dio/io.dart'; 7 | 8 | // Project imports: 9 | import '../exceptions.dart'; 10 | 11 | class ApiClient { 12 | static final ApiClient _instance = ApiClient._(); 13 | late final Dio dio; 14 | 15 | ApiClient._(); 16 | 17 | static ApiClient get instance => _instance; 18 | 19 | void initialize({ 20 | required String network, 21 | required String address, 22 | required String apiToken, 23 | }) { 24 | final isUnixSocket = network == 'unix'; 25 | final baseUrl = _getBaseUrl(isUnixSocket, address); 26 | 27 | dio = Dio() 28 | ..options = BaseOptions( 29 | baseUrl: baseUrl, 30 | contentType: Headers.jsonContentType, 31 | sendTimeout: const Duration(seconds: 5), 32 | connectTimeout: const Duration(seconds: 5), 33 | receiveTimeout: const Duration(seconds: 60), 34 | ) 35 | ..interceptors.addAll([ 36 | _createAuthInterceptor(apiToken), 37 | _createErrorInterceptor(), 38 | ]); 39 | 40 | if (isUnixSocket) { 41 | _configureUnixSocket(address); 42 | } 43 | } 44 | 45 | String _getBaseUrl(bool isUnixSocket, String address) { 46 | if (isUnixSocket) return 'http://127.0.0.1'; 47 | return 'http://$address'; 48 | } 49 | 50 | InterceptorsWrapper _createAuthInterceptor(String apiToken) { 51 | return InterceptorsWrapper( 52 | onRequest: (options, handler) { 53 | if (apiToken.isNotEmpty) { 54 | options.headers['X-Api-Token'] = apiToken; 55 | } 56 | handler.next(options); 57 | }, 58 | ); 59 | } 60 | 61 | InterceptorsWrapper _createErrorInterceptor() { 62 | return InterceptorsWrapper( 63 | onError: (error, handler) { 64 | if (error.type == DioExceptionType.connectionTimeout || 65 | error.type == DioExceptionType.sendTimeout || 66 | error.type == DioExceptionType.receiveTimeout) { 67 | handler.reject( 68 | DioException( 69 | requestOptions: error.requestOptions, 70 | error: TimeoutException(), 71 | ), 72 | ); 73 | return; 74 | } 75 | 76 | if (error.response != null) { 77 | final response = error.response!; 78 | if (response.data != null && response.data['code'] != 0) { 79 | handler.reject( 80 | DioException( 81 | requestOptions: error.requestOptions, 82 | error: ApiResponseException( 83 | response.data['code'], 84 | response.data['msg'] ?? 'Unknown error', 85 | ), 86 | ), 87 | ); 88 | return; 89 | } 90 | } 91 | 92 | handler.reject( 93 | DioException( 94 | requestOptions: error.requestOptions, 95 | error: NetworkException( 96 | error.message ?? 'Network error', 97 | error.error, 98 | error.stackTrace, 99 | ), 100 | ), 101 | ); 102 | }, 103 | ); 104 | } 105 | 106 | void _configureUnixSocket(String address) { 107 | (dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () { 108 | final client = HttpClient(); 109 | client.connectionFactory = (_, __, ___) { 110 | return Socket.startConnect( 111 | InternetAddress(address, type: InternetAddressType.unix), 112 | 0, 113 | ); 114 | }; 115 | return client; 116 | }; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /lib/app/core/api/gopeed_api/endpoints/base_api.dart: -------------------------------------------------------------------------------- 1 | // Flutter imports: 2 | import 'package:flutter/foundation.dart'; 3 | 4 | // Package imports: 5 | import 'package:dio/dio.dart'; 6 | 7 | // Project imports: 8 | import '../client/api_client.dart'; 9 | 10 | /// API 基类 11 | abstract class BaseApi { 12 | Dio get dio => _dio ?? ApiClient.instance.dio; 13 | Dio? _dio; 14 | 15 | /// 用于测试时注入 mock dio 客户端 16 | @visibleForTesting 17 | set dio(Dio? value) => _dio = value; 18 | } 19 | -------------------------------------------------------------------------------- /lib/app/core/api/gopeed_api/endpoints/config_api.dart: -------------------------------------------------------------------------------- 1 | // Project imports: 2 | import '../../../models/gopeed_models/common/models.dart'; 3 | import 'base_api.dart'; 4 | 5 | class ConfigApi extends BaseApi { 6 | Future getConfig() async { 7 | final response = await dio.get("/api/v1/config"); 8 | return DownloaderConfig.fromJson(response.data['data']); 9 | } 10 | 11 | Future putConfig(DownloaderConfig config) async { 12 | await dio.put("/api/v1/config", data: config); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /lib/app/core/api/gopeed_api/endpoints/info_api.dart: -------------------------------------------------------------------------------- 1 | // Project imports: 2 | import '../../../models/gopeed_models/common/models.dart'; 3 | import 'base_api.dart'; 4 | 5 | class InfoApi extends BaseApi { 6 | Future getInfo() async { 7 | final response = await dio.get("/api/v1/info"); 8 | return ServerInfo.fromJson(response.data['data']); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /lib/app/core/api/gopeed_api/endpoints/resolve_api.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:dio/dio.dart'; 3 | 4 | // Project imports: 5 | import '../../../models/gopeed_models/common/models.dart'; 6 | import 'base_api.dart'; 7 | 8 | class ResolveApi extends BaseApi { 9 | Future resolve( 10 | Request request, { 11 | CancelToken? cancelToken, 12 | }) async { 13 | final response = await dio.post( 14 | "/api/v1/resolve", 15 | data: request, 16 | cancelToken: cancelToken, 17 | ); 18 | return ResolveResult.fromJson(response.data['data']); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /lib/app/core/api/gopeed_api/endpoints/task_api.dart: -------------------------------------------------------------------------------- 1 | // Project imports: 2 | import '../../../models/gopeed_models/common/models.dart'; 3 | import 'base_api.dart'; 4 | 5 | class TaskApi extends BaseApi { 6 | /// 获取任务列表 7 | Future>> getTasks(List statuses) async { 8 | final response = await dio.get( 9 | "/api/v1/tasks", 10 | queryParameters: { 11 | "status": statuses.map((e) => e.name).toList(), 12 | }, 13 | ); 14 | return Result.fromJson(response.data, (json) => json as List); 15 | } 16 | 17 | /// 批量创建任务 18 | Future>> createTaskBatch( 19 | CreateTaskBatch batch) async { 20 | final response = await dio.post("/api/v1/tasks/batch", data: batch); 21 | return Result.fromJson( 22 | response.data, (json) => json as Map); 23 | } 24 | 25 | /// 批量任务操作基础方法 26 | Future>> _batchOperation( 27 | String path, { 28 | List? ids, 29 | List? statuses, 30 | List? notStatuses, 31 | bool force = false, 32 | }) async { 33 | final response = await dio.put( 34 | path, 35 | queryParameters: { 36 | if (ids != null) "id": ids, 37 | if (statuses != null) "status": statuses.map((e) => e.name).toList(), 38 | if (notStatuses != null) 39 | "notStatus": notStatuses.map((e) => e.name).toList(), 40 | if (force) "force": force, 41 | }, 42 | ); 43 | return Result.fromJson( 44 | response.data, (json) => json as Map); 45 | } 46 | 47 | /// 批量暂停任务 48 | Future>> pauseTasks({ 49 | List? ids, 50 | List? statuses, 51 | List? notStatuses, 52 | }) async { 53 | return _batchOperation( 54 | "/api/v1/tasks/pause", 55 | ids: ids, 56 | statuses: statuses, 57 | notStatuses: notStatuses, 58 | ); 59 | } 60 | 61 | /// 批量继续任务 62 | Future>> continueTasks({ 63 | List? ids, 64 | List? statuses, 65 | List? notStatuses, 66 | }) async { 67 | return _batchOperation( 68 | "/api/v1/tasks/continue", 69 | ids: ids, 70 | statuses: statuses, 71 | notStatuses: notStatuses, 72 | ); 73 | } 74 | 75 | /// 批量删除任务 76 | Future>> deleteTasks({ 77 | List? ids, 78 | List? statuses, 79 | List? notStatuses, 80 | bool force = false, 81 | }) async { 82 | final response = await dio.delete( 83 | "/api/v1/tasks", 84 | queryParameters: { 85 | if (ids != null) "id": ids, 86 | if (statuses != null) "status": statuses.map((e) => e.name).toList(), 87 | if (notStatuses != null) 88 | "notStatus": notStatuses.map((e) => e.name).toList(), 89 | "force": force, 90 | }, 91 | ); 92 | return Result.fromJson( 93 | response.data, (json) => json as Map); 94 | } 95 | 96 | /// 获取任务统计信息 97 | Future>> getTaskStats(String id) async { 98 | final response = await dio.get("/api/v1/tasks/$id/stats"); 99 | return Result.fromJson( 100 | response.data, (json) => json as Map); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /lib/app/core/api/gopeed_api/exceptions.dart: -------------------------------------------------------------------------------- 1 | /// API 异常基类 2 | abstract class ApiException implements Exception { 3 | final String message; 4 | final dynamic error; 5 | final StackTrace? stackTrace; 6 | 7 | const ApiException(this.message, [this.error, this.stackTrace]); 8 | 9 | @override 10 | String toString() => 'ApiException: $message${error != null ? ' ($error)' : ''}'; 11 | } 12 | 13 | /// 连接超时异常 14 | class TimeoutException extends ApiException { 15 | const TimeoutException([super.message = 'Request timed out']); 16 | } 17 | 18 | /// API 响应错误 19 | class ApiResponseException extends ApiException { 20 | final int code; 21 | 22 | const ApiResponseException(this.code, String message) : super(message); 23 | 24 | @override 25 | String toString() => 'ApiResponseException: [$code] $message'; 26 | } 27 | 28 | /// 网络错误 29 | class NetworkException extends ApiException { 30 | const NetworkException(super.message, [super.error, super.stackTrace]); 31 | } 32 | -------------------------------------------------------------------------------- /lib/app/core/app_config/desktop_config.dart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/lib/app/core/app_config/desktop_config.dart -------------------------------------------------------------------------------- /lib/app/core/app_config/mobile_config.dart: -------------------------------------------------------------------------------- 1 | // Dart imports: 2 | import 'dart:async'; 3 | import 'dart:ui'; 4 | 5 | // Package imports: 6 | import 'package:flutter_background_service/flutter_background_service.dart'; 7 | 8 | class BackgroundServiceHelper { 9 | static Future initializeService() async { 10 | final service = FlutterBackgroundService(); 11 | 12 | await service.configure( 13 | iosConfiguration: IosConfiguration( 14 | autoStart: true, 15 | onForeground: onStart, 16 | onBackground: onIosBackground, 17 | ), 18 | androidConfiguration: AndroidConfiguration( 19 | onStart: onStart, 20 | autoStart: true, 21 | isForegroundMode: true, 22 | notificationChannelId: 'my_service', 23 | initialNotificationTitle: '服务已启动', 24 | initialNotificationContent: '应用正在后台运行...', 25 | foregroundServiceTypes: [AndroidForegroundType.dataSync,AndroidForegroundType.mediaPlayback]), 26 | ); 27 | await service.startService(); 28 | } 29 | 30 | @pragma('vm:entry-point') 31 | static Future onIosBackground(ServiceInstance service) async { 32 | return true; 33 | } 34 | 35 | @pragma('vm:entry-point') 36 | static void onStart(ServiceInstance service) async { 37 | DartPluginRegistrant.ensureInitialized(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lib/app/core/app_config/tracker_config.dart: -------------------------------------------------------------------------------- 1 | // const trackerSubscribeUrls = [ 2 | // 'https://github.com/ngosang/trackerslist/raw/master/trackers_all.txt', 3 | // 'https://github.com/XIU2/TrackersListCollection/raw/master/all.txt', 4 | // ]; 5 | 6 | // const trackerCdns = [ 7 | // ["https://fastly.jsdelivr.net/gh", r".*github.com(/.*)/raw/master(/.*)"], 8 | // [ 9 | // "https://ghproxy.com/https://raw.githubusercontent.com", 10 | // r".*github.com(/.*)/raw(/.*)" 11 | // ], 12 | // [ 13 | // "https://mirror.ghproxy.com/https://raw.githubusercontent.com", 14 | // r".*github.com(/.*)/raw(/.*)" 15 | // ], 16 | // ]; 17 | 18 | // final trackerSubscribeUrlCdns = 19 | // trackerSubscribeUrls.asMap().map((_, url) => MapEntry( 20 | // url, 21 | // [ 22 | // url, 23 | // ...trackerCdns.map((cdn) => 24 | // "${cdn[0]}${RegExp(cdn[1]).firstMatch(url)!.group(1)!}") 25 | // ], 26 | // )); 27 | // refreshTrackers() { 28 | // final btConfig = downloaderConfig.value.protocolConfig.bt; 29 | // final btExtConfig = downloaderConfig.value.extra.bt; 30 | // btConfig.trackers.clear(); 31 | // btConfig.trackers.addAll(btExtConfig.subscribeTrackers); 32 | // btConfig.trackers.addAll(btExtConfig.customTrackers); 33 | // // remove duplicate 34 | // btConfig.trackers.toSet().toList(); 35 | // } 36 | 37 | // Future _initTrackerUpdate() async { 38 | // final btExtConfig = downloaderConfig.value.extra.bt; 39 | // final lastUpdateTime = btExtConfig.lastTrackerUpdateTime; 40 | // // if last update time is null or more than 1 day, update trackers 41 | // if (btExtConfig.autoUpdateTrackers && 42 | // (lastUpdateTime == null || 43 | // lastUpdateTime.difference(DateTime.now()).inDays < 0)) { 44 | // try { 45 | // await trackerUpdate(); 46 | // } catch (e) { 47 | // logger.w("tracker update fail", error: e); 48 | // } 49 | // } 50 | // } 51 | 52 | // Future trackerUpdate() async { 53 | // final btExtConfig = downloaderConfig.value.extra.bt; 54 | // final result = []; 55 | // for (var u in btExtConfig.trackerSubscribeUrls) { 56 | // final cdns = trackerSubscribeUrlCdns[u]; 57 | // if (cdns == null) { 58 | // continue; 59 | // } 60 | // try { 61 | // final trackers = 62 | // await Util.anyOk(cdns.map((cdn) => _fetchTrackers(cdn))); 63 | // result.addAll(trackers); 64 | // } catch (e) { 65 | // logger.w("subscribe trackers fail, url: $u", error: e); 66 | // return; 67 | // } 68 | // } 69 | // btExtConfig.subscribeTrackers.clear(); 70 | // btExtConfig.subscribeTrackers.addAll(result); 71 | // downloaderConfig.update((val) { 72 | // val!.extra.bt.lastTrackerUpdateTime = DateTime.now(); 73 | // }); 74 | // refreshTrackers(); 75 | 76 | // await saveConfig(); 77 | // } 78 | 79 | 80 | 81 | // Future> _fetchTrackers(String subscribeUrl) async { 82 | // final resp = await proxyRequest(subscribeUrl); 83 | // if (resp.statusCode != 200) { 84 | // throw Exception( 85 | // 'Failed to get trackers, status code: ${resp.statusCode}'); 86 | // } 87 | // if (resp.data == null || resp.data!.isEmpty) { 88 | // throw Exception('Failed to get trackers, data is null'); 89 | // } 90 | // const ls = LineSplitter(); 91 | // return ls.convert(resp.data!).where((e) => e.isNotEmpty).toList(); 92 | // } 93 | 94 | // _initTrackerUpdate().onError((error, stackTrace) => logger 95 | // .w("initTrackerUpdate error", error: error, stackTrace: stackTrace)); 96 | -------------------------------------------------------------------------------- /lib/app/core/database/database.dart: -------------------------------------------------------------------------------- 1 | // Dart imports: 2 | import 'dart:convert'; 3 | 4 | // Package imports: 5 | import 'package:hive_flutter/hive_flutter.dart'; 6 | 7 | // Project imports: 8 | import 'entity.dart'; 9 | 10 | const String _startConfig = 'startConfig'; 11 | const String _lastRunningConfig = 'lastRunningConfig'; 12 | const String _windowState = 'windowState'; 13 | const String _bookmark = 'bookmark'; 14 | const String _createHistory = 'createHistory'; 15 | 16 | class Database { 17 | static final Database _instance = Database._internal(); 18 | 19 | static Database get instance => _instance; 20 | 21 | factory Database() { 22 | return _instance; 23 | } 24 | 25 | late Box box; 26 | 27 | Database._internal(); 28 | 29 | Future init() async { 30 | await Hive.initFlutter(); 31 | box = await Hive.openBox('database'); 32 | } 33 | 34 | void save(String key, T entity) { 35 | box.put(key, jsonEncode(entity)); 36 | } 37 | 38 | T? get(String key, T Function(dynamic json) fromJsonT) { 39 | final json = box.get(key); 40 | if (json == null) { 41 | return null; 42 | } 43 | return fromJsonT(jsonDecode(json)); 44 | } 45 | 46 | void clear(String key) { 47 | box.delete(key); 48 | } 49 | 50 | void saveStartConfig(StartConfigEntity entity) { 51 | save(_startConfig, entity); 52 | } 53 | 54 | StartConfigEntity? getStartConfig() { 55 | return get( 56 | _startConfig, (json) => StartConfigEntity.fromJson(json)); 57 | } 58 | 59 | /// Patch non-null fields with the original value 60 | void saveWindowState(WindowStateEntity entity) { 61 | final state = getWindowState(); 62 | entity.isMaximized ??= state?.isMaximized; 63 | entity.width ??= state?.width; 64 | entity.height ??= state?.height; 65 | save(_windowState, entity); 66 | } 67 | 68 | WindowStateEntity? getWindowState() { 69 | return get( 70 | _windowState, (json) => WindowStateEntity.fromJson(json)); 71 | } 72 | 73 | /// Use map to ensure that the same directory only saves the latest bookmark 74 | void saveBookmark(MapEntry entry) { 75 | final map = getBookmark() ?? {}; 76 | map[entry.key] = entry.value; 77 | save>(_bookmark, map); 78 | } 79 | 80 | Map? getBookmark() { 81 | return get>(_bookmark, (json) { 82 | return (json as Map) 83 | .map((key, value) => MapEntry(key, value.toString())); 84 | }); 85 | } 86 | 87 | void saveCreateHistory(String url) { 88 | var list = getCreateHistory() ?? []; 89 | list.remove(url); 90 | list.insert(0, url); 91 | if (list.length > 64) { 92 | list.removeLast(); 93 | } 94 | save>(_createHistory, list); 95 | } 96 | 97 | List? getCreateHistory() { 98 | return get>(_createHistory, (json) { 99 | return (json as List).map((e) => e.toString()).toList(); 100 | }); 101 | } 102 | 103 | void clearCreateHistory() { 104 | clear(_createHistory); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /lib/app/core/database/entity.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:json_annotation/json_annotation.dart'; 3 | 4 | part 'entity.g.dart'; 5 | 6 | @JsonSerializable() 7 | class StartConfigEntity { 8 | String network; 9 | String address; 10 | String apiToken; 11 | 12 | StartConfigEntity({ 13 | required this.network, 14 | required this.address, 15 | required this.apiToken, 16 | }); 17 | 18 | factory StartConfigEntity.fromJson(Map json) => 19 | _$StartConfigEntityFromJson(json); 20 | Map toJson() => _$StartConfigEntityToJson(this); 21 | } 22 | 23 | @JsonSerializable() 24 | class WindowStateEntity { 25 | bool? isMaximized; 26 | double? width; 27 | double? height; 28 | 29 | WindowStateEntity({ 30 | this.isMaximized, 31 | this.width, 32 | this.height, 33 | }); 34 | 35 | factory WindowStateEntity.fromJson(Map json) => 36 | _$WindowStateEntityFromJson(json); 37 | Map toJson() => _$WindowStateEntityToJson(this); 38 | } 39 | -------------------------------------------------------------------------------- /lib/app/core/database/entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | StartConfigEntity _$StartConfigEntityFromJson(Map json) => StartConfigEntity( 10 | network: json['network'] as String, 11 | address: json['address'] as String, 12 | apiToken: json['apiToken'] as String, 13 | ); 14 | 15 | Map _$StartConfigEntityToJson(StartConfigEntity instance) => 16 | { 17 | 'network': instance.network, 18 | 'address': instance.address, 19 | 'apiToken': instance.apiToken, 20 | }; 21 | 22 | WindowStateEntity _$WindowStateEntityFromJson(Map json) => WindowStateEntity( 23 | isMaximized: json['isMaximized'] as bool?, 24 | width: (json['width'] as num?)?.toDouble(), 25 | height: (json['height'] as num?)?.toDouble(), 26 | ); 27 | 28 | Map _$WindowStateEntityToJson(WindowStateEntity instance) => 29 | { 30 | 'isMaximized': instance.isMaximized, 31 | 'width': instance.width, 32 | 'height': instance.height, 33 | }; 34 | -------------------------------------------------------------------------------- /lib/app/core/local_storage/app_storage.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:hive_flutter/hive_flutter.dart'; 3 | import 'package:hooks_riverpod/hooks_riverpod.dart'; 4 | 5 | class AppStorage { 6 | // ignore: unused_field 7 | Box? _box; 8 | 9 | /// for initialling app local storage 10 | Future initAppStorage() async { 11 | await Hive.initFlutter(); 12 | // TODO: add your storage name here 13 | _box = await Hive.openBox('hello world'); 14 | } 15 | 16 | // example of storing & getting value 17 | 18 | /// for storing uploaded string value 19 | // final String _helloWorld = 'helloWorld'; 20 | 21 | // /// for getting string from box 22 | // String? getHelloWorld() { 23 | // return _box?.get(_helloWorld) as String?; 24 | // } 25 | 26 | // /// for storing helloWorld to app 27 | // Future putHelloWorld(String helloWorld) async { 28 | // await _box?.put(_helloWorld, helloWorld); 29 | // } 30 | 31 | /// for clearing all data in box 32 | Future clearAllData() async { 33 | await _box?.clear(); 34 | } 35 | } 36 | 37 | final appStorageProvider = Provider( 38 | (_) { 39 | throw UnimplementedError(); 40 | }, 41 | ); 42 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/config.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'config.freezed.dart'; 5 | part 'config.g.dart'; 6 | 7 | @freezed 8 | class DownloaderConfig with _$DownloaderConfig { 9 | @Assert('maxRunning >= 0', 'maxRunning must be non-negative') 10 | const factory DownloaderConfig({ 11 | @Default('') String downloadDir, 12 | @Default(0) int maxRunning, 13 | @Default(ProtocolConfig()) ProtocolConfig protocolConfig, 14 | @Default(ExtraConfig()) ExtraConfig extra, 15 | @Default(ProxyConfig()) ProxyConfig proxy, 16 | }) = _DownloaderConfig; 17 | 18 | factory DownloaderConfig.fromJson(Map json) => 19 | _$DownloaderConfigFromJson(json); 20 | } 21 | 22 | @freezed 23 | class ProtocolConfig with _$ProtocolConfig { 24 | const factory ProtocolConfig({ 25 | @Default(HttpConfig()) HttpConfig http, 26 | @Default(BtConfig()) BtConfig bt, 27 | }) = _ProtocolConfig; 28 | 29 | factory ProtocolConfig.fromJson(Map json) => 30 | _$ProtocolConfigFromJson(json); 31 | } 32 | 33 | @freezed 34 | class HttpConfig with _$HttpConfig { 35 | const factory HttpConfig({ 36 | @Default('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' 37 | '(KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36') 38 | String userAgent, 39 | @Default(16) int connections, 40 | @Default(false) bool useServerCtime, 41 | }) = _HttpConfig; 42 | 43 | factory HttpConfig.fromJson(Map json) => 44 | _$HttpConfigFromJson(json); 45 | } 46 | 47 | @freezed 48 | class BtConfig with _$BtConfig { 49 | const factory BtConfig({ 50 | @Default(0) int listenPort, 51 | @Default([]) List trackers, 52 | }) = _BtConfig; 53 | 54 | factory BtConfig.fromJson(Map json) => 55 | _$BtConfigFromJson(json); 56 | } 57 | 58 | @freezed 59 | class ExtraConfig with _$ExtraConfig { 60 | const factory ExtraConfig({ 61 | @Default('') String themeMode, 62 | @Default('') String locale, 63 | @Default(false) bool lastDeleteTaskKeep, 64 | @Default(ExtraConfigBt()) ExtraConfigBt bt, 65 | }) = _ExtraConfig; 66 | 67 | factory ExtraConfig.fromJson(Map json) => 68 | _$ExtraConfigFromJson(json); 69 | } 70 | 71 | @freezed 72 | class ProxyConfig with _$ProxyConfig { 73 | const factory ProxyConfig({ 74 | @Default(false) bool enable, 75 | @Default(false) bool system, 76 | @Default('') String scheme, 77 | @Default('') String host, 78 | @Default('') String usr, 79 | @Default('') String pwd, 80 | }) = _ProxyConfig; 81 | 82 | factory ProxyConfig.fromJson(Map json) => 83 | _$ProxyConfigFromJson(json); 84 | } 85 | 86 | @freezed 87 | class ExtraConfigBt with _$ExtraConfigBt { 88 | const ExtraConfigBt._(); 89 | 90 | const factory ExtraConfigBt({ 91 | @Default([]) List trackerSubscribeUrls, 92 | @Default([]) List subscribeTrackers, 93 | @Default(true) bool autoUpdateTrackers, 94 | @JsonKey(name: 'last_tracker_update_time') String? lastTrackerUpdateTime, 95 | @Default([]) List customTrackers, 96 | }) = _ExtraConfigBt; 97 | 98 | factory ExtraConfigBt.fromJson(Map json) => 99 | _$ExtraConfigBtFromJson(json); 100 | 101 | DateTime? get lastTrackerUpdateDateTime => lastTrackerUpdateTime != null 102 | ? DateTime.parse(lastTrackerUpdateTime!) 103 | : null; 104 | } 105 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/enums.dart: -------------------------------------------------------------------------------- 1 | import 'package:json_annotation/json_annotation.dart'; 2 | 3 | enum Status { 4 | @JsonValue("ready") ready, 5 | @JsonValue("running") running, 6 | @JsonValue("pause") pause, 7 | @JsonValue("wait") wait, 8 | @JsonValue("error") error, 9 | @JsonValue("done") done, 10 | } 11 | 12 | enum Protocol { 13 | @JsonValue("") none, 14 | @JsonValue("http") http, 15 | @JsonValue("bt") bt, 16 | } 17 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/meta.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | // Project imports: 5 | import 'options.dart'; 6 | import 'request.dart'; 7 | import 'resource.dart'; 8 | 9 | part 'meta.freezed.dart'; 10 | part 'meta.g.dart'; 11 | 12 | @freezed 13 | class Meta with _$Meta { 14 | const factory Meta({ 15 | required Request req, 16 | Resource? res, 17 | required Options opts, 18 | }) = _Meta; 19 | 20 | factory Meta.fromJson(Map json) => _$MetaFromJson(json); 21 | } 22 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/models.dart: -------------------------------------------------------------------------------- 1 | export 'enums.dart'; 2 | export 'meta.dart'; 3 | export 'options.dart'; 4 | export 'progress.dart'; 5 | export 'request.dart'; 6 | export 'resource.dart'; 7 | export 'config.dart'; 8 | export 'result.dart'; 9 | export 'task.dart'; 10 | export 'server_info.dart'; 11 | export 'resolve_result.dart'; 12 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/options.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'options.freezed.dart'; 5 | part 'options.g.dart'; 6 | 7 | @freezed 8 | class Options with _$Options { 9 | const factory Options({ 10 | required String name, 11 | required String path, 12 | @Default([]) List selectFiles, 13 | Object? extra, 14 | }) = _Options; 15 | 16 | factory Options.fromJson(Map json) => 17 | _$OptionsFromJson(json); 18 | } 19 | 20 | @freezed 21 | class OptsExtraHttp with _$OptsExtraHttp { 22 | const factory OptsExtraHttp({ 23 | @Default(0) int connections, 24 | @Default(false) bool autoTorrent, 25 | }) = _OptsExtraHttp; 26 | 27 | factory OptsExtraHttp.fromJson(Map json) => 28 | _$OptsExtraHttpFromJson(json); 29 | } 30 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/progress.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'progress.freezed.dart'; 5 | part 'progress.g.dart'; 6 | 7 | @freezed 8 | class Progress with _$Progress { 9 | const factory Progress({ 10 | required int used, 11 | required int speed, 12 | required int downloaded, 13 | @Default(0) int uploadSpeed, 14 | @Default(0) int uploaded, 15 | }) = _Progress; 16 | 17 | factory Progress.fromJson(Map json) => 18 | _$ProgressFromJson(json); 19 | } 20 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/request.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'request.freezed.dart'; 5 | part 'request.g.dart'; 6 | 7 | @freezed 8 | class Request with _$Request { 9 | const factory Request({ 10 | required String url, 11 | Map? extra, 12 | Map? labels, 13 | }) = _Request; 14 | 15 | factory Request.fromJson(Map json) => 16 | _$RequestFromJson(json); 17 | } 18 | 19 | @freezed 20 | class ReqExtraHttp with _$ReqExtraHttp { 21 | const factory ReqExtraHttp({ 22 | @Default('GET') String method, 23 | @Default({}) Map header, 24 | @Default('') String body, 25 | }) = _ReqExtraHttp; 26 | 27 | factory ReqExtraHttp.fromJson(Map json) => 28 | _$ReqExtraHttpFromJson(json); 29 | } 30 | 31 | @freezed 32 | class ReqExtraBt with _$ReqExtraBt { 33 | const factory ReqExtraBt({ 34 | @Default([]) List trackers, 35 | }) = _ReqExtraBt; 36 | 37 | factory ReqExtraBt.fromJson(Map json) => 38 | _$ReqExtraBtFromJson(json); 39 | } 40 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/resolve_result.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | // Project imports: 5 | import 'resource.dart'; 6 | 7 | part 'resolve_result.freezed.dart'; 8 | part 'resolve_result.g.dart'; 9 | 10 | @freezed 11 | class ResolveResult with _$ResolveResult { 12 | const factory ResolveResult({ 13 | @Default("") String id, 14 | required Resource res, 15 | }) = _ResolveResult; 16 | 17 | factory ResolveResult.fromJson(Map json) => 18 | _$ResolveResultFromJson(json); 19 | } 20 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/resource.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | // Project imports: 5 | import 'request.dart'; 6 | 7 | part 'resource.freezed.dart'; 8 | part 'resource.g.dart'; 9 | 10 | @freezed 11 | class Resource with _$Resource { 12 | const factory Resource({ 13 | @Default("") String name, 14 | @Default(0) int size, 15 | @Default(false) bool range, 16 | required List files, 17 | @Default("") String hash, 18 | }) = _Resource; 19 | 20 | factory Resource.fromJson(Map json) => 21 | _$ResourceFromJson(json); 22 | } 23 | 24 | @freezed 25 | class FileInfo with _$FileInfo { 26 | const factory FileInfo({ 27 | @Default("") String path, 28 | required String name, 29 | @Default(0) int size, 30 | String? ctime, 31 | Request? req, 32 | }) = _FileInfo; 33 | 34 | factory FileInfo.fromJson(Map json) => 35 | _$FileInfoFromJson(json); 36 | } 37 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/result.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | import 'package:hapee/app/core/models/gopeed_models/common/task.dart'; 4 | 5 | part 'result.freezed.dart'; 6 | part 'result.g.dart'; 7 | 8 | /// API 响应结果 9 | @Freezed(genericArgumentFactories: true) 10 | class Result with _$Result { 11 | const factory Result({ 12 | required int code, // 响应码,0表示成功,其他值表示错误 13 | @Default('') String msg, // 错误消息,当code!=0时有值 14 | T? data, // 成功数据,当code==0时有值 15 | }) = _Result; 16 | 17 | factory Result.fromJson( 18 | Map json, 19 | T Function(Object?) fromJsonT, 20 | ) => 21 | _$ResultFromJson(json, fromJsonT); 22 | } 23 | 24 | /// 扩展方法 25 | extension ResultExtension on Result { 26 | /// 是否成功 27 | bool get isSuccess => code == 0; 28 | 29 | /// 处理结果 30 | T when({ 31 | required T Function(dynamic data) onData, 32 | required T Function(String message, StackTrace stackTrace) onError, 33 | }) { 34 | if (isSuccess && data != null) { 35 | return onData(data); 36 | } 37 | return onError(msg, StackTrace.current); 38 | } 39 | 40 | /// 获取任务列表数据 41 | List getTaskList() { 42 | if (data == null) return []; 43 | final list = data as List; 44 | return list.map((e) { 45 | // print('Task JSON: $e'); // 打印每个任务的原始数据 46 | try { 47 | return Task.fromJson(e as Map); 48 | } catch (error, stack) { 49 | print('Error parsing task: $error'); 50 | print('Stack: $stack'); 51 | print('Problematic JSON: $e'); 52 | rethrow; 53 | } 54 | }).toList(); 55 | } 56 | 57 | /// 获取字符串数据 58 | String getString() { 59 | if (!isSuccess) throw Exception(msg); 60 | if (data == null) throw Exception('Data is null'); 61 | return data as String; 62 | } 63 | 64 | /// 获取字符串列表数据 65 | List getStringList() { 66 | if (!isSuccess) throw Exception(msg); 67 | if (data == null) throw Exception('Data is null'); 68 | return (data as List).cast(); 69 | } 70 | 71 | /// 获取任务统计数据 72 | TaskBtStats getTaskStats() { 73 | if (!isSuccess) throw Exception(msg); 74 | if (data == null) throw Exception('Data is null'); 75 | return TaskBtStats.fromJson(data as Map); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/result_extension.dart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/lib/app/core/models/gopeed_models/common/result_extension.dart -------------------------------------------------------------------------------- /lib/app/core/models/gopeed_models/common/server_info.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'server_info.freezed.dart'; 5 | part 'server_info.g.dart'; 6 | 7 | @freezed 8 | class ServerInfo with _$ServerInfo { 9 | const factory ServerInfo({ 10 | required String version, 11 | required String os, 12 | required String arch, 13 | required String goVersion, 14 | required String gitHash, 15 | required String buildTime, 16 | }) = _ServerInfo; 17 | 18 | factory ServerInfo.fromJson(Map json) => 19 | _$ServerInfoFromJson(json); 20 | } 21 | -------------------------------------------------------------------------------- /lib/app/core/router/router.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:go_router/go_router.dart'; 3 | import 'package:hooks_riverpod/hooks_riverpod.dart'; 4 | 5 | // Project imports: 6 | import '../../features/main/view/main_view.dart'; 7 | import '../../features/sync/view/sync_view.dart'; 8 | import '../../features/create/view/create_view.dart'; 9 | 10 | /// 11 | /// for getting routers that are present in the app 12 | /// 13 | final routerProvider = Provider( 14 | (ref) { 15 | return GoRouter( 16 | initialLocation: '/sync', 17 | routes: [ 18 | ShellRoute( 19 | builder: (context, state, child) => MainView(child: child), 20 | routes: [ 21 | GoRoute( 22 | path: '/sync', 23 | name: 'sync', 24 | builder: (context, state) => const SyncView(), 25 | ), 26 | GoRoute( 27 | path: '/create', 28 | name: 'create', 29 | builder: (context, state) => const CreateView(), 30 | ), 31 | // TODO: Add other main routes (settings, lab) here 32 | ], 33 | ), 34 | ], 35 | ); 36 | }, 37 | ); 38 | -------------------------------------------------------------------------------- /lib/app/core/style/app_style.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.dart'; 3 | 4 | class AppStyle { 5 | // Breakpoints for AdaptiveScaffold 6 | static const mobileBreakpoint = Breakpoint(endWidth: mobileWidth); 7 | static const tabletBreakpoint = 8 | Breakpoint(beginWidth: mobileWidth, endWidth: tabletWidth); 9 | static const desktopBreakpoint = 10 | Breakpoint(beginWidth: tabletWidth, endWidth: desktopWidth); 11 | static const largeDesktopBreakpoint = 12 | Breakpoint(beginWidth: desktopWidth, endWidth: largeDesktopWidth); 13 | static const ultraWideBreakpoint = Breakpoint(beginWidth: largeDesktopWidth); 14 | 15 | // Responsive layout widths 16 | static const double mobileWidth = 600; // Mobile breakpoint 17 | static const double tabletWidth = 800; // Tablet breakpoint 18 | static const double desktopWidth = 1000; // Desktop breakpoint 19 | static const double largeDesktopWidth = 1200; // Large desktop breakpoint 20 | 21 | // Base spacing units 22 | static const double xs = 4.0; // Extra small spacing 23 | static const double sm = 8.0; // Small spacing 24 | static const double md = 16.0; // Medium spacing 25 | static const double lg = 24.0; // Large spacing 26 | static const double xl = 32.0; // Extra large spacing 27 | 28 | // Padding presets 29 | static const defaultPadding = EdgeInsets.all(sm); 30 | static const horizontalPadding = EdgeInsets.symmetric(horizontal: md); 31 | static const contentPadding = EdgeInsets.symmetric( 32 | horizontal: md, 33 | vertical: md * 0.75, 34 | ); 35 | 36 | // Border radius presets 37 | static const double smRadius = 4.0; // Small radius 38 | static const double mdRadius = 8.0; // Medium radius 39 | static const double lgRadius = 12.0; // Large radius 40 | static const double xlRadius = 16.0; // Extra large radius 41 | 42 | // Font size presets 43 | static const double fontSizeSmall = 12.0; // Small text 44 | static const double fontSizeMedium = 14.0; // Medium text 45 | static const double fontSizeLarge = 16.0; // Large text 46 | static const double fontSizeTitle = 20.0; // Title text 47 | 48 | // Icon size presets 49 | static const double iconSizeSmall = 16.0; // Small icons 50 | static const double iconSizeMedium = 20.0; // Medium icons 51 | static const double iconSizeLarge = 24.0; // Large icons 52 | 53 | // Grid presets 54 | static const double gridMaxCrossAxisExtent = 300.0; // Max grid item width 55 | static const double gridMainAxisSpacing = sm; // Vertical grid spacing 56 | static const double gridCrossAxisSpacing = sm; // Horizontal grid spacing 57 | static const double gridChildAspectRatio = 1.5; // Grid item aspect ratio 58 | 59 | // Progress indicator presets 60 | static const double progressIndicatorHeight = 4.0; // Progress bar height 61 | 62 | // DataGrid presets 63 | static const double dataGridLineWidth = 0.5; // Grid line width 64 | static const double dataGridOpacity = 0.3; // Grid opacity 65 | static const double dataGridOpacityLight = 0.5; // Light grid opacity 66 | 67 | // Card presets 68 | static const double cardElevation = 1.0; // Card shadow elevation 69 | 70 | // Layout presets 71 | static const double sizedBoxHeight = 8.0; // Spacer height 72 | 73 | // Text style presets 74 | static const TextStyle title = TextStyle( 75 | fontSize: fontSizeTitle, 76 | fontWeight: FontWeight.bold, 77 | height: 1.2, 78 | ); 79 | 80 | static const TextStyle subtitle = TextStyle( 81 | fontSize: fontSizeLarge, 82 | fontWeight: FontWeight.w500, 83 | height: 1.2, 84 | ); 85 | 86 | static const TextStyle body = TextStyle( 87 | fontSize: fontSizeMedium, 88 | height: 1.5, 89 | ); 90 | } 91 | -------------------------------------------------------------------------------- /lib/app/core/theme/app_theme.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:hapee/app/core/style/app_style.dart'; 3 | 4 | class AppTheme { 5 | static ThemeData get lightTheme { 6 | return ThemeData( 7 | useMaterial3: true, 8 | colorScheme: ColorScheme.fromSeed( 9 | seedColor: const Color(0xFF6750A4), 10 | brightness: Brightness.light, 11 | ), 12 | // 文字样式 13 | textTheme: TextTheme( 14 | displayLarge: TextStyle( 15 | fontSize: AppStyle.fontSizeTitle, fontWeight: FontWeight.bold), 16 | bodyLarge: TextStyle(fontSize: AppStyle.fontSizeLarge), 17 | bodyMedium: TextStyle(fontSize: AppStyle.fontSizeMedium), 18 | labelLarge: TextStyle( 19 | fontSize: AppStyle.fontSizeLarge, fontWeight: FontWeight.w500), 20 | ), 21 | // 卡片样式 22 | cardTheme: CardTheme( 23 | elevation: AppStyle.cardElevation, 24 | margin: AppStyle.defaultPadding, 25 | shape: RoundedRectangleBorder( 26 | borderRadius: BorderRadius.circular(AppStyle.smRadius), 27 | ), 28 | ), 29 | // 按钮样式 30 | elevatedButtonTheme: ElevatedButtonThemeData( 31 | style: ElevatedButton.styleFrom( 32 | padding: AppStyle.contentPadding, 33 | shape: RoundedRectangleBorder( 34 | borderRadius: BorderRadius.circular(AppStyle.smRadius), 35 | ), 36 | ), 37 | ), 38 | // 输入框样式 39 | inputDecorationTheme: InputDecorationTheme( 40 | border: OutlineInputBorder( 41 | borderRadius: BorderRadius.circular(AppStyle.smRadius), 42 | ), 43 | contentPadding: AppStyle.contentPadding, 44 | ), 45 | // 图标主题 46 | iconTheme: IconThemeData( 47 | size: AppStyle.iconSizeMedium, 48 | ), 49 | // 进度指示器主题 50 | progressIndicatorTheme: const ProgressIndicatorThemeData( 51 | linearMinHeight: AppStyle.progressIndicatorHeight, 52 | ), 53 | ); 54 | } 55 | 56 | static ThemeData get darkTheme { 57 | return lightTheme.copyWith( 58 | colorScheme: ColorScheme.fromSeed( 59 | seedColor: const Color(0xFF6750A4), 60 | brightness: Brightness.dark, 61 | ), 62 | ); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /lib/app/core/utils/file_icon_helper.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:material_file_icon/material_file_icon.dart'; 3 | 4 | class FileIconHelper { 5 | static final Map _cache = {}; 6 | 7 | static Widget getIcon(String fileName, {double size = 18}) { 8 | final extension = 9 | fileName.contains('.') ? fileName.split('.').last.toLowerCase() : ''; 10 | 11 | return _cache.putIfAbsent(extension, () { 12 | return MFIcon( 13 | extension.isEmpty ? fileName : 'file.$extension', 14 | size: size, 15 | ); 16 | }); 17 | } 18 | 19 | static void clearCache() { 20 | _cache.clear(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /lib/app/core/utils/file_icons.dart: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /lib/app/core/utils/file_utils.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:open_filex/open_filex.dart'; 3 | 4 | class FileUtils { 5 | /// Opens a file and shows error message if failed 6 | static Future openFile(String path, BuildContext context) async { 7 | final result = await OpenFilex.open(path); 8 | if (result.type != ResultType.done && context.mounted) { 9 | ScaffoldMessenger.of(context).showSnackBar( 10 | SnackBar( 11 | content: Text('Failed to open file: ${result.message}'), 12 | ), 13 | ); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /lib/app/core/utils/util.dart: -------------------------------------------------------------------------------- 1 | // Dart imports: 2 | import 'dart:async'; 3 | import 'dart:convert'; 4 | import 'dart:io'; 5 | import 'dart:math'; 6 | 7 | // Flutter imports: 8 | import 'package:flutter/foundation.dart'; 9 | 10 | // Package imports: 11 | import 'package:path_provider/path_provider.dart'; 12 | import '../models/gopeed_models/common/models.dart'; 13 | 14 | class Util { 15 | static final Future storageDir = _initStorageDir(); 16 | 17 | static Future _initStorageDir() async { 18 | return (await getApplicationSupportDirectory()).path; 19 | } 20 | 21 | static String cleanPath(String path) { 22 | if (Platform.isWindows) { 23 | path = path.replaceAll(RegExp(r'\\(?=[\\/])'), "/"); 24 | } 25 | 26 | if (path.startsWith(".")) { 27 | path = path.substring(1); 28 | } 29 | if (path.startsWith("/")) { 30 | path = path.substring(1); 31 | } 32 | return path; 33 | } 34 | 35 | static String safeDir(String path) { 36 | if (path == "." || path == "./" || path == ".\\") { 37 | return ""; 38 | } 39 | return path; 40 | } 41 | 42 | static String safePathJoin(List paths) { 43 | return paths 44 | .where((e) => e.isNotEmpty) 45 | .map((e) => safeDir(e)) 46 | .join("/") 47 | .replaceAll(RegExp(r'//'), "/"); 48 | } 49 | 50 | static String formatBytes(int bytes) { 51 | if (bytes <= 0) return '0 B'; 52 | const suffixes = ['B', 'KB', 'MB', 'GB', 'TB']; 53 | var i = (log(bytes) / log(1024)).floor(); 54 | i = i.clamp(0, suffixes.length - 1); 55 | return '${(bytes / pow(1024, i)).toStringAsFixed(1)} ${suffixes[i]}'; 56 | } 57 | 58 | static int parseToBytes(String formattedSize) { 59 | final regex = RegExp(r'(\d+\.?\d*)\s*([KMGTPEZY]?B)', caseSensitive: false); 60 | final match = regex.firstMatch(formattedSize); 61 | 62 | if (match == null) return 0; 63 | 64 | final size = double.parse(match.group(1)!); 65 | final unit = match.group(2)!.toUpperCase(); 66 | 67 | const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; 68 | final power = units.indexOf(unit); 69 | 70 | return (size * pow(1024, power)).round(); 71 | } 72 | 73 | static String getStatusText(Status status) { 74 | switch (status) { 75 | case Status.ready: 76 | return '就绪'; 77 | case Status.running: 78 | return '下载中'; 79 | case Status.pause: 80 | return '已暂停'; 81 | case Status.wait: 82 | return '等待中'; 83 | case Status.error: 84 | return '错误'; 85 | case Status.done: 86 | return '已完成'; 87 | } 88 | } 89 | 90 | static bool get isAndroid => !kIsWeb && Platform.isAndroid; 91 | static bool get isIOS => !kIsWeb && Platform.isIOS; 92 | static bool get isMobile => !kIsWeb && (Platform.isAndroid || Platform.isIOS); 93 | static bool get isDesktop => 94 | !kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS); 95 | static bool get isWindows => !kIsWeb && Platform.isWindows; 96 | static bool get isMacOS => !kIsWeb && Platform.isMacOS; 97 | static bool get isLinux => !kIsWeb && Platform.isLinux; 98 | static bool get isWeb => kIsWeb; 99 | 100 | static bool get supportUnixSocket => 101 | !kIsWeb && 102 | (Platform.isLinux || 103 | Platform.isMacOS || 104 | Platform.isAndroid || 105 | Platform.isIOS); 106 | 107 | static List textToLines(String text) { 108 | if (text.isEmpty) { 109 | return []; 110 | } 111 | const ls = LineSplitter(); 112 | return ls.convert(text).where((line) => line.isNotEmpty).toList(); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /lib/app/core/widgets/adaptive_icon.dart: -------------------------------------------------------------------------------- 1 | // Dart imports: 2 | import 'dart:io' show Platform; 3 | 4 | // Flutter imports: 5 | import 'package:flutter/cupertino.dart'; 6 | import 'package:flutter/material.dart'; 7 | 8 | class AdaptiveIcon extends StatelessWidget { 9 | final IconData materialIcon; 10 | final IconData cupertinoIcon; 11 | final double? size; 12 | final Color? color; 13 | 14 | const AdaptiveIcon({ 15 | super.key, 16 | required this.materialIcon, 17 | required this.cupertinoIcon, 18 | this.size, 19 | this.color, 20 | }); 21 | 22 | @override 23 | Widget build(BuildContext context) { 24 | // iOS 使用 Cupertino 风格 25 | if (Platform.isIOS || Platform.isMacOS) { 26 | return Icon( 27 | cupertinoIcon, 28 | size: size, 29 | color: color, 30 | ); 31 | } 32 | 33 | // 其他平台使用 Material 风格 34 | return Icon( 35 | materialIcon, 36 | size: size, 37 | color: color, 38 | ); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /lib/app/core/widgets/error_view.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | class ErrorView extends StatelessWidget { 4 | const ErrorView({ 5 | super.key, 6 | required this.error, 7 | required this.stackTrace, 8 | this.onRetry, 9 | }); 10 | 11 | final Object error; 12 | final StackTrace stackTrace; 13 | final VoidCallback? onRetry; 14 | 15 | @override 16 | Widget build(BuildContext context) { 17 | return Center( 18 | child: Padding( 19 | padding: const EdgeInsets.all(16.0), 20 | child: Column( 21 | mainAxisAlignment: MainAxisAlignment.center, 22 | children: [ 23 | SelectableText.rich( 24 | TextSpan( 25 | children: [ 26 | const TextSpan( 27 | text: '错误信息:\n', 28 | style: TextStyle(fontWeight: FontWeight.bold), 29 | ), 30 | TextSpan(text: '$error\n\n'), 31 | const TextSpan( 32 | text: '堆栈跟踪:\n', 33 | style: TextStyle(fontWeight: FontWeight.bold), 34 | ), 35 | TextSpan(text: '$stackTrace'), 36 | ], 37 | ), 38 | ), 39 | if (onRetry != null) ...[ 40 | const SizedBox(height: 16), 41 | ElevatedButton.icon( 42 | onPressed: onRetry, 43 | icon: const Icon(Icons.refresh), 44 | label: const Text('重试'), 45 | ), 46 | ], 47 | ], 48 | ), 49 | ), 50 | ); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /lib/app/features/main/providers/main_providers.dart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/lib/app/features/main/providers/main_providers.dart -------------------------------------------------------------------------------- /lib/app/features/main/repository/main_repository.dart: -------------------------------------------------------------------------------- 1 | // // Project imports: 2 | // import '../../../../baas/firebase_collection_example/firebase_collection.dart'; 3 | 4 | // abstract class MainRepository { 5 | // MainRepository(this.firebaseCollection); 6 | 7 | // final FirebaseCollection firebaseCollection; 8 | // } 9 | -------------------------------------------------------------------------------- /lib/app/features/main/repository/main_repository_fake.dart: -------------------------------------------------------------------------------- 1 | // // Project imports: 2 | // import 'main_repository.dart'; 3 | 4 | // class MainRepositoryFake extends MainRepository { 5 | // MainRepositoryFake(super.firebaseCollection); 6 | // // TODO add your methods here 7 | // } 8 | -------------------------------------------------------------------------------- /lib/app/features/main/repository/main_repository_impl.dart: -------------------------------------------------------------------------------- 1 | // // Package imports: 2 | // import 'package:hooks_riverpod/hooks_riverpod.dart'; 3 | 4 | // // Project imports: 5 | // import '../../../../baas/firebase_collection_example/firebase_collection.dart'; 6 | // import 'main_repository.dart'; 7 | 8 | // class MainRepositoryImpl extends MainRepository { 9 | // MainRepositoryImpl(super.firebaseCollection); 10 | // // TODO add your methods here 11 | // } 12 | 13 | // final mainRepositoryProvider = Provider.autoDispose((ref) { 14 | // final firebaseCollection = ref.watch(firebaseCollectionProvider); 15 | // return MainRepositoryImpl(firebaseCollection); 16 | // }); 17 | -------------------------------------------------------------------------------- /lib/app/features/main/view/main_view.dart: -------------------------------------------------------------------------------- 1 | // Flutter imports: 2 | import 'package:flutter/material.dart'; 3 | 4 | // Package imports: 5 | import 'package:flutter_adaptive_scaffold/flutter_adaptive_scaffold.dart'; 6 | import 'package:hapee/l10n/l10n.dart'; 7 | import 'package:hooks_riverpod/hooks_riverpod.dart'; 8 | import 'package:go_router/go_router.dart'; 9 | 10 | // Project imports: 11 | import 'package:hapee/app/core/style/app_style.dart'; 12 | 13 | class MainView extends HookConsumerWidget { 14 | const MainView({ 15 | super.key, 16 | required this.child, 17 | }); 18 | 19 | final Widget child; 20 | 21 | @override 22 | Widget build(BuildContext context, WidgetRef ref) { 23 | final location = GoRouterState.of(context).uri.path; 24 | final selectedIndex = switch (location) { 25 | '/sync' => 0, 26 | '/settings' => 1, 27 | '/lab' => 2, 28 | _ => 0, 29 | }; 30 | 31 | return AdaptiveScaffold( 32 | transitionDuration: const Duration(milliseconds: 0), 33 | internalAnimations: false, 34 | smallBreakpoint: AppStyle.mobileBreakpoint, 35 | mediumBreakpoint: AppStyle.tabletBreakpoint, 36 | mediumLargeBreakpoint: AppStyle.desktopBreakpoint, 37 | largeBreakpoint: AppStyle.largeDesktopBreakpoint, 38 | extraLargeBreakpoint: AppStyle.ultraWideBreakpoint, 39 | useDrawer: false, 40 | selectedIndex: selectedIndex, 41 | onSelectedIndexChange: (index) { 42 | switch (index) { 43 | case 0: 44 | context.go('/sync'); 45 | case 1: 46 | context.go('/settings'); 47 | case 2: 48 | context.go('/lab'); 49 | } 50 | }, 51 | destinations: [ 52 | NavigationDestination( 53 | icon: const Icon(Icons.sync_outlined), 54 | selectedIcon: const Icon(Icons.sync), 55 | label: context.l10n.download, 56 | ), 57 | NavigationDestination( 58 | icon: const Icon(Icons.settings_outlined), 59 | selectedIcon: const Icon(Icons.settings), 60 | label: context.l10n.setting, 61 | ), 62 | NavigationDestination( 63 | icon: const Icon(Icons.science_outlined), 64 | selectedIcon: const Icon(Icons.science), 65 | label: context.l10n.preferences_lab, 66 | ), 67 | ], 68 | body: (context) => Card( 69 | margin: EdgeInsets.zero, 70 | shape: const RoundedRectangleBorder(), 71 | child: child, 72 | ), 73 | ); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /lib/app/features/sync/extension/status_extension.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:hapee/app/core/models/gopeed_models/common/models.dart'; 3 | import 'package:hapee/l10n/l10n.dart'; 4 | 5 | extension StatusTextX on Status { 6 | String getLocalizedText(BuildContext context) { 7 | final l10n = context.l10n; 8 | switch (this) { 9 | case Status.running: 10 | return l10n.downloading; 11 | case Status.done: 12 | return l10n.downloaded; 13 | case Status.pause: 14 | return l10n.paused; 15 | case Status.wait: 16 | return l10n.task_waiting; 17 | case Status.error: 18 | return l10n.error; 19 | default: 20 | return ''; 21 | } 22 | } 23 | 24 | Color getStatusColor(BuildContext context) { 25 | final theme = Theme.of(context); 26 | switch (this) { 27 | case Status.running: 28 | return theme.colorScheme.primary; 29 | case Status.pause: 30 | return theme.colorScheme.secondary; 31 | case Status.error: 32 | return theme.colorScheme.error; 33 | case Status.done: 34 | return theme.colorScheme.tertiary; 35 | case Status.wait: 36 | return theme.colorScheme.primary.withOpacity(0.5); 37 | default: 38 | return theme.disabledColor; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /lib/app/features/sync/provider/sync_providers.dart: -------------------------------------------------------------------------------- 1 | import 'package:hooks_riverpod/hooks_riverpod.dart'; 2 | import 'package:riverpod_annotation/riverpod_annotation.dart'; 3 | import '../../../core/api/gopeed_api/api.dart'; 4 | import '../../../core/models/gopeed_models/common/models.dart'; 5 | 6 | part 'sync_providers.g.dart'; 7 | 8 | /// 视图模式 9 | enum ViewMode { grid, table } 10 | 11 | /// 任务操作类型 12 | enum TaskOperation { delete, pause, continue_ } 13 | 14 | @riverpod 15 | class ViewModeNotifier extends _$ViewModeNotifier { 16 | @override 17 | ViewMode build() => ViewMode.grid; 18 | 19 | void toggle() { 20 | state = state == ViewMode.grid ? ViewMode.table : ViewMode.grid; 21 | } 22 | } 23 | 24 | /// 任务列表状态 25 | @riverpod 26 | Stream> tasks(Ref ref) async* { 27 | while (true) { 28 | final result = await Api.taskApi.getTasks([ 29 | Status.running, 30 | Status.wait, 31 | Status.pause, 32 | Status.done, 33 | Status.error, 34 | ]); 35 | 36 | if (!result.isSuccess) { 37 | yield []; 38 | await Future.delayed(const Duration(seconds: 5)); // 错误后延长重试时间 39 | continue; 40 | } 41 | 42 | yield result.getTaskList(); 43 | await Future.delayed(const Duration(seconds: 1)); 44 | } 45 | } 46 | 47 | /// 搜索查询 48 | @riverpod 49 | class SearchQueryNotifier extends _$SearchQueryNotifier { 50 | @override 51 | String build() => ''; 52 | 53 | void update(String query) { 54 | state = query; 55 | } 56 | } 57 | 58 | /// 过滤后的任务列表 59 | @riverpod 60 | List filteredTasks(Ref ref) { 61 | final tasks = ref.watch(tasksProvider).value ?? []; 62 | final query = ref.watch(searchQueryNotifierProvider).toLowerCase(); 63 | 64 | if (query.isEmpty) { 65 | return tasks; 66 | } 67 | 68 | return tasks.where((task) { 69 | return task.displayName.toLowerCase().contains(query); 70 | }).toList(); 71 | } 72 | 73 | /// 批量操作任务选择状态 74 | @riverpod 75 | class BatchTaskOperationNotifier extends _$BatchTaskOperationNotifier { 76 | @override 77 | Set build() => {}; 78 | 79 | bool get isNotEmpty => state.isNotEmpty; 80 | 81 | bool contains(String taskId) => state.contains(taskId); 82 | 83 | void toggleTask(String taskId) { 84 | if (state.contains(taskId)) { 85 | state = Set.from(state)..remove(taskId); 86 | } else { 87 | state = Set.from(state)..add(taskId); 88 | } 89 | } 90 | 91 | void selectAll(List tasks) { 92 | state = tasks.map((e) => e.id).toSet(); 93 | } 94 | 95 | void clearSelection() { 96 | state = {}; 97 | } 98 | } 99 | 100 | /// 处理任务操作的基础方法 101 | Future _handleTaskOperation( 102 | TaskOperation operation, 103 | List taskIds, 104 | Ref ref, { 105 | bool force = false, 106 | }) async { 107 | if (taskIds.isEmpty) return; 108 | 109 | Result> result; 110 | 111 | switch (operation) { 112 | case TaskOperation.delete: 113 | result = await Api.taskApi.deleteTasks(ids: taskIds, force: force); 114 | break; 115 | case TaskOperation.pause: 116 | result = await Api.taskApi.pauseTasks(ids: taskIds); 117 | break; 118 | case TaskOperation.continue_: 119 | result = await Api.taskApi.continueTasks(ids: taskIds); 120 | break; 121 | } 122 | 123 | ref.invalidate(tasksProvider); 124 | } 125 | 126 | /// 批量任务操作 127 | @riverpod 128 | Future batchTaskOperation( 129 | Ref ref, 130 | TaskOperation operation, { 131 | bool force = false, 132 | }) async { 133 | final selectedTasks = ref.read(batchTaskOperationNotifierProvider); 134 | await _handleTaskOperation( 135 | operation, 136 | selectedTasks.toList(), 137 | ref, 138 | force: force, 139 | ); 140 | } 141 | 142 | /// 单个任务操作 143 | @riverpod 144 | Future taskOperation( 145 | Ref ref, 146 | String taskId, 147 | TaskOperation operation, { 148 | bool force = false, 149 | }) async { 150 | await _handleTaskOperation( 151 | operation, 152 | [taskId], 153 | ref, 154 | force: force, 155 | ); 156 | } 157 | 158 | /// 批量创建任务 159 | @riverpod 160 | Future batchCreateTasks(Ref ref, CreateTaskBatch batch) async { 161 | final result = await Api.taskApi.createTaskBatch(batch); 162 | ref.invalidate(tasksProvider); 163 | } 164 | -------------------------------------------------------------------------------- /lib/baas/baas.dart: -------------------------------------------------------------------------------- 1 | 2 | 3 | enum DatabaseType { firebase, pocketbase } 4 | 5 | abstract class BaaS { 6 | Future initialize(); 7 | Future signUp({ 8 | required String email, 9 | required String password, 10 | }); 11 | 12 | Future signIn({ 13 | required String email, 14 | required String password, 15 | }); 16 | 17 | Future signOut(); 18 | 19 | Future getData({ 20 | required String collection, 21 | required String id, 22 | required T Function(Map json) fromJson, 23 | }); 24 | 25 | Future> getDataList({ 26 | required String collection, 27 | required T Function(Map json) fromJson, 28 | String? filter, 29 | int? page, 30 | int? perPage, 31 | }); 32 | 33 | Stream streamData({ 34 | required String collection, 35 | required String id, 36 | required T Function(Map json) fromJson, 37 | }); 38 | } 39 | -------------------------------------------------------------------------------- /lib/baas/firebase.dart: -------------------------------------------------------------------------------- 1 | 2 | // class FirebaseBaaS implements BaaS { 3 | // @override 4 | // Future initialize() async { 5 | // await Firebase.initializeApp(); 6 | // // 其他初始化代码 7 | // } 8 | 9 | // // 实现其他方法 10 | // } 11 | -------------------------------------------------------------------------------- /lib/baas/pocketbase.dart: -------------------------------------------------------------------------------- 1 | // import 'package:pocketbase/pocketbase.dart'; 2 | // import 'package:flutter_riverpod/flutter_riverpod.dart'; 3 | // import './baas.dart'; 4 | // import 'package:fpdart/fpdart.dart'; 5 | 6 | // class PocketBaseBaaS implements BaaS { 7 | // late final PocketBase _pb; 8 | 9 | // // 1. 构造函数方式 10 | // PocketBaseBaaS() { 11 | // _pb = PocketBase( 12 | // const String.fromEnvironment('POCKETBASE_URL'), 13 | // ); 14 | // } 15 | 16 | // @override 17 | // Future initialize() async { 18 | // // 可以在这里: 19 | // // 1. 验证连接 20 | // try { 21 | // await _pb.health.check(); 22 | // } catch (e) { 23 | // throw Exception('PocketBase connection failed: $e'); 24 | // } 25 | 26 | // // 2. 恢复会话 27 | // final authStore = _pb.authStore; 28 | // if (authStore.isValid) { 29 | // try { 30 | // await _pb.collection('users').authRefresh(); 31 | // } catch (_) { 32 | // authStore.clear(); 33 | // } 34 | // } 35 | 36 | // // 3. 初始化其他依赖 37 | // // await _initializeOtherServices(); 38 | // } 39 | 40 | // // 认证相关方法 41 | // @override 42 | // Future signUp({ 43 | // required String email, 44 | // required String password, 45 | // }) async { 46 | // try { 47 | // await _pb.collection('users').create(body: { 48 | // 'email': email, 49 | // 'password': password, 50 | // 'passwordConfirm': password, 51 | // }); 52 | // } catch (e) { 53 | // throw _handlePocketBaseError(e); 54 | // } 55 | // } 56 | 57 | // @override 58 | // Future signIn({ 59 | // required String email, 60 | // required String password, 61 | // }) async { 62 | // try { 63 | // await _pb.collection('users').authWithPassword( 64 | // email, 65 | // password, 66 | // ); 67 | // } catch (e) { 68 | // throw _handlePocketBaseError(e); 69 | // } 70 | // } 71 | 72 | // @override 73 | // Future signOut() async { 74 | // _pb.authStore.clear(); 75 | // } 76 | 77 | // // 数据操作方法 78 | // @override 79 | // Future getData({ 80 | // required String collection, 81 | // required String id, 82 | // required T Function(Map json) fromJson, 83 | // }) async { 84 | // try { 85 | // final record = await _pb.collection(collection).getOne(id); 86 | // return fromJson(record.toJson()); 87 | // } catch (e) { 88 | // throw _handlePocketBaseError(e); 89 | // } 90 | // } 91 | 92 | // @override 93 | // Future>> getDataList({ 94 | // required String collection, 95 | // required T Function(Map json) fromJson, 96 | // String? filter, 97 | // int? page, 98 | // int? perPage, 99 | // }) async { 100 | // try { 101 | // final records = await _pb.collection(collection).getList( 102 | // filter: filter, 103 | // page: page ?? 1, 104 | // perPage: perPage ?? 20, 105 | // ); 106 | // return right(records.items.map((e) => fromJson(e.toJson())).toList()); 107 | // } catch (e) { 108 | // final errorMessage = e is ClientException 109 | // ? e.response['message'] ?? '未知错误' 110 | // : e.toString(); 111 | // return left(errorMessage); 112 | // } 113 | // } 114 | 115 | // // 实时数据 116 | // @override 117 | // Stream streamData({ 118 | // required String collection, 119 | // required String id, 120 | // required T Function(Map json) fromJson, 121 | // }) { 122 | // return _pb 123 | // .collection(collection) 124 | // .subscribe('*', (e) => e.record.id == id) 125 | // .map((e) => fromJson(e.record.toJson())); 126 | // } 127 | 128 | // // 错误处理 129 | // Exception _handlePocketBaseError(dynamic error) { 130 | // if (error is ClientException) { 131 | // switch (error.statusCode) { 132 | // case 400: 133 | // return Exception('Invalid request: ${error.response}'); 134 | // case 401: 135 | // return Exception('Unauthorized'); 136 | // case 403: 137 | // return Exception('Forbidden'); 138 | // case 404: 139 | // return Exception('Not found'); 140 | // default: 141 | // return Exception('PocketBase error: ${error.message}'); 142 | // } 143 | // } 144 | // return Exception('Unknown error: $error'); 145 | // } 146 | // } 147 | 148 | // // Provider 149 | // final pocketBaseBaaSProvider = Provider((ref) { 150 | // return PocketBaseBaaS(); 151 | // }); 152 | -------------------------------------------------------------------------------- /lib/baas/pocketbase_baas.dart: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/lib/baas/pocketbase_baas.dart -------------------------------------------------------------------------------- /lib/gopeed/common/libgopeed_channel.dart: -------------------------------------------------------------------------------- 1 | // Dart imports: 2 | import 'dart:convert'; 3 | 4 | // Flutter imports: 5 | import 'package:flutter/services.dart'; 6 | 7 | // Project imports: 8 | import 'libgopeed_interface.dart'; 9 | import 'start_config.dart'; 10 | 11 | class LibgopeedChannel implements LibgopeedInterface { 12 | static const _channel = MethodChannel('gopeed.com/libgopeed'); 13 | 14 | @override 15 | Future start(StartConfig cfg) async { 16 | final port = await _channel.invokeMethod('start', { 17 | 'cfg': jsonEncode(cfg), 18 | }); 19 | return port as int; 20 | } 21 | 22 | @override 23 | Future stop() async { 24 | return await _channel.invokeMethod('stop'); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /lib/gopeed/common/libgopeed_ffi.dart: -------------------------------------------------------------------------------- 1 | // Dart imports: 2 | import 'dart:async'; 3 | import 'dart:convert'; 4 | import 'dart:ffi'; 5 | 6 | // Package imports: 7 | import 'package:ffi/ffi.dart'; 8 | 9 | // Project imports: 10 | import '../ffi/libgopeed_bind.dart'; 11 | import 'libgopeed_interface.dart'; 12 | import 'start_config.dart'; 13 | 14 | class LibgopeedFFi implements LibgopeedInterface { 15 | late LibgopeedBind _libgopeed; 16 | 17 | LibgopeedFFi(LibgopeedBind libgopeed) { 18 | _libgopeed = libgopeed; 19 | } 20 | 21 | @override 22 | Future start(StartConfig cfg) { 23 | var completer = Completer(); 24 | var result = _libgopeed.Start(jsonEncode(cfg).toNativeUtf8().cast()); 25 | if (result.r1 != nullptr) { 26 | completer.completeError(Exception(result.r1.cast().toDartString())); 27 | } else { 28 | completer.complete(result.r0); 29 | } 30 | return completer.future; 31 | } 32 | 33 | @override 34 | Future stop() { 35 | var completer = Completer(); 36 | _libgopeed.Stop(); 37 | completer.complete(); 38 | return completer.future; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /lib/gopeed/common/libgopeed_interface.dart: -------------------------------------------------------------------------------- 1 | // Project imports: 2 | import 'start_config.dart'; 3 | 4 | abstract class LibgopeedInterface { 5 | Future start(StartConfig cfg); 6 | 7 | Future stop(); 8 | } 9 | -------------------------------------------------------------------------------- /lib/gopeed/common/start_config.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:freezed_annotation/freezed_annotation.dart'; 3 | 4 | part 'start_config.freezed.dart'; 5 | part 'start_config.g.dart'; 6 | 7 | @freezed 8 | class StartConfig with _$StartConfig { 9 | const factory StartConfig({ 10 | @Default('') String network, 11 | @Default('') String address, 12 | @Default('bolt') String storage, 13 | @Default('') String storageDir, 14 | @Default(0) int refreshInterval, 15 | @Default('') String apiToken, 16 | }) = _StartConfig; 17 | 18 | factory StartConfig.fromJson(Map json) => 19 | _$StartConfigFromJson(json); 20 | } 21 | -------------------------------------------------------------------------------- /lib/gopeed/common/start_config.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'start_config.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | _$StartConfigImpl _$$StartConfigImplFromJson(Map json) => _$StartConfigImpl( 10 | network: json['network'] as String? ?? '', 11 | address: json['address'] as String? ?? '', 12 | storage: json['storage'] as String? ?? 'bolt', 13 | storageDir: json['storageDir'] as String? ?? '', 14 | refreshInterval: (json['refreshInterval'] as num?)?.toInt() ?? 0, 15 | apiToken: json['apiToken'] as String? ?? '', 16 | ); 17 | 18 | Map _$$StartConfigImplToJson(_$StartConfigImpl instance) => 19 | { 20 | 'network': instance.network, 21 | 'address': instance.address, 22 | 'storage': instance.storage, 23 | 'storageDir': instance.storageDir, 24 | 'refreshInterval': instance.refreshInterval, 25 | 'apiToken': instance.apiToken, 26 | }; 27 | -------------------------------------------------------------------------------- /lib/gopeed/entry/libgopeed_boot_browser.dart: -------------------------------------------------------------------------------- 1 | // Dart imports: 2 | import 'dart:async'; 3 | 4 | // Project imports: 5 | import '../common/start_config.dart'; 6 | import '../libgopeed_boot.dart'; 7 | 8 | LibgopeedBoot create() => LibgopeedBootBrowser(); 9 | 10 | class LibgopeedBootBrowser implements LibgopeedBoot { 11 | // do nothing 12 | @override 13 | Future start(StartConfig cfg) async { 14 | return 0; 15 | } 16 | 17 | @override 18 | Future stop() async {} 19 | } 20 | -------------------------------------------------------------------------------- /lib/gopeed/entry/libgopeed_boot_native.dart: -------------------------------------------------------------------------------- 1 | // Dart imports: 2 | import 'dart:ffi'; 3 | import 'dart:io'; 4 | import 'dart:isolate'; 5 | 6 | // Project imports: 7 | import 'package:hapee/app/core/utils/util.dart'; 8 | import '../common/libgopeed_channel.dart'; 9 | import '../common/libgopeed_ffi.dart'; 10 | import '../common/libgopeed_interface.dart'; 11 | import '../common/start_config.dart'; 12 | import '../ffi/libgopeed_bind.dart'; 13 | import '../libgopeed_boot.dart'; 14 | 15 | LibgopeedBoot create() => LibgopeedBootNative(); 16 | 17 | class LibgopeedBootNative implements LibgopeedBoot { 18 | late LibgopeedInterface _libgopeed; 19 | 20 | LibgopeedBootNative() { 21 | if (!Util.isDesktop) _libgopeed = LibgopeedChannel(); 22 | } 23 | 24 | @override 25 | Future start(StartConfig cfg) async { 26 | return Util.isDesktop 27 | ? await Isolate.run(() { 28 | _libgopeed = LibgopeedFFi(LibgopeedBind(DynamicLibrary.open( 29 | 'libgopeed.${Platform.isWindows ? 'dll' : Platform.isMacOS ? 'dylib' : 'so'}'))); 30 | return _libgopeed.start(cfg); 31 | }) 32 | : await _libgopeed.start(cfg); 33 | } 34 | 35 | @override 36 | Future stop() => _libgopeed.stop(); 37 | } 38 | -------------------------------------------------------------------------------- /lib/gopeed/libgopeed_boot.dart: -------------------------------------------------------------------------------- 1 | // Project imports: 2 | import 'common/start_config.dart'; 3 | 4 | import "libgopeed_boot_stub.dart" 5 | if (dart.library.html) 'entry/libgopeed_boot_browser.dart' 6 | if (dart.library.io) 'entry/libgopeed_boot_native.dart'; 7 | 8 | abstract class LibgopeedBoot { 9 | static LibgopeedBoot? _instance; 10 | 11 | static LibgopeedBoot get instance { 12 | _instance ??= LibgopeedBoot(); 13 | return _instance!; 14 | } 15 | 16 | factory LibgopeedBoot() => create(); 17 | 18 | Future start(StartConfig cfg); 19 | 20 | Future stop(); 21 | } 22 | -------------------------------------------------------------------------------- /lib/gopeed/libgopeed_boot_stub.dart: -------------------------------------------------------------------------------- 1 | // Project imports: 2 | import 'libgopeed_boot.dart'; 3 | 4 | LibgopeedBoot create() => throw UnimplementedError(); 5 | -------------------------------------------------------------------------------- /lib/l10n/arb/app_ta.arb: -------------------------------------------------------------------------------- 1 | { 2 | "label": "தமிழ்", 3 | "error": "பிழை", 4 | "tip": "குறிப்பு", 5 | "on": "On", 6 | "task": "பணிகள்", 7 | "downloading": "பதிவிறக்குகிறது", 8 | "downloaded": "பதிவிறக்கம் செய்யப்பட்டது", 9 | "setting": "அமைப்புகள் ", 10 | "donate": "நன்கொடை", 11 | "exit": "வெளியேறு", 12 | "create": "பணியை உருவாக்கு", 13 | "directDownload": "நேரடி பதிவிறக்கம்", 14 | "advancedOptions": "மேம்பட்ட விருப்பங்கள்", 15 | "downloadLink": "தரவிறக்க இணைப்பு", 16 | "downloadLinkValid": "பதிவிறக்க இணைப்பை உள்ளிடவும்", 17 | "downloadLinkHit": "பதிவிறக்க இணைப்பை உள்ளிடவும், HTTP/HTTPS/MAGNET ஆகியவற்றை ஏற்கும்", 18 | "downloadLinkHitDesktop": ", அல்லது torrent கோப்பை நேரடியாக இங்கே இழுக்கவும்", 19 | "download": "பதிவிறக்கு", 20 | "noFileSelected": "குறைந்தபட்சம் ஒரு கோப்பைத் தேர்ந்தெடுக்கவும்.", 21 | "noStoragePermission": "சேமிப்பக அனுமதி தேவை", 22 | "selectFile": "கோப்பைத் தேர்ந்தெடுக்கவும்", 23 | "rename": "பெயறைமாற்று", 24 | "basic": "அடிப்படை", 25 | "advanced": "மேம்பட்ட", 26 | "general": "பொதுவான", 27 | "downloadDir": "பதிவிரக்குமிடம்", 28 | "downloadDirValid": "பதிவிரக்குமிடத்தை தேர்வு செயுங்கள்", 29 | "connections": "தொடர்புகள்", 30 | "useServerCtime": "Use server time for file creation", 31 | "maxRunning": "அதிகபட்ச இயங்கும் பணிகள்", 32 | "items": "{count} items", 33 | "subscribeTracker": "Subscribe Tracker", 34 | "subscribeFail": "Subscribe failed, please check network or try again later", 35 | "update": "புதுப்பிக்கவும்", 36 | "updateDaily": "தினமும் புதுப்பிக்கவும்", 37 | "lastUpdate": "கடைசியாக புதுப்பிக்கப்பட்டது: {time}", 38 | 39 | "addTrackerHit": "Please enter the tracker server url, one per line", 40 | "ui": "UI", 41 | "theme": "தீம்", 42 | "themeSystem": "இயல்புநிலை", 43 | "themeLight": "வெண்மையானநிலை", 44 | "themeDark": "இருண்டநிலை", 45 | "locale": "மொழி", 46 | "about": "எங்களை பற்றி", 47 | "version": "பதிப்பு", 48 | "protocol": "நெறிமுறை", 49 | "port": "Port", 50 | "apiToken": "API Token", 51 | "notSet": "NS", 52 | "set": "SET", 53 | "portInUse": "Port [{port}] is in use, please change the port", 54 | "effectAfterRestart": "Effect after restart", 55 | "show": "காட்டு", 56 | "startAll": "அனைத்தையும் தொடங்கு", 57 | "pauseAll": "அனைத்தையும் நிறுத்திவை", 58 | "deleteTask": "பணியை நீக்கு", 59 | "deleteTaskTip": "பதிவிறக்கம் செய்யப்பட்ட கோப்புகளை வைத்திரு", 60 | "newVersionTitle": "புதிய பதிப்பைக் கண்டறியவும் {version}", 61 | "newVersionUpdate": "இப்பொழுது புதுப்பி", 62 | "extensions": "நீட்டிப்புகள்", 63 | "extensionInstallUrl": "நிறுவப்படும் URL", 64 | "extensionInstallSuccess": "வெற்றிகரமாக நிறுவப்பட்டது", 65 | "extensionUpdateSuccess": "வெற்றிகரமாக புதுப்பிக்கப்பட்டது", 66 | "extensionDelete": "நீட்டிப்பை நீக்கு", 67 | "extensionAlreadyLatest": "இது ஏற்கனவே சமீபத்திய பதிப்பாகும்", 68 | "extensionFind": "நீட்டிப்புகளைக் கண்டறியவும்", 69 | "extensionDevelop": "நீட்டிப்புகளை உருவாக்கவும்", 70 | "history": "வரலாறு", 71 | "clearHistory": "உள்ளீடுகளை நீக்கு", 72 | "noHistoryFound": "உள்ளீடுகள் இல்லை", 73 | "serviceTitle": "பதிவிறக்க சேவை", 74 | "serviceText": "இயக்கத்தில் உள்ளது", 75 | "proxy": "பதிலி", 76 | "noProxy": "பதிலி இல்லாமல் ", 77 | "systemProxy": "இயல்புநிலை பதிலி", 78 | "customProxy": "மாற்றியமைக்கப்பட்ட பதிலி", 79 | "server": "சேவையகம்", 80 | "username": "பயனர் பெயர்", 81 | "password": "கடவுச்சொல்", 82 | "thanks": "நன்றி", 83 | 84 | "browserExtension": "உலாவி நீட்டிப்பு", 85 | "launchAtStartup": "தொடக்கத்தின் போது இயங்கு" 86 | } 87 | -------------------------------------------------------------------------------- /lib/l10n/l10n.dart: -------------------------------------------------------------------------------- 1 | // ignore_for_file: file_names 2 | 3 | // Flutter imports: 4 | import 'package:flutter/widgets.dart'; 5 | 6 | // Package imports: 7 | import 'package:flutter_gen/gen_l10n/app_localizations.dart'; 8 | 9 | export 'package:flutter_gen/gen_l10n/app_localizations.dart'; 10 | 11 | extension AppLocalizationsX on BuildContext { 12 | AppLocalizations get l10n => AppLocalizations.of(this)!; 13 | } 14 | -------------------------------------------------------------------------------- /lib/main.dart: -------------------------------------------------------------------------------- 1 | // Flutter imports: 2 | import 'package:flutter/material.dart'; 3 | 4 | // Package imports: 5 | import 'package:hooks_riverpod/hooks_riverpod.dart'; 6 | import 'package:sentry_flutter/sentry_flutter.dart'; 7 | 8 | // Project imports: 9 | import 'package:hapee/app/core/app_config/app_config.dart'; 10 | import 'package:hapee/app/core/database/database.dart'; 11 | import 'package:hapee/gopeed/libgopeed_boot.dart'; 12 | import 'package:hapee/app/core/api/gopeed_api/api.dart'; 13 | import 'app/app.dart'; 14 | 15 | Future main() async { 16 | WidgetsFlutterBinding.ensureInitialized(); 17 | 18 | await SentryFlutter.init( 19 | (options) => options.dsn = String.fromEnvironment('SENTRY_DSN'), 20 | appRunner: () async { 21 | await Database.instance.init(); 22 | final appConfig = AppConfig(); 23 | await appConfig.loadStartConfig(); 24 | appConfig.runningPort = 25 | await LibgopeedBoot.instance.start(appConfig.startConfig); 26 | Api.init(appConfig.startConfig.network, appConfig.runningAddress(), 27 | appConfig.startConfig.apiToken); 28 | 29 | runApp( 30 | ProviderScope( 31 | child: const App(), 32 | ), 33 | ); 34 | }, 35 | ); 36 | } 37 | -------------------------------------------------------------------------------- /linux/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral 2 | -------------------------------------------------------------------------------- /linux/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.10) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | 12 | # Serves the same purpose as list(TRANSFORM ... PREPEND ...), 13 | # which isn't available in 3.10. 14 | function(list_prepend LIST_NAME PREFIX) 15 | set(NEW_LIST "") 16 | foreach(element ${${LIST_NAME}}) 17 | list(APPEND NEW_LIST "${PREFIX}${element}") 18 | endforeach(element) 19 | set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) 20 | endfunction() 21 | 22 | # === Flutter Library === 23 | # System-level dependencies. 24 | find_package(PkgConfig REQUIRED) 25 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) 26 | pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) 27 | pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) 28 | 29 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") 30 | 31 | # Published to parent scope for install step. 32 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 33 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 34 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 35 | set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) 36 | 37 | list(APPEND FLUTTER_LIBRARY_HEADERS 38 | "fl_basic_message_channel.h" 39 | "fl_binary_codec.h" 40 | "fl_binary_messenger.h" 41 | "fl_dart_project.h" 42 | "fl_engine.h" 43 | "fl_json_message_codec.h" 44 | "fl_json_method_codec.h" 45 | "fl_message_codec.h" 46 | "fl_method_call.h" 47 | "fl_method_channel.h" 48 | "fl_method_codec.h" 49 | "fl_method_response.h" 50 | "fl_plugin_registrar.h" 51 | "fl_plugin_registry.h" 52 | "fl_standard_message_codec.h" 53 | "fl_standard_method_codec.h" 54 | "fl_string_codec.h" 55 | "fl_value.h" 56 | "fl_view.h" 57 | "flutter_linux.h" 58 | ) 59 | list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") 60 | add_library(flutter INTERFACE) 61 | target_include_directories(flutter INTERFACE 62 | "${EPHEMERAL_DIR}" 63 | ) 64 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") 65 | target_link_libraries(flutter INTERFACE 66 | PkgConfig::GTK 67 | PkgConfig::GLIB 68 | PkgConfig::GIO 69 | ) 70 | add_dependencies(flutter flutter_assemble) 71 | 72 | # === Flutter tool backend === 73 | # _phony_ is a non-existent file to force this command to run every time, 74 | # since currently there's no way to get a full input/output list from the 75 | # flutter tool. 76 | add_custom_command( 77 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 78 | ${CMAKE_CURRENT_BINARY_DIR}/_phony_ 79 | COMMAND ${CMAKE_COMMAND} -E env 80 | ${FLUTTER_TOOL_ENVIRONMENT} 81 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" 82 | ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} 83 | VERBATIM 84 | ) 85 | add_custom_target(flutter_assemble DEPENDS 86 | "${FLUTTER_LIBRARY}" 87 | ${FLUTTER_LIBRARY_HEADERS} 88 | ) 89 | -------------------------------------------------------------------------------- /linux/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | #include 11 | 12 | void fl_register_plugins(FlPluginRegistry* registry) { 13 | g_autoptr(FlPluginRegistrar) sentry_flutter_registrar = 14 | fl_plugin_registry_get_registrar_for_plugin(registry, "SentryFlutterPlugin"); 15 | sentry_flutter_plugin_register_with_registrar(sentry_flutter_registrar); 16 | g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = 17 | fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); 18 | url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); 19 | } 20 | -------------------------------------------------------------------------------- /linux/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void fl_register_plugins(FlPluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /linux/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | sentry_flutter 7 | url_launcher_linux 8 | ) 9 | 10 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 11 | ) 12 | 13 | set(PLUGIN_BUNDLED_LIBRARIES) 14 | 15 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 16 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) 17 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 18 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 19 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 20 | endforeach(plugin) 21 | 22 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 23 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) 24 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 25 | endforeach(ffi_plugin) 26 | -------------------------------------------------------------------------------- /linux/main.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | int main(int argc, char** argv) { 4 | g_autoptr(MyApplication) app = my_application_new(); 5 | return g_application_run(G_APPLICATION(app), argc, argv); 6 | } 7 | -------------------------------------------------------------------------------- /linux/my_application.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | #include 4 | #ifdef GDK_WINDOWING_X11 5 | #include 6 | #endif 7 | 8 | #include "flutter/generated_plugin_registrant.h" 9 | 10 | struct _MyApplication { 11 | GtkApplication parent_instance; 12 | char** dart_entrypoint_arguments; 13 | }; 14 | 15 | G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) 16 | 17 | // Implements GApplication::activate. 18 | static void my_application_activate(GApplication* application) { 19 | MyApplication* self = MY_APPLICATION(application); 20 | GtkWindow* window = 21 | GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); 22 | 23 | // Use a header bar when running in GNOME as this is the common style used 24 | // by applications and is the setup most users will be using (e.g. Ubuntu 25 | // desktop). 26 | // If running on X and not using GNOME then just use a traditional title bar 27 | // in case the window manager does more exotic layout, e.g. tiling. 28 | // If running on Wayland assume the header bar will work (may need changing 29 | // if future cases occur). 30 | gboolean use_header_bar = TRUE; 31 | #ifdef GDK_WINDOWING_X11 32 | GdkScreen* screen = gtk_window_get_screen(window); 33 | if (GDK_IS_X11_SCREEN(screen)) { 34 | const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); 35 | if (g_strcmp0(wm_name, "GNOME Shell") != 0) { 36 | use_header_bar = FALSE; 37 | } 38 | } 39 | #endif 40 | if (use_header_bar) { 41 | GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); 42 | gtk_widget_show(GTK_WIDGET(header_bar)); 43 | gtk_header_bar_set_title(header_bar, "hapee"); 44 | gtk_header_bar_set_show_close_button(header_bar, TRUE); 45 | gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); 46 | } else { 47 | gtk_window_set_title(window, "hapee"); 48 | } 49 | 50 | gtk_window_set_default_size(window, 1280, 720); 51 | gtk_widget_show(GTK_WIDGET(window)); 52 | 53 | g_autoptr(FlDartProject) project = fl_dart_project_new(); 54 | fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); 55 | 56 | FlView* view = fl_view_new(project); 57 | gtk_widget_show(GTK_WIDGET(view)); 58 | gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); 59 | 60 | fl_register_plugins(FL_PLUGIN_REGISTRY(view)); 61 | 62 | gtk_widget_grab_focus(GTK_WIDGET(view)); 63 | } 64 | 65 | // Implements GApplication::local_command_line. 66 | static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { 67 | MyApplication* self = MY_APPLICATION(application); 68 | // Strip out the first argument as it is the binary name. 69 | self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); 70 | 71 | g_autoptr(GError) error = nullptr; 72 | if (!g_application_register(application, nullptr, &error)) { 73 | g_warning("Failed to register: %s", error->message); 74 | *exit_status = 1; 75 | return TRUE; 76 | } 77 | 78 | g_application_activate(application); 79 | *exit_status = 0; 80 | 81 | return TRUE; 82 | } 83 | 84 | // Implements GApplication::startup. 85 | static void my_application_startup(GApplication* application) { 86 | //MyApplication* self = MY_APPLICATION(object); 87 | 88 | // Perform any actions required at application startup. 89 | 90 | G_APPLICATION_CLASS(my_application_parent_class)->startup(application); 91 | } 92 | 93 | // Implements GApplication::shutdown. 94 | static void my_application_shutdown(GApplication* application) { 95 | //MyApplication* self = MY_APPLICATION(object); 96 | 97 | // Perform any actions required at application shutdown. 98 | 99 | G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); 100 | } 101 | 102 | // Implements GObject::dispose. 103 | static void my_application_dispose(GObject* object) { 104 | MyApplication* self = MY_APPLICATION(object); 105 | g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); 106 | G_OBJECT_CLASS(my_application_parent_class)->dispose(object); 107 | } 108 | 109 | static void my_application_class_init(MyApplicationClass* klass) { 110 | G_APPLICATION_CLASS(klass)->activate = my_application_activate; 111 | G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; 112 | G_APPLICATION_CLASS(klass)->startup = my_application_startup; 113 | G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; 114 | G_OBJECT_CLASS(klass)->dispose = my_application_dispose; 115 | } 116 | 117 | static void my_application_init(MyApplication* self) {} 118 | 119 | MyApplication* my_application_new() { 120 | return MY_APPLICATION(g_object_new(my_application_get_type(), 121 | "application-id", APPLICATION_ID, 122 | "flags", G_APPLICATION_NON_UNIQUE, 123 | nullptr)); 124 | } 125 | -------------------------------------------------------------------------------- /linux/my_application.h: -------------------------------------------------------------------------------- 1 | #ifndef FLUTTER_MY_APPLICATION_H_ 2 | #define FLUTTER_MY_APPLICATION_H_ 3 | 4 | #include 5 | 6 | G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, 7 | GtkApplication) 8 | 9 | /** 10 | * my_application_new: 11 | * 12 | * Creates a new Flutter-based application. 13 | * 14 | * Returns: a new #MyApplication. 15 | */ 16 | MyApplication* my_application_new(); 17 | 18 | #endif // FLUTTER_MY_APPLICATION_H_ 19 | -------------------------------------------------------------------------------- /macos/.gitignore: -------------------------------------------------------------------------------- 1 | # Flutter-related 2 | **/Flutter/ephemeral/ 3 | **/Pods/ 4 | 5 | # Xcode-related 6 | **/dgph 7 | **/xcuserdata/ 8 | -------------------------------------------------------------------------------- /macos/Flutter/Flutter-Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "ephemeral/Flutter-Generated.xcconfig" 2 | -------------------------------------------------------------------------------- /macos/Flutter/Flutter-Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "ephemeral/Flutter-Generated.xcconfig" 2 | -------------------------------------------------------------------------------- /macos/Flutter/GeneratedPluginRegistrant.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | import FlutterMacOS 6 | import Foundation 7 | 8 | import connectivity_plus 9 | import device_info_plus 10 | import package_info_plus 11 | import path_provider_foundation 12 | import sentry_flutter 13 | import shared_preferences_foundation 14 | import url_launcher_macos 15 | 16 | func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { 17 | ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin")) 18 | DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) 19 | FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) 20 | PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) 21 | SentryFlutterPlugin.register(with: registry.registrar(forPlugin: "SentryFlutterPlugin")) 22 | SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) 23 | UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) 24 | } 25 | -------------------------------------------------------------------------------- /macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 43 | 49 | 50 | 51 | 52 | 53 | 63 | 65 | 71 | 72 | 73 | 74 | 80 | 82 | 88 | 89 | 90 | 91 | 93 | 94 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /macos/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /macos/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | @main 5 | class AppDelegate: FlutterAppDelegate { 6 | override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { 7 | return true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "16x16", 5 | "idiom" : "mac", 6 | "filename" : "app_icon_16.png", 7 | "scale" : "1x" 8 | }, 9 | { 10 | "size" : "16x16", 11 | "idiom" : "mac", 12 | "filename" : "app_icon_32.png", 13 | "scale" : "2x" 14 | }, 15 | { 16 | "size" : "32x32", 17 | "idiom" : "mac", 18 | "filename" : "app_icon_32.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "32x32", 23 | "idiom" : "mac", 24 | "filename" : "app_icon_64.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "128x128", 29 | "idiom" : "mac", 30 | "filename" : "app_icon_128.png", 31 | "scale" : "1x" 32 | }, 33 | { 34 | "size" : "128x128", 35 | "idiom" : "mac", 36 | "filename" : "app_icon_256.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "256x256", 41 | "idiom" : "mac", 42 | "filename" : "app_icon_256.png", 43 | "scale" : "1x" 44 | }, 45 | { 46 | "size" : "256x256", 47 | "idiom" : "mac", 48 | "filename" : "app_icon_512.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "512x512", 53 | "idiom" : "mac", 54 | "filename" : "app_icon_512.png", 55 | "scale" : "1x" 56 | }, 57 | { 58 | "size" : "512x512", 59 | "idiom" : "mac", 60 | "filename" : "app_icon_1024.png", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png -------------------------------------------------------------------------------- /macos/Runner/Configs/AppInfo.xcconfig: -------------------------------------------------------------------------------- 1 | // Application-level settings for the Runner target. 2 | // 3 | // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the 4 | // future. If not, the values below would default to using the project name when this becomes a 5 | // 'flutter create' template. 6 | 7 | // The application's name. By default this is also the title of the Flutter window. 8 | PRODUCT_NAME = hapee 9 | 10 | // The application's bundle identifier 11 | PRODUCT_BUNDLE_IDENTIFIER = com.example.hapeeNext 12 | 13 | // The copyright displayed in application information 14 | PRODUCT_COPYRIGHT = Copyright © 2024 com.example. All rights reserved. 15 | -------------------------------------------------------------------------------- /macos/Runner/Configs/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Debug.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /macos/Runner/Configs/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Release.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /macos/Runner/Configs/Warnings.xcconfig: -------------------------------------------------------------------------------- 1 | WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings 2 | GCC_WARN_UNDECLARED_SELECTOR = YES 3 | CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES 4 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE 5 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES 6 | CLANG_WARN_PRAGMA_PACK = YES 7 | CLANG_WARN_STRICT_PROTOTYPES = YES 8 | CLANG_WARN_COMMA = YES 9 | GCC_WARN_STRICT_SELECTOR_MATCH = YES 10 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES 11 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES 12 | GCC_WARN_SHADOW = YES 13 | CLANG_WARN_UNREACHABLE_CODE = YES 14 | -------------------------------------------------------------------------------- /macos/Runner/DebugProfile.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.cs.allow-jit 8 | 9 | com.apple.security.network.server 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /macos/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleVersion 22 | $(FLUTTER_BUILD_NUMBER) 23 | LSMinimumSystemVersion 24 | $(MACOSX_DEPLOYMENT_TARGET) 25 | NSHumanReadableCopyright 26 | $(PRODUCT_COPYRIGHT) 27 | NSMainNibFile 28 | MainMenu 29 | NSPrincipalClass 30 | NSApplication 31 | 32 | 33 | -------------------------------------------------------------------------------- /macos/Runner/MainFlutterWindow.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | // Add the LaunchAtLogin module 4 | import LaunchAtLogin 5 | // 6 | 7 | class MainFlutterWindow: NSWindow { 8 | override func awakeFromNib() { 9 | let flutterViewController = FlutterViewController() 10 | let windowFrame = self.frame 11 | self.contentViewController = flutterViewController 12 | self.setFrame(windowFrame, display: true) 13 | 14 | // Add FlutterMethodChannel platform code 15 | FlutterMethodChannel( 16 | name: "launch_at_startup", binaryMessenger: flutterViewController.engine.binaryMessenger 17 | ) 18 | .setMethodCallHandler { (_ call: FlutterMethodCall, result: @escaping FlutterResult) in 19 | switch call.method { 20 | case "launchAtStartupIsEnabled": 21 | result(LaunchAtLogin.isEnabled) 22 | case "launchAtStartupSetEnabled": 23 | if let arguments = call.arguments as? [String: Any] { 24 | LaunchAtLogin.isEnabled = arguments["setEnabledValue"] as! Bool 25 | } 26 | result(nil) 27 | default: 28 | result(FlutterMethodNotImplemented) 29 | } 30 | } 31 | // 32 | RegisterGeneratedPlugins(registry: flutterViewController) 33 | 34 | super.awakeFromNib() 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /macos/Runner/Release.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /macos/RunnerTests/RunnerTests.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | import XCTest 4 | 5 | class RunnerTests: XCTestCase { 6 | 7 | func testExample() { 8 | // If you add code to the Runner application, consider adding tests here. 9 | // See https://developer.apple.com/documentation/xctest for more information about using XCTest. 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | # TODO: add your app name here 2 | name: hapee 3 | # TODO: add your app description here 4 | description: A new Flutter project. 5 | 6 | # The following line prevents the package from being accidentally published to 7 | # pub.dev using `flutter pub publish`. This is preferred for private packages. 8 | publish_to: "none" # Remove this line if you wish to publish to pub.dev 9 | 10 | # The following defines the version and build number for your application. 11 | # A version number is three numbers separated by dots, like 1.2.43 12 | # followed by an optional build number separated by a +. 13 | # Both the version and the builder number may be overridden in flutter 14 | # build by specifying --build-name and --build-number, respectively. 15 | # In Android, build-name is used as versionName while build-number used as versionCode. 16 | # Read more about Android versioning at https://developer.android.com/studio/publish/versioning 17 | # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. 18 | # Read more about iOS versioning at 19 | # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html 20 | version: 1.0.0+1 21 | 22 | environment: 23 | sdk: ">=3.0.0 <4.0.0" 24 | 25 | # Dependencies specify other packages that your package needs in order to work. 26 | # To automatically upgrade your package dependencies to the latest versions 27 | # consider running `flutter pub upgrade --major-versions`. Alternatively, 28 | # dependencies can be manually updated by changing the version numbers below to 29 | # the latest version available on pub.dev. To see which dependencies have newer 30 | # versions available, run `flutter pub outdated`. 31 | dependencies: 32 | flutter: 33 | sdk: flutter 34 | flutter_localizations: 35 | sdk: flutter 36 | cupertino_icons: ^1.0.5 # Android✔ iOS✔ Web✔ Windows✔ macOS✔ Linux✔ 37 | 38 | go_router: ^14.4.1 # Android✔ iOS✔ Web✔ Windows✔ macOS✔ Linux✔ 39 | hive: ^2.2.3 40 | hive_flutter: ^1.1.0 # Android✔ iOS✔ Web✔ Windows✔ macOS✔ Linux✔ 41 | hooks_riverpod: ^2.6.1 # Android✔ iOS✔ Web✔ Windows✔ macOS✔ Linux✔ 42 | flutter_hooks: ^0.20.5 # Android✔ iOS✔ Web✔ Windows✔ macOS✔ Linux✔ 43 | 44 | pocketbase: ^0.18.1 45 | riverpod_annotation: ^2.6.1 46 | dio: ^5.7.0 47 | html: ^0.15.4 48 | # File handling 49 | path_provider: ^2.1.2 50 | flutter_adaptive_scaffold: ^0.3.1 51 | json_annotation: ^4.9.0 52 | fluent_ui: ^4.9.2 # Windows UI toolkit 53 | fluentui_system_icons: ^1.1.264 54 | material_file_icon: ^0.4.0 55 | connectivity_plus: ^6.1.0 56 | freezed_annotation: ^2.4.4 57 | launch_at_startup: ^0.3.1 58 | url_launcher: ^6.2.3 59 | upgrader: ^11.3.0 60 | logger: ^2.4.0 61 | flutter_background_service: ^5.0.10 62 | mix: ^1.5.2 63 | mockito: ^5.4.4 64 | syncfusion_flutter_datagrid: ^24.1.41 65 | sentry_flutter: ^8.10.1 66 | data_table_2: ^2.5.8 67 | open_filex: ^4.3.4 68 | file_picker: ^8.1.4 69 | # Form handling 70 | flutter_form_builder: ^9.1.2 71 | form_builder_validators: ^11.0.0 72 | 73 | dev_dependencies: 74 | freezed: ^2.4.6 75 | flutter_lints: ^5.0.0 76 | path: ^1.8.3 77 | yaml: ^3.1.2 78 | flutter_test: 79 | sdk: flutter 80 | very_good_analysis: ^5.1.0 81 | intl: ^0.19.0 82 | flutter_launcher_icons: ^0.14.1 83 | build_runner: ^2.4.13 84 | riverpod_generator: ^2.6.1 85 | json_serializable: ^6.8.0 86 | mix_lint: ^0.1.1 87 | custom_lint: ^0.6.8 88 | import_sorter: ^4.6.0 89 | 90 | 91 | # For information on the generic Dart part of this file, see the 92 | # following page: https://dart.dev/tools/pub/pubspec 93 | # The following section is specific to Flutter packages. 94 | flutter: 95 | # The following line ensures that the Material Icons font is 96 | # included with your application, so that you can use the icons in 97 | # the material Icons class. 98 | uses-material-design: true 99 | generate: true 100 | # To add assets to your application, add an assets section, like this: 101 | # assets: 102 | # - images/a_dot_burr.jpeg 103 | # - images/a_dot_ham.jpeg 104 | # An image asset can refer to one or more resolution-specific "variants", see 105 | # https://flutter.dev/assets-and-images/#resolution-aware 106 | # For details regarding adding assets from package dependencies, see 107 | # https://flutter.dev/assets-and-images/#from-packages 108 | # To add custom fonts to your application, add a fonts section here, 109 | # in this "flutter" section. Each entry in this list should have a 110 | # "family" key with the font family name, and a "fonts" key with a 111 | # list giving the asset and other descriptors for the font. For 112 | # example: 113 | # fonts: 114 | # - family: Schyler 115 | # fonts: 116 | # - asset: fonts/Schyler-Regular.ttf 117 | # - asset: fonts/Schyler-Italic.ttf 118 | # style: italic 119 | # - family: Trajan Pro 120 | # fonts: 121 | # - asset: fonts/TrajanPro.ttf 122 | # - asset: fonts/TrajanPro_Bold.ttf 123 | # weight: 700 124 | # 125 | # For details regarding fonts from package dependencies, 126 | # see https://flutter.dev/custom-fonts/#from-packages 127 | -------------------------------------------------------------------------------- /test/api/config_api_test.dart: -------------------------------------------------------------------------------- 1 | // // Package imports: 2 | // import 'package:dio/dio.dart'; 3 | // import 'package:flutter_test/flutter_test.dart'; 4 | // import 'package:mockito/mockito.dart'; 5 | 6 | // // Project imports: 7 | // import 'package:hapee/gopeed_api/endpoints/config_api.dart'; 8 | // import 'package:hapee/app/core/models/gopeed_models/common/models.dart'; 9 | // import '../mocks.mocks.dart'; 10 | 11 | // void main() { 12 | // group('ConfigApi', () { 13 | // late MockDio mockDio; 14 | // late ConfigApi configApi; 15 | 16 | // setUp(() { 17 | // mockDio = MockDio(); 18 | // configApi = ConfigApi()..dio = mockDio; 19 | // }); 20 | 21 | // test('getConfig should return downloader config', () async { 22 | // final mockResponse = { 23 | // 'code': 0, 24 | // 'msg': '', 25 | // 'data': { 26 | // 'downloadDir': '/downloads', 27 | // 'maxRunning': 3, 28 | // 'protocolConfig': { 29 | // 'http': { 30 | // 'userAgent': 'test-agent', 31 | // 'connections': 16, 32 | // 'useServerCtime': false 33 | // }, 34 | // 'bt': {'listenPort': 6881, 'trackers': []} 35 | // }, 36 | // 'extra': { 37 | // 'themeMode': 'dark', 38 | // 'locale': 'en', 39 | // 'lastDeleteTaskKeep': false, 40 | // 'bt': { 41 | // 'trackerSubscribeUrls': [], 42 | // 'subscribeTrackers': [], 43 | // 'autoUpdateTrackers': true, 44 | // 'customTrackers': [] 45 | // } 46 | // }, 47 | // 'proxy': { 48 | // 'enable': false, 49 | // 'system': false, 50 | // 'scheme': 'http', 51 | // 'host': '', 52 | // 'usr': '', 53 | // 'pwd': '' 54 | // } 55 | // } 56 | // }; 57 | 58 | // when(mockDio.get(any)).thenAnswer( 59 | // (_) async => Response( 60 | // data: mockResponse, 61 | // statusCode: 200, 62 | // requestOptions: RequestOptions(path: ''), 63 | // ), 64 | // ); 65 | 66 | // final config = await configApi.getConfig(); 67 | 68 | // expect(config.downloadDir, equals('/downloads')); 69 | // expect(config.maxRunning, equals(3)); 70 | // expect(config.protocolConfig.http.connections, equals(16)); 71 | // expect(config.extra.themeMode, equals('dark')); 72 | 73 | // verify(mockDio.get('/api/v1/config')).called(1); 74 | // }); 75 | 76 | // test('putConfig should update config', () async { 77 | // final mockResponse = {'code': 0, 'msg': '', 'data': null}; 78 | 79 | // when(mockDio.put(any, data: anyNamed('data'))).thenAnswer( 80 | // (_) async => Response( 81 | // data: mockResponse, 82 | // statusCode: 200, 83 | // requestOptions: RequestOptions(path: ''), 84 | // ), 85 | // ); 86 | 87 | // final config = DownloaderConfig( 88 | // downloadDir: '/new-downloads', 89 | // maxRunning: 5, 90 | // ); 91 | 92 | // await configApi.putConfig(config); 93 | 94 | // verify(mockDio.put('/api/v1/config', data: config)).called(1); 95 | // }); 96 | // }); 97 | // } 98 | -------------------------------------------------------------------------------- /test/api/info_api_test.dart: -------------------------------------------------------------------------------- 1 | // // Package imports: 2 | // import 'package:dio/dio.dart'; 3 | // import 'package:flutter_test/flutter_test.dart'; 4 | // import 'package:mockito/mockito.dart'; 5 | 6 | // // Project imports: 7 | // import 'package:hapee/gopeed_api/endpoints/info_api.dart'; 8 | // import 'package:hapee/gopeed_api/exceptions.dart'; 9 | // import '../mocks.mocks.dart'; 10 | 11 | // void main() { 12 | // group('InfoApi', () { 13 | // late MockDio mockDio; 14 | // late InfoApi infoApi; 15 | 16 | // setUp(() { 17 | // mockDio = MockDio(); 18 | // infoApi = InfoApi()..dio = mockDio; 19 | // }); 20 | 21 | // test('getInfo should return server info', () async { 22 | // final mockResponse = { 23 | // 'code': 0, 24 | // 'msg': '', 25 | // 'data': { 26 | // 'version': '1.0.0', 27 | // 'runtime': 'go1.20', 28 | // 'os': 'linux', 29 | // 'arch': 'amd64', 30 | // 'inDocker': false 31 | // } 32 | // }; 33 | 34 | // when(mockDio.get(any)).thenAnswer( 35 | // (_) async => Response( 36 | // data: mockResponse, 37 | // statusCode: 200, 38 | // requestOptions: RequestOptions(path: ''), 39 | // ), 40 | // ); 41 | 42 | // final info = await infoApi.getInfo(); 43 | 44 | // expect(info.version, equals('1.0.0')); 45 | // expect(info.runtime, equals('go1.20')); 46 | // expect(info.os, equals('linux')); 47 | // expect(info.arch, equals('amd64')); 48 | // expect(info.inDocker, equals(false)); 49 | 50 | // verify(mockDio.get('/api/v1/info')).called(1); 51 | // }); 52 | 53 | // test('getInfo should handle error response', () async { 54 | // final errorResponse = { 55 | // 'code': 1001, 56 | // 'msg': 'Server error', 57 | // 'data': null, 58 | // }; 59 | 60 | // when(mockDio.get(any)).thenThrow( 61 | // DioException( 62 | // requestOptions: RequestOptions(path: ''), 63 | // response: Response( 64 | // requestOptions: RequestOptions(path: ''), 65 | // data: errorResponse, 66 | // statusCode: 500, 67 | // ), 68 | // error: ApiResponseException( 69 | // errorResponse['code'] as int, 70 | // errorResponse['msg'] as String, 71 | // ), 72 | // ), 73 | // ); 74 | 75 | // expect( 76 | // () => infoApi.getInfo(), 77 | // throwsA( 78 | // isA().having( 79 | // (e) => (e.error as ApiResponseException), 80 | // 'error', 81 | // isA() 82 | // .having((e) => e.code, 'code', equals(1001)) 83 | // .having((e) => e.message, 'message', equals('Server error')), 84 | // ), 85 | // ), 86 | // ); 87 | // }); 88 | 89 | // test('getInfo should handle timeout', () async { 90 | // when(mockDio.get(any)).thenThrow( 91 | // DioException( 92 | // requestOptions: RequestOptions(path: ''), 93 | // type: DioExceptionType.connectionTimeout, 94 | // error: const TimeoutException(), 95 | // ), 96 | // ); 97 | 98 | // expect( 99 | // () => infoApi.getInfo(), 100 | // throwsA( 101 | // isA().having( 102 | // (e) => e.error, 103 | // 'error', 104 | // isA(), 105 | // ), 106 | // ), 107 | // ); 108 | // }); 109 | // }); 110 | // } 111 | -------------------------------------------------------------------------------- /test/api/performance_test.dart: -------------------------------------------------------------------------------- 1 | // // Package imports: 2 | // import 'package:flutter_test/flutter_test.dart'; 3 | 4 | // // Project imports: 5 | // import 'package:hapee/gopeed_api/api.dart'; 6 | // import 'package:hapee/gopeed_models/models.dart'; 7 | 8 | // void main() { 9 | // group('API Performance Tests', () { 10 | // setUpAll(() { 11 | // Api.init('tcp', '127.0.0.1:9999', ''); 12 | // }); 13 | 14 | // test('Response Time Test', () async { 15 | // const iterations = 100; 16 | // final stopwatch = Stopwatch()..start(); 17 | 18 | // for (var i = 0; i < iterations; i++) { 19 | // await Api.infoApi.getInfo(); 20 | // } 21 | 22 | // stopwatch.stop(); 23 | // final averageResponseTime = stopwatch.elapsedMilliseconds / iterations; 24 | 25 | // // 平均响应时间应该小于 100ms 26 | // expect(averageResponseTime, lessThan(100)); 27 | // }); 28 | 29 | // test('Concurrent Requests Test', () async { 30 | // const concurrentRequests = 20; 31 | // final stopwatch = Stopwatch()..start(); 32 | 33 | // // 并发发送请求 34 | // await Future.wait( 35 | // List.generate( 36 | // concurrentRequests, 37 | // (_) => Api.infoApi.getInfo(), 38 | // ), 39 | // ); 40 | 41 | // stopwatch.stop(); 42 | // final totalTime = stopwatch.elapsedMilliseconds; 43 | 44 | // // 所有请求应该在 2 秒内完成 45 | // expect(totalTime, lessThan(2000)); 46 | // }); 47 | 48 | // test('Error Recovery Test', () async { 49 | // const iterations = 10; 50 | // int successCount = 0; 51 | 52 | // // 模拟不稳定的网络环境 53 | // for (var i = 0; i < iterations; i++) { 54 | // try { 55 | // await Api.taskApi.getTasks([Status.running]); 56 | // successCount++; 57 | // } catch (_) { 58 | // // 忽略错误 59 | // } 60 | // // 随机延迟模拟网络波动 61 | // await Future.delayed(Duration(milliseconds: 100 * i)); 62 | // } 63 | 64 | // // 成功率应该大于 80% 65 | // expect(successCount / iterations, greaterThan(0.8)); 66 | // }); 67 | 68 | // test('Memory Usage Test', () async { 69 | // final initialMemory = DateTime.now().millisecondsSinceEpoch; 70 | // const iterations = 1000; 71 | 72 | // // 重复创建和释放资源 73 | // for (var i = 0; i < iterations; i++) { 74 | // final request = Request(url: 'https://example.com/test$i.zip'); 75 | // await Api.resolveApi.resolve(request); 76 | // } 77 | 78 | // final memoryUsed = DateTime.now().millisecondsSinceEpoch - initialMemory; 79 | 80 | // // 内存增长应该在合理范围内 81 | // expect(memoryUsed, lessThan(5000)); // 5秒内完成 82 | // }); 83 | 84 | // test('Large Payload Test', () async { 85 | // // 创建大量任务并获取列表 86 | // const taskCount = 100; 87 | // final tasks = await Future.wait( 88 | // List.generate( 89 | // taskCount, 90 | // (i) => Api.taskApi.createTask( 91 | // CreateTask( 92 | // req: Request(url: 'https://example.com/test$i.zip'), 93 | // ), 94 | // ), 95 | // ), 96 | // ); 97 | 98 | // expect(tasks.length, equals(taskCount)); 99 | 100 | // // 获取所有任务详情 101 | // final stopwatch = Stopwatch()..start(); 102 | // final taskList = await Api.taskApi.getTasks([Status.ready]); 103 | // stopwatch.stop(); 104 | 105 | // // 处理大量数据的响应时间应该在合理范围内 106 | // expect(stopwatch.elapsedMilliseconds, lessThan(1000)); 107 | // expect(taskList.length, greaterThanOrEqualTo(taskCount)); 108 | // }); 109 | // }); 110 | // } 111 | -------------------------------------------------------------------------------- /test/api/resolve_api_test.dart: -------------------------------------------------------------------------------- 1 | // // Package imports: 2 | // import 'package:dio/dio.dart'; 3 | // import 'package:flutter_test/flutter_test.dart'; 4 | // import 'package:mockito/mockito.dart'; 5 | 6 | // // Project imports: 7 | // import 'package:hapee/gopeed_api/endpoints/resolve_api.dart'; 8 | // import 'package:hapee/gopeed_api/exceptions.dart'; 9 | // import 'package:hapee/app/core/models/gopeed_models/common/models.dart'; 10 | // import '../mocks.mocks.dart'; 11 | 12 | // void main() { 13 | // group('ResolveApi', () { 14 | // late MockDio mockDio; 15 | // late ResolveApi resolveApi; 16 | 17 | // setUp(() { 18 | // mockDio = MockDio(); 19 | // resolveApi = ResolveApi()..dio = mockDio; 20 | // }); 21 | 22 | // test('resolve should return resolve result', () async { 23 | // final mockResponse = { 24 | // 'code': 0, 25 | // 'msg': '', 26 | // 'data': { 27 | // 'id': 'resolve-1', 28 | // 'res': { 29 | // 'name': 'example.zip', 30 | // 'size': 1024, 31 | // 'range': true, 32 | // 'files': [ 33 | // { 34 | // 'name': 'example.zip', 35 | // 'path': '', 36 | // 'size': 1024, 37 | // 'req': {'url': 'https://example.com/example.zip'} 38 | // } 39 | // ], 40 | // 'hash': '' 41 | // } 42 | // } 43 | // }; 44 | 45 | // when(mockDio.post(any, data: anyNamed('data'))).thenAnswer( 46 | // (_) async => Response( 47 | // data: mockResponse, 48 | // statusCode: 200, 49 | // requestOptions: RequestOptions(path: ''), 50 | // ), 51 | // ); 52 | 53 | // final request = Request(url: 'https://example.com/example.zip'); 54 | // final result = await resolveApi.resolve(request); 55 | 56 | // expect(result.id, equals('resolve-1')); 57 | // expect(result.res.name, equals('example.zip')); 58 | // expect(result.res.size, equals(1024)); 59 | // expect(result.res.range, equals(true)); 60 | // expect(result.res.files.length, equals(1)); 61 | // expect(result.res.files[0].name, equals('example.zip')); 62 | // expect(result.res.files[0].size, equals(1024)); 63 | 64 | // verify(mockDio.post('/api/v1/resolve', data: request)).called(1); 65 | // }); 66 | 67 | // test('resolve should handle request cancellation', () async { 68 | // final cancelToken = CancelToken(); 69 | // cancelToken.cancel('Cancelled by user'); 70 | 71 | // expect( 72 | // () => resolveApi.resolve( 73 | // Request(url: 'https://example.com/test.zip'), 74 | // cancelToken: cancelToken, 75 | // ), 76 | // throwsA(isA().having( 77 | // (e) => e.type, 78 | // 'type', 79 | // equals(DioExceptionType.cancel), 80 | // )), 81 | // ); 82 | // }); 83 | 84 | // test('resolve should handle invalid URL', () async { 85 | // when(mockDio.post(any, data: anyNamed('data'))).thenThrow( 86 | // DioException( 87 | // requestOptions: RequestOptions(path: ''), 88 | // response: Response( 89 | // requestOptions: RequestOptions(path: ''), 90 | // data: { 91 | // 'code': 1001, 92 | // 'msg': 'Invalid URL format', 93 | // }, 94 | // statusCode: 400, 95 | // ), 96 | // error: ApiResponseException(1001, 'Invalid URL format'), 97 | // ), 98 | // ); 99 | 100 | // expect( 101 | // () => resolveApi.resolve(Request(url: 'invalid-url')), 102 | // throwsA(isA().having( 103 | // (e) => e.error, 104 | // 'error', 105 | // isA() 106 | // .having((e) => e.code, 'code', equals(1001)) 107 | // .having( 108 | // (e) => e.message, 'message', equals('Invalid URL format')), 109 | // )), 110 | // ); 111 | // }); 112 | // }); 113 | // } 114 | -------------------------------------------------------------------------------- /test/api/task_api_test.dart: -------------------------------------------------------------------------------- 1 | // // Package imports: 2 | // import 'package:dio/dio.dart'; 3 | // import 'package:flutter_test/flutter_test.dart'; 4 | // import 'package:mockito/mockito.dart'; 5 | 6 | // // Project imports: 7 | // import 'package:hapee/gopeed_api/endpoints/task_api.dart'; 8 | // import 'package:hapee/gopeed_models/models.dart'; 9 | // import '../mocks.mocks.dart'; 10 | 11 | // void main() { 12 | // group('TaskApi', () { 13 | // late MockDio mockDio; 14 | // late TaskApi taskApi; 15 | 16 | // setUp(() { 17 | // mockDio = MockDio(); 18 | // taskApi = TaskApi()..dio = mockDio; 19 | // }); 20 | 21 | // test('getTasks should return task list', () async { 22 | // final mockResponse = { 23 | // 'code': 0, 24 | // 'msg': '', 25 | // 'data': [ 26 | // { 27 | // 'id': '1', 28 | // 'protocol': 'http', 29 | // 'name': 'test.zip', 30 | // 'meta': { 31 | // 'req': {'url': 'https://example.com/test.zip'}, 32 | // 'opts': {'name': 'test.zip', 'path': '/downloads'} 33 | // }, 34 | // 'status': 'running', 35 | // 'uploading': false, 36 | // 'progress': { 37 | // 'used': 1000, 38 | // 'speed': 100, 39 | // 'downloaded': 500, 40 | // 'uploadSpeed': 0, 41 | // 'uploaded': 0 42 | // }, 43 | // 'size': 1000, 44 | // 'createdAt': '2023-01-01T00:00:00Z', 45 | // 'updatedAt': '2023-01-01T00:00:00Z' 46 | // } 47 | // ] 48 | // }; 49 | 50 | // when(mockDio.get(any)).thenAnswer( 51 | // (_) async => Response( 52 | // data: mockResponse, 53 | // statusCode: 200, 54 | // requestOptions: RequestOptions(path: ''), 55 | // ), 56 | // ); 57 | 58 | // final tasks = await taskApi.getTasks([Status.running]); 59 | 60 | // expect(tasks.length, equals(1)); 61 | // expect(tasks[0].id, equals('1')); 62 | // expect(tasks[0].name, equals('test.zip')); 63 | // expect(tasks[0].status, equals(Status.running)); 64 | // expect(tasks[0].progress.downloaded, equals(500)); 65 | 66 | // verify(mockDio.get('/api/v1/tasks?status=running')).called(1); 67 | // }); 68 | 69 | // test('createTask should return task id', () async { 70 | // const mockTaskId = 'new-task-id'; 71 | // final mockResponse = { 72 | // 'code': 0, 73 | // 'msg': '', 74 | // 'data': mockTaskId 75 | // }; 76 | 77 | // when(mockDio.post(any, data: anyNamed('data'))).thenAnswer( 78 | // (_) async => Response( 79 | // data: mockResponse, 80 | // statusCode: 200, 81 | // requestOptions: RequestOptions(path: ''), 82 | // ), 83 | // ); 84 | 85 | // final createTask = CreateTask( 86 | // req: Request(url: 'https://example.com/test.zip'), 87 | // ); 88 | 89 | // final taskId = await taskApi.createTask(createTask); 90 | 91 | // expect(taskId, equals(mockTaskId)); 92 | // verify(mockDio.post('/api/v1/tasks', data: createTask)).called(1); 93 | // }); 94 | 95 | // test('pauseTask should call correct endpoint', () async { 96 | // const taskId = 'task-1'; 97 | // final mockResponse = {'code': 0, 'msg': '', 'data': null}; 98 | 99 | // when(mockDio.put(any)).thenAnswer( 100 | // (_) async => Response( 101 | // data: mockResponse, 102 | // statusCode: 200, 103 | // requestOptions: RequestOptions(path: ''), 104 | // ), 105 | // ); 106 | 107 | // await taskApi.pauseTask(taskId); 108 | // verify(mockDio.put('/api/v1/tasks/$taskId/pause')).called(1); 109 | // }); 110 | 111 | // test('continueTask should call correct endpoint', () async { 112 | // const taskId = 'task-1'; 113 | // final mockResponse = {'code': 0, 'msg': '', 'data': null}; 114 | 115 | // when(mockDio.put(any)).thenAnswer( 116 | // (_) async => Response( 117 | // data: mockResponse, 118 | // statusCode: 200, 119 | // requestOptions: RequestOptions(path: ''), 120 | // ), 121 | // ); 122 | 123 | // await taskApi.continueTask(taskId); 124 | // verify(mockDio.put('/api/v1/tasks/$taskId/continue')).called(1); 125 | // }); 126 | 127 | // test('deleteTask should call correct endpoint', () async { 128 | // const taskId = 'task-1'; 129 | // final mockResponse = {'code': 0, 'msg': '', 'data': null}; 130 | 131 | // when(mockDio.delete(any)).thenAnswer( 132 | // (_) async => Response( 133 | // data: mockResponse, 134 | // statusCode: 200, 135 | // requestOptions: RequestOptions(path: ''), 136 | // ), 137 | // ); 138 | 139 | // await taskApi.deleteTask(taskId, true); 140 | // verify(mockDio.delete('/api/v1/tasks/$taskId?force=true')).called(1); 141 | // }); 142 | // }); 143 | // } 144 | -------------------------------------------------------------------------------- /test/create/view/create_page_test.dart: -------------------------------------------------------------------------------- 1 | // // ignore_for_file: prefer_const_constructors 2 | 3 | // import 'package:flutter/material.dart'; 4 | // import 'package:hapee/app/features/create/create.dart'; 5 | // import 'package:flutter_test/flutter_test.dart'; 6 | 7 | // void main() { 8 | // group('CreatePage', () { 9 | // group('route', () { 10 | // test('is routable', () { 11 | // expect(CreatePage.route(), isA()); 12 | // }); 13 | // }); 14 | 15 | // testWidgets('renders CreateView', (tester) async { 16 | // await tester.pumpWidget(MaterialApp(home: CreatePage())); 17 | // expect(find.byType(CreateView), findsOneWidget); 18 | // }); 19 | // }); 20 | // } 21 | -------------------------------------------------------------------------------- /test/create/view/widgets/create_body_test.dart: -------------------------------------------------------------------------------- 1 | // // ignore_for_file: prefer_const_constructors 2 | 3 | // import 'package:flutter/material.dart'; 4 | // import 'package:hapee/app/features/create/create.dart'; 5 | // import 'package:flutter_test/flutter_test.dart'; 6 | 7 | // void main() { 8 | // group('CreateBody', () { 9 | // testWidgets('renders Text', (tester) async { 10 | // await tester.pumpWidget( 11 | // MaterialApp(home: CreateBody()), 12 | // ); 13 | 14 | // expect(find.byType(Text), findsOneWidget); 15 | // }); 16 | // }); 17 | // } 18 | -------------------------------------------------------------------------------- /test/edge_cases/api_edge_cases_test.dart: -------------------------------------------------------------------------------- 1 | // // Package imports: 2 | // import 'package:dio/dio.dart'; 3 | // import 'package:flutter_test/flutter_test.dart'; 4 | 5 | // // Project imports: 6 | // import 'package:hapee/gopeed_api/api.dart'; 7 | // import 'package:hapee/gopeed_api/exceptions.dart'; 8 | // import 'package:hapee/gopeed_models/models.dart'; 9 | 10 | // void main() { 11 | // group('API Edge Cases Tests', () { 12 | // setUpAll(() { 13 | // Api.init('tcp', '127.0.0.1:9999', ''); 14 | // }); 15 | 16 | // group('Task API Edge Cases', () { 17 | // test('should handle empty task list', () async { 18 | // final tasks = await Api.taskApi.getTasks([Status.done]); 19 | // expect(tasks, isEmpty); 20 | // }); 21 | 22 | // test('should handle non-existent task', () async { 23 | // expect( 24 | // () => Api.taskApi.pauseTask('non-existent-id'), 25 | // throwsA(isA().having( 26 | // (e) => e.error, 27 | // 'error', 28 | // isA(), 29 | // )), 30 | // ); 31 | // }); 32 | 33 | // test('should handle invalid task status transition', () async { 34 | // final taskId = await Api.taskApi.createTask(CreateTask( 35 | // req: Request(url: 'https://example.com/test.zip'), 36 | // )); 37 | 38 | // // 尝试继续一个未暂停的任务 39 | // expect( 40 | // () => Api.taskApi.continueTask(taskId), 41 | // throwsA(isA().having( 42 | // (e) => e.error, 43 | // 'error', 44 | // isA(), 45 | // )), 46 | // ); 47 | // }); 48 | // }); 49 | 50 | // group('Config API Edge Cases', () { 51 | // test('should handle invalid config values', () async { 52 | // final config = await Api.configApi.getConfig(); 53 | 54 | // // 尝试设置无效的最大任务数 55 | // expect( 56 | // () => Api.configApi.putConfig(config.copyWith(maxRunning: -1)), 57 | // throwsA(isA().having( 58 | // (e) => e.error, 59 | // 'error', 60 | // isA(), 61 | // )), 62 | // ); 63 | // }); 64 | 65 | // test('should handle non-existent download directory', () async { 66 | // final config = await Api.configApi.getConfig(); 67 | 68 | // expect( 69 | // () => Api.configApi.putConfig(config.copyWith( 70 | // downloadDir: '/non/existent/path', 71 | // )), 72 | // throwsA(isA().having( 73 | // (e) => e.error, 74 | // 'error', 75 | // isA(), 76 | // )), 77 | // ); 78 | // }); 79 | // }); 80 | 81 | // group('Resolve API Edge Cases', () { 82 | // test('should handle malformed URLs', () async { 83 | // expect( 84 | // () => Api.resolveApi.resolve(Request(url: 'invalid-url')), 85 | // throwsA(isA().having( 86 | // (e) => e.error, 87 | // 'error', 88 | // isA(), 89 | // )), 90 | // ); 91 | // }); 92 | 93 | // test('should handle very long URLs', () async { 94 | // final longUrl = 'https://example.com/${'a' * 2048}'; 95 | // expect( 96 | // () => Api.resolveApi.resolve(Request(url: longUrl)), 97 | // throwsA(isA().having( 98 | // (e) => e.error, 99 | // 'error', 100 | // isA(), 101 | // )), 102 | // ); 103 | // }); 104 | 105 | // test('should handle special characters in URLs', () async { 106 | // final specialUrl = 'https://example.com/test file with spaces.zip'; 107 | // final result = await Api.resolveApi.resolve(Request(url: specialUrl)); 108 | // expect(result.id, isNotEmpty); 109 | // }); 110 | // }); 111 | 112 | // group('Network Edge Cases', () { 113 | // test('should handle slow network', () async { 114 | // // 模拟慢速网络 115 | // await Future.delayed(const Duration(seconds: 2)); 116 | // final info = await Api.infoApi.getInfo(); 117 | // expect(info.version, isNotEmpty); 118 | // }); 119 | 120 | // test('should handle request cancellation', () async { 121 | // final cancelToken = CancelToken(); 122 | // Future.delayed(const Duration(milliseconds: 100), () { 123 | // cancelToken.cancel('Cancelled by user'); 124 | // }); 125 | 126 | // expect( 127 | // () => Api.resolveApi.resolve( 128 | // Request(url: 'https://example.com/test.zip'), 129 | // cancelToken: cancelToken, 130 | // ), 131 | // throwsA(isA()), 132 | // ); 133 | // }); 134 | // }); 135 | // }); 136 | // } 137 | -------------------------------------------------------------------------------- /test/integration/download_workflow_test.dart: -------------------------------------------------------------------------------- 1 | // // Package imports: 2 | // import 'package:flutter_test/flutter_test.dart'; 3 | 4 | // // Project imports: 5 | // import 'package:hapee/gopeed_api/api.dart'; 6 | // import 'package:hapee/gopeed_models/models.dart'; 7 | 8 | // void main() { 9 | // group('Download Workflow Integration Tests', () { 10 | // setUpAll(() { 11 | // Api.init('tcp', '127.0.0.1:9999', ''); 12 | // }); 13 | 14 | // test('Complete download workflow', () async { 15 | // // 1. 检查服务器状态 16 | // final serverInfo = await Api.infoApi.getInfo(); 17 | // expect(serverInfo.version, isNotEmpty); 18 | 19 | // // 2. 获取并更新配置 20 | // final config = await Api.configApi.getConfig(); 21 | // await Api.configApi.putConfig(config.copyWith( 22 | // maxRunning: 3, 23 | // downloadDir: '/test-downloads', 24 | // )); 25 | 26 | // // 3. 解析下载链接 27 | // final request = Request(url: 'https://example.com/test.zip'); 28 | // final resolveResult = await Api.resolveApi.resolve(request); 29 | // expect(resolveResult.res.files, isNotEmpty); 30 | 31 | // // 4. 创建下载任务 32 | // final taskId = await Api.taskApi.createTask(CreateTask( 33 | // rid: resolveResult.id, 34 | // opt: Options( 35 | // name: resolveResult.res.files.first.name, 36 | // path: '/test-downloads', 37 | // ), 38 | // )); 39 | 40 | // // 5. 监控下载进度 41 | // bool isCompleted = false; 42 | // int retryCount = 0; 43 | // const maxRetries = 10; 44 | 45 | // while (!isCompleted && retryCount < maxRetries) { 46 | // final tasks = await Api.taskApi.getTasks([Status.running, Status.done]); 47 | // final task = tasks.firstWhere((t) => t.id == taskId); 48 | 49 | // if (task.status == Status.done) { 50 | // isCompleted = true; 51 | // } else { 52 | // // 测试暂停/继续功能 53 | // await Api.taskApi.pauseTask(taskId); 54 | // final pausedTasks = await Api.taskApi.getTasks([Status.pause]); 55 | // expect(pausedTasks.any((t) => t.id == taskId), isTrue); 56 | 57 | // await Api.taskApi.continueTask(taskId); 58 | // final runningTasks = await Api.taskApi.getTasks([Status.running]); 59 | // expect(runningTasks.any((t) => t.id == taskId), isTrue); 60 | 61 | // retryCount++; 62 | // await Future.delayed(const Duration(seconds: 1)); 63 | // } 64 | // } 65 | 66 | // // 6. 清理测试数据 67 | // await Api.taskApi.deleteTask(taskId, true); 68 | // final remainingTasks = await Api.taskApi.getTasks([Status.done]); 69 | // expect(remainingTasks.any((t) => t.id == taskId), isFalse); 70 | // }); 71 | // }); 72 | // } 73 | -------------------------------------------------------------------------------- /test/mocks.dart: -------------------------------------------------------------------------------- 1 | // Package imports: 2 | import 'package:dio/dio.dart'; 3 | import 'package:mockito/annotations.dart'; 4 | 5 | @GenerateMocks([Dio]) 6 | void main() {} 7 | -------------------------------------------------------------------------------- /test/sync/view/sync_page_test.dart: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- /test/sync/view/widgets/sync_body_test.dart: -------------------------------------------------------------------------------- 1 | // -------------------------------------------------------------------------------- /test/widget_test.dart: -------------------------------------------------------------------------------- 1 | // This is a basic Flutter widget test. 2 | // 3 | // To perform an interaction with a widget in your test, use the WidgetTester 4 | // utility in the flutter_test package. For example, you can send tap and scroll 5 | // gestures. You can also use WidgetTester to find child widgets in the widget 6 | // tree, read text, and verify that the values of widget properties are correct. 7 | 8 | // Flutter imports: 9 | import 'package:flutter/material.dart'; 10 | 11 | // Package imports: 12 | import 'package:flutter_test/flutter_test.dart'; 13 | 14 | // Project imports: 15 | import 'package:hapee/app/app.dart'; 16 | 17 | // import 'package:hapee/main.dart'; 18 | 19 | void main() { 20 | testWidgets('Counter increments smoke test', (WidgetTester tester) async { 21 | // Build our app and trigger a frame. 22 | await tester.pumpWidget(const App()); 23 | 24 | // Verify that our counter starts at 0. 25 | expect(find.text('0'), findsOneWidget); 26 | expect(find.text('1'), findsNothing); 27 | 28 | // Tap the '+' icon and trigger a frame. 29 | await tester.tap(find.byIcon(Icons.add)); 30 | await tester.pump(); 31 | 32 | // Verify that our counter has incremented. 33 | expect(find.text('0'), findsNothing); 34 | expect(find.text('1'), findsOneWidget); 35 | }); 36 | } 37 | -------------------------------------------------------------------------------- /tool.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | // 项目根目录 5 | final projectRoot = 'C:/Users/Administrator/StudioProjects/hapee_next/lib'; 6 | 7 | // 项目名称 8 | final packageName = 'hapee'; 9 | 10 | // 遍历项目中的所有 Dart 文件 11 | Directory(projectRoot).listSync(recursive: true).forEach((entity) { 12 | if (entity is File && entity.path.endsWith('.dart')) { 13 | final file = entity; 14 | final content = file.readAsStringSync(); 15 | 16 | // 使用正则表达式替换相对路径为 package 路径 17 | final newContent = content.replaceAllMapped( 18 | RegExp(r"import\s+'(\.\./)+(.+?);"), 19 | (match) => "import 'package:$packageName/${match.group(2)};", 20 | ); 21 | 22 | // 如果内容有变化,写回文件 23 | if (newContent != content) { 24 | file.writeAsStringSync(newContent); 25 | print('Updated imports in: ${file.path}'); 26 | } 27 | } 28 | }); 29 | } 30 | -------------------------------------------------------------------------------- /web/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/web/favicon.png -------------------------------------------------------------------------------- /web/icons/Icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/web/icons/Icon-192.png -------------------------------------------------------------------------------- /web/icons/Icon-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/web/icons/Icon-512.png -------------------------------------------------------------------------------- /web/icons/Icon-maskable-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/web/icons/Icon-maskable-192.png -------------------------------------------------------------------------------- /web/icons/Icon-maskable-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/web/icons/Icon-maskable-512.png -------------------------------------------------------------------------------- /web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | hapee 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /web/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hapee", 3 | "short_name": "hapee", 4 | "start_url": ".", 5 | "display": "standalone", 6 | "background_color": "#0175C2", 7 | "theme_color": "#0175C2", 8 | "description": "A new Flutter project.", 9 | "orientation": "portrait-primary", 10 | "prefer_related_applications": false, 11 | "icons": [ 12 | { 13 | "src": "icons/Icon-192.png", 14 | "sizes": "192x192", 15 | "type": "image/png" 16 | }, 17 | { 18 | "src": "icons/Icon-512.png", 19 | "sizes": "512x512", 20 | "type": "image/png" 21 | }, 22 | { 23 | "src": "icons/Icon-maskable-192.png", 24 | "sizes": "192x192", 25 | "type": "image/png", 26 | "purpose": "maskable" 27 | }, 28 | { 29 | "src": "icons/Icon-maskable-512.png", 30 | "sizes": "512x512", 31 | "type": "image/png", 32 | "purpose": "maskable" 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /windows/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral/ 2 | 3 | # Visual Studio user-specific files. 4 | *.suo 5 | *.user 6 | *.userosscache 7 | *.sln.docstates 8 | 9 | # Visual Studio build-related files. 10 | x64/ 11 | x86/ 12 | 13 | # Visual Studio cache files 14 | # files ending in .cache can be ignored 15 | *.[Cc]ache 16 | # but keep track of directories ending in .cache 17 | !*.[Cc]ache/ 18 | -------------------------------------------------------------------------------- /windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Project-level configuration. 2 | cmake_minimum_required(VERSION 3.14) 3 | 4 | project(hapee LANGUAGES CXX) 5 | 6 | # The name of the executable created for the application. Change this to change 7 | # the on-disk name of your application. 8 | set(BINARY_NAME "hapee") 9 | 10 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent 11 | # versions of CMake. 12 | cmake_policy(VERSION 3.14...3.25) 13 | 14 | # Define build configuration option. 15 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) 16 | if(IS_MULTICONFIG) 17 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" 18 | CACHE STRING "" FORCE) 19 | else() 20 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 21 | set(CMAKE_BUILD_TYPE "Debug" CACHE 22 | STRING "Flutter build mode" FORCE) 23 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 24 | "Debug" "Profile" "Release") 25 | endif() 26 | endif() 27 | # Define settings for the Profile build mode. 28 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") 29 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") 30 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") 31 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") 32 | 33 | # Use Unicode for all projects. 34 | add_definitions(-DUNICODE -D_UNICODE) 35 | 36 | # Compilation settings that should be applied to most targets. 37 | # 38 | # Be cautious about adding new options here, as plugins use this function by 39 | # default. In most cases, you should add new options to specific targets instead 40 | # of modifying this function. 41 | function(APPLY_STANDARD_SETTINGS TARGET) 42 | target_compile_features(${TARGET} PUBLIC cxx_std_17) 43 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") 44 | target_compile_options(${TARGET} PRIVATE /EHsc) 45 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") 46 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") 47 | endfunction() 48 | 49 | # Flutter library and tool build rules. 50 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 51 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 52 | 53 | # Application build; see runner/CMakeLists.txt. 54 | add_subdirectory("runner") 55 | 56 | 57 | # Generated plugin build rules, which manage building the plugins and adding 58 | # them to the application. 59 | include(flutter/generated_plugins.cmake) 60 | 61 | 62 | # === Installation === 63 | # Support files are copied into place next to the executable, so that it can 64 | # run in place. This is done instead of making a separate bundle (as on Linux) 65 | # so that building and running from within Visual Studio will work. 66 | set(BUILD_BUNDLE_DIR "$") 67 | # Make the "install" step default, as it's required to run. 68 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) 69 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 70 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 71 | endif() 72 | 73 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 74 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") 75 | 76 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 77 | COMPONENT Runtime) 78 | 79 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 80 | COMPONENT Runtime) 81 | 82 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 83 | COMPONENT Runtime) 84 | 85 | install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/libgopeed.dll" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 86 | COMPONENT Runtime) 87 | 88 | if(PLUGIN_BUNDLED_LIBRARIES) 89 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" 90 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 91 | COMPONENT Runtime) 92 | endif() 93 | 94 | # Copy the native assets provided by the build.dart from all packages. 95 | set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") 96 | install(DIRECTORY "${NATIVE_ASSETS_DIR}" 97 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 98 | COMPONENT Runtime) 99 | 100 | # Fully re-copy the assets directory on each build to avoid having stale files 101 | # from a previous install. 102 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 103 | install(CODE " 104 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 105 | " COMPONENT Runtime) 106 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 107 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 108 | 109 | # Install the AOT library on non-Debug builds only. 110 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 111 | CONFIGURATIONS Profile;Release 112 | COMPONENT Runtime) 113 | -------------------------------------------------------------------------------- /windows/CMakeSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "x64-Debug", 5 | "generator": "Ninja", 6 | "configurationType": "Debug", 7 | "inheritEnvironments": [ "msvc_x64_x64" ], 8 | "buildRoot": "${projectDir}\\out\\build\\${name}", 9 | "installRoot": "${projectDir}\\out\\install\\${name}", 10 | "cmakeCommandArgs": "", 11 | "buildCommandArgs": "", 12 | "ctestCommandArgs": "", 13 | "variables": [], 14 | "environments": [ 15 | { 16 | "PATH": "${env.PATH};C:\\Program Files\\Git\\bin" 17 | } 18 | ] 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /windows/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.14) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") 12 | 13 | # Set fallback configurations for older versions of the flutter tool. 14 | if (NOT DEFINED FLUTTER_TARGET_PLATFORM) 15 | set(FLUTTER_TARGET_PLATFORM "windows-x64") 16 | endif() 17 | 18 | # === Flutter Library === 19 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") 20 | 21 | # Published to parent scope for install step. 22 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 23 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 24 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 25 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) 26 | 27 | list(APPEND FLUTTER_LIBRARY_HEADERS 28 | "flutter_export.h" 29 | "flutter_windows.h" 30 | "flutter_messenger.h" 31 | "flutter_plugin_registrar.h" 32 | "flutter_texture_registrar.h" 33 | ) 34 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") 35 | add_library(flutter INTERFACE) 36 | target_include_directories(flutter INTERFACE 37 | "${EPHEMERAL_DIR}" 38 | ) 39 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") 40 | add_dependencies(flutter flutter_assemble) 41 | 42 | # === Wrapper === 43 | list(APPEND CPP_WRAPPER_SOURCES_CORE 44 | "core_implementations.cc" 45 | "standard_codec.cc" 46 | ) 47 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") 48 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN 49 | "plugin_registrar.cc" 50 | ) 51 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") 52 | list(APPEND CPP_WRAPPER_SOURCES_APP 53 | "flutter_engine.cc" 54 | "flutter_view_controller.cc" 55 | ) 56 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") 57 | 58 | # Wrapper sources needed for a plugin. 59 | add_library(flutter_wrapper_plugin STATIC 60 | ${CPP_WRAPPER_SOURCES_CORE} 61 | ${CPP_WRAPPER_SOURCES_PLUGIN} 62 | ) 63 | apply_standard_settings(flutter_wrapper_plugin) 64 | set_target_properties(flutter_wrapper_plugin PROPERTIES 65 | POSITION_INDEPENDENT_CODE ON) 66 | set_target_properties(flutter_wrapper_plugin PROPERTIES 67 | CXX_VISIBILITY_PRESET hidden) 68 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) 69 | target_include_directories(flutter_wrapper_plugin PUBLIC 70 | "${WRAPPER_ROOT}/include" 71 | ) 72 | add_dependencies(flutter_wrapper_plugin flutter_assemble) 73 | 74 | # Wrapper sources needed for the runner. 75 | add_library(flutter_wrapper_app STATIC 76 | ${CPP_WRAPPER_SOURCES_CORE} 77 | ${CPP_WRAPPER_SOURCES_APP} 78 | ) 79 | apply_standard_settings(flutter_wrapper_app) 80 | target_link_libraries(flutter_wrapper_app PUBLIC flutter) 81 | target_include_directories(flutter_wrapper_app PUBLIC 82 | "${WRAPPER_ROOT}/include" 83 | ) 84 | add_dependencies(flutter_wrapper_app flutter_assemble) 85 | 86 | # === Flutter tool backend === 87 | # _phony_ is a non-existent file to force this command to run every time, 88 | # since currently there's no way to get a full input/output list from the 89 | # flutter tool. 90 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") 91 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) 92 | add_custom_command( 93 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 94 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} 95 | ${CPP_WRAPPER_SOURCES_APP} 96 | ${PHONY_OUTPUT} 97 | COMMAND ${CMAKE_COMMAND} -E env 98 | ${FLUTTER_TOOL_ENVIRONMENT} 99 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" 100 | ${FLUTTER_TARGET_PLATFORM} $ 101 | VERBATIM 102 | ) 103 | add_custom_target(flutter_assemble DEPENDS 104 | "${FLUTTER_LIBRARY}" 105 | ${FLUTTER_LIBRARY_HEADERS} 106 | ${CPP_WRAPPER_SOURCES_CORE} 107 | ${CPP_WRAPPER_SOURCES_PLUGIN} 108 | ${CPP_WRAPPER_SOURCES_APP} 109 | ) 110 | -------------------------------------------------------------------------------- /windows/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | void RegisterPlugins(flutter::PluginRegistry* registry) { 14 | ConnectivityPlusWindowsPluginRegisterWithRegistrar( 15 | registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); 16 | SentryFlutterPluginRegisterWithRegistrar( 17 | registry->GetRegistrarForPlugin("SentryFlutterPlugin")); 18 | UrlLauncherWindowsRegisterWithRegistrar( 19 | registry->GetRegistrarForPlugin("UrlLauncherWindows")); 20 | } 21 | -------------------------------------------------------------------------------- /windows/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void RegisterPlugins(flutter::PluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /windows/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | connectivity_plus 7 | sentry_flutter 8 | url_launcher_windows 9 | ) 10 | 11 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 12 | ) 13 | 14 | set(PLUGIN_BUNDLED_LIBRARIES) 15 | 16 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 17 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) 18 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 19 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 20 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 21 | endforeach(plugin) 22 | 23 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 24 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) 25 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 26 | endforeach(ffi_plugin) 27 | -------------------------------------------------------------------------------- /windows/git_path.cmake: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/windows/git_path.cmake -------------------------------------------------------------------------------- /windows/libgopeed.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/windows/libgopeed.dll -------------------------------------------------------------------------------- /windows/libgopeed.h: -------------------------------------------------------------------------------- 1 | /* Code generated by cmd/cgo; DO NOT EDIT. */ 2 | 3 | /* package github.com/GopeedLab/gopeed/bind/desktop */ 4 | 5 | 6 | #line 1 "cgo-builtin-export-prolog" 7 | 8 | #include 9 | 10 | #ifndef GO_CGO_EXPORT_PROLOGUE_H 11 | #define GO_CGO_EXPORT_PROLOGUE_H 12 | 13 | #ifndef GO_CGO_GOSTRING_TYPEDEF 14 | typedef struct { const char *p; ptrdiff_t n; } _GoString_; 15 | #endif 16 | 17 | #endif 18 | 19 | /* Start of preamble from import "C" comments. */ 20 | 21 | 22 | 23 | 24 | /* End of preamble from import "C" comments. */ 25 | 26 | 27 | /* Start of boilerplate cgo prologue. */ 28 | #line 1 "cgo-gcc-export-header-prolog" 29 | 30 | #ifndef GO_CGO_PROLOGUE_H 31 | #define GO_CGO_PROLOGUE_H 32 | 33 | typedef signed char GoInt8; 34 | typedef unsigned char GoUint8; 35 | typedef short GoInt16; 36 | typedef unsigned short GoUint16; 37 | typedef int GoInt32; 38 | typedef unsigned int GoUint32; 39 | typedef long long GoInt64; 40 | typedef unsigned long long GoUint64; 41 | typedef GoInt64 GoInt; 42 | typedef GoUint64 GoUint; 43 | typedef size_t GoUintptr; 44 | typedef float GoFloat32; 45 | typedef double GoFloat64; 46 | #ifdef _MSC_VER 47 | #include 48 | typedef _Fcomplex GoComplex64; 49 | typedef _Dcomplex GoComplex128; 50 | #else 51 | typedef float _Complex GoComplex64; 52 | typedef double _Complex GoComplex128; 53 | #endif 54 | 55 | /* 56 | static assertion to make sure the file is being used on architecture 57 | at least with matching size of GoInt. 58 | */ 59 | typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1]; 60 | 61 | #ifndef GO_CGO_GOSTRING_TYPEDEF 62 | typedef _GoString_ GoString; 63 | #endif 64 | typedef void *GoMap; 65 | typedef void *GoChan; 66 | typedef struct { void *t; void *v; } GoInterface; 67 | typedef struct { void *data; GoInt len; GoInt cap; } GoSlice; 68 | 69 | #endif 70 | 71 | /* End of boilerplate cgo prologue. */ 72 | 73 | #ifdef __cplusplus 74 | extern "C" { 75 | #endif 76 | 77 | 78 | /* Return type for Start */ 79 | struct Start_return { 80 | GoInt r0; 81 | char* r1; 82 | }; 83 | extern __declspec(dllexport) struct Start_return Start(char* cfg); 84 | extern __declspec(dllexport) void Stop(); 85 | 86 | #ifdef __cplusplus 87 | } 88 | #endif 89 | -------------------------------------------------------------------------------- /windows/runner/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | project(runner LANGUAGES CXX) 3 | 4 | # Define the application target. To change its name, change BINARY_NAME in the 5 | # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer 6 | # work. 7 | # 8 | # Any new source files that you add to the application should be added here. 9 | add_executable(${BINARY_NAME} WIN32 10 | "flutter_window.cpp" 11 | "main.cpp" 12 | "utils.cpp" 13 | "win32_window.cpp" 14 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 15 | "Runner.rc" 16 | "runner.exe.manifest" 17 | ) 18 | 19 | # Apply the standard set of build settings. This can be removed for applications 20 | # that need different build settings. 21 | apply_standard_settings(${BINARY_NAME}) 22 | 23 | # Add preprocessor definitions for the build version. 24 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") 25 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") 26 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") 27 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") 28 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") 29 | 30 | # Disable Windows macros that collide with C++ standard library functions. 31 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") 32 | 33 | # Add dependency libraries and include directories. Add any application-specific 34 | # dependencies here. 35 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) 36 | target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") 37 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") 38 | 39 | # Run the Flutter tool portions of the build. This must not be removed. 40 | add_dependencies(${BINARY_NAME} flutter_assemble) 41 | -------------------------------------------------------------------------------- /windows/runner/Runner.rc: -------------------------------------------------------------------------------- 1 | // Microsoft Visual C++ generated resource script. 2 | // 3 | #pragma code_page(65001) 4 | #include "resource.h" 5 | 6 | #define APSTUDIO_READONLY_SYMBOLS 7 | ///////////////////////////////////////////////////////////////////////////// 8 | // 9 | // Generated from the TEXTINCLUDE 2 resource. 10 | // 11 | #include "winres.h" 12 | 13 | ///////////////////////////////////////////////////////////////////////////// 14 | #undef APSTUDIO_READONLY_SYMBOLS 15 | 16 | ///////////////////////////////////////////////////////////////////////////// 17 | // English (United States) resources 18 | 19 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) 20 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US 21 | 22 | #ifdef APSTUDIO_INVOKED 23 | ///////////////////////////////////////////////////////////////////////////// 24 | // 25 | // TEXTINCLUDE 26 | // 27 | 28 | 1 TEXTINCLUDE 29 | BEGIN 30 | "resource.h\0" 31 | END 32 | 33 | 2 TEXTINCLUDE 34 | BEGIN 35 | "#include ""winres.h""\r\n" 36 | "\0" 37 | END 38 | 39 | 3 TEXTINCLUDE 40 | BEGIN 41 | "\r\n" 42 | "\0" 43 | END 44 | 45 | #endif // APSTUDIO_INVOKED 46 | 47 | 48 | ///////////////////////////////////////////////////////////////////////////// 49 | // 50 | // Icon 51 | // 52 | 53 | // Icon with lowest ID value placed first to ensure application icon 54 | // remains consistent on all systems. 55 | IDI_APP_ICON ICON "resources\\app_icon.ico" 56 | 57 | 58 | ///////////////////////////////////////////////////////////////////////////// 59 | // 60 | // Version 61 | // 62 | 63 | #if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) 64 | #define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD 65 | #else 66 | #define VERSION_AS_NUMBER 1,0,0,0 67 | #endif 68 | 69 | #if defined(FLUTTER_VERSION) 70 | #define VERSION_AS_STRING FLUTTER_VERSION 71 | #else 72 | #define VERSION_AS_STRING "1.0.0" 73 | #endif 74 | 75 | VS_VERSION_INFO VERSIONINFO 76 | FILEVERSION VERSION_AS_NUMBER 77 | PRODUCTVERSION VERSION_AS_NUMBER 78 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK 79 | #ifdef _DEBUG 80 | FILEFLAGS VS_FF_DEBUG 81 | #else 82 | FILEFLAGS 0x0L 83 | #endif 84 | FILEOS VOS__WINDOWS32 85 | FILETYPE VFT_APP 86 | FILESUBTYPE 0x0L 87 | BEGIN 88 | BLOCK "StringFileInfo" 89 | BEGIN 90 | BLOCK "040904e4" 91 | BEGIN 92 | VALUE "CompanyName", "com.example" "\0" 93 | VALUE "FileDescription", "hapee" "\0" 94 | VALUE "FileVersion", VERSION_AS_STRING "\0" 95 | VALUE "InternalName", "hapee" "\0" 96 | VALUE "LegalCopyright", "Copyright (C) 2024 com.example. All rights reserved." "\0" 97 | VALUE "OriginalFilename", "hapee.exe" "\0" 98 | VALUE "ProductName", "hapee" "\0" 99 | VALUE "ProductVersion", VERSION_AS_STRING "\0" 100 | END 101 | END 102 | BLOCK "VarFileInfo" 103 | BEGIN 104 | VALUE "Translation", 0x409, 1252 105 | END 106 | END 107 | 108 | #endif // English (United States) resources 109 | ///////////////////////////////////////////////////////////////////////////// 110 | 111 | 112 | 113 | #ifndef APSTUDIO_INVOKED 114 | ///////////////////////////////////////////////////////////////////////////// 115 | // 116 | // Generated from the TEXTINCLUDE 3 resource. 117 | // 118 | 119 | 120 | ///////////////////////////////////////////////////////////////////////////// 121 | #endif // not APSTUDIO_INVOKED 122 | -------------------------------------------------------------------------------- /windows/runner/flutter_window.cpp: -------------------------------------------------------------------------------- 1 | #include "flutter_window.h" 2 | 3 | #include 4 | 5 | #include "flutter/generated_plugin_registrant.h" 6 | 7 | FlutterWindow::FlutterWindow(const flutter::DartProject& project) 8 | : project_(project) {} 9 | 10 | FlutterWindow::~FlutterWindow() {} 11 | 12 | bool FlutterWindow::OnCreate() { 13 | if (!Win32Window::OnCreate()) { 14 | return false; 15 | } 16 | 17 | RECT frame = GetClientArea(); 18 | 19 | // The size here must match the window dimensions to avoid unnecessary surface 20 | // creation / destruction in the startup path. 21 | flutter_controller_ = std::make_unique( 22 | frame.right - frame.left, frame.bottom - frame.top, project_); 23 | // Ensure that basic setup of the controller was successful. 24 | if (!flutter_controller_->engine() || !flutter_controller_->view()) { 25 | return false; 26 | } 27 | RegisterPlugins(flutter_controller_->engine()); 28 | SetChildContent(flutter_controller_->view()->GetNativeWindow()); 29 | 30 | flutter_controller_->engine()->SetNextFrameCallback([&]() { 31 | this->Show(); 32 | }); 33 | 34 | // Flutter can complete the first frame before the "show window" callback is 35 | // registered. The following call ensures a frame is pending to ensure the 36 | // window is shown. It is a no-op if the first frame hasn't completed yet. 37 | flutter_controller_->ForceRedraw(); 38 | 39 | return true; 40 | } 41 | 42 | void FlutterWindow::OnDestroy() { 43 | if (flutter_controller_) { 44 | flutter_controller_ = nullptr; 45 | } 46 | 47 | Win32Window::OnDestroy(); 48 | } 49 | 50 | LRESULT 51 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message, 52 | WPARAM const wparam, 53 | LPARAM const lparam) noexcept { 54 | // Give Flutter, including plugins, an opportunity to handle window messages. 55 | if (flutter_controller_) { 56 | std::optional result = 57 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, 58 | lparam); 59 | if (result) { 60 | return *result; 61 | } 62 | } 63 | 64 | switch (message) { 65 | case WM_FONTCHANGE: 66 | flutter_controller_->engine()->ReloadSystemFonts(); 67 | break; 68 | } 69 | 70 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam); 71 | } 72 | -------------------------------------------------------------------------------- /windows/runner/flutter_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_FLUTTER_WINDOW_H_ 2 | #define RUNNER_FLUTTER_WINDOW_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "win32_window.h" 10 | 11 | // A window that does nothing but host a Flutter view. 12 | class FlutterWindow : public Win32Window { 13 | public: 14 | // Creates a new FlutterWindow hosting a Flutter view running |project|. 15 | explicit FlutterWindow(const flutter::DartProject& project); 16 | virtual ~FlutterWindow(); 17 | 18 | protected: 19 | // Win32Window: 20 | bool OnCreate() override; 21 | void OnDestroy() override; 22 | LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, 23 | LPARAM const lparam) noexcept override; 24 | 25 | private: 26 | // The project to run. 27 | flutter::DartProject project_; 28 | 29 | // The Flutter instance hosted by this window. 30 | std::unique_ptr flutter_controller_; 31 | }; 32 | 33 | #endif // RUNNER_FLUTTER_WINDOW_H_ 34 | -------------------------------------------------------------------------------- /windows/runner/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "flutter_window.h" 6 | #include "utils.h" 7 | 8 | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, 9 | _In_ wchar_t *command_line, _In_ int show_command) { 10 | // Attach to console when present (e.g., 'flutter run') or create a 11 | // new console when running with a debugger. 12 | if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { 13 | CreateAndAttachConsole(); 14 | } 15 | 16 | // Initialize COM, so that it is available for use in the library and/or 17 | // plugins. 18 | ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); 19 | 20 | flutter::DartProject project(L"data"); 21 | 22 | std::vector command_line_arguments = 23 | GetCommandLineArguments(); 24 | 25 | project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); 26 | 27 | FlutterWindow window(project); 28 | Win32Window::Point origin(10, 10); 29 | Win32Window::Size size(1280, 720); 30 | if (!window.Create(L"hapee", origin, size)) { 31 | return EXIT_FAILURE; 32 | } 33 | window.SetQuitOnClose(true); 34 | 35 | ::MSG msg; 36 | while (::GetMessage(&msg, nullptr, 0, 0)) { 37 | ::TranslateMessage(&msg); 38 | ::DispatchMessage(&msg); 39 | } 40 | 41 | ::CoUninitialize(); 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /windows/runner/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by Runner.rc 4 | // 5 | #define IDI_APP_ICON 101 6 | 7 | // Next default values for new objects 8 | // 9 | #ifdef APSTUDIO_INVOKED 10 | #ifndef APSTUDIO_READONLY_SYMBOLS 11 | #define _APS_NEXT_RESOURCE_VALUE 102 12 | #define _APS_NEXT_COMMAND_VALUE 40001 13 | #define _APS_NEXT_CONTROL_VALUE 1001 14 | #define _APS_NEXT_SYMED_VALUE 101 15 | #endif 16 | #endif 17 | -------------------------------------------------------------------------------- /windows/runner/resources/app_icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hugetiny/Hapee/e4f8820c7a0f47a7394b04a494f8222c822f63c9/windows/runner/resources/app_icon.ico -------------------------------------------------------------------------------- /windows/runner/runner.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PerMonitorV2 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /windows/runner/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | void CreateAndAttachConsole() { 11 | if (::AllocConsole()) { 12 | FILE *unused; 13 | if (freopen_s(&unused, "CONOUT$", "w", stdout)) { 14 | _dup2(_fileno(stdout), 1); 15 | } 16 | if (freopen_s(&unused, "CONOUT$", "w", stderr)) { 17 | _dup2(_fileno(stdout), 2); 18 | } 19 | std::ios::sync_with_stdio(); 20 | FlutterDesktopResyncOutputStreams(); 21 | } 22 | } 23 | 24 | std::vector GetCommandLineArguments() { 25 | // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. 26 | int argc; 27 | wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); 28 | if (argv == nullptr) { 29 | return std::vector(); 30 | } 31 | 32 | std::vector command_line_arguments; 33 | 34 | // Skip the first argument as it's the binary name. 35 | for (int i = 1; i < argc; i++) { 36 | command_line_arguments.push_back(Utf8FromUtf16(argv[i])); 37 | } 38 | 39 | ::LocalFree(argv); 40 | 41 | return command_line_arguments; 42 | } 43 | 44 | std::string Utf8FromUtf16(const wchar_t* utf16_string) { 45 | if (utf16_string == nullptr) { 46 | return std::string(); 47 | } 48 | unsigned int target_length = ::WideCharToMultiByte( 49 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 50 | -1, nullptr, 0, nullptr, nullptr) 51 | -1; // remove the trailing null character 52 | int input_length = (int)wcslen(utf16_string); 53 | std::string utf8_string; 54 | if (target_length == 0 || target_length > utf8_string.max_size()) { 55 | return utf8_string; 56 | } 57 | utf8_string.resize(target_length); 58 | int converted_length = ::WideCharToMultiByte( 59 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 60 | input_length, utf8_string.data(), target_length, nullptr, nullptr); 61 | if (converted_length == 0) { 62 | return std::string(); 63 | } 64 | return utf8_string; 65 | } 66 | -------------------------------------------------------------------------------- /windows/runner/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_UTILS_H_ 2 | #define RUNNER_UTILS_H_ 3 | 4 | #include 5 | #include 6 | 7 | // Creates a console for the process, and redirects stdout and stderr to 8 | // it for both the runner and the Flutter library. 9 | void CreateAndAttachConsole(); 10 | 11 | // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string 12 | // encoded in UTF-8. Returns an empty std::string on failure. 13 | std::string Utf8FromUtf16(const wchar_t* utf16_string); 14 | 15 | // Gets the command line arguments passed in as a std::vector, 16 | // encoded in UTF-8. Returns an empty std::vector on failure. 17 | std::vector GetCommandLineArguments(); 18 | 19 | #endif // RUNNER_UTILS_H_ 20 | -------------------------------------------------------------------------------- /windows/runner/win32_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_WIN32_WINDOW_H_ 2 | #define RUNNER_WIN32_WINDOW_H_ 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | // A class abstraction for a high DPI-aware Win32 Window. Intended to be 11 | // inherited from by classes that wish to specialize with custom 12 | // rendering and input handling 13 | class Win32Window { 14 | public: 15 | struct Point { 16 | unsigned int x; 17 | unsigned int y; 18 | Point(unsigned int x, unsigned int y) : x(x), y(y) {} 19 | }; 20 | 21 | struct Size { 22 | unsigned int width; 23 | unsigned int height; 24 | Size(unsigned int width, unsigned int height) 25 | : width(width), height(height) {} 26 | }; 27 | 28 | Win32Window(); 29 | virtual ~Win32Window(); 30 | 31 | // Creates a win32 window with |title| that is positioned and sized using 32 | // |origin| and |size|. New windows are created on the default monitor. Window 33 | // sizes are specified to the OS in physical pixels, hence to ensure a 34 | // consistent size this function will scale the inputted width and height as 35 | // as appropriate for the default monitor. The window is invisible until 36 | // |Show| is called. Returns true if the window was created successfully. 37 | bool Create(const std::wstring& title, const Point& origin, const Size& size); 38 | 39 | // Show the current window. Returns true if the window was successfully shown. 40 | bool Show(); 41 | 42 | // Release OS resources associated with window. 43 | void Destroy(); 44 | 45 | // Inserts |content| into the window tree. 46 | void SetChildContent(HWND content); 47 | 48 | // Returns the backing Window handle to enable clients to set icon and other 49 | // window properties. Returns nullptr if the window has been destroyed. 50 | HWND GetHandle(); 51 | 52 | // If true, closing this window will quit the application. 53 | void SetQuitOnClose(bool quit_on_close); 54 | 55 | // Return a RECT representing the bounds of the current client area. 56 | RECT GetClientArea(); 57 | 58 | protected: 59 | // Processes and route salient window messages for mouse handling, 60 | // size change and DPI. Delegates handling of these to member overloads that 61 | // inheriting classes can handle. 62 | virtual LRESULT MessageHandler(HWND window, 63 | UINT const message, 64 | WPARAM const wparam, 65 | LPARAM const lparam) noexcept; 66 | 67 | // Called when CreateAndShow is called, allowing subclass window-related 68 | // setup. Subclasses should return false if setup fails. 69 | virtual bool OnCreate(); 70 | 71 | // Called when Destroy is called. 72 | virtual void OnDestroy(); 73 | 74 | private: 75 | friend class WindowClassRegistrar; 76 | 77 | // OS callback called by message pump. Handles the WM_NCCREATE message which 78 | // is passed when the non-client area is being created and enables automatic 79 | // non-client DPI scaling so that the non-client area automatically 80 | // responds to changes in DPI. All other messages are handled by 81 | // MessageHandler. 82 | static LRESULT CALLBACK WndProc(HWND const window, 83 | UINT const message, 84 | WPARAM const wparam, 85 | LPARAM const lparam) noexcept; 86 | 87 | // Retrieves a class instance pointer for |window| 88 | static Win32Window* GetThisFromHandle(HWND const window) noexcept; 89 | 90 | // Update the window frame's theme to match the system theme. 91 | static void UpdateTheme(HWND const window); 92 | 93 | bool quit_on_close_ = false; 94 | 95 | // window handle for top level window. 96 | HWND window_handle_ = nullptr; 97 | 98 | // window handle for hosted content. 99 | HWND child_content_ = nullptr; 100 | }; 101 | 102 | #endif // RUNNER_WIN32_WINDOW_H_ 103 | --------------------------------------------------------------------------------