Repository: vauvenal5/yaga Branch: master Commit: 0ac666be88c9 Files: 349 Total size: 496.8 KB Directory structure: gitextract_rmnzmdnm/ ├── .fvm/ │ └── fvm_config.json ├── .github/ │ └── workflows/ │ ├── build-android.yml │ └── publish-play-store.yml ├── .gitignore ├── .metadata ├── .vscode/ │ └── launch.json ├── Gemfile ├── LICENSE ├── README.md ├── analysis_options.yaml ├── android/ │ ├── .gitignore │ ├── app/ │ │ ├── build.gradle │ │ └── src/ │ │ ├── debug/ │ │ │ └── AndroidManifest.xml │ │ ├── dev/ │ │ │ └── res/ │ │ │ └── drawable/ │ │ │ └── ic_launcher_background.xml │ │ ├── main/ │ │ │ ├── AndroidManifest.xml │ │ │ ├── kotlin/ │ │ │ │ └── com/ │ │ │ │ └── github/ │ │ │ │ └── vauvenal5/ │ │ │ │ └── yaga/ │ │ │ │ └── MainActivity.kt │ │ │ └── res/ │ │ │ ├── drawable/ │ │ │ │ ├── ic_launcher_background.xml │ │ │ │ ├── ic_launcher_foreground.xml │ │ │ │ └── launch_background.xml │ │ │ ├── drawable-anydpi-v24/ │ │ │ │ └── ic_bg_service_small.xml │ │ │ ├── drawable-v21/ │ │ │ │ └── launch_background.xml │ │ │ ├── mipmap-anydpi-v26/ │ │ │ │ └── ic_launcher.xml │ │ │ ├── values/ │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ │ ├── values-night/ │ │ │ │ └── styles.xml │ │ │ └── xml/ │ │ │ └── file_paths_yaga.xml │ │ └── profile/ │ │ └── AndroidManifest.xml │ ├── build.gradle │ ├── gradle/ │ │ └── wrapper/ │ │ └── gradle-wrapper.properties │ ├── gradle.properties │ ├── settings.gradle │ └── settings_aar.gradle ├── assets/ │ ├── icon/ │ │ └── readme.md │ └── news.md ├── build.yaml ├── fastlane/ │ ├── Appfile │ ├── Fastfile │ └── metadata/ │ └── android/ │ └── en-US/ │ ├── changelogs/ │ │ ├── 134.txt │ │ ├── 140.txt │ │ ├── 141.txt │ │ ├── 142.txt │ │ ├── 143.txt │ │ ├── 144.txt │ │ ├── 145.txt │ │ ├── 146.txt │ │ ├── 147.txt │ │ ├── 150.txt │ │ ├── 151.txt │ │ ├── 1510.txt │ │ ├── 1511.txt │ │ ├── 152.txt │ │ ├── 153.txt │ │ ├── 154.txt │ │ ├── 155.txt │ │ ├── 156.txt │ │ ├── 157.txt │ │ ├── 158.txt │ │ ├── 159.txt │ │ ├── 1600.txt │ │ ├── 1601.txt │ │ ├── 1602.txt │ │ ├── 1603.txt │ │ ├── 1700.txt │ │ ├── 1701.txt │ │ ├── 1702.txt │ │ ├── 1703.txt │ │ ├── 1704.txt │ │ ├── 1705.txt │ │ ├── 1800.txt │ │ ├── 1801.txt │ │ ├── 1802.txt │ │ ├── 1900.txt │ │ ├── 1901.txt │ │ ├── 2000.txt │ │ ├── 2001.txt │ │ ├── 2002.txt │ │ ├── 2003.txt │ │ ├── 2100.txt │ │ ├── 2101.txt │ │ ├── 2102.txt │ │ ├── 2103.txt │ │ ├── 2104.txt │ │ ├── 2105.txt │ │ ├── 2200.txt │ │ ├── 2201.txt │ │ ├── 2202.txt │ │ ├── 2203.txt │ │ ├── 2204.txt │ │ ├── 2205.txt │ │ ├── 2206.txt │ │ ├── 2207.txt │ │ ├── 2208.txt │ │ ├── 2300.txt │ │ ├── 2301.txt │ │ ├── 2302.txt │ │ ├── 2303.txt │ │ ├── 2304.txt │ │ ├── 2305.txt │ │ ├── 2306.txt │ │ ├── 2307.txt │ │ ├── 2308.txt │ │ ├── 2309.txt │ │ ├── 2310.txt │ │ ├── 2311.txt │ │ ├── 2312.txt │ │ ├── 2400.txt │ │ ├── 2500.txt │ │ ├── 2501.txt │ │ ├── 2502.txt │ │ ├── 2503.txt │ │ ├── 2600.txt │ │ ├── 2601.txt │ │ ├── 2700.txt │ │ ├── 2701.txt │ │ ├── 2800.txt │ │ ├── 2801.txt │ │ ├── 2802.txt │ │ ├── 2803.txt │ │ ├── 2804.txt │ │ ├── 2805.txt │ │ ├── 2900.txt │ │ ├── 2901.txt │ │ ├── 2902.txt │ │ ├── 3000.txt │ │ ├── 3001.txt │ │ ├── 3002.txt │ │ ├── 3003.txt │ │ ├── 4000.txt │ │ ├── 4001.txt │ │ ├── 4002.txt │ │ ├── 4003.txt │ │ ├── 4004.txt │ │ ├── 4005.txt │ │ ├── 4100.txt │ │ ├── 4200.txt │ │ ├── 4201.txt │ │ ├── 4300.txt │ │ └── 4301.txt │ ├── full_description.txt │ ├── short_description.txt │ └── title.txt ├── ios/ │ ├── .gitignore │ ├── Flutter/ │ │ ├── AppFrameworkInfo.plist │ │ ├── Debug.xcconfig │ │ └── Release.xcconfig │ ├── Runner/ │ │ ├── AppDelegate.swift │ │ ├── Assets.xcassets/ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ └── Contents.json │ │ │ └── LaunchImage.imageset/ │ │ │ ├── Contents.json │ │ │ └── README.md │ │ ├── Base.lproj/ │ │ │ ├── LaunchScreen.storyboard │ │ │ └── Main.storyboard │ │ ├── Info.plist │ │ └── Runner-Bridging-Header.h │ ├── Runner.xcodeproj/ │ │ ├── project.pbxproj │ │ ├── project.xcworkspace/ │ │ │ └── contents.xcworkspacedata │ │ └── xcshareddata/ │ │ └── xcschemes/ │ │ └── Runner.xcscheme │ └── Runner.xcworkspace/ │ └── contents.xcworkspacedata ├── lib/ │ ├── main.dart │ ├── managers/ │ │ ├── file_manager/ │ │ │ ├── file_manager.dart │ │ │ ├── file_manager_base.dart │ │ │ └── isolateable/ │ │ │ ├── file_action_manager.dart │ │ │ └── isolated_file_manager.dart │ │ ├── file_service_manager/ │ │ │ ├── favorite_not_supported_mixin.dart │ │ │ ├── file_service_manager.dart │ │ │ ├── isolateable/ │ │ │ │ ├── local_file_manager.dart │ │ │ │ ├── nextcloud_background_file_manager.dart │ │ │ │ └── nextcloud_file_manger.dart │ │ │ └── media_file_manager.dart │ │ ├── global_settings_manager.dart │ │ ├── isolateable/ │ │ │ ├── isolated_global_settings_manager.dart │ │ │ ├── isolated_settings_manager.dart │ │ │ ├── mapping_manager.dart │ │ │ ├── sort_manager.dart │ │ │ └── sync_manager.dart │ │ ├── navigation_manager.dart │ │ ├── nextcloud_manager.dart │ │ ├── settings_manager.dart │ │ ├── settings_manager_base.dart │ │ ├── tab_manager.dart │ │ └── widget_local/ │ │ └── file_list_local_manager.dart │ ├── model/ │ │ ├── category_view_config.dart │ │ ├── fetched_file.dart │ │ ├── general_view_config.dart │ │ ├── local_file.dart │ │ ├── mapping_node.dart │ │ ├── nc_file.dart │ │ ├── nc_login_data.dart │ │ ├── nc_origin.dart │ │ ├── preferences/ │ │ │ ├── action_preference.dart │ │ │ ├── bool_preference.dart │ │ │ ├── choice_preference.dart │ │ │ ├── complex_preference.dart │ │ │ ├── int_preference.dart │ │ │ ├── mapping_preference.dart │ │ │ ├── preference.dart │ │ │ ├── section_preference.dart │ │ │ ├── serializable_preference.dart │ │ │ ├── serializers/ │ │ │ │ ├── base_type_serializer.dart │ │ │ │ ├── int_serializer.dart │ │ │ │ └── uri_serializer.dart │ │ │ ├── string_list_preference.dart │ │ │ ├── string_preference.dart │ │ │ ├── uri_preference.dart │ │ │ └── value_preference.dart │ │ ├── preview_fetch_meta.dart │ │ ├── route_args/ │ │ │ ├── choice_selector_screen_arguments.dart │ │ │ ├── directory_navigation_screen_arguments.dart │ │ │ ├── focus_view_arguments.dart │ │ │ ├── image_screen_arguments.dart │ │ │ ├── navigatable_screen_arguments.dart │ │ │ ├── path_selector_screen_arguments.dart │ │ │ └── settings_screen_arguments.dart │ │ ├── sort_config.dart │ │ ├── sorted_category_list.dart │ │ ├── sorted_file_folder_list.dart │ │ ├── sorted_file_list.dart │ │ ├── sync_file.dart │ │ └── system_location.dart │ ├── services/ │ │ ├── file_provider_service.dart │ │ ├── intent_service.dart │ │ ├── isolateable/ │ │ │ ├── local_file_service.dart │ │ │ ├── nextcloud_service.dart │ │ │ └── system_location_service.dart │ │ ├── media_file_service.dart │ │ ├── name_exchange_service.dart │ │ ├── secure_storage_service.dart │ │ ├── service.dart │ │ ├── shared_preferences_service.dart │ │ └── uri_name_resolver.dart │ ├── utils/ │ │ ├── background_worker/ │ │ │ ├── background_channel.dart │ │ │ ├── background_commands.dart │ │ │ ├── background_worker.dart │ │ │ ├── json_convertable.dart │ │ │ ├── messages/ │ │ │ │ ├── background_downloaded_request.dart │ │ │ │ └── background_init_msg.dart │ │ │ └── work_tracker.dart │ │ ├── download_file_image.dart │ │ ├── forground_worker/ │ │ │ ├── bridges/ │ │ │ │ ├── file_manager_bridge.dart │ │ │ │ ├── nextcloud_manager_bridge.dart │ │ │ │ └── settings_manager_bridge.dart │ │ │ ├── foreground_worker.dart │ │ │ ├── handlers/ │ │ │ │ ├── file_list_request_handler.dart │ │ │ │ ├── nextcloud_file_manager_handler.dart │ │ │ │ └── user_handler.dart │ │ │ ├── isolate_handler_regestry.dart │ │ │ ├── isolate_msg_handler.dart │ │ │ ├── isolateable.dart │ │ │ └── messages/ │ │ │ ├── download_file_request.dart │ │ │ ├── download_preview_complete.dart │ │ │ ├── download_preview_request.dart │ │ │ ├── file_list_done.dart │ │ │ ├── file_list_message.dart │ │ │ ├── file_list_request.dart │ │ │ ├── file_list_response.dart │ │ │ ├── file_update_msg.dart │ │ │ ├── files_action/ │ │ │ │ ├── delete_files_request.dart │ │ │ │ ├── destination_action_files_request.dart │ │ │ │ ├── favorite_files_request.dart │ │ │ │ ├── files_action_done.dart │ │ │ │ └── files_action_request.dart │ │ │ ├── flush_logs_message.dart │ │ │ ├── image_update_msg.dart │ │ │ ├── init_msg.dart │ │ │ ├── login_state_msg.dart │ │ │ ├── merge_sort_done.dart │ │ │ ├── merge_sort_request.dart │ │ │ ├── message.dart │ │ │ ├── preference_msg.dart │ │ │ ├── single_file_message.dart │ │ │ └── sort_request.dart │ │ ├── log_error_file_handler.dart │ │ ├── logger.dart │ │ ├── navigation/ │ │ │ ├── yaga_route_information_parser.dart │ │ │ ├── yaga_router.dart │ │ │ └── yaga_router_delegate.dart │ │ ├── ncfile_stream_extensions.dart │ │ ├── nextcloud_client_factory.dart │ │ ├── nextcloud_colors.dart │ │ ├── self_signed_cert_handler.dart │ │ ├── service_locator.dart │ │ └── uri_utils.dart │ └── views/ │ ├── screens/ │ │ ├── browse_view.dart │ │ ├── category_view_screen.dart │ │ ├── choice_selector_screen.dart │ │ ├── directory_screen.dart │ │ ├── directory_traversal_screen.dart │ │ ├── favorites_view.dart │ │ ├── focus_view.dart │ │ ├── home_view.dart │ │ ├── image_screen.dart │ │ ├── nc_address_screen.dart │ │ ├── nc_login_screen.dart │ │ ├── path_selector_screen.dart │ │ ├── settings_screen.dart │ │ ├── splash_screen.dart │ │ └── yaga_home_screen.dart │ └── widgets/ │ ├── action_danger_dialog.dart │ ├── address_form_advanced.dart │ ├── address_form_simple.dart │ ├── avatar_widget.dart │ ├── circle_avatar_icon.dart │ ├── favorite_icon.dart │ ├── folder_icon.dart │ ├── image_search.dart │ ├── image_view_container.dart │ ├── image_views/ │ │ ├── category_view.dart │ │ ├── category_view_exp.dart │ │ ├── nc_grid_view.dart │ │ ├── nc_list_view.dart │ │ └── utils/ │ │ ├── grid_delegate.dart │ │ └── view_configuration.dart │ ├── list_menu_entry.dart │ ├── path_widget.dart │ ├── preferences/ │ │ ├── action_preference_widget.dart │ │ ├── bool_preference_widget.dart │ │ ├── choice_preference_widget.dart │ │ ├── int_preference_widget.dart │ │ ├── mapping_preference_widget.dart │ │ ├── preference_list_tile_widget.dart │ │ ├── section_preference_widget.dart │ │ ├── string_preference_widget.dart │ │ └── uri_preference_widget.dart │ ├── remote_folder_widget.dart │ ├── remote_image_widget.dart │ ├── search_icon_button.dart │ ├── select_cancel_bottom_navigation.dart │ ├── selection_action_cancel_dialog.dart │ ├── selection_app_bar.dart │ ├── selection_popup_menu_button.dart │ ├── selection_select_all.dart │ ├── selection_title.dart │ ├── selection_will_pop_scope.dart │ ├── yaga_about_dialog.dart │ ├── yaga_bottom_nav_bar.dart │ ├── yaga_drawer.dart │ └── yaga_popup_menu_button.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 ├── pubspec.yaml └── test/ ├── managers/ │ └── isolateable/ │ └── mapping_manager_test.dart ├── utils/ │ └── uri_utils_test.dart └── widget_test.dart ================================================ FILE CONTENTS ================================================ ================================================ FILE: .fvm/fvm_config.json ================================================ { "flutterSdkVersion": "3.16.3", "flavors": {} } ================================================ FILE: .github/workflows/build-android.yml ================================================ name: Build Android on: workflow_dispatch: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Create Android Keystore id: android_keystore uses: timheuer/base64-to-file@v1.2 with: fileName: 'yaga.jks' encodedString: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} - name: Create key.properties run: | echo "storeFile=${{ steps.android_keystore.outputs.filePath }}" > android/key.properties echo "storePassword=${{ secrets.STORE_PASSWORD }}" >> android/key.properties echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> android/key.properties echo "keyAlias=${{ secrets.KEY_ALIAS }}" >> android/key.properties - uses: actions/setup-java@v3 with: distribution: 'temurin' java-version: '17' cache: 'gradle' - uses: subosito/flutter-action@v2 with: flutter-version: '3.16.3' channel: 'stable' cache: false - run: flutter pub get - run: flutter pub run build_runner build --delete-conflicting-outputs - run: flutter build appbundle --flavor play - uses: actions/upload-artifact@v3 with: name: app-play-release.aab path: ./build/app/outputs/bundle/playRelease/app-play-release.aab - name: Convert aab to apk id: convert_aab uses: mukeshsolanki/bundletool-action@v1.0.2 with: aabFile: ./build/app/outputs/bundle/playRelease/app-play-release.aab base64Keystore: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} keystorePassword: ${{ secrets.STORE_PASSWORD }} keystoreAlias: ${{ secrets.KEY_ALIAS }} keyPassword: ${{ secrets.KEY_PASSWORD }} bundletoolVersion: '1.15.6' - uses: actions/upload-artifact@v3 with: name: app-play-release.apk path: ${{ steps.convert_aab.outputs.apkPath }} internal: needs: build uses: vauvenal5/yaga/.github/workflows/publish-play-store.yml@master with: stage: 'internal' secrets: googlePlayJsonBase64: ${{ secrets.GOOGLE_PLAY_JSON_BASE64 }} alpha: needs: internal uses: vauvenal5/yaga/.github/workflows/publish-play-store.yml@master with: stage: 'alpha' secrets: googlePlayJsonBase64: ${{ secrets.GOOGLE_PLAY_JSON_BASE64 }} github: needs: internal uses: vauvenal5/yaga/.github/workflows/publish-play-store.yml@master with: stage: 'github' secrets: googlePlayJsonBase64: ${{ secrets.GOOGLE_PLAY_JSON_BASE64 }} beta: needs: alpha uses: vauvenal5/yaga/.github/workflows/publish-play-store.yml@master with: stage: 'beta' secrets: googlePlayJsonBase64: ${{ secrets.GOOGLE_PLAY_JSON_BASE64 }} ================================================ FILE: .github/workflows/publish-play-store.yml ================================================ name: Publish to Play Store on: workflow_call: inputs: stage: required: true type: string secrets: googlePlayJsonBase64: required: true jobs: publish: environment: ${{ inputs.stage }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/download-artifact@v3 if: ${{ inputs.stage == 'internal' || inputs.stage == 'github'}} with: name: app-play-release.aab path: ./build/app/outputs/bundle/playRelease - uses: actions/download-artifact@v3 if: ${{ inputs.stage == 'github' }} with: name: app-play-release.apk path: ./build/app/outputs/flutter-apk - uses: ruby/setup-ruby@v1 with: ruby-version: '3.0' # Not needed with a .ruby-version file bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Create Android Keystore id: android_keystore uses: timheuer/base64-to-file@v1.2 with: fileName: 'google-play.json' fileDir: './android/' encodedString: ${{ secrets.googlePlayJsonBase64 }} - run: cd fastlane - run: bundle exec fastlane ${{ inputs.stage }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .gitignore ================================================ # Miscellaneous *.class *.log *.pyc *.swp .DS_Store .atom/ .buildlog/ .history .svn/ docker docker/.dev # IntelliJ related *.iml *.ipr *.iws .idea/ # The .vscode folder contains launch configuration and tasks you configure in # VS Code which you may wish to be included in version control, so this line # is commented out by default. #.vscode/ # Flutter/Dart/Pub related **/doc/api/ .dart_tool/ .flutter-plugins .flutter-plugins-dependencies .packages .pub-cache/ .pub/ /build/ # Web related lib/generated_plugin_registrant.dart # Exceptions to above rules. !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages android/key.properties fastlane/README.md fastlane/report.xml android/google-play.json **/*.g.dart .env # Generated by flutter_launcher_icons package android/app/src/main/res/mipmap-hdpi/ic_launcher.png android/app/src/main/res/mipmap-mdpi/ic_launcher.png android/app/src/main/res/mipmap-xhdpi/ic_launcher.png android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png .fvm/flutter_sdk /yaga.jks /yaga.jks.base64 ================================================ FILE: .metadata ================================================ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: "b0366e0a3f089e15fd89c97604ab402fe26b724c" channel: "stable" project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c base_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c - platform: linux create_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c base_revision: b0366e0a3f089e15fd89c97604ab402fe26b724c # User provided section # List of Local paths (relative to this file) that should be # ignored by the migrate tool. # # Files that are not part of the templates will be ignored by default. unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj' ================================================ FILE: .vscode/launch.json ================================================ { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Flutter", "request": "launch", "args": [ "--flavor", "play" ], "type": "dart" }, { "name": "Flutter Profile", "request": "launch", "args": [ "--flavor", "play" ], "type": "dart", "flutterMode": "profile" } ] } ================================================ FILE: Gemfile ================================================ source "https://rubygems.org" gem "fastlane" ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # Nextcloud Yaga - Yet Another Gallery App ## Table of Contents * [State of Yaga](#state-of-yaga) * [Features](#features) * [Next Steps](#next-steps) * [Getting Started](#getting-started) * [Recomendations](#recomendations) * [iOS Support](#ios-support) * [Necessary work](#necessary-work) ## State of Yaga This app is in an open beta stage. It is tested and fairly stable on an Android One device with Android version 10. You can download it from Google Play. For more information on how to use the app [read the docs](https://vauvenal5.github.io/yaga-docs/). [Get it on Google Play](https://play.google.com/store/apps/details?id=com.github.vauvenal5.yaga) [Get it on F-Droid](https://f-droid.org/packages/com.github.vauvenal5.yaga) ### Features - Nextcloud login flow is implemented - Flutter WebView is used and some strange behavior can come from bugs in there. Usually retrying fixes the issue. - Login token is being persisted with the `flutter_secure_storage` plugin. - Category view - Displays images in groups sorted by date modified, as list, or as simple grid. - Path to display can be set in the view settings. - Path can be local or remote. - Browse view - Allows for browsing local and remote directories. - Has a focus mode implemented which allows to view current folder like in Category view without changing settings. - Image view - Opening an image from the category or browse view will result in a image view, displaying the image. - If opened from category view, displayed images are currently limited to the choosen date. - If opened from browser view, displayed images are limited to the current folder. - Images can be shared with other apps from this view. - Root Mapping - Allows to set directory mappings between local and remote directories. Basically allowing you to chose where to store your downloaded images or a subset of them. - Default mapping points to app folder. - Currently limited to one mapping. - Previews are always mapped to cache. ### Next Steps My current plan is to release a stable `v1.0.0` version around christmas this year. For this release I am aming to complete all features that are required for the app to feel like a complete gallery app with respect to the provided functionality. You can track planned features, current issues as well as what is sceduled for `v1.0.0` in the [issues](https://github.com/vauvenal5/yaga/issues) section. ## Building from Sources - Generate your own keystore as described in the flutter docs. - The project uses generation for some classes so you have to first run `flutter pub run build_runner build --delete-conflicting-outputs` - From the main directory then run: `flutter build apk --flavor play` - Copy the app to your device and make a local installation. ## Recomendations It is highly recommended to configure the image preview generator plugin on your Nextcloud server. This will significantly improve fetching times of previews. ## APK Signature If you decide to download the APK file attached to a Github release, you can verify the APK signature in the following way: ``` apksigner verify --print-certs app-play-release.apk ``` The output should look like this: ``` Signer #1 certificate DN: CN=vauvenal5, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown Signer #1 certificate SHA-256 digest: dd1652817e4ed5cbd341336add61a10851fd93b2b79c93124ec9d584fdc54b06 Signer #1 certificate SHA-1 digest: 1c54e02710c9ef669c0e75950e25825a5a11a349 Signer #1 certificate MD5 digest: 7f8367b3ebbc8618b1dc0dff81e225b9 ``` ## iOS Support I am physically unable to support iOS. I simply do not own the hardware and I also do not intend buying it. If Apple changes its policies about development SDKs I will gladly add iOS support. If somebody is willing to contribute the necessary steps for iOS support fell free to open a PR. ### Necessary work - It will be necessary to recheck the used libraries to see if they support iOS. (This I might do at some point in the future.) - Some things rely on Android only implementations, for example the storage paths. They need to be changed to a OS independent implementation. (This I might do at some point in the future.) - Necessary build configuration in the iOS project files. (Not going to happen for the time being.) - Publishing in the app store. (Not going to happen for the time being.) ================================================ FILE: analysis_options.yaml ================================================ include: package:lint/analysis_options.yaml linter: rules: sort_pub_dependencies: false ================================================ FILE: android/.gitignore ================================================ gradle-wrapper.jar /.gradle /captures/ /gradlew /gradlew.bat /local.properties GeneratedPluginRegistrant.java /google-play.json.base64 ================================================ FILE: android/app/build.gradle ================================================ def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion 34 sourceSets { main.java.srcDirs += 'src/main/kotlin' } lintOptions { disable 'InvalidPackage' } defaultConfig { applicationId "com.github.vauvenal5.yaga" minSdkVersion 24 targetSdkVersion 33 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } flavorDimensions "deploy" productFlavors { dev { dimension "deploy" applicationIdSuffix '.dev' versionNameSuffix "-dev" resValue "string", "app_name", "Yaga Dev" } play { dimension "deploy" resValue "string", "app_name", "Yaga" } // fdroid { // dimension "deploy" // resValue "string", "app_name", "Yaga" // signingConfig null // } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test:runner:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1' } ================================================ FILE: android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/dev/res/drawable/ic_launcher_background.xml ================================================ ================================================ FILE: android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/kotlin/com/github/vauvenal5/yaga/MainActivity.kt ================================================ package com.github.vauvenal5.yaga import android.content.Intent import android.net.Uri import android.util.Log import android.widget.Toast import androidx.annotation.NonNull import androidx.core.content.FileProvider import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugins.GeneratedPluginRegistrant import java.io.File import java.lang.IllegalArgumentException class MainActivity: FlutterActivity() { private val INTENT_CHANNEL = "yaga.channel.intent"; private val GET_INTENT_ACTION_METHOD = "getIntentAction"; private val GET_INTENT_TYPE_METHOD = "getIntentType"; private val GET_INTENT_SET_RESULT = "setSelectedFile"; private val ATTACH_DATA = "attachData"; override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { GeneratedPluginRegistrant.registerWith(flutterEngine); val intent = getIntent(); //todo: check if granted //todo: check if Android verison is high enough // Intent(Settings.ACTION_REQUEST_MANAGE_MEDIA).apply { // data = Uri.parse("package:$packageName") // try { // startActivityForResult(this, 303) // } catch (e: Exception) { // } // } MethodChannel(flutterEngine.dartExecutor.binaryMessenger, INTENT_CHANNEL).setMethodCallHandler { call, result -> if(call.method.contentEquals(GET_INTENT_ACTION_METHOD)) { result.success(intent.getAction()); } else if (call.method.contentEquals(GET_INTENT_TYPE_METHOD)) { result.success(intent.getType()); } else if (call.method.contentEquals(GET_INTENT_SET_RESULT)) { handleShareSelectedImageIntent(call, result) } else if (call.method.contentEquals(ATTACH_DATA)) { attachData(call, result) } else { result.notImplemented() } } } private fun attachData(call: MethodCall, resultChannel: MethodChannel.Result) { val resultIntent = prepIntent(call, resultChannel) resultIntent.setAction(Intent.ACTION_ATTACH_DATA) this.startActivity(Intent.createChooser(resultIntent, "Use picture as...")) resultChannel.success(null) } private fun handleShareSelectedImageIntent(call: MethodCall, resultChannel: MethodChannel.Result) { val resultIntent = prepIntent(call, resultChannel) setResult(RESULT_OK, resultIntent) resultChannel.success(true) finish() } private fun prepIntent(call: MethodCall, resultChannel: MethodChannel.Result): Intent { val resultIntent = Intent(); val path = call.argument("path"); val mime = call.argument("mime"); if(path == null || mime == null) { shareSelectedImageFailed(resultIntent, resultChannel) } val fileUri: Uri? = try { FileProvider.getUriForFile( this, this.packageName + ".fileprovider", File(path!!) ) } catch (e: IllegalArgumentException) { Log.e("File Provider", "Could not retrieve content url for file.", e) null } if(fileUri == null) { shareSelectedImageFailed(resultIntent, resultChannel) } resultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) resultIntent.setDataAndType(fileUri, mime) return resultIntent; } private fun shareSelectedImageFailed(resultIntent: Intent, resultChannel: MethodChannel.Result) { Toast.makeText(activity, "Failed to share image.", Toast.LENGTH_SHORT).show() resultIntent.setDataAndType(null, "") setResult(RESULT_CANCELED, resultIntent) resultChannel.success(false) finish() } //todo: this code might solve the copy issue // private fun addItem(name: String, filePath: String, mime: String): Uri { // val collection = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //// MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) // MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_INTERNAL) // } else { // MediaStore.Images.Media.EXTERNAL_CONTENT_URI // } // // var relativePath = filePath.split("/0/").last() // relativePath = relativePath.substring(0, relativePath.length - name.length - 1) // Log.i("MediaStore", relativePath); // // val values = ContentValues().apply { // put(MediaStore.Images.Media.DISPLAY_NAME, name) // put(MediaStore.Images.Media.MIME_TYPE, mime) // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //// put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + "Yaga") // put(MediaStore.MediaColumns.RELATIVE_PATH, relativePath) // put(MediaStore.Images.Media.IS_PENDING, 1) // } // } // // val resolver = applicationContext.contentResolver // val uri = resolver.insert(collection, values)!! // // try { //// resolver.openOutputStream(uri).use { os -> //// File(filePath).inputStream().use { it.copyTo(os!!) } //// } // // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // values.clear() // values.put(MediaStore.Images.Media.IS_PENDING, 0) // resolver.update(uri, values, null, null) // } // } catch (ex: IOException) { // Log.e("MediaStore", ex.message, ex) // } // // return uri; // } } ================================================ FILE: android/app/src/main/res/drawable/ic_launcher_background.xml ================================================ ================================================ FILE: android/app/src/main/res/drawable/ic_launcher_foreground.xml ================================================ ================================================ FILE: android/app/src/main/res/drawable/launch_background.xml ================================================ ================================================ FILE: android/app/src/main/res/drawable-anydpi-v24/ic_bg_service_small.xml ================================================ ================================================ FILE: android/app/src/main/res/drawable-v21/launch_background.xml ================================================ ================================================ FILE: android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: android/app/src/main/res/values/colors.xml ================================================ #0082c9 ================================================ FILE: android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: android/app/src/main/res/values-night/styles.xml ================================================ ================================================ FILE: android/app/src/main/res/xml/file_paths_yaga.xml ================================================ ================================================ FILE: android/app/src/profile/AndroidManifest.xml ================================================ ================================================ FILE: android/build.gradle ================================================ buildscript { ext.kotlin_version = '1.7.10' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.3.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } tasks.register("clean", Delete) { delete rootProject.buildDir } ================================================ FILE: android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: android/gradle.properties ================================================ org.gradle.jvmargs=-Xmx1536M android.enableR8=true android.useAndroidX=true android.enableJetifier=true ================================================ FILE: android/settings.gradle ================================================ include ':app' def flutterProjectRoot = rootProject.projectDir.parentFile.toPath() def plugins = new Properties() def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins') if (pluginsFile.exists()) { pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) } } plugins.each { name, path -> def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() include ":$name" project(":$name").projectDir = pluginDirectory } ================================================ FILE: android/settings_aar.gradle ================================================ include ':app' ================================================ FILE: assets/icon/readme.md ================================================ # Android Icons The SVG files found in this directory are the lead files for the app icons. For API 26+ changes to the SVGs have to be manually propagated to the respective VectorDrawables in `../android/app/src/main/resources/drawable`. For APIs smaller then 26 a `icon.png` has to be created from `icon.svg`. Then run the following command to generate the required icons. ```sh flutter pub run flutter_launcher_icons:main -f pubspec.yaml ``` ================================================ FILE: assets/news.md ================================================ ## What's New **Breaking Changes:** Started with refactoring for Android 11+ support. This has major impact on the app, please consider raising any issues you discover on Github. Refer to the docs for more information. **FDroid release will not be updated for the time being if you need any of the removed features and are still on Android 10 (API Level 29) or lower consider installing from there.** ## Changelog - targeting Android 12 (API Level 31) - refactoring to MediaStore API for local file access - root mapping deprecated: will be refactored in future when full MediaStore API support is implemented - automatically resetting root mapping to revert back to default app directory - local move/copy are currently not supported - local delete is supported but requires user confirmation - on Android 12 (API 31+) you can assign MANAGE_MEDIA rights to the app to avoid delete confirmation dialog - SD card support is broken - file provider for other apps is fixed - about app dialog was updated to support news ================================================ FILE: build.yaml ================================================ targets: $default: auto_apply_builders: true builders: "built_value_generator:built_value": enabled: true generate_for: - lib/model/preferences/*.dart ================================================ FILE: fastlane/Appfile ================================================ json_key_file("./android/google-play.json") # Path to the json secret file - Follow https://docs.fastlane.tools/actions/supply/#setup to get one package_name("com.github.vauvenal5.yaga") # e.g. com.krausefx.app ================================================ FILE: fastlane/Fastfile ================================================ # This file contains the fastlane.tools configuration # You can find the documentation at https://docs.fastlane.tools # # For a list of all available actions, check out # # https://docs.fastlane.tools/actions # # For a list of all available plugins, check out # # https://docs.fastlane.tools/plugins/available-plugins # # Uncomment the line if you want fastlane to automatically update itself # update_fastlane default_platform(:android) platform :android do lane :internal do # Dir.chdir("..") do # sh("flutter build appbundle --flavor play") # end upload_to_play_store( track: 'internal', aab: './build/app/outputs/bundle/playRelease/app-play-release.aab', skip_upload_apk: 'true', skip_upload_metadata: 'true', skip_upload_images: 'true', skip_upload_screenshots: 'true', ) end lane :alpha do upload_to_play_store( track: 'internal', track_promote_to: 'alpha', version_code: get_code(), skip_upload_aab: 'true', skip_upload_apk: 'true', skip_upload_metadata: 'true', skip_upload_images: 'true', skip_upload_screenshots: 'true', ) end lane :beta do upload_to_play_store( track: 'alpha', track_promote_to: 'beta', version_code: get_code(), skip_upload_aab: 'true', skip_upload_apk: 'true', skip_upload_metadata: 'true', skip_upload_images: 'true', skip_upload_screenshots: 'true', ) end lane :meta do upload_to_play_store( track: 'beta', version_code: get_code(), skip_upload_aab: 'true', skip_upload_apk: 'true', ) end lane :github do # Dir.chdir("..") do # sh("flutter build apk --flavor play") # end version = get_version() code = get_code() set_github_release( repository_name: "vauvenal5/yaga", # api_token: ENV["GITHUB_TOKEN"], # for local use api_bearer: ENV["GITHUB_TOKEN"], # for Github actions name: version, tag_name: version, description: (File.read("metadata/android/en-US/changelogs/"+code.to_s+".txt") rescue "No changelog provided."), commitish: "master", upload_assets: ["./build/app/outputs/flutter-apk/app-play-release.apk"] ) end def get_version_or_code(capture) pubspec = File.read('../pubspec.yaml') regex = /version:\s(\d+\.\d+\.\d+)\+(\d+)/ return pubspec[regex, capture] end def get_version() return "v"+get_version_or_code(1) end def get_code() return get_version_or_code(2).to_i end end ================================================ FILE: fastlane/metadata/android/en-US/changelogs/134.txt ================================================ - fixed general settings login/logout bug - added splashscreen ================================================ FILE: fastlane/metadata/android/en-US/changelogs/140.txt ================================================ - introduced focus mode to browse view ================================================ FILE: fastlane/metadata/android/en-US/changelogs/141.txt ================================================ - introduced focus mode to browse view - fix title in focus mode ================================================ FILE: fastlane/metadata/android/en-US/changelogs/142.txt ================================================ - introduced focus mode to browse view - fix title in focus mode - minor improvement to drop down menus ================================================ FILE: fastlane/metadata/android/en-US/changelogs/143.txt ================================================ - introduced focus mode to browse view - fix title in focus mode - minor improvement to drop down menus - fix isolates to properly shutdown/startup on app state change ================================================ FILE: fastlane/metadata/android/en-US/changelogs/144.txt ================================================ - introduced focus mode to browse view - fix title in focus mode - minor improvement to drop down menus - fix isolates to properly shutdown/startup on app state change - fix isolate startup ================================================ FILE: fastlane/metadata/android/en-US/changelogs/145.txt ================================================ - introduced focus mode to browse view - fix title in focus mode - minor improvement to drop down menus - fix isolates to properly shutdown/startup on app state change - fix isolate startup - minor visual improvements - code improvements ================================================ FILE: fastlane/metadata/android/en-US/changelogs/146.txt ================================================ - introduced focus mode to browse view - fix title in focus mode - minor improvement to drop down menus - fix isolates to properly shutdown/startup on app state change - fix isolate startup - minor visual improvements - code improvements - fix to laoding mapper setting ================================================ FILE: fastlane/metadata/android/en-US/changelogs/147.txt ================================================ - fix recursive loading when offline - fix recursive loading for local device ================================================ FILE: fastlane/metadata/android/en-US/changelogs/150.txt ================================================ - implement GET_CONTENT handler - introduce navigator 2.0 to directory traversal ================================================ FILE: fastlane/metadata/android/en-US/changelogs/151.txt ================================================ - add ACTION_PICK filter ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1510.txt ================================================ - fix memory leak when downloading a lot of previews - fix UI freeze when loading a lot of directories recursively ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1511.txt ================================================ - fix mapping manager when mapping non root folder - fix url validation ================================================ FILE: fastlane/metadata/android/en-US/changelogs/152.txt ================================================ - implement GET_CONTENT handler - introduce navigator 2.0 to directory traversal - add ACTION_PICK filter - open default screen for image select ================================================ FILE: fastlane/metadata/android/en-US/changelogs/153.txt ================================================ - implement GET_CONTENT handler - introduce navigator 2.0 to directory traversal - add ACTION_PICK filter - open default screen for image select - fix removal of upstream removed folders ================================================ FILE: fastlane/metadata/android/en-US/changelogs/154.txt ================================================ - implement GET_CONTENT handler - introduce navigator 2.0 to directory traversal - add ACTION_PICK filter - open default screen for image select - fix removal of upstream removed folders - fix recursive update issue from browse to home view ================================================ FILE: fastlane/metadata/android/en-US/changelogs/155.txt ================================================ - implement GET_CONTENT handler - introduce navigator 2.0 to directory traversal - add ACTION_PICK filter - open default screen for image select - fix removal of upstream removed folders - fix recursive update issue from browse to home view - fix memory leak ================================================ FILE: fastlane/metadata/android/en-US/changelogs/156.txt ================================================ - implement GET_CONTENT handler - introduce navigator 2.0 to directory traversal - add ACTION_PICK filter - open default screen for image select - fix removal of upstream removed folders - fix recursive update issue from browse to home view - fix memory leak - fix browse view recursive issue when entering focus view ================================================ FILE: fastlane/metadata/android/en-US/changelogs/157.txt ================================================ This release is identical to v0.15.6. There were build changes for FDroid support. - implement GET_CONTENT handler - introduce navigator 2.0 to directory traversal - add ACTION_PICK filter - open default screen for image select - fix removal of upstream removed folders - fix recursive update issue from browse to home view - fix memory leak - fix browse view recursive issue when entering focus view ================================================ FILE: fastlane/metadata/android/en-US/changelogs/158.txt ================================================ - fix memory leak when downloading a lot of previews - fix UI freeze when loading a lot of directories recursively ================================================ FILE: fastlane/metadata/android/en-US/changelogs/159.txt ================================================ - fix memory leak when downloading a lot of previews - fix UI freeze when loading a lot of directories recursively ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1600.txt ================================================ - add switch to disable URL validation in login mask ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1601.txt ================================================ - enable production logging for warn and err ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1602.txt ================================================ - enable production logging for warn and err - correctly set log level ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1603.txt ================================================ - fix username handling with special characters ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1700.txt ================================================ - introducing multi-select ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1701.txt ================================================ - introducing multi-select - allow sharing of multiple images ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1702.txt ================================================ - introducing multi-select - allow sharing of multiple images - fix ripple effect on image tiles ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1703.txt ================================================ - introducing multi-select - allow sharing of multiple images - fix ripple effect on image tiles - fix NC behinde subpath issue - fix fixedOrigin propagation for root mapping ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1704.txt ================================================ - introducing multi-select - allow sharing of multiple images - fix ripple effect on image tiles - fix NC behinde subpath issue - fix fixedOrigin propagation for root mapping - replace button bar with bottom nav to align style and fix reder issue ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1705.txt ================================================ - introducing multi-select - allow sharing of multiple images - fix ripple effect on image tiles - fix NC behinde subpath issue - fix fixedOrigin propagation for root mapping - replace button bar with bottom nav to align style and fix reder issue - fix issue of app not being properly navigated to grant access site ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1800.txt ================================================ - delete file locally and remotely - fix recursive remove on server detection ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1801.txt ================================================ - delete file locally and remotely - fix recursive remove on server detection - fix broken communication after background ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1802.txt ================================================ - fix bug when login name and user name are not the same ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1900.txt ================================================ - add browser based login flow as alternative to webview ================================================ FILE: fastlane/metadata/android/en-US/changelogs/1901.txt ================================================ - fix broken cancel button on login screen - fix endless loading indicator when preview download fails - fix show user agent in browser login flow - fix persisting unchanged mapping issue ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2000.txt ================================================ - implement support for copying files - implement support for moving files ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2001.txt ================================================ - implement support for copying files - implement support for moving files - !!! please note: if file exists in destination it will be overwritten !!! ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2002.txt ================================================ - implement support for copying files - implement support for moving files - ignore same destination actions - !!! please note: if file exists in destination it will be overwritten !!! ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2003.txt ================================================ - implement support for copying files - implement support for moving files - ignore same destination actions - ask for overwrite mode ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2100.txt ================================================ - implement avatar caching - disable multi-select in path selector view ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2101.txt ================================================ - implement avatar caching - disable multi-select in path selector view - add warning dialog for root mapping ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2102.txt ================================================ - fix lost data issue by making delete syncs optional ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2103.txt ================================================ - move sorting to background ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2104.txt ================================================ - move sorting to background ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2105.txt ================================================ - move sorting to background ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2200.txt ================================================ - introducing simple support for self-signed certificates ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2201.txt ================================================ - fix local name handling if file/folder containes encoded chars (#86) ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2202.txt ================================================ - fix local name handling if file/folder containes encoded chars (#86) ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2203.txt ================================================ - improve logging ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2204.txt ================================================ - fix minor issue in special char handling - improve logging ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2205.txt ================================================ - fix color gradient - refactor icon - fix jumping splash screen ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2206.txt ================================================ - fix color gradient - refactor icon - fix jumping splash screen ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2207.txt ================================================ - fix color gradient - refactor icon - fix jumping splash screen ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2208.txt ================================================ - remove host check from unsigned cert checks - fix bug in auto-revoking on exception ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2300.txt ================================================ - add ability to send logs from within app - improve logging - improve self-signed cert usability ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2301.txt ================================================ - add ability to send logs from within app - improve logging - improve self-signed cert usability ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2302.txt ================================================ - add ability to send logs from within app - improve logging - improve self-signed cert usability - fix for fdroid build ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2303.txt ================================================ - improve logging in list error cases - replace loading indicator for previews with default image ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2304.txt ================================================ - improve performance when loading previews for many files ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2305.txt ================================================ - improve performance when loading previews for many files ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2306.txt ================================================ - improve performance when loading previews for many files ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2307.txt ================================================ - improve performance when loading previews for many files ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2308.txt ================================================ - improve performance when loading previews for many files ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2309.txt ================================================ - fix broken preview of local files ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2310.txt ================================================ - fix image scroll controler ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2311.txt ================================================ - move download to background ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2312.txt ================================================ - move download to background - fix bug in category search ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2400.txt ================================================ - implement switch for auto persist on download ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2500.txt ================================================ - implement download files select action ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2501.txt ================================================ - fix url validation issue - improve logging ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2502.txt ================================================ - major upgrade of dependencies - fixes folder names that look like ports issue ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2503.txt ================================================ - add confirmation dialog for logout - re-work preview fetching ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2600.txt ================================================ - experimental sd card support, pls read https://github.com/vauvenal5/yaga/issues/23 ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2601.txt ================================================ - experimental sd card support, pls read https://github.com/vauvenal5/yaga/issues/23 ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2700.txt ================================================ - targeting Android 12 (API Level 31) - refactoring to MediaStore API for local file access - root mapping deprecated - automatically resetting root mapping - local move/copy are currently not supported - local delete is supported but requires user confirmation - on Android 12 (API 31+) you can assign MANAGE_MEDIA rights to avoid delete confirmation dialog - SD card support is broken - file provider for other apps is fixed - about app dialog was updated to support news ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2701.txt ================================================ - targeting Android 12 (API Level 31) - refactoring to MediaStore API for local file access - root mapping deprecated - automatically resetting root mapping - local move/copy are currently not supported - local delete is supported but requires user confirmation - on Android 12 (API 31+) you can assign MANAGE_MEDIA rights to avoid delete confirmation dialog - SD card support is broken - file provider for other apps fixed - about app dialog was updated to support news - privacy policy link added ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2800.txt ================================================ - moved file actions into background thread - background feature can be switched on and off in general settings ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2801.txt ================================================ - moved file actions into background thread - background feature can be switched on and off in general settings ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2802.txt ================================================ - add support for attach to functionality of Android (needed for wallpapers) ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2803.txt ================================================ - enable hidding of app bar in image view by tap ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2804.txt ================================================ - enable hidding of app bar in image view by tap - enable hidding of android overlays ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2805.txt ================================================ - enable hidding of app bar in image view by tap - enable hidding of android overlays ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2900.txt ================================================ - implement slideshow feature ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2901.txt ================================================ - implement slideshow feature - add wakelock ================================================ FILE: fastlane/metadata/android/en-US/changelogs/2902.txt ================================================ - implement slideshow feature - add wakelock - add random mode - add back to beginning - add auto stop at end ================================================ FILE: fastlane/metadata/android/en-US/changelogs/3000.txt ================================================ - replace deprecated NC client with new one ================================================ FILE: fastlane/metadata/android/en-US/changelogs/3001.txt ================================================ - replace deprecated NC client with new one - fix file action dialog in foreground worker mode ================================================ FILE: fastlane/metadata/android/en-US/changelogs/3002.txt ================================================ - replace deprecated NC client with new one - fix file action dialog in foreground worker mode - refactor background bridge ================================================ FILE: fastlane/metadata/android/en-US/changelogs/3003.txt ================================================ - minor fixes in file action handling - new Nextcloud client version ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4000.txt ================================================ - implement favorites view ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4001.txt ================================================ - mark favorites in lists and grids ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4002.txt ================================================ - fix favorites icon color - migrate to newest nextcloud client version ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4003.txt ================================================ - fix minor issue with special characters in folder names ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4004.txt ================================================ - fix minor issue with special characters in folder names - internal testing of Github releases ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4005.txt ================================================ - fix minor issue with special characters in folder names - internal testing of Github releases ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4100.txt ================================================ - add minimal linux support - refactor views to support big screens - fix missing permission bug ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4200.txt ================================================ - favorites can be set and removed from app - reworked select all to smart select - some code clean up ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4201.txt ================================================ - fix bug when persisting image is disabled ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4300.txt ================================================ - add download button to image view - add favorite button to image view - add keybindings for linux (left/right arrow --- navigate, page up/down --- navigate, f --- Favorite) ================================================ FILE: fastlane/metadata/android/en-US/changelogs/4301.txt ================================================ - fix offline support ================================================ FILE: fastlane/metadata/android/en-US/full_description.txt ================================================ Nextcloud Yaga is a Nextcloud first gallery app. It aimes to give you the full functionality of a modern gallery app while utilizing your private Nextcloud server as backend. You can find the documentation here: https://vauvenal5.github.io/yaga-docs/ For details on the development state and currently implemented features, have a look on the Github page. https://github.com/vauvenal5/yaga ================================================ FILE: fastlane/metadata/android/en-US/short_description.txt ================================================ A Nextcloud first gallery app. ================================================ FILE: fastlane/metadata/android/en-US/title.txt ================================================ Nextcloud Yaga ================================================ FILE: ios/.gitignore ================================================ *.mode1v3 *.mode2v3 *.moved-aside *.pbxuser *.perspectivev3 **/*sync/ .sconsign.dblite .tags* **/.vagrant/ **/DerivedData/ Icon? **/Pods/ **/.symlinks/ profile xcuserdata **/.generated/ Flutter/App.framework Flutter/Flutter.framework Flutter/Flutter.podspec Flutter/Generated.xcconfig Flutter/app.flx Flutter/app.zip Flutter/flutter_assets/ Flutter/flutter_export_environment.sh ServiceDefinitions.json Runner/GeneratedPluginRegistrant.* # Exceptions to above rules. !default.mode1v3 !default.mode2v3 !default.pbxuser !default.perspectivev3 ================================================ FILE: ios/Flutter/AppFrameworkInfo.plist ================================================ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable App CFBundleIdentifier io.flutter.flutter.app CFBundleInfoDictionaryVersion 6.0 CFBundleName App CFBundlePackageType FMWK CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1.0 MinimumOSVersion 8.0 ================================================ FILE: ios/Flutter/Debug.xcconfig ================================================ #include "Generated.xcconfig" ================================================ FILE: ios/Flutter/Release.xcconfig ================================================ #include "Generated.xcconfig" ================================================ FILE: ios/Runner/AppDelegate.swift ================================================ import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } ================================================ FILE: ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "size" : "20x20", "idiom" : "iphone", "filename" : "Icon-App-20x20@2x.png", "scale" : "2x" }, { "size" : "20x20", "idiom" : "iphone", "filename" : "Icon-App-20x20@3x.png", "scale" : "3x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@1x.png", "scale" : "1x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@2x.png", "scale" : "2x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@3x.png", "scale" : "3x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "Icon-App-40x40@2x.png", "scale" : "2x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "Icon-App-40x40@3x.png", "scale" : "3x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "Icon-App-60x60@2x.png", "scale" : "2x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "Icon-App-60x60@3x.png", "scale" : "3x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "Icon-App-20x20@1x.png", "scale" : "1x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "Icon-App-20x20@2x.png", "scale" : "2x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "Icon-App-29x29@1x.png", "scale" : "1x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "Icon-App-29x29@2x.png", "scale" : "2x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "Icon-App-40x40@1x.png", "scale" : "1x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "Icon-App-40x40@2x.png", "scale" : "2x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "Icon-App-76x76@1x.png", "scale" : "1x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "Icon-App-76x76@2x.png", "scale" : "2x" }, { "size" : "83.5x83.5", "idiom" : "ipad", "filename" : "Icon-App-83.5x83.5@2x.png", "scale" : "2x" }, { "size" : "1024x1024", "idiom" : "ios-marketing", "filename" : "Icon-App-1024x1024@1x.png", "scale" : "1x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json ================================================ { "images" : [ { "idiom" : "universal", "filename" : "LaunchImage.png", "scale" : "1x" }, { "idiom" : "universal", "filename" : "LaunchImage@2x.png", "scale" : "2x" }, { "idiom" : "universal", "filename" : "LaunchImage@3x.png", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md ================================================ # Launch Screen Assets You can customize the launch screen with your own desired assets by replacing the image files in this directory. You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. ================================================ FILE: ios/Runner/Base.lproj/LaunchScreen.storyboard ================================================ ================================================ FILE: ios/Runner/Base.lproj/Main.storyboard ================================================ ================================================ FILE: ios/Runner/Info.plist ================================================ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName yaga CFBundlePackageType APPL CFBundleShortVersionString $(FLUTTER_BUILD_NAME) CFBundleSignature ???? CFBundleVersion $(FLUTTER_BUILD_NUMBER) LSRequiresIPhoneOS UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIViewControllerBasedStatusBarAppearance ================================================ FILE: ios/Runner/Runner-Bridging-Header.h ================================================ #import "GeneratedPluginRegistrant.h" ================================================ FILE: ios/Runner.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 3B80C3941E831B6300D905FE /* App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; }; 3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; }; 9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ 9705A1C41CF9048500538489 /* Embed Frameworks */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 10; files = ( 3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */, 9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */, ); name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 3B80C3931E831B6300D905FE /* App.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = App.framework; path = Flutter/App.framework; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 9740EEBA1CF902C7004384FC /* Flutter.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Flutter.framework; path = Flutter/Flutter.framework; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 97C146EB1CF9000F007C117D /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */, 3B80C3941E831B6300D905FE /* App.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( 3B80C3931E831B6300D905FE /* App.framework */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEBA1CF902C7004384FC /* Flutter.framework */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, 9740EEB31CF90195004384FC /* Generated.xcconfig */, ); name = Flutter; sourceTree = ""; }; 97C146E51CF9000F007C117D = { isa = PBXGroup; children = ( 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, ); sourceTree = ""; }; 97C146EF1CF9000F007C117D /* Products */ = { isa = PBXGroup; children = ( 97C146EE1CF9000F007C117D /* Runner.app */, ); name = Products; sourceTree = ""; }; 97C146F01CF9000F007C117D /* Runner */ = { isa = PBXGroup; children = ( 97C146FA1CF9000F007C117D /* Main.storyboard */, 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, 97C146F11CF9000F007C117D /* Supporting Files */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, ); path = Runner; sourceTree = ""; }; 97C146F11CF9000F007C117D /* Supporting Files */ = { isa = PBXGroup; children = ( ); name = "Supporting Files"; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, ); buildRules = ( ); dependencies = ( ); name = Runner; productName = Runner; productReference = 97C146EE1CF9000F007C117D /* Runner.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 1020; ORGANIZATIONNAME = "The Chromium Authors"; TargetAttributes = { 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; LastSwiftMigration = 1100; }; }; }; buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 97C146E51CF9000F007C117D; productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 97C146EC1CF9000F007C117D /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Thin Binary"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" thin"; }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Run Script"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 97C146EA1CF9000F007C117D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ 97C146FA1CF9000F007C117D /* Main.storyboard */ = { isa = PBXVariantGroup; children = ( 97C146FB1CF9000F007C117D /* Base */, ); name = Main.storyboard; sourceTree = ""; }; 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( 97C147001CF9000F007C117D /* Base */, ); name = LaunchScreen.storyboard; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 249021D3217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; name = Profile; }; 249021D4217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); PRODUCT_BUNDLE_IDENTIFIER = com.github.vauvenal5.yaga; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Profile; }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; 97C147041CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; name = Release; }; 97C147061CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); PRODUCT_BUNDLE_IDENTIFIER = com.github.vauvenal5.yaga; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; }; 97C147071CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); PRODUCT_BUNDLE_IDENTIFIER = com.github.vauvenal5.yaga; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 97C147031CF9000F007C117D /* Debug */, 97C147041CF9000F007C117D /* Release */, 249021D3217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 97C147061CF9000F007C117D /* Debug */, 97C147071CF9000F007C117D /* Release */, 249021D4217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 97C146E61CF9000F007C117D /* Project object */; } ================================================ FILE: ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme ================================================ ================================================ FILE: ios/Runner.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: lib/main.dart ================================================ import 'package:catcher_2/catcher_2.dart'; import 'package:flutter/material.dart'; import 'package:yaga/managers/global_settings_manager.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/preferences/choice_preference.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/navigation/yaga_router_delegate.dart'; import 'package:yaga/utils/nextcloud_colors.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/utils/navigation/yaga_route_information_parser.dart'; import 'package:yaga/views/screens/splash_screen.dart'; Future main() async { await YagaLogger.init(); setupServiceLocator(); final Catcher2Options releaseOptions = Catcher2Options(SilentReportMode(), [ YagaLogger.fileHandler, ]); Catcher2( rootWidget: MyApp(), debugConfig: releaseOptions, releaseConfig: releaseOptions, enableLogger: false, ); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final ThemeData dark = ThemeData( useMaterial3: false, brightness: Brightness.dark, colorScheme: ColorScheme.fromSwatch( accentColor: NextcloudColors.lightBlue, brightness: Brightness.dark, ), ); final ThemeData light = ThemeData( useMaterial3: false, // brightness: Brightness.light, colorScheme: ColorScheme.fromSwatch( accentColor: NextcloudColors.lightBlue, brightness: Brightness.light, ), ); const String title = "Nextcloud Yaga"; return FutureBuilder( future: YagaLogger.printBaseLog().then( (_) => getIt.allReady(), ), builder: (context, snapshot) { if (!snapshot.hasData) { return MaterialApp( title: title, theme: light, darkTheme: dark, home: SplashScreen(), ); } final settingsManager = getIt.get(); return StreamBuilder( initialData: getIt .get() .loadPreferenceFromString(GlobalSettingsManager.theme), stream: settingsManager.updateSettingCommand .where((event) => event.key == GlobalSettingsManager.theme.key) .where((event) => event is ChoicePreference) .map((event) => event as ChoicePreference), builder: (context, snapshot) { if (snapshot.data!.value == "system") { return MaterialApp.router( title: title, theme: light, darkTheme: dark, routeInformationParser: YagaRouteInformationParser(), routerDelegate: YagaRouterDelegate(), ); } return MaterialApp.router( title: title, theme: snapshot.data!.value == "light" ? light : dark, routeInformationParser: YagaRouteInformationParser(), routerDelegate: YagaRouterDelegate(), ); }, ); }, ); } } ================================================ FILE: lib/managers/file_manager/file_manager.dart ================================================ import 'dart:io'; import 'package:rx_command/rx_command.dart'; import 'package:rxdart/rxdart.dart'; import 'package:yaga/managers/file_manager/file_manager_base.dart'; import 'package:yaga/managers/file_service_manager/media_file_manager.dart'; import 'package:yaga/managers/global_settings_manager.dart'; import 'package:yaga/model/fetched_file.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/background_worker/background_worker.dart'; import 'package:yaga/utils/forground_worker/foreground_worker.dart'; import 'package:yaga/utils/forground_worker/messages/download_file_request.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_request.dart'; import 'package:yaga/utils/forground_worker/messages/file_update_msg.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/delete_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_done.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_request.dart'; import 'package:yaga/utils/forground_worker/messages/sort_request.dart'; import 'package:yaga/utils/ncfile_stream_extensions.dart'; class FileManager extends FileManagerBase { RxCommand downloadImageCommand = RxCommand.createSync((param) => param); RxCommand fetchFileListCommand = RxCommand.createSync((param) => param); RxCommand sortFilesListCommand = RxCommand.createSync((param) => param); RxCommand filesActionCommand = RxCommand.createSync((param) => param); final MediaFileManager _mediaFileManager; final SharedPreferencesService _sharedPreferencesService; final ForegroundWorker _foregroundWorker; final BackgroundWorker _backgroundWorker; FileManager( this._mediaFileManager, this._sharedPreferencesService, this._foregroundWorker, this._backgroundWorker, ) { registerFileManager(_mediaFileManager); fetchFileListCommand .where((event) => _mediaFileManager.isRelevant(event.uri.scheme)) .flatMap( (value) => _mediaFileManager .listFiles(value.uri) .collectToList() .map((event) => SortRequest(value.key, event, value)), ) .listen((event) { sortFilesListCommand(event); }); filesActionCommand .where((event) => event is DeleteFilesRequest) .map((event) => event as DeleteFilesRequest) .where((event) => event.sourceDir.scheme == _mediaFileManager.scheme) .listen(_handleLocalDeleteRequest); filesActionCommand.where((event) => event.sourceDir.scheme != _mediaFileManager.scheme).listen(_handleFilesAction); //todo: re-enable when copy/move support is added // fileActionCommand // .where((event) => event is DestinationActionFilesRequest) // .map((event) => event as DestinationActionFilesRequest) // .listen((event) { // if(event.action == DestinationAction.copy) { // _mediaFileManager.copyFile(event.files.first, event.destination); // } else { // _mediaFileManager.moveFile(event.files.first, event.destination); // } // }); downloadImageCommand.listen(_handleDownload); } @override Stream listFiles(Uri uri, {bool recursive = false}) { // not supported in UI branch because to computational intensive throw UnimplementedError(); } void _handleLocalDeleteRequest(DeleteFilesRequest request) async { _mediaFileManager.deleteFiles(request.files).then((files) { for (var file in files) { fileUpdateMessage(FileUpdateMsg("", file)); } }).whenComplete( () => filesActionDoneCommand(FilesActionDone(request.key, request.sourceDir)), ); } void _handleFilesAction(FilesActionRequest request) async { final useBackground = _sharedPreferencesService .loadPreferenceFromBool( GlobalSettingsManager.useBackground, ) .value; useBackground ? _backgroundWorker.sendRequest(request) : _foregroundWorker.sendRequest(request); } void _handleDownload(DownloadFileRequest request) async { final NcFile ncFile = request.file; // if file exists locally and download is not forced then load the local file if (!request.forceDownload && ncFile.localFile != null && await ncFile.localFile!.file.exists()) { ncFile.localFile!.exists = true; //todo: why are we directly reading the file in here and not in the service? fetchedFileCommand( FetchedFile( ncFile, await (ncFile.localFile!.file as File).readAsBytes(), ), ); return; } final autoPersist = _sharedPreferencesService .loadPreferenceFromBool( GlobalSettingsManager.autoPersist, ) .value; final useBackground = _sharedPreferencesService .loadPreferenceFromBool( GlobalSettingsManager.useBackground, ) .value; request.persist = request.forceDownload || autoPersist; if (useBackground && request.persist) { // in case persistence is active download in true background _backgroundWorker.sendRequest(request); } else { // otherwise download in foreground worker _foregroundWorker.sendRequest(request); } } } ================================================ FILE: lib/managers/file_manager/file_manager_base.dart ================================================ import 'package:flutter/foundation.dart'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/file_service_manager/file_service_manager.dart'; import 'package:yaga/model/fetched_file.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_message.dart'; import 'package:yaga/utils/forground_worker/messages/file_update_msg.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_done.dart'; /// File Managers provide files functions, i.e. copy/delete/move/download /// with context of required actions over multiple services abstract class FileManagerBase { RxCommand updateImageCommand = RxCommand.createSync((param) => param); late RxCommand fetchedFileCommand; //todo: Background: this should be moved out of here because it does not concern FileActionsManager RxCommand updateFilesCommand = RxCommand.createSync((param) => param); // responses RxCommand filesActionDoneCommand = RxCommand.createSync((param) => param); RxCommand fileUpdateMessage = RxCommand.createSync((param) => param); @protected Map fileServiceManagers = {}; FileManagerBase() { fetchedFileCommand = RxCommand.createSync((param) { updateImageCommand(param.file); return param; }); } void registerFileManager(FileServiceManager fileServiceManager) { fileServiceManagers.putIfAbsent(fileServiceManager.scheme, () => fileServiceManager); } //todo: fileManager refactoring: this method should not be callable from the UI Stream listFiles(Uri uri, {bool recursive = false}); } ================================================ FILE: lib/managers/file_manager/isolateable/file_action_manager.dart ================================================ import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:nextcloud/nextcloud.dart'; import 'package:rx_command/rx_command.dart'; import 'package:rxdart/rxdart.dart'; import 'package:yaga/managers/file_manager/file_manager_base.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/isolateable/local_file_service.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/utils/background_worker/background_channel.dart'; import 'package:yaga/utils/forground_worker/messages/file_update_msg.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/delete_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/destination_action_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/favorite_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_done.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_request.dart'; import 'package:yaga/utils/forground_worker/messages/image_update_msg.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/utils/uri_utils.dart'; class FileActionManager extends FileManagerBase { final _logger = YagaLogger.getLogger(FileActionManager); RxCommand cancelActionCommand = RxCommand.createSyncNoParam(() => true); Future initBackground( BackgroundChannel backgroundToMain, ) async { updateImageCommand.listen( (file) => backgroundToMain.send(ImageUpdateMsg("", file)), ); return this; } Future downloadFile(NcFile file, {bool persist = false}) async { return getIt.get().downloadImage(file.uri).then((value) async { if (persist) { await getIt.get().createFile( file: file.localFile!.file as File, bytes: value, lastModified: file.lastModified, ); file.localFile!.exists = true; } return value; }); } Future deleteFiles(DeleteFilesRequest message) async => _cancelableAction( message, (file) async => fileServiceManagers[file.uri.scheme]?.deleteFile(file, local: message.local), ); Future copyMoveRequest(DestinationActionFilesRequest message) => message.action == DestinationAction.copy ? _copyFiles(message) : _moveFiles(message); Future _copyFiles(DestinationActionFilesRequest message) async => _cancelableAction( message, (file) async => fileServiceManagers[file.uri.scheme]?.copyFile( file, message.destination, overwrite: message.overwrite, ), filter: (file) => _destinationFilter(file, message.destination), ); Future _moveFiles(DestinationActionFilesRequest message) async => _cancelableAction( message, (file) async => fileServiceManagers[file.uri.scheme] ?.moveFile( file, message.destination, overwrite: message.overwrite, ) .then( (value) => fileUpdateMessage(FileUpdateMsg("", file)), ), filter: (file) => _destinationFilter(file, message.destination), ); Future toggleFavorites(FavoriteFilesRequest message) => Stream.fromIterable(message.files) .asyncMap( (file) => fileServiceManagers[file.uri.scheme]?.toggleFavorite(file).then((file) => updateImageCommand(file)), ) .toList(); bool _destinationFilter(NcFile file, Uri destination) => !compareFilePathToTargetFilePath(file, destination); Future _cancelableAction( FilesActionRequest request, Future Function(NcFile) action, { bool Function(NcFile file)? filter, }) => Stream.fromIterable(request.files) .where((event) => filter == null || filter(event)) .asyncMap( (file) => action(file).catchError( (err) => null, test: (err) => err is DynamiteApiException || err is FileSystemException, ), ) .where((event) => event != null) .takeUntil( cancelActionCommand.doOnData((event) => _logger.finest("Canceling action!")), ) .toList() .whenComplete( () => filesActionDoneCommand(FilesActionDone(request.key, request.sourceDir)), ); @override Stream listFiles(Uri uri, {bool recursive = false}) { // not supported in true background because not needed when app not in foreground throw UnimplementedError(); } } ================================================ FILE: lib/managers/file_manager/isolateable/isolated_file_manager.dart ================================================ import 'dart:isolate'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/file_manager/isolateable/file_action_manager.dart'; import 'package:yaga/managers/isolateable/sort_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/sort_config.dart'; import 'package:yaga/model/sorted_file_list.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_message.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_response.dart'; import 'package:yaga/utils/forground_worker/messages/file_update_msg.dart'; import 'package:yaga/utils/forground_worker/messages/image_update_msg.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/logger.dart'; import 'package:rxdart/rxdart.dart'; class IsolatedFileManager extends FileActionManager with Isolateable { final _logger = YagaLogger.getLogger(IsolatedFileManager); final SortManager _sortManager; RxCommand updateFilesCommand = RxCommand.createSync((param) => param); IsolatedFileManager(this._sortManager); @override Future initIsolated( InitMsg init, SendPort isolateToMain, ) async { //todo: we probably can improve the capsuling of front end and foreground_worker communication further //--> check if it is possible to completely hide communications in bridges updateImageCommand.listen( (file) => isolateToMain.send(ImageUpdateMsg("", file)), ); updateFilesCommand.listen((event) => isolateToMain.send(event)); return this; } Future listFileLists( String requestKey, Uri uri, SortConfig sortConfig, { bool recursive = false, bool favorites = false, }) async { return fileServiceManagers[uri.scheme] ?.listFileList(uri, recursive: recursive, favorites: favorites) .map((event) => _sortManager.sortList(event, sortConfig)) .fold( null, (SortedFileList>? previous, element) { if (previous == null) { updateFilesCommand( FileListResponse(requestKey, uri, element, recursive: recursive), ); return element; } if (_sortManager.mergeSort(previous, element)) { updateFilesCommand( FileListResponse(requestKey, uri, previous, recursive: recursive), ); } return previous; }, ).then((value) => value); } @override Stream listFiles(Uri uri, {bool recursive = false}) { //todo: throw when scheme is not registered return fileServiceManagers[uri.scheme]?.listFiles(uri).flatMap((file) => file.isDirectory && recursive ? listFiles(file.uri, recursive: recursive) : Stream.value(file)) ?? const Stream.empty(); } } ================================================ FILE: lib/managers/file_service_manager/favorite_not_supported_mixin.dart ================================================ import 'package:yaga/model/nc_file.dart'; mixin FavoriteNotSupportedMixin { Future toggleFavorite(NcFile file,) => throw UnimplementedError(); } ================================================ FILE: lib/managers/file_service_manager/file_service_manager.dart ================================================ import 'package:yaga/model/nc_file.dart'; /// FileServiceManagers are providing basic file manager functions /// encapsulating required actions for one specific source. abstract class FileServiceManager { final String scheme = ""; Stream listFiles(Uri uri, {bool recursive = false}); Stream> listFileList(Uri uri, {bool recursive = false, bool favorites = false,}); Future deleteFile(NcFile file, {required bool local}); Future copyFile(NcFile file, Uri destination, {bool overwrite = false}); Future moveFile(NcFile file, Uri destination, {bool overwrite = false}); Future toggleFavorite(NcFile file,); } ================================================ FILE: lib/managers/file_service_manager/isolateable/local_file_manager.dart ================================================ import 'dart:io'; import 'package:mime/mime.dart'; import 'package:yaga/managers/file_manager/file_manager_base.dart'; import 'package:yaga/managers/file_service_manager/favorite_not_supported_mixin.dart'; import 'package:yaga/managers/file_service_manager/file_service_manager.dart'; import 'package:yaga/model/local_file.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/isolateable/local_file_service.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/file_update_msg.dart'; import 'package:yaga/utils/ncfile_stream_extensions.dart'; import 'package:yaga/utils/uri_utils.dart'; import 'package:rxdart/rxdart.dart'; // this class is still needed for offline support class LocalFileManager with Isolateable, FavoriteNotSupportedMixin implements FileServiceManager { final FileManagerBase _fileManager; final LocalFileService _localFileService; final SystemLocationService _systemPathService; @override String get scheme => _systemPathService.internalStorage.origin.scheme; LocalFileManager( this._fileManager, this._localFileService, this._systemPathService) { _fileManager.registerFileManager(this); } @override //todo: should add a wrapper around uri to distinguish between internal and absolute uri // --> for example this serivce requires a internal uri but the call from within the nextcloudFileManager passes an absolute uri! Stream listFiles( Uri uri, { bool recursive = false, }) { //todo: add uri check? or simply handle exception? return _listLocalFiles(uri) .recursively(_listLocalFiles, recursive: recursive); } @override Stream> listFileList( Uri uri, { bool recursive = false, bool favorites = false, }) { return listFiles(uri, recursive: recursive).collectToList(); } Stream _listLocalFiles(Uri uri, {bool favorites = false}) { //todo: add uri check? or simply handle exception? return Stream.value(uri) .map(_systemPathService.absoluteUriFromInternal) .map((uri) => Directory.fromUri(uri)) .flatMap((dir) => _localFileService.list(dir)) .map((event) { final Uri uri = _systemPathService.internalUriFromAbsolute(event.uri); final NcFile file = _createFile(uri, event); file.localFile = LocalFile(event, event.existsSync()); return file; }); } NcFile _createFile(Uri uri, FileSystemEntity event) { if (event is Directory) { final NcFile file = NcFile.directory( uri, getNameFromUri(uri), ); //todo: think about this! file.lastModified = DateTime.now(); return file; } final NcFile file = NcFile.file( uri, getNameFromUri(uri), lookupMimeType(event.path), ); //todo: this value is not necessarily correct(!) file.lastModified = (event as File).lastModifiedSync().toUtc(); return file; } @override Future deleteFile(NcFile file, {required bool local}) async { _localFileService.deleteFile(file.localFile!.file); _fileManager.fileUpdateMessage(FileUpdateMsg("", file)); return file; } @override Future copyFile(NcFile file, Uri destination, {bool overwrite = false}) async { _localFileService.copyFile( file, _systemPathService.absoluteUriFromInternal(destination), overwrite: overwrite, ); return file; } @override Future moveFile(NcFile file, Uri destination, {bool overwrite = false}) async { _localFileService.moveFile( file, _systemPathService.absoluteUriFromInternal(destination), overwrite: overwrite, ); return file; } } ================================================ FILE: lib/managers/file_service_manager/isolateable/nextcloud_background_file_manager.dart ================================================ import 'package:flutter/foundation.dart'; import 'package:yaga/managers/file_manager/file_manager_base.dart'; import 'package:yaga/managers/file_service_manager/file_service_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/isolateable/local_file_service.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/utils/forground_worker/messages/file_update_msg.dart'; import 'package:yaga/utils/logger.dart'; class NextcloudBackgroundFileManager implements FileServiceManager { final _logger = YagaLogger.getLogger(NextcloudBackgroundFileManager); @protected final NextCloudService nextCloudService; @protected final LocalFileService localFileService; @protected final FileManagerBase fileManager; NextcloudBackgroundFileManager(this.nextCloudService, this.localFileService, this.fileManager); Future initBackground() async { fileManager.registerFileManager(this); return this; } //todo: background: clean up file manager mess @override Future deleteFile(NcFile file, {required bool local}) async { if (local) { localFileService.deleteFile(file.localFile!.file); file.localFile!.exists = false; fileManager.updateImageCommand(file); return file; } return nextCloudService .deleteFile(file) .then((value) => deleteLocalFile(file)) .then((file) { fileManager.fileUpdateMessage(FileUpdateMsg("", file)); return file; }); } @protected Future deleteLocalFile(NcFile file) async { _logger.warning("Removing local file! (${file.uri.path})"); localFileService.deleteFile(file.localFile!.file); localFileService.deleteFile(file.previewFile!.file); return file; } @override Stream> listFileList(Uri uri, {bool recursive = false, bool favorites = false,}) { // not supported in true background since listing files makes only sense when app in foreground throw UnimplementedError(); } @override Stream listFiles(Uri uri, {bool recursive = false}) { // not supported in true background since listing files makes only sense when app in foreground throw UnimplementedError(); } @override Future copyFile(NcFile file, Uri destination, {bool overwrite = false}) => nextCloudService.copyFile(file, destination, overwrite: overwrite); @override Future moveFile(NcFile file, Uri destination, {bool overwrite = false}) => nextCloudService .moveFile(file, destination, overwrite: overwrite) // this is a very simplified fix for a complex problem: // if we want to move existing files locally we need to decide if it // is really necessary to do this in the background // if yes, we have also to consider the implications on the UI: // * dialog has to be removed // * this makes the action non cancelable // technical requirements: // * MappingManger has to be refactored to be usable in background .then((value) => deleteLocalFile(value)); @override Future toggleFavorite(NcFile file) => nextCloudService.toggleFavorite(file); @override String get scheme => nextCloudService.scheme; } ================================================ FILE: lib/managers/file_service_manager/isolateable/nextcloud_file_manger.dart ================================================ import 'dart:io'; import 'package:nextcloud/nextcloud.dart'; import 'package:rx_command/rx_command.dart'; import 'package:rxdart/rxdart.dart'; import 'package:yaga/managers/file_manager/file_manager_base.dart'; import 'package:yaga/managers/file_service_manager/isolateable/nextcloud_background_file_manager.dart'; import 'package:yaga/managers/isolateable/mapping_manager.dart'; import 'package:yaga/managers/isolateable/sync_manager.dart'; import 'package:yaga/model/local_file.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/preview_fetch_meta.dart'; import 'package:yaga/services/isolateable/local_file_service.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/file_update_msg.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/ncfile_stream_extensions.dart'; class NextcloudFileManager extends NextcloudBackgroundFileManager with Isolateable { final _logger = YagaLogger.getLogger(NextcloudFileManager); final MappingManager _mappingManager; final SyncManager _syncManager; final RxCommand _getPreviewCommand = RxCommand.createSync((param) => param); final RxCommand _readyForNextPreviewRequest = RxCommand.createSync((param) => param); final RxCommand downloadPreviewCommand = RxCommand.createSync((param) => param); final RxCommand updatePreviewCommand = RxCommand.createSync((param) => param); final RxCommand downloadPreviewFaildCommand = RxCommand.createSync((param) => param); NextcloudFileManager( FileManagerBase fileManager, NextCloudService nextCloudService, LocalFileService localFileService, this._mappingManager, this._syncManager, ) : super(nextCloudService, localFileService, fileManager){ fileManager.registerFileManager(this); _getPreviewCommand .zipWith( // this stream is managing the amount of allowed parallel downloads of previews (currently 10) _readyForNextPreviewRequest.doOnData( (event) => _logger.info("Arming preview index: $event"), ), (ncFile, int number) => PreviewFetchMeta(ncFile, number), ) .doOnData( (event) => _logger.info( "Fetching preview index: ${event.fetchIndex}", ), ) // debounce requests which have been added multiple times due to scrolling .where((ncFileMeta) { if (ncFileMeta.file.previewFile!.file.existsSync()) { _logger.info("Preview exists index: ${ncFileMeta.fetchIndex}"); _readyForNextPreviewRequest(ncFileMeta.fetchIndex); return false; } return true; }) .flatMap( (ncFileMeta) => Stream.fromFuture( nextCloudService.getPreview(ncFileMeta.file.uri).then( (value) async { ncFileMeta.file.previewFile!.file = await localFileService.createFile( file: ncFileMeta.file.previewFile!.file as File, bytes: value, lastModified: ncFileMeta.file.lastModified); ncFileMeta.file.previewFile!.exists = true; _logger.info("Preview fetched index: ${ncFileMeta.fetchIndex}"); _logger.fine("Preview fetched: (${ncFileMeta.file.uri})"); return ncFileMeta; }, //todo: do we really need both error handlers onError: (err, StackTrace stacktrace) { if(err is DynamiteApiException && err.statusCode == 404) { _logger.warning( "Preview not found for file: ${ncFileMeta.file.name}", ); } else { _logger.warning( "Preview fetching failed, index: ${ncFileMeta.fetchIndex}", ); _logger.severe( "Unexpected error while loading preview", err, stacktrace, ); } downloadPreviewFaildCommand(ncFileMeta.file); return PreviewFetchMeta(ncFileMeta.file, ncFileMeta.fetchIndex, success: false); }, ), ), ) .doOnData((event) => _readyForNextPreviewRequest(event.fetchIndex)) .where((event) => event.success) .listen( (ncFileMeta) => updatePreviewCommand(ncFileMeta.file), onError: (error, StackTrace stacktrace) { final int index = (_readyForNextPreviewRequest.lastResult! + 1) % 10; _logger.warning("Error on stream. Reintroducing index: $index"); _readyForNextPreviewRequest(index); _logger.severe( "Unexpected error in preview stream", error, stacktrace, ); }, ); //init preview stream for 10 simultanious requests RangeStream(1, 10).listen((event) => _readyForNextPreviewRequest(event)); downloadPreviewCommand.listen((ncFile) { if (ncFile.previewFile != null && ncFile.previewFile!.file.existsSync()) { ncFile.previewFile!.exists = true; updatePreviewCommand(ncFile); return; } _getPreviewCommand(ncFile); }); } @override String get scheme => nextCloudService.scheme; @override Stream listFiles( Uri uri, { bool recursive = false, }) { //todo: add uri check return _syncManager.addUri(uri).asStream().flatMap((value) => Rx.merge([ _listLocalFileList(uri, recursive), _listNextcloudFiles(uri, recursive), ]).doOnDone(() => _finishSync(uri))) as Stream; } @override Stream> listFileList( Uri uri, { bool recursive = false, bool favorites = false, }) { //todo: add uri check _logger.finer("Listing... ($uri)"); return _syncManager.addUri(uri).asStream().flatMap((_) => Rx.merge([ _listLocalFileList(uri, recursive), _listNextcloudFiles(uri, recursive, favorites: favorites).collectToList(), ]).doOnData((event) { _logger.finer("Emiting list! ($uri)"); }).doOnDone(() => _finishSync(uri))); } Stream _listNextcloudFiles(Uri uri, bool recursive, {bool favorites = false}) { return _listNextcloudFilesUpstream(uri, favorites: favorites) .recursively(_listNextcloudFilesUpstream, recursive: recursive, favorites: favorites) .doOnData((file) => _syncManager.addRemoteFile(uri, file)) .doOnError((err, stack) => _syncManager.removeUri(uri)); } Stream _listNextcloudFilesUpstream(Uri uri, {bool favorites = false}) { return nextCloudService.list(uri, favorites).asyncMap((file) async { if (!file.isDirectory) { file.localFile = await _createLocalFile(file.uri); file.previewFile = await _createTmpFile(file.uri); } return file; }); } Stream> _listLocalFileList(Uri uri, bool recursive) { return Rx.merge([ _listTmpFiles(uri, recursive), _listLocalFiles(uri, recursive), ]) .doOnData((file) => _syncManager.addFile(uri, file)) .distinctUnique() .toList() .asStream(); } Stream _listLocalFiles(Uri uri, bool recursive) => _listFromLocalFileManager( uri, recursive, _mappingManager.mapToLocalUri, (file) async { file.uri = await _mappingManager.mapToRemoteUri(file.uri, uri); //todo: should this be a FileSystemEntity? // file.localFile = await _mappingManager.mapToLocalFile(file.uri); if (!file.isDirectory) { file.previewFile = await _createTmpFile(file.uri); } return file; }, ); Stream _listTmpFiles(Uri uri, bool recursive) => _listFromLocalFileManager( uri, recursive, _mappingManager.mapToTmpUri, (file) async { file.uri = await _mappingManager.mapTmpToRemoteUri(file.uri, uri); //todo: should this be a FileSystemEntity? if (!file.isDirectory) { file.previewFile = file.localFile; file.localFile = await _createLocalFile(file.uri); } // file.previewFile = _localFileService.getTmpFile(file.uri.path); return file; }, ); Stream _listFromLocalFileManager( Uri uri, bool recursive, Future Function(Uri) mappingCall, Future Function(NcFile) resultMapping) { return mappingCall(uri) .asStream() .flatMap((value) => fileManager.listFiles(value, recursive: recursive)) .asyncMap(resultMapping); } Future _finishSync(Uri uri) { return _syncManager.syncUri(uri).then((files) async { for (final NcFile file in files) { if (await _mappingManager.isSyncDelete(file.uri)) { deleteLocalFile(file); } else { fileManager.fileUpdateMessage(FileUpdateMsg("", file)); } } }); } Future _createLocalFile(Uri uri) async { File file = File.fromUri(await _mappingManager.mapToLocalUri(uri)); return LocalFile(file, file.existsSync()); } Future _createTmpFile(Uri uri) async { File file = File.fromUri(await _mappingManager.mapToTmpUri(uri)); return LocalFile(file, file.existsSync()); } } ================================================ FILE: lib/managers/file_service_manager/media_file_manager.dart ================================================ import 'dart:io'; import 'package:yaga/managers/file_service_manager/favorite_not_supported_mixin.dart'; import 'package:yaga/managers/file_service_manager/file_service_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/media_file_service.dart'; class MediaFileManager with FavoriteNotSupportedMixin implements FileServiceManager { final MediaFileService _mediaFileService; MediaFileManager(this._mediaFileService); @override Future deleteFile(NcFile file, {required bool local}) { return deleteFiles(List.filled(1, file)).then((value) => value.first); } Future> deleteFiles(List files) { return _mediaFileService.deleteFile(files); } @override Stream> listFileList(Uri uri, {bool recursive = false, bool favorites = false}) { // TODO: implement listFileList throw UnimplementedError(); } @override Stream listFiles(Uri uri, {bool recursive = false}) { return _mediaFileService.listFiles(uri); } @override // todo: currently this is reusing the file-scheme which is meant for local access probably should use a different one? String get scheme => _mediaFileService.scheme; @override Future copyFile(NcFile file, Uri destination, {bool overwrite = false}) { // TODO: implement copyFile throw UnimplementedError(); } @override Future moveFile(NcFile file, Uri destination, {bool overwrite = false}) { // TODO: implement moveFile throw UnimplementedError(); } bool isRelevant(String scheme) { return Platform.isAndroid && scheme == this.scheme; } } ================================================ FILE: lib/managers/global_settings_manager.dart ================================================ import 'dart:io'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/nc_login_data.dart'; import 'package:yaga/model/preferences/action_preference.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/model/preferences/choice_preference.dart'; import 'package:yaga/model/preferences/int_preference.dart'; import 'package:yaga/model/preferences/mapping_preference.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/preferences/section_preference.dart'; import 'package:yaga/model/preferences/string_preference.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/uri_utils.dart'; class GlobalSettingsManager { final List _globalSettingsCache = []; static const String _MAPPING_KEY = "mapping"; static SectionPreference ncSection = SectionPreference((b) => b ..key = "nc" ..title = "Nextcloud"); static BoolPreference autoPersist = BoolPreference((b) => b ..key = ncSection.prepareKey("autoPersist") ..title = "Persist on View Image" ..value = true); static SectionPreference appSection = SectionPreference((b) => b ..key = "app" ..title = "General"); static ChoicePreference theme = ChoicePreference((b) => b ..key = appSection.prepareKey("theme") ..title = "Theme" ..value = "system" ..choices = { "system": "Follow System Theme", "light": "Light Theme", "dark": "Dark Theme" }); static ActionPreference sendLogs = ActionPreference((b) => b ..key = appSection.prepareKey("logs") ..title = "Send Logs" ..action = YagaLogger.shareLogs ..enabled = Platform.isAndroid); static ActionPreference? reset; static StringPreference newsSeenVersion = StringPreference( (b) => b ..key = appSection.prepareKey("newsSeen") ..title = "News Seen Version" ..value = "", ); static BoolPreference useBackground = BoolPreference( (b) => b ..key = ncSection.prepareKey("useBackground") ..title = "File actions in background" ..value = Platform.isAndroid ..enabled = Platform.isAndroid, ); static SectionPreference slideshowSection = SectionPreference( (b) => b ..key = "show" ..title = "Slideshow", ); static IntPreference slideShowInterval = IntPreference( (b) => b ..key = slideshowSection.prepareKey("interval") ..title = "Interval in seconds" ..value = 5, ); static BoolPreference slideShowRandom = BoolPreference( (b) => b..key = slideshowSection.prepareKey("random") ..title = "Random order" ..value = false, ); static BoolPreference slideShowAutoStop = BoolPreference( (b) => b..key = slideshowSection.prepareKey("autoStop") ..title = "Stop at end" ..value = false, ); RxCommand registerGlobalSettingCommand = RxCommand.createSync((param) => param); late RxCommand removeGlobalSettingCommand; RxCommand, List> updateGlobalSettingsCommand = RxCommand.createSync((param) => param); RxCommand updateRootMappingPreference = RxCommand.createSync((param) => param); final NextCloudManager _nextcloudManager; final SettingsManager _settingsManager; final NextCloudService _nextCloudService; final SystemLocationService _systemLocationService; GlobalSettingsManager(this._nextcloudManager, this._settingsManager, this._nextCloudService, this._systemLocationService) { registerGlobalSettingCommand.listen((pref) { if (_globalSettingsCache.contains(pref)) { return; } _globalSettingsCache.add(pref); updateGlobalSettingsCommand(_globalSettingsCache); }); removeGlobalSettingCommand = RxCommand.createSync((param) => _globalSettingsCache .removeWhere((element) => element.key == param.key)); removeGlobalSettingCommand.listen((value) { updateGlobalSettingsCommand(_globalSettingsCache); }); _nextcloudManager.updateLoginStateCommand .listen((value) => _handleLoginState(value)); _nextcloudManager.logoutCommand.listen((value) { final MappingPreference mapping = getDefaultMappingPreference( local: _systemLocationService.internalStorage.uri, remote: Uri(), ); _settingsManager.removeMappingPreferenceCommand(mapping); removeGlobalSettingCommand(mapping); removeGlobalSettingCommand(reset); removeGlobalSettingCommand(autoPersist); removeGlobalSettingCommand(ncSection); }); _settingsManager.updateSettingCommand .where((event) => event.key == ncSection.prepareKey(_MAPPING_KEY)) .listen( (event) => updateRootMappingPreference(event as MappingPreference)); } Future init() async { registerGlobalSettingCommand(appSection); registerGlobalSettingCommand(useBackground); registerGlobalSettingCommand(theme); registerGlobalSettingCommand(sendLogs); registerGlobalSettingCommand(slideshowSection); registerGlobalSettingCommand(slideShowInterval); registerGlobalSettingCommand(slideShowRandom); registerGlobalSettingCommand(slideShowAutoStop); _handleLoginState( _nextcloudManager.updateLoginStateCommand.lastResult!, ); return this; } MappingPreference getDefaultMappingPreference({ required Uri local, required Uri remote, }) { return MappingPreference( (b) => b ..key = ncSection.prepareKey(_MAPPING_KEY) ..title = "Root Mapping" ..value = false ..local.value = local ..local.enabled = false ..remote.value = remote ..remote.enabled = false, ); } void _handleLoginState(NextCloudLoginData loginData) { if (_nextCloudService.isLoggedIn()) { final MappingPreference mapping = getDefaultMappingPreference( local: fromUri( uri: _systemLocationService.internalStorage.uri, path: "${_systemLocationService.internalStorage.uri.path}/${_nextCloudService.origin!.userDomain}", ), remote: _nextCloudService.origin!.userEncodedDomainRoot, ); reset = ActionPreference( (b) => b ..key = ncSection.prepareKey("reset") ..title = "Reset Root Mapping" ..action = () { _settingsManager.persistMappingPreferenceCommand(mapping); _settingsManager.loadMappingPreferenceCommand(mapping); }, ); registerGlobalSettingCommand(ncSection); registerGlobalSettingCommand(mapping); // registerGlobalSettingCommand(reset); registerGlobalSettingCommand(autoPersist); //instead of loading the root mapping we are resetting it here to default values //_settingsManager.loadMappingPreferenceCommand(mapping); reset!.action.call(); } } } ================================================ FILE: lib/managers/isolateable/isolated_global_settings_manager.dart ================================================ import 'dart:isolate'; import 'package:yaga/managers/global_settings_manager.dart'; import 'package:yaga/managers/isolateable/isolated_settings_manager.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; class IsolatedGlobalSettingsManager with Isolateable { @override Future initIsolated( InitMsg init, SendPort isolateToMain, ) async { _autoPersist = init.autoPersist; return this; } final IsolatedSettingsManager _settingsManager; late BoolPreference _autoPersist; BoolPreference get autoPersist => _autoPersist; IsolatedGlobalSettingsManager(this._settingsManager) { _settingsManager.updateSettingCommand .where((event) => event.key == GlobalSettingsManager.autoPersist.key) .map((event) => event as BoolPreference) .listen((value) => _autoPersist = value); } } ================================================ FILE: lib/managers/isolateable/isolated_settings_manager.dart ================================================ import 'dart:isolate'; import 'package:yaga/managers/settings_manager_base.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; class IsolatedSettingsManager extends SettingsManagerBase with Isolateable { @override Future initIsolated( InitMsg init, SendPort isolateToMain, ) async { if(init.mapping != null) { updateSettingCommand(init.mapping); } return this; } } ================================================ FILE: lib/managers/isolateable/mapping_manager.dart ================================================ import 'dart:isolate'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/settings_manager_base.dart'; import 'package:yaga/model/mapping_node.dart'; import 'package:yaga/model/preferences/mapping_preference.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/uri_utils.dart'; class MappingManager with Isolateable { final _logger = YagaLogger.getLogger(MappingManager); final NextCloudService _nextCloudService; final SystemLocationService _systemLocationService; final SettingsManagerBase _settingsManager; RxCommand mappingUpdatedCommand = RxCommand.createSync((param) => param); MappingNode root = MappingNode(); Map mappings = {}; MappingManager(this._settingsManager, this._nextCloudService, this._systemLocationService) { _settingsManager.updateSettingCommand .where((event) => event is MappingPreference) .listen((event) => handleMappingUpdate(event as MappingPreference)); } @override Future initIsolated( InitMsg init, SendPort isolateToMain, ) async { handleMappingUpdate(init.mapping); return this; } //todo: use a bridge and commands to handle incoming msgs in forgraound worker // @visibleForTesting void handleMappingUpdate(MappingPreference? event) { if (event == null) { return; } if (mappings.containsKey(event.key)) { _removeFromTree(mappings[event.key]!.remote.value.pathSegments, 0, root); } //todo: somehow/somewhere the view needs to be refreshed when the mapping changes _addMappingPreferenceToTree(event, 0, root); mappings[event.key!] = event; mappingUpdatedCommand(event); } void _removeFromTree(List path, int index, MappingNode current) { if (index == path.length) { current.mapping = null; return; } _removeFromTree(path, index + 1, current.nodes[path[index]]!); } void _addMappingPreferenceToTree( MappingPreference pref, int pathIndex, MappingNode currentNode) { if (pathIndex >= pref.remote.value.pathSegments.length - 1) { currentNode.mapping = pref; return; } final String pathSegment = pref.remote.value.pathSegments[pathIndex]; currentNode.nodes.putIfAbsent(pathSegment, () => MappingNode()); _addMappingPreferenceToTree( pref, pathIndex + 1, currentNode.nodes[pathSegment]!); } MappingPreference _getMappingPrefernce(Uri uri, MappingPreference selected, int pathIndex, MappingNode? currentNode) { if (currentNode == null) { return selected; } if (uri.pathSegments.length == pathIndex) { return currentNode.mapping ?? selected; } return _getMappingPrefernce(uri, currentNode.mapping ?? selected, pathIndex + 1, currentNode.nodes[uri.pathSegments[pathIndex]]); } MappingPreference _getRootMappingPreference(Uri remoteUri) => _getMappingPrefernce( remoteUri, _getDefaultMapping(_systemLocationService.internalStorage.uri), 0, root); String _appendLocalMappingFolder(String path) { return chainPathSegments( path, _nextCloudService.origin!.userDomain, ); } Future isSyncDelete(Uri remoteUri) async => _getRootMappingPreference( remoteUri, ).syncDeletes.value; Future mapToLocalUri(Uri remoteUri) async => _mapUri( remoteUri, _getRootMappingPreference(remoteUri), ); Future mapToTmpUri(Uri remoteUri) async { return _mapUri(remoteUri, _getDefaultMapping(_systemLocationService.internalCache.uri)); } Uri _mapUri(Uri remoteUri, MappingPreference mapping) { _logger.fine("Mapping remoteUri: $remoteUri"); _logger.fine("Mapping local: ${mapping.local.value}"); _logger.fine("Mapping remote: ${mapping.remote.value}"); final Uri mappedUri = fromPathList(uri: mapping.local.value, paths: [ mapping.local.value.path, remoteUri.path.replaceFirst(mapping.remote.value.path, "") ]); _logger.fine("Mapped uri: $mappedUri"); //todo: is returning an absolute uri from mapping manager the best option? return _systemLocationService.absoluteUriFromInternal(mappedUri); } //todo: check what we are doing with this MappingPreference _getDefaultMapping(Uri root) { return MappingPreference( (builder) => builder ..key = "default" ..title = "default" ..remote.value = _nextCloudService.origin!.userEncodedDomainRoot ..local.value = fromUri( uri: root, path: _appendLocalMappingFolder(root.path), ), ); } Future mapToRemoteUri(Uri local, Uri remote) async { final MappingPreference mapping = _getRootMappingPreference(remote); final String relativePath = local.path.replaceFirst( mapping == null ? _systemLocationService.internalStorage.uri.path : mapping.local.value.path, "", ); return fromPathList( uri: remote, paths: [mapping.remote.value.path, relativePath]); } Future mapTmpToRemoteUri(Uri local, Uri remote) async { final Uri defaultInternal = _systemLocationService.internalCache.uri; final String relativePath = local.path .replaceFirst(_appendLocalMappingFolder(defaultInternal.path), ""); return fromUri(uri: remote, path: relativePath); } } ================================================ FILE: lib/managers/isolateable/sort_manager.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/sort_config.dart'; import 'package:yaga/model/sorted_category_list.dart'; import 'package:yaga/model/sorted_file_folder_list.dart'; import 'package:yaga/model/sorted_file_list.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; class SortManager with Isolateable { final Map< SortType, SortedFileList Function( List files, List folders, SortConfig config, )> _sortHandlers = {}; final Map)> _sortListHandlers = {}; final Map _mergeSortHandlers = {}; final Map _mixedMergeHandlers = {}; SortManager() { _sortHandlers[SortType.list] = _sortFileFolders; _sortHandlers[SortType.category] = _sortCategory; _sortListHandlers[SortProperty.name] = _sortListByName; _sortListHandlers[SortProperty.dateModified] = _sortListByDateModified; _mergeSortHandlers[SortType.list] = (SortedFileList main, SortedFileList addition) { if (main is SortedFileFolderList) { return _mergeFileFolders(main, addition); } return false; }; _mergeSortHandlers[SortType.category] = (SortedFileList main, SortedFileList addition) { if (main is SortedCategoryList && addition is SortedCategoryList) { return _mergeCategories(main, addition); } return false; }; _mixedMergeHandlers[SortType.list] = _mergeSortHandlers[SortType.list]!; _mixedMergeHandlers[SortType.category] = (SortedFileList main, SortedFileList addition) { if(main is SortedCategoryList && addition is SortedFileFolderList) { return _mixedMergeCategoryList(main, addition); } return false; }; } bool mergeSort(SortedFileList main, SortedFileList addition) { if (main.config.sortType == addition.config.sortType) { return _mergeSortHandlers[main.config.sortType]!(main, addition); } return _mixedMergeHandlers[main.config.sortType]!(main, addition); } bool _mixedMergeCategoryList( SortedCategoryList main, SortedFileFolderList addition, ) { final bool changed = _mergeLists(main.folders, addition.folders, null); final SortedCategoryList convertedAddition = sortList( addition.files, main.config, ) as SortedCategoryList; return _mergeCategories(main, convertedAddition) || changed; } bool _mergeFileFolders( SortedFileFolderList main, SortedFileList addition, ) { final bool changed = _mergeLists( main.files, addition.files, main.config.fileSortProperty, ); return _mergeLists( main.folders, addition.folders, main.config.folderSortProperty, ) || changed; } bool _mergeCategories(SortedCategoryList main, SortedCategoryList addition) { bool changed = false; addition.categories .where((key) => main.categories.contains(key)) .map( (key) => _mergeLists( main.categorizedFiles[key]!, addition.categorizedFiles[key]!, main.config.fileSortProperty, ), ) .forEach((catChanged) => changed = changed || catChanged); addition.categories.where((key) => !main.categories.contains(key)).forEach( (key) { changed = true; main.categories.add(key); main.categorizedFiles[key] = addition.categorizedFiles[key]!; }, ); _sortCategories(main.categories); return _mergeLists(main.folders, addition.folders, null) || changed; } bool _mergeLists( List main, List addition, SortProperty? prop, ) { final size = main.length; addition .where((element) => !main.contains(element)) .forEach((element) => main.add(element)); if (prop != null) { _sortListHandlers[prop]!(main); } return size < main.length; } SortedFileList sortList(List files, SortConfig config) { final List filesToSort = []; final List foldersToSort = []; for (final file in files) { if (file.isDirectory) { foldersToSort.add(file); } else { filesToSort.add(file); } } return _sortHandlers[config.sortType]!(filesToSort, foldersToSort, config); } SortedFileFolderList _sortFileFolders( List files, List folders, SortConfig config, ) { _sortListHandlers[config.fileSortProperty]!(files); _sortListHandlers[config.folderSortProperty]!(folders); return SortedFileFolderList(config, files, folders); } SortedCategoryList _sortCategory( List files, List folders, SortConfig config, ) { final sorted = SortedCategoryList(config, folders: folders); for (final file in files) { final String key = SortedCategoryList.createKey(file); if (!sorted.categories.contains(key)) { sorted.categories.add(key); } sorted.categorizedFiles.putIfAbsent(key, () => []); if (!sorted.categorizedFiles[key]!.contains(file)) { sorted.categorizedFiles[key]!.add(file); } } _sortCategories(sorted.categories); sorted.categorizedFiles .forEach((key, value) => _sortListByDateModified(value)); return sorted; } void _sortListByDateModified(List list) => list.sort( (a, b) => b.lastModified!.compareTo(a.lastModified!), ); void _sortListByName(List list) => list.sort( (a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()), ); void _sortCategories(List categories) => categories.sort((date1, date2) => date2.compareTo(date1)); } ================================================ FILE: lib/managers/isolateable/sync_manager.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/sync_file.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/logger.dart'; class SyncManager with Isolateable { final _logger = YagaLogger.getLogger(SyncManager); final Map> _syncMatrix = {}; Future addUri(Uri key) async { _syncMatrix.putIfAbsent(key, () => {}); } SyncFile? _addFile(Uri key, NcFile file) { return _syncMatrix[key]?.putIfAbsent(file.uri, () => SyncFile(file)); } Future addFile(Uri key, NcFile file) async { _logger.fine("Adding file ${file.uri.path}"); _addFile(key, file); } Future addRemoteFile(Uri key, NcFile file) async { _logger.fine("Adding remote file ${file.uri.path}"); _addFile(key, file)?.remote = true; } Future> syncUri(Uri key) async { return _syncMatrix .remove(key) ?.values .where((file) => !file.remote) .map((e) => e.file) .toList() ?? const []; } Future removeUri(Uri key) async { _syncMatrix.remove(key); } } ================================================ FILE: lib/managers/navigation_manager.dart ================================================ import 'package:rx_command/rx_command.dart'; import 'package:yaga/model/route_args/directory_navigation_screen_arguments.dart'; class NavigationManager { RxCommand showDirectoryNavigation = RxCommand.createSync((param) => param, initialLastResult: null); } ================================================ FILE: lib/managers/nextcloud_manager.dart ================================================ import 'dart:async'; import 'dart:io'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/model/nc_login_data.dart'; import 'package:rxdart/rxdart.dart'; import 'package:yaga/services/isolateable/local_file_service.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/services/secure_storage_service.dart'; import 'package:yaga/utils/self_signed_cert_handler.dart'; import 'package:yaga/utils/uri_utils.dart'; class NextCloudManager { late RxCommand loginCommand; late RxCommand _internalLoginCommand; //todo: this command has a bad naming since it only gets triggered on login not logout late RxCommand updateLoginStateCommand; late RxCommand logoutCommand; late RxCommand updateAvatarCommand; final SecureStorageService _secureStorageService; final NextCloudService _nextCloudService; final LocalFileService _localFileService; final SystemLocationService _systemLocationService; final SelfSignedCertHandler _selfSignedCertHandler; NextCloudManager( this._nextCloudService, this._secureStorageService, this._localFileService, this._systemLocationService, this._selfSignedCertHandler, ) { loginCommand = RxCommand.createFromStream( (param) => _createLoginDataPersisStream(param!)); loginCommand.listen((value) => _internalLoginCommand(value)); _internalLoginCommand = RxCommand.createSync((param) => param); _internalLoginCommand.listen((event) async { final origin = await _nextCloudService.login(event); if (event.id == "" || event.displayName == "") { await _selfSignedCertHandler.persistCert(); await _secureStorageService.savePreference( NextCloudLoginDataKeys.id, origin.username); await _secureStorageService.savePreference( NextCloudLoginDataKeys.displayName, origin.displayName); } updateLoginStateCommand(event); updateAvatarCommand(); }); updateLoginStateCommand = RxCommand.createSync( (param) => param, initialLastResult: NextCloudLoginData.empty(), ); logoutCommand = RxCommand.createFromStream( (_) => _createLoginDataPersisStream(NextCloudLoginData.empty()), ); logoutCommand .doOnData((event) => _nextCloudService.logout()) .listen((value) { _selfSignedCertHandler.revokeCert(); updateLoginStateCommand(value); updateAvatarCommand(); }); updateAvatarCommand = RxCommand.createAsync((_) => _handleAvatarUpdate(), initialLastResult: _avatarFile); } Future _handleAvatarUpdate() async { final File avatar = _avatarFile; if (_nextCloudService.isLoggedIn()) { return _nextCloudService .getAvatar() .then( (value) => _localFileService.createFile( file: avatar, bytes: value, ), ) .catchError((_) => avatar); } _localFileService.deleteFile(avatar); return avatar; } File get _avatarFile => File( chainPathSegments( _systemLocationService .absoluteUriFromInternal(_systemLocationService.internalCache.uri) .path, "${_nextCloudService.origin?.userDomain}.avatar", ), ); Future init() async { final String server = await _secureStorageService .loadPreference(NextCloudLoginDataKeys.server); final String user = await _secureStorageService.loadPreference(NextCloudLoginDataKeys.user); final String password = await _secureStorageService .loadPreference(NextCloudLoginDataKeys.password); final String userId = await _secureStorageService.loadPreference(NextCloudLoginDataKeys.id); final String displayName = await _secureStorageService .loadPreference(NextCloudLoginDataKeys.displayName); if (server != "" && user != "" && password != "") { final Completer login = Completer(); updateLoginStateCommand .where((event) => !login.isCompleted) .listen((value) => login.complete(this)); _internalLoginCommand(NextCloudLoginData( Uri.parse(server), user, password, id: userId, displayName: displayName, )); return login.future; } return this; } Stream _createLoginDataPersisStream( NextCloudLoginData data) { //todo: Background: can we persist this as a json? json support was added as part of the background worker return ForkJoinStream.list([ _secureStorageService .savePreference(NextCloudLoginDataKeys.server, data.server.toString()) .asStream(), _secureStorageService .savePreference(NextCloudLoginDataKeys.user, data.user) .asStream(), _secureStorageService .savePreference(NextCloudLoginDataKeys.password, data.password) .asStream(), _secureStorageService .savePreference(NextCloudLoginDataKeys.id, data.id) .asStream(), _secureStorageService .savePreference(NextCloudLoginDataKeys.displayName, data.displayName) .asStream(), ]).map((_) => data); } } ================================================ FILE: lib/managers/settings_manager.dart ================================================ import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/settings_manager_base.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/model/preferences/int_preference.dart'; import 'package:yaga/model/preferences/mapping_preference.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/uri_preference.dart'; import 'package:yaga/model/preferences/value_preference.dart'; import 'package:yaga/services/shared_preferences_service.dart'; typedef PrefFunction = T Function(T); class SettingsManager extends SettingsManagerBase { final SharedPreferencesService _sharedPreferencesService; late RxCommand, void> persistStringSettingCommand; late RxCommand persistBoolSettingCommand; late RxCommand persistMappingPreferenceCommand; late RxCommand removeMappingPreferenceCommand; late RxCommand loadMappingPreferenceCommand; late RxCommand persistIntSettingCommand; SettingsManager(this._sharedPreferencesService) { persistStringSettingCommand = RxCommand.createAsync((param) => _sharedPreferencesService.savePreferenceToString(param).then((value) => _checkPersistResult(value, param, _sharedPreferencesService.loadPreferenceFromString))); persistBoolSettingCommand = RxCommand.createAsync((param) => _sharedPreferencesService.savePreferenceToBool(param).then((value) => _checkPersistResult(value, param, _sharedPreferencesService.loadPreferenceFromBool))); persistIntSettingCommand = RxCommand.createAsync( (param) => _sharedPreferencesService.savePreferenceToInt(param).then( (value) => _checkPersistResult( value, param, _sharedPreferencesService.loadPreferenceFromInt, ), ), ); persistMappingPreferenceCommand = RxCommand.createSync((param) => param); persistMappingPreferenceCommand.listen((value) async { //todo: add error handling in case one of those fails // await _sharedPreferencesService.saveComplexPreference(value, // overrideValue: false); await _sharedPreferencesService.savePreferenceToBool(value); await _sharedPreferencesService.savePreferenceToString(value.remote); await _sharedPreferencesService.savePreferenceToString(value.local); await _sharedPreferencesService.savePreferenceToBool(value.syncDeletes); // _sharedPreferencesService.saveComplexPreference(value).then((res) => _sharedPreferencesService.savePreferenceToBool(value).then((res) => _checkPersistResult( res, value, _sharedPreferencesService.loadPreferenceFromBool)); }); removeMappingPreferenceCommand = RxCommand.createSync((param) => param); removeMappingPreferenceCommand.listen((value) async { await _sharedPreferencesService.removePreference(value.local); await _sharedPreferencesService.removePreference(value.remote); await _sharedPreferencesService.removePreference(value.syncDeletes); await _sharedPreferencesService.removePreference(value); }); loadMappingPreferenceCommand = RxCommand.createSync((param) => param); loadMappingPreferenceCommand.listen((value) { final UriPreference remote = _sharedPreferencesService.loadPreferenceFromString(value.remote); final UriPreference local = _sharedPreferencesService.loadPreferenceFromString(value.local); final BoolPreference syncDeletes = _sharedPreferencesService.loadPreferenceFromBool(value.syncDeletes); updateSettingCommand(_sharedPreferencesService.loadPreferenceFromBool( value.rebuild( (b) => b ..remote = remote.toBuilder() ..local = local.toBuilder() ..syncDeletes = syncDeletes.toBuilder(), ), )); }); } void _checkPersistResult( bool res, T defaultPref, T Function(T) onLoadPref) { if (!res) { //todo: add error handling if value==false //return; } updateSettingCommand(onLoadPref(defaultPref)); } } ================================================ FILE: lib/managers/settings_manager_base.dart ================================================ import 'package:rx_command/rx_command.dart'; import 'package:yaga/model/preferences/preference.dart'; abstract class SettingsManagerBase { late RxCommand updateSettingCommand; SettingsManagerBase() { updateSettingCommand = RxCommand.createSync((param) => param); } } ================================================ FILE: lib/managers/tab_manager.dart ================================================ import 'package:rx_command/rx_command.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; class TabManager { RxCommand tabChangedCommand = RxCommand.createSync((param) => param); } ================================================ FILE: lib/managers/widget_local/file_list_local_manager.dart ================================================ import 'dart:async'; import 'package:rx_command/rx_command.dart'; import 'package:uuid/uuid.dart'; import 'package:yaga/managers/file_manager/file_manager.dart'; import 'package:yaga/managers/isolateable/mapping_manager.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/model/preferences/mapping_preference.dart'; import 'package:yaga/model/sort_config.dart'; import 'package:yaga/model/sorted_category_list.dart'; import 'package:yaga/model/sorted_file_folder_list.dart'; import 'package:yaga/model/sorted_file_list.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/utils/forground_worker/foreground_worker.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_done.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_request.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_response.dart'; import 'package:yaga/utils/forground_worker/messages/file_update_msg.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/delete_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/destination_action_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/favorite_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_done.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_request.dart'; import 'package:yaga/utils/forground_worker/messages/merge_sort_done.dart'; import 'package:yaga/utils/forground_worker/messages/merge_sort_request.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/service_locator.dart'; // this is a widget local manager, meaning that it is intendet to exist per widget that needs its functionality // however this also means that the owning widget has to manage init and disposal // treat it like local state class FileListLocalManager { final _logger = YagaLogger.getLogger(FileListLocalManager); BoolPreference recursive; List selected = []; final bool allowSelecting; SortConfig _sortConfig; RxCommand loadingChangedCommand = RxCommand.createSync((param) => param, initialLastResult: false); late RxCommand filesChangedCommand; late RxCommand selectFileCommand = RxCommand.createSync((param) => param); late RxCommand selectionModeChanged = RxCommand.createSync((param) => param, initialLastResult: false); late RxCommand, List> selectionChangedCommand = RxCommand.createSync((param) => param); StreamSubscription? _updatedMappingPreferenceCommandSubscription; StreamSubscription? _updateFileListSubscripton; StreamSubscription? _updateRecursiveSubscription; //todo: we are here directly using the worker, we should be going over the file manager bridge final ForegroundWorker _worker; final FileManager _fileManager; StreamSubscription? _foregroundMessageCommandSubscription; StreamSubscription? _foregroundMergeSortSubscription; Uri _uri; late String managerKey; final bool favorites; bool get isInSelectionMode => selected.isNotEmpty; FileListLocalManager(this._uri, this.recursive, this._sortConfig, { this.allowSelecting = true, this.favorites = false, }) : _worker = getIt.get(), _fileManager = getIt.get() { filesChangedCommand = RxCommand.createSync( (param) => param, initialLastResult: emptyFileList, ); Uuid uuid = const Uuid(); managerKey = uuid.v1(); } SortedFileList get sorted => filesChangedCommand.lastResult!; Uri get uri => _uri; SortConfig get sortConfig => _sortConfig; SortedFileList get emptyFileList { if (_sortConfig.sortType == SortType.list) { return SortedFileFolderList.empty(_sortConfig); } else { return SortedCategoryList.empty(_sortConfig); } } void dispose() { _foregroundMessageCommandSubscription?.cancel(); _updatedMappingPreferenceCommandSubscription?.cancel(); _updateFileListSubscripton?.cancel(); _updateRecursiveSubscription?.cancel(); _foregroundMergeSortSubscription?.cancel(); } void updateFilesAndFolders() { //cancel old subscription _foregroundMessageCommandSubscription?.cancel(); _updateFileListSubscripton?.cancel(); loadingChangedCommand(true); //todo: why are we still rebuilding this subScriptions on refetch? //todo: in future communication with the background worker should be done by bridges & handlers, and not directly _foregroundMessageCommandSubscription = _fileManager.updateFilesCommand .where((event) => //file list may contain recursively loaded files; this is done so we minimize the UI thread merging of lists //todo: maybe there is a better approach to this (event.uri == uri) || (recursive.value && event.uri.toString().startsWith(uri.toString()))) .listen((event) { if (event is FileListResponse) { _logger.warning( "${event.key} (received list - #images: ${event.files.files.length})", ); // if uri is not equal then it could be a sub dir loaded by the copy command for example if (event.key == managerKey && event.uri == uri) { _showNewFiles(event.files); } else { // in this case we are interested in the data but can not tell if the data is not missing crutial parts // todo: can we build a bridge for this? _sendMergeSortRequest( MergeSortRequest( managerKey, //primarely to counter hot reloads filesChangedCommand.lastResult ?? emptyFileList, event.files, uri: uri, recursive: recursive.value, ), ); } } if (event is FileListDone && event.key == managerKey) { _logger.warning("$managerKey (done - manager key)"); _logger.warning("${event.key} (done - event key)"); loadingChangedCommand(false); } }); _updateFileListSubscripton = _fileManager.fileUpdateMessage.listen((event) => _removeFileFromList(event.file)); _logger.warning("$managerKey (start)"); _fileManager.fetchFileListCommand(FileListRequest( managerKey, uri, _sortConfig, recursive: recursive.value, favorites: favorites, )); } void _showNewFiles(SortedFileList files) { if (files.config == _sortConfig) { filesChangedCommand(files); } else { _sendMergeSortRequest( MergeSortRequest( managerKey, emptyFileList, files, ), ); } } void _sendMergeSortRequest(MergeSortRequest request) => _worker.sendRequest(request); //todo: changing the view type while fetching the list will not fetch all files bool setSortConfig(SortConfig sortConfig) { final changed = sortConfig != _sortConfig; _sortConfig = sortConfig; if (loadingChangedCommand.lastResult!) { return changed; } if (changed) { //todo: loading changed has to be improved... currently if we are fetching a list and changing the config simulatniously the first to be done will stop the loading indicator loadingChangedCommand(true); _sendMergeSortRequest( MergeSortRequest( managerKey, emptyFileList, filesChangedCommand.lastResult!, updateLoading: true, ), ); } return changed; } void _removeFileFromList(NcFile file) { _logger.warning("$managerKey (delete)"); final SortedFileList files = filesChangedCommand.lastResult!; //todo: delete and re-sort are interfearing with each other if (files.remove(file)) { //todo: what happens is that the deletes might be triggered on states before the resort is done filesChangedCommand(files); } } /* bool _fileIsFromThisManager(String eventKey) { return eventKey.startsWith(managerKey); } */ void refetch({Uri? uri}) { _uri = uri ?? _uri; updateFilesAndFolders(); } void initState() { updateFilesAndFolders(); _updatedMappingPreferenceCommandSubscription = getIt .get() .mappingUpdatedCommand .listen( (value) { // currently local file is not checked when comparing two NcFiles // thats why we have to clear the entire list and repopulate it // otherwise availability icons will not be refreshed // because NcFiles in list will not be refreshed and will still point to old local files removeAll(); refetch(); }, ); _updateRecursiveSubscription = getIt .get() .updateSettingCommand .where((event) => event.key == recursive.key) .map((event) => event as BoolPreference) .where((event) => event.value != recursive.value) .listen((event) { recursive = event; refetch(); }); selectFileCommand.where((_) => allowSelecting).listen((file) { final bool selectionMode = isInSelectionMode; file.selected = !file.selected; file.selected ? selected.add(file) : selected.remove(file); //using updateImageCommand is more effective then filesChangedCommand since it is not updating the whole list //however, keep in mind that this will update all widgets displaying this file not only the one in the current view //it might be a good idea to create a view local version of this command that relays global updates getIt.get().updateImageCommand(file); if (selectionMode != isInSelectionMode) { selectionModeChanged(isInSelectionMode); } else { selectionChangedCommand(selected); } }); _foregroundMergeSortSubscription = _worker.isolateResponseCommand .where((event) => event.key == managerKey) .where((event) => event is MergeSortDone) .map((event) => event as MergeSortDone) .listen((event) { _showNewFiles(event.sorted); if (event.updateLoading) { loadingChangedCommand(false); } }); } Future removeAll() async { filesChangedCommand(filesChangedCommand.lastResult! ..removeAll()); } bool isAllSelected() { final hasSelectedFolders = this.hasSelectedFolders; final hasSelectedFiles = this.hasSelectedFiles; if (hasSelectedFiles && hasSelectedFolders) { return selected.length == sorted.length; } if (hasSelectedFiles) { return selected.length == sorted.files.length; } return selected.length == sorted.folders.length; } Future toggleSelect() => isAllSelected() ? deselectAll() : selectAll(); Future deselectAll() async { final fileManager = getIt.get(); for (final file in selected) { file.selected = false; fileManager.updateImageCommand(file); } selected = []; selectionModeChanged(isInSelectionMode); } Future selectAll() async { final fileManager = getIt.get(); final hasSelectedFolders = this.hasSelectedFolders; final hasSelectedFiles = this.hasSelectedFiles; final sorted = filesChangedCommand.lastResult; selected = []; if (hasSelectedFiles) { selected.addAll(sorted!.files); } if (hasSelectedFolders) { selected.addAll(sorted!.folders); } for (final file in selected) { file.selected = true; fileManager.updateImageCommand(file); } selectionChangedCommand(selected); } Future deleteSelected({required bool local}) => _executeActionForSelection( DeleteFilesRequest( key: managerKey, files: selected, local: local, sourceDir: uri, ), ); Future favoriteSelected() => _executeActionForSelection( FavoriteFilesRequest( key: managerKey, files: selected, sourceDir: uri, ), ); Future copySelected(Uri destination, {bool overwrite = false}) => _executeActionForSelection( DestinationActionFilesRequest( key: managerKey, files: selected, destination: destination, overwrite: overwrite, sourceDir: uri, ), ); Future moveSelected(Uri destination, {bool overwrite = false}) => _executeActionForSelection( DestinationActionFilesRequest( key: managerKey, files: selected, destination: destination, action: DestinationAction.move, overwrite: overwrite, sourceDir: uri, ), ); Future _executeActionForSelection(FilesActionRequest action) async { final Completer jobDone = Completer(); _fileManager.filesActionCommand(action); final StreamSubscription actionSub = _fileManager.filesActionDoneCommand.where((event) => event.key == managerKey).listen((event) { jobDone.complete(true); _fileManager.fetchFileListCommand(FileListRequest( managerKey, event.destination, _sortConfig, )); }); return jobDone.future.whenComplete(() => actionSub.cancel()).whenComplete(() => deselectAll()); } void cancelSelectionAction() { _worker.sendRequest(FilesActionDone(managerKey, _uri)); } bool get isRemoteUri => getIt.get().isUriOfService(uri); bool get hasSelectedFolders => selected .where((e) => e.isDirectory) .firstOrNull ?.isDirectory ?? false; bool get hasSelectedFiles => !(selected .where((e) => !e.isDirectory) .firstOrNull ?.isDirectory ?? true); } ================================================ FILE: lib/model/category_view_config.dart ================================================ import 'package:yaga/model/general_view_config.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; class CategoryViewConfig { // final Uri defaultPath; final String pref; final YagaHomeTab? selectedTab; final bool? hasDrawer; final bool favorites; // final bool pathEnabled; final String? title; final GeneralViewConfig generalViewConfig; CategoryViewConfig({ required Uri defaultPath, required this.pref, this.selectedTab, this.hasDrawer, required bool pathEnabled, this.title, this.favorites = false }) : generalViewConfig = GeneralViewConfig(pref, defaultPath, pathEnabled: pathEnabled); } ================================================ FILE: lib/model/fetched_file.dart ================================================ import 'dart:typed_data'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; class FetchedFile extends Message { final NcFile file; final Uint8List data; FetchedFile(this.file, this.data) : super("FetchedFile"); } ================================================ FILE: lib/model/general_view_config.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/preferences/section_preference.dart'; import 'package:yaga/model/preferences/uri_preference.dart'; class GeneralViewConfig { final SectionPreference general; final UriPreference path; factory GeneralViewConfig( String pref, Uri defaultPath, { required bool pathEnabled, }) { final SectionPreference general = SectionPreference((b) => b ..key = Preference.prefixKey(pref, "general") ..title = "General"); final UriPreference path = UriPreference((b) => b ..key = general.prepareKey("path") ..title = "Path" ..value = defaultPath ..enabled = pathEnabled); return GeneralViewConfig.internal(general, path); } @protected GeneralViewConfig.internal(this.general, this.path); } ================================================ FILE: lib/model/local_file.dart ================================================ import 'dart:io'; class LocalFile { static const _jsonFileUrl = "fileUrl"; static const _jsonExists = "exists"; FileSystemEntity file; bool exists; LocalFile(this.file, this.exists); LocalFile.fromJson(Map json, {required bool isDirectory}) : file = isDirectory ? Directory.fromUri(Uri.parse(json[_jsonFileUrl] as String)) : File.fromUri(Uri.parse(json[_jsonFileUrl] as String)), exists = json[_jsonExists] as bool; Map toJson() { return { _jsonFileUrl: file.uri.toString(), _jsonExists: exists, }; } } ================================================ FILE: lib/model/mapping_node.dart ================================================ import 'package:yaga/model/preferences/mapping_preference.dart'; class MappingNode { Map nodes = {}; MappingPreference? mapping; } ================================================ FILE: lib/model/nc_file.dart ================================================ import 'package:mime/mime.dart'; import 'package:path/path.dart' as p; import 'package:yaga/model/local_file.dart'; class NcFile { static const String _jsonIsDirectory = "isDirectory"; static const String _jsonName = "name"; static const String _jsonFileExtension = "fileExtension"; static const String _jsonUri = "uri"; static const String _jsonUpstreamId = "upstreamId"; static const String _jsonLocalFile = "localFile"; static const String _jsonPreviewFile = "previewFile"; static const String _jsonLastModified = "lastModified"; static const String _jsonSelected = "selected"; static const String _jsonFavorite = "favorite"; final bool isDirectory; final String name; final String fileExtension; Uri uri; String? upstreamId; LocalFile? localFile; LocalFile? previewFile; DateTime? lastModified; bool selected = false; bool favorite = false; NcFile(this.uri, this.name, this.fileExtension, {required this.isDirectory, this.upstreamId}); NcFile.fromJson(Map json) : isDirectory = json[_jsonIsDirectory] as bool, name = json[_jsonName] as String, fileExtension = json[_jsonFileExtension] as String, uri = Uri.parse(json[_jsonUri] as String), upstreamId = json[_jsonUpstreamId] == null ? null : json[_jsonUpstreamId] as String, localFile = json[_jsonLocalFile] == null ? null : LocalFile.fromJson( json[_jsonLocalFile] as Map, isDirectory: json[_jsonIsDirectory] as bool, ), previewFile = json[_jsonPreviewFile] == null ? null : LocalFile.fromJson( json[_jsonPreviewFile] as Map, isDirectory: json[_jsonIsDirectory] as bool, ), lastModified = json[_jsonLastModified] == null ? null : DateTime.parse(json[_jsonLastModified] as String), selected = json[_jsonSelected] as bool, favorite = json[_jsonFavorite] as bool; factory NcFile.file(Uri uri, String name, String? mime) { String ext = p.extension(name).replaceAll('.', ''); if (ext.isEmpty) { ext = extensionFromMime(mime ?? ''); } return NcFile(uri, name, ext, isDirectory: false); } factory NcFile.directory(Uri uri, String name, {String? upstreamId}) => NcFile( uri, name, '', isDirectory: true, upstreamId: upstreamId, ); @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) return false; return other is NcFile && other.uri.toString() == uri.toString() && other.upstreamId == upstreamId; } @override int get hashCode => Object.hash(uri, upstreamId); Map toJson() { return { _jsonIsDirectory: isDirectory, _jsonName: name, _jsonFileExtension: fileExtension, _jsonUri: uri.toString(), _jsonUpstreamId: upstreamId, _jsonLocalFile: localFile?.toJson(), _jsonPreviewFile: previewFile?.toJson(), _jsonLastModified: lastModified?.toString(), _jsonSelected: selected, _jsonFavorite: favorite }; } } ================================================ FILE: lib/model/nc_login_data.dart ================================================ class NextCloudLoginDataKeys { static const String server = "server"; static const String user = "user"; static const String password = "password"; static const String id = "id"; static const String displayName = "displayName"; } class NextCloudLoginData { final Uri? server; final String user; final String password; final String id; final String displayName; NextCloudLoginData( this.server, this.user, this.password, { this.id = "", this.displayName = "", }); factory NextCloudLoginData.empty() => NextCloudLoginData(null, "", "",); //todo: Background: use auto-generation for formJson/toJson? NextCloudLoginData.fromJson(Map json) : server = Uri.parse(json[NextCloudLoginDataKeys.server] as String), user = json[NextCloudLoginDataKeys.user] as String, password = json[NextCloudLoginDataKeys.password] as String, id = json[NextCloudLoginDataKeys.id] as String, displayName = json[NextCloudLoginDataKeys.displayName] as String; Map toJson() { return { NextCloudLoginDataKeys.server: server.toString(), NextCloudLoginDataKeys.user: user, NextCloudLoginDataKeys.password: password, NextCloudLoginDataKeys.id: id, NextCloudLoginDataKeys.displayName: displayName, }; } } ================================================ FILE: lib/model/nc_origin.dart ================================================ class NcOrigin { /// This uri represents the original server uri with port and path if specified. /// Only the scheme is changed to 'nc'. /// /// In case of a local file: file://device.local /// /// Examples for valid [uri] values: /// * cloud.com: Domain /// * nc.cloud.com: Subdomain /// * www.cloud.com: Equal to subdomain. /// * www.cloud.com/nc: Nextcloud root behind subpath. /// * www.cloud.com:7443: Nextcloud root behind different port. final Uri uri; /// Examples for valid [username] values: /// * Simple username: xyz /// * Username with special characters: xyz@email.com /// * LDAP UUID: 2522ba7c2-xxxxxxxx-yyyyyy final String username; /// Display name, username, loign name can be different things in Nextcloud. /// Display name can be equal to the username or anything else like: Forename Lastname final String displayName; /// Can be an email or an username. final String loginName; NcOrigin( this.uri, this.username, this.displayName, this.loginName, ); String get domain => uri.host; //todo: when refactoring, how will we handle subpaths in origin for user home folder in app directory? /// We are using the login name for backwards compability however if a user logs out and in again with different login names /// then this user will not be mapped back to the right data folder. String get userDomain => "$loginName@${uri.host}"; /// This is the old representation of root. Still needed for the [MappingManager] to work properly. /// Returns uri in form: nc://user@host/ /// With user being encoded. /// We are using the login name for backwards compability however if a user logs out and in again with different login names /// then this user will not be mapped back to the right data folder. Uri get userEncodedDomainRoot => Uri( scheme: uri.scheme, userInfo: Uri.encodeComponent(loginName), host: uri.host, path: "/", ); } ================================================ FILE: lib/model/preferences/action_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:yaga/model/preferences/preference.dart'; part 'action_preference.g.dart'; abstract class ActionPreference implements Preference, Built { Function() get action; static void _initializeBuilder(ActionPreferenceBuilder b) => Preference.initBuilder(b); factory ActionPreference([void Function(ActionPreferenceBuilder) updates]) = _$ActionPreference; ActionPreference._(); } ================================================ FILE: lib/model/preferences/bool_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/serializers/base_type_serializer.dart'; import 'package:yaga/model/preferences/value_preference.dart'; part 'bool_preference.g.dart'; abstract class BoolPreference with BaseTypeSerializer implements SerializablePreference, Built { static void _initializeBuilder(BoolPreferenceBuilder b) => ValuePreference.initBuilder(b); factory BoolPreference([void Function(BoolPreferenceBuilder) updates]) = _$BoolPreference; BoolPreference._(); } ================================================ FILE: lib/model/preferences/choice_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/serializers/base_type_serializer.dart'; import 'package:yaga/model/preferences/value_preference.dart'; part 'choice_preference.g.dart'; abstract class ChoicePreference with BaseTypeSerializer implements SerializablePreference, Built { Map get choices; static void _initializeBuilder(ChoicePreferenceBuilder b) => ValuePreference.initBuilder(b); factory ChoicePreference([void Function(ChoicePreferenceBuilder) updates]) = _$ChoicePreference; ChoicePreference._(); } ================================================ FILE: lib/model/preferences/complex_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:flutter/foundation.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/value_preference.dart'; part 'complex_preference.g.dart'; //todo: is the bool value ever used? @BuiltValue(instantiable: false) abstract class ComplexPreference implements SerializablePreference { @protected static T initBuilder(T b) => ValuePreference.initBuilder(b); @override ComplexPreference rebuild(void Function(ComplexPreferenceBuilder) updates); @override ComplexPreferenceBuilder toBuilder(); } ================================================ FILE: lib/model/preferences/int_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/serializers/base_type_serializer.dart'; import 'package:yaga/model/preferences/serializers/int_serializer.dart'; import 'package:yaga/model/preferences/value_preference.dart'; part 'int_preference.g.dart'; abstract class IntPreference with BaseTypeSerializer implements SerializablePreference, Built { static void _initializeBuilder(IntPreferenceBuilder b) => ValuePreference.initBuilder(b); factory IntPreference([void Function(IntPreferenceBuilder) updates]) = _$IntPreference; IntPreference._(); } ================================================ FILE: lib/model/preferences/mapping_preference.dart ================================================ //todo: Preference clone functions should be unified library preference; import 'package:built_value/built_value.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/model/preferences/complex_preference.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/preferences/serializers/base_type_serializer.dart'; import 'package:yaga/model/preferences/uri_preference.dart'; part 'mapping_preference.g.dart'; abstract class MappingPreference with BaseTypeSerializer implements ComplexPreference, Built { UriPreference get remote; UriPreference get local; BoolPreference get syncDeletes; //todo: still need a solution for key prefixes static void _initializeBuilder(MappingPreferenceBuilder b) => ComplexPreference.initBuilder(b) ..value = true ..remote.key = "remote" ..remote.title = "Remote Path" //todo: scheme has to be retrieved from actual service ..remote.schemeFilter = "nc" ..local.key = "local" ..local.title = "Local Path" ..local.schemeFilter = "file" ..syncDeletes.key = "syncDeletes" ..syncDeletes.title = "Sync Server Deletes" ..syncDeletes.value = true; static void _finalizeBuilder(MappingPreferenceBuilder b) => b ..remote.key = Preference.prefixKey(b.key!, b.remote.key!) ..local.key = Preference.prefixKey(b.key!, b.local.key!) ..syncDeletes.key = Preference.prefixKey(b.key!, b.syncDeletes.key!); factory MappingPreference([void Function(MappingPreferenceBuilder) updates]) = _$MappingPreference; MappingPreference._(); } ================================================ FILE: lib/model/preferences/preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:flutter/foundation.dart'; part 'preference.g.dart'; @BuiltValue(instantiable: false) abstract class Preference { String? get key; String? get title; bool? get enabled; static String prefixKey(String prefix, String key) => key.startsWith(prefix) ? key : "$prefix:$key"; @protected static PreferenceBuilder initBuilder( PreferenceBuilder b) => b..enabled = true; Preference rebuild(void Function(PreferenceBuilder) updates); PreferenceBuilder toBuilder(); } ================================================ FILE: lib/model/preferences/section_preference.dart ================================================ //todo: refactor all preferences to respect enabled library preference; import 'package:built_value/built_value.dart'; import 'package:yaga/model/preferences/preference.dart'; part 'section_preference.g.dart'; abstract class SectionPreference implements Preference, Built { String prepareKey(String keyPart) => Preference.prefixKey(key!, keyPart); static void _initializeBuilder(SectionPreferenceBuilder b) => Preference.initBuilder(b); factory SectionPreference([void Function(SectionPreferenceBuilder) updates]) = _$SectionPreference; SectionPreference._(); } ================================================ FILE: lib/model/preferences/serializable_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:flutter/foundation.dart'; import 'package:yaga/model/preferences/value_preference.dart'; part 'serializable_preference.g.dart'; @BuiltValue(instantiable: false) abstract class SerializablePreference> implements ValuePreference { @protected static T initBuilder( ValuePreferenceBuilder b) => ValuePreference.initBuilder(b); SerializableType serialize(); PreferenceType deserialize(SerializableType? value); @override PreferenceType rebuild( void Function( SerializablePreferenceBuilder) updates); @override SerializablePreferenceBuilder toBuilder(); } ================================================ FILE: lib/model/preferences/serializers/base_type_serializer.dart ================================================ import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/value_preference.dart'; mixin BaseTypeSerializer> implements SerializablePreference { @override T serialize() { return value; } @override P deserialize(T? value) { return (value == null ? this : rebuild((b) => b..value = value)) as P; } } ================================================ FILE: lib/model/preferences/serializers/int_serializer.dart ================================================ import 'package:yaga/model/preferences/int_preference.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; mixin IntSerializer implements SerializablePreference { @override String serialize() { return value.toString(); } @override IntPreference deserialize(String? value) { return value == null ? this as IntPreference : rebuild((b) => b..value = int.parse(value)); } } ================================================ FILE: lib/model/preferences/serializers/uri_serializer.dart ================================================ import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/uri_preference.dart'; mixin UriSerializer implements SerializablePreference { @override String serialize() { return value.toString(); } @override UriPreference deserialize(String? value) { return value == null ? this as UriPreference : rebuild((b) => b..value = Uri.parse(value)); } } ================================================ FILE: lib/model/preferences/string_list_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/serializers/base_type_serializer.dart'; import 'package:yaga/model/preferences/value_preference.dart'; part 'string_list_preference.g.dart'; abstract class StringListPreference with BaseTypeSerializer, StringListPreference> implements SerializablePreference, List, StringListPreference>, Built { static void _initializeBuilder(StringListPreferenceBuilder b) => ValuePreference.initBuilder(b); factory StringListPreference( [void Function(StringListPreferenceBuilder) updates]) = _$StringListPreference; StringListPreference._(); } ================================================ FILE: lib/model/preferences/string_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/serializers/base_type_serializer.dart'; import 'package:yaga/model/preferences/value_preference.dart'; part 'string_preference.g.dart'; abstract class StringPreference with BaseTypeSerializer implements SerializablePreference, Built { static void _initializeBuilder(StringPreferenceBuilder b) => ValuePreference.initBuilder(b); factory StringPreference([void Function(StringPreferenceBuilder) updates]) = _$StringPreference; StringPreference._(); } ================================================ FILE: lib/model/preferences/uri_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/model/preferences/serializers/uri_serializer.dart'; import 'package:yaga/model/preferences/value_preference.dart'; part 'uri_preference.g.dart'; abstract class UriPreference with UriSerializer implements SerializablePreference, Built { bool get fixedOrigin; String get schemeFilter; static void _initializeBuilder(UriPreferenceBuilder b) => ValuePreference.initBuilder(b) ..fixedOrigin = false ..schemeFilter = ""; factory UriPreference([void Function(UriPreferenceBuilder) updates]) = _$UriPreference; UriPreference._(); } ================================================ FILE: lib/model/preferences/value_preference.dart ================================================ library preference; import 'package:built_value/built_value.dart'; import 'package:flutter/foundation.dart'; import 'package:yaga/model/preferences/preference.dart'; part 'value_preference.g.dart'; @BuiltValue(instantiable: false) abstract class ValuePreference implements Preference { T get value; @protected static T initBuilder( ValuePreferenceBuilder b) => Preference.initBuilder(b) as T; @override ValuePreference rebuild(void Function(ValuePreferenceBuilder) updates); @override ValuePreferenceBuilder toBuilder(); } ================================================ FILE: lib/model/preview_fetch_meta.dart ================================================ import 'package:yaga/model/nc_file.dart'; class PreviewFetchMeta { final NcFile file; final int fetchIndex; final bool success; PreviewFetchMeta(this.file, this.fetchIndex, {this.success = true}); } ================================================ FILE: lib/model/route_args/choice_selector_screen_arguments.dart ================================================ import 'package:yaga/model/preferences/choice_preference.dart'; class ChoiceSelectorScreenArguments { final ChoicePreference choicePreference; final void Function() onCancel; final void Function(String) onSelect; ChoiceSelectorScreenArguments( this.choicePreference, this.onSelect, this.onCancel); } ================================================ FILE: lib/model/route_args/directory_navigation_screen_arguments.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/route_args/navigatable_screen_arguments.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; class DirectoryNavigationScreenArguments extends NavigatableScreenArguments { final ViewConfiguration viewConfig; final bool leadingBackArrow; final bool fixedOrigin; final String schemeFilter; final String title; final Widget Function(BuildContext, Uri)? bottomBarBuilder; DirectoryNavigationScreenArguments({ required Uri uri, required this.title, required this.viewConfig, this.bottomBarBuilder, this.leadingBackArrow = true, this.fixedOrigin = false, this.schemeFilter = "", }) : super(uri: uri); } ================================================ FILE: lib/model/route_args/focus_view_arguments.dart ================================================ import 'package:yaga/views/screens/yaga_home_screen.dart'; class FocusViewArguments { final Uri path; final bool favorites; final YagaHomeTab selected; final String prefPrefix; FocusViewArguments(this.path, this.favorites, this.selected, this.prefPrefix); } ================================================ FILE: lib/model/route_args/image_screen_arguments.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/nc_file.dart'; class ImageScreenArguments { final List images; final int index; final String? title; final IconButton Function(BuildContext, NcFile)? mainActionBuilder; ImageScreenArguments( this.images, this.index, { this.title, this.mainActionBuilder, }); } ================================================ FILE: lib/model/route_args/navigatable_screen_arguments.dart ================================================ class NavigatableScreenArguments { final Uri uri; NavigatableScreenArguments({required this.uri}); } ================================================ FILE: lib/model/route_args/path_selector_screen_arguments.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/route_args/navigatable_screen_arguments.dart'; class PathSelectorScreenArguments extends NavigatableScreenArguments { final void Function(Uri)? onSelect; final void Function(List, int)? onFileTap; final String? title; final bool fixedOrigin; final String schemeFilter; PathSelectorScreenArguments({ required Uri uri, this.onSelect, this.onFileTap, this.title, this.fixedOrigin = false, this.schemeFilter = "", }) : super(uri: uri); } ================================================ FILE: lib/model/route_args/settings_screen_arguments.dart ================================================ import 'package:rx_command/rx_command.dart'; import 'package:yaga/model/preferences/preference.dart'; class SettingsScreenArguments { RxCommand? onSettingChangedCommand; List preferences; void Function()? onCommit; void Function()? onCancel; SettingsScreenArguments({ required this.preferences, this.onSettingChangedCommand, this.onCommit, this.onCancel, }); } ================================================ FILE: lib/model/sort_config.dart ================================================ import 'package:equatable/equatable.dart'; enum SortProperty { name, dateModified, } enum SortType { list, category, } class SortConfig extends Equatable { final SortType sortType; final SortProperty folderSortProperty; final SortProperty fileSortProperty; const SortConfig( this.sortType, this.fileSortProperty, this.folderSortProperty); @override List get props => [sortType, folderSortProperty, fileSortProperty]; } ================================================ FILE: lib/model/sorted_category_list.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/sort_config.dart'; import 'package:yaga/model/sorted_file_list.dart'; class SortedCategoryList extends SortedFileList { @override final List folders; final List categories = []; final Map> categorizedFiles = {}; SortedCategoryList( SortConfig config, { required this.folders, }) : super(config); factory SortedCategoryList.empty(SortConfig config) => SortedCategoryList(config, folders: []); static String createKey(NcFile file) => file.lastModified.toString().split(" ")[0]; @override List get files => categorizedFiles.values.fold( [], (previousValue, element) => previousValue..addAll(element), ); @override bool remove(NcFile file) { bool removed = false; if (file.isDirectory) { removed = folders.remove(file); if (removed) { for (final catFiles in categorizedFiles.values) { catFiles.removeWhere( (f) => f.uri.path.startsWith(file.uri.path), ); } categorizedFiles.removeWhere((key, value) => value.isEmpty); } return removed; } final String key = createKey(file); if (categorizedFiles.containsKey(key)) { removed = categorizedFiles[key]!.remove(file); if (removed && categorizedFiles[key]!.isEmpty) { categories.remove(key); categorizedFiles.remove(key); } } return removed; } @override void removeAll() { categories.clear(); categorizedFiles.clear(); folders.clear(); } @override SortedFileList applyFilter( bool Function(NcFile p1) filter, ) { final filteredFolders = folders .where( (element) => filter(element), ) .toList(); final filtered = SortedCategoryList(config, folders: filteredFolders); for (final cat in categories) { final filteredCat = categorizedFiles[cat]! .where( (element) => filter(element), ) .toList(); if (filteredCat.isNotEmpty) { filtered.categories.add(cat); filtered.categorizedFiles[cat] = filteredCat; } } return filtered; } } ================================================ FILE: lib/model/sorted_file_folder_list.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/sort_config.dart'; import 'package:yaga/model/sorted_file_list.dart'; class SortedFileFolderList extends SortedFileList { @override final List files; @override final List folders; SortedFileFolderList( SortConfig config, this.files, this.folders, ) : super(config); factory SortedFileFolderList.empty( SortConfig config, ) => SortedFileFolderList(config, [], []); @override bool remove(NcFile file) { if (file.isDirectory) { final bool removed = folders.remove(file); if (removed) { files.removeWhere( (element) => element.uri.path.startsWith(file.uri.path), ); } return removed; } return files.remove(file); } @override void removeAll() { files.clear(); folders.clear(); } @override SortedFileList applyFilter( bool Function(NcFile p1) filter, ) { final filteredFiles = files .where( (element) => filter(element), ) .toList(); final filteredFolders = folders .where( (element) => filter(element), ) .toList(); return SortedFileFolderList(config, filteredFiles, filteredFolders); } } ================================================ FILE: lib/model/sorted_file_list.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/sort_config.dart'; abstract class SortedFileList> { final SortConfig config; SortedFileList(this.config); List get files; List get folders; /// Removes give file or folder from the collection. /// If it is a folder then also all files belonging to that folder are removed. bool remove(NcFile file); void removeAll(); SortedFileList applyFilter(bool Function(NcFile) filter); int get length => files.length + folders.length; } ================================================ FILE: lib/model/sync_file.dart ================================================ import 'package:yaga/model/nc_file.dart'; class SyncFile { NcFile file; bool remote; SyncFile(this.file, {this.remote = false}); } ================================================ FILE: lib/model/system_location.dart ================================================ import 'dart:io'; import 'package:yaga/utils/uri_utils.dart'; class SystemLocation { final String privatePath; final String publicPath; final Uri absoluteUri; final Uri origin; SystemLocation(Directory directory, this.origin,) : privatePath = directory.path, publicPath = "", absoluteUri = directory.uri; SystemLocation.fromSplitter(Directory directory, this.origin, String splitter) : privatePath = directory.path.split(splitter)[0], publicPath = splitter + directory.path.split(splitter)[1], absoluteUri = directory.uri; Uri get uri => fromUri(uri: origin, path: publicPath); } ================================================ FILE: lib/services/file_provider_service.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/service.dart'; abstract class FileProviderService> extends Service { Stream list(Uri dir, bool favorites) => const Stream.empty(); } ================================================ FILE: lib/services/intent_service.dart ================================================ import 'dart:io'; import 'package:flutter/services.dart'; import 'package:mime/mime.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/service.dart'; class IntentService extends Service { static const _intentChannel = MethodChannel('yaga.channel.intent'); late String _intentAction; @override Future init() async { _intentAction = Platform.isAndroid ? await getIntentAction() : "linux"; return this; } String getCachedIntentAction() => _intentAction; Future getIntentAction() async { return _intentChannel .invokeMethod("getIntentAction") .then((value) => value.toString()); } Future setSelectedFile(NcFile file) async { //todo: maybe we should keep the mime type in the NcFile object final String mime = lookupMimeType(file.localFile!.file.path)??''; return _intentChannel.invokeMethod("setSelectedFile", { "path": file.localFile!.file.path, "mime": mime, }).then((value) => value as bool); } Future attachData(NcFile file) async { final String mime = lookupMimeType(file.localFile!.file.path)??''; return _intentChannel.invokeMethod("attachData", { "path": file.localFile!.file.path, "mime": mime, }); } bool get isOpenForSelect => _intentAction == "android.intent.action.GET_CONTENT" || _intentAction == "android.intent.action.PICK"; } ================================================ FILE: lib/services/isolateable/local_file_service.dart ================================================ import 'dart:io'; import 'dart:isolate'; import 'package:mime/mime.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:rxdart/rxdart.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/service.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/uri_utils.dart'; class LocalFileService extends Service implements Isolateable { late PermissionStatus _permissionState; @override Future init() async { if (Platform.isAndroid) { _permissionState = await Permission.storage.request(); await Permission.manageExternalStorage.request(); } else { _permissionState = PermissionStatus.granted; } return this; } @override Future initIsolated( InitMsg init, SendPort isolateToMain, ) async { _permissionState = PermissionStatus.granted; return this; } Future initBackgroundable() async { _permissionState = PermissionStatus.granted; return this; } Future createFile({ required File file, required List bytes, DateTime? lastModified, }) async { logger.fine("Creating file ${file.path}"); await file.create(recursive: true); final File res = await file.writeAsBytes(bytes, flush: true); if (lastModified != null) { await res.setLastModified(lastModified); } return res; } //todo: refactor when adding remote delete function void deleteFile(FileSystemEntity file) { //todo: null exception comes from webview cache files //todo: subtask1: local files in cache and default app dir should be in a user@cloud.bla folder //todo: subtask3: webview should not cache data if (file.existsSync()) { file.deleteSync(recursive: true); } } Stream list(Directory directory) { return Stream.value(_permissionState) .where((permissionState) => permissionState.isGranted) .flatMap((_) => directory.exists().asStream()) .where((exists) => exists) .flatMap((_) => directory.list(recursive: false, followLinks: false)) .where((event) => event is Directory || _checkMimeType(event.path)); } //todo: is this filtering here at the right place? bool _checkMimeType(String path) { final String type = lookupMimeType(path) ?? ''; return type.startsWith("image"); } void copyFile(NcFile file, Uri destination, {bool overwrite = false}) { (file.localFile! as File).copySync( _checkExists(destination, file.name, overwrite), ); } void moveFile(NcFile file, Uri destination, {bool overwrite = false}) { (file.localFile! as File).renameSync( _checkExists(destination, file.name, overwrite), ); } String _checkExists(Uri destination, String name, bool overwrite) { final String path = chainPathSegments(destination.path, name); if (!overwrite && File(path).existsSync()) { throw FileSystemException("File exists!", path); } return path; } } ================================================ FILE: lib/services/isolateable/nextcloud_service.dart ================================================ import 'dart:async'; import 'dart:isolate'; import 'dart:typed_data'; import 'package:nextcloud/core.dart'; import 'package:nextcloud/provisioning_api.dart'; import 'package:rxdart/rxdart.dart'; import 'package:nextcloud/nextcloud.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/nc_login_data.dart'; import 'package:yaga/model/nc_origin.dart'; import 'package:yaga/services/file_provider_service.dart'; import 'package:yaga/services/service.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/nextcloud_client_factory.dart'; import 'package:yaga/utils/uri_utils.dart'; class NextCloudService with Service, Isolateable implements FileProviderService { //todo: it will probably be best to replace nc with https since it does not bring any actual advantage // --> however this is a breaking change final String scheme = "nc"; NcOrigin? _origin; NextcloudClient? _client; NextCloudClientFactory nextCloudClientFactory; NextCloudService(this.nextCloudClientFactory); @override Future initIsolated( InitMsg init, SendPort isolateToMain, ) async { if (init.lastLoginData.server != null) { await login(init.lastLoginData); } return this; } Future initBackgroundable( NextCloudLoginData lastLoginData, ) async { if (lastLoginData.server != null) { await login(lastLoginData); } return this; } Future login(NextCloudLoginData loginData) async { //todo: can we get rid of the client factory? _client = nextCloudClientFactory.createNextCloudClient( loginData.server!, loginData.user, loginData.password, ); if (loginData.id == "" || loginData.displayName == "") { final userData = await _client?.provisioningApi.users .getCurrentUser() .catchError(_logAndRethrow); final displayName = userData?.body.ocs.data.displayName ?? userData?.body.ocs.data.displayName; return _origin = NcOrigin( fromUri(uri: loginData.server!, scheme: scheme), userData?.body.ocs.data.id ?? loginData.id, displayName ?? loginData.displayName, loginData.user, ); } return _origin = NcOrigin( fromUri(uri: loginData.server!, scheme: scheme), loginData.id, loginData.displayName, loginData.user, ); } void logout() { _client = null; _origin = null; } bool isLoggedIn() => _client != null; PathUri _prepUriForLib(Uri path) => PathUri.parse(Uri.decodeComponent(path.path)); Stream? _listOrReport(Uri dir, bool favorite) { return favorite ? _client?.webdav .report( PathUri.parse('/'), WebDavOcFilterRules( ocfavorite: 1, ), prop: WebDavPropWithoutValues.fromBools( nchaspreview: true, davgetcontenttype: true, davgetlastmodified: true, davresourcetype: true, ocfavorite: true, ), ) .asStream() .flatMap((value) => Stream.fromIterable(value.toWebDavFiles())) : _client?.webdav .propfind( _prepUriForLib(dir), prop: WebDavPropWithoutValues.fromBools( nchaspreview: true, davgetcontenttype: true, davgetlastmodified: true, ocfavorite: true, ), ) .asStream() .flatMap((value) => Stream.fromIterable(value.toWebDavFiles()..removeAt(0))); } @override Stream list(Uri dir, bool favorite) { logger.info("Listing ${dir.toString()}"); logger.info("NcOrigin: ${_origin?.userEncodedDomainRoot}"); return _listOrReport(dir, favorite) //todo: this will improve responsiveness in case of a bad connection but it can not be used as long // as we are using the sync manager for deletes and not the activity log. // .catchError((err) { // _logError(err); // return []; // }) ?.where( (event) => event.isDirectory || event.mimeType != null && event.mimeType!.startsWith("image"), ) .map((webDavFile) { logger.info("Mapping ${webDavFile.path}"); //todo: here we are hiding the origin path, if any, because we are not interested in it, the much bigger problem is: // we cannot assume that the origin is depictable by url.host // furthermore for identifing the upstream of a file we actually need an origin-url + username // since, when adding multi user support in future, in theory you can have multiple users on the same cloud // to properly be able to identify the origin of a NcFile we need to split the information currently stored in the uri property in three: // file.origin: Uri // file.username: String // file.path: String/Uri (not sure yet) // file.origin + file.username can identify the NextCloudClient // file.path represents only the relative path of that file // --> however, we can not simply substitute the [NcFile.uri] field as long as the [MppingManager] has not been reworked // --> the [MappingManager] needs now to be able to map [NcLocations(NcOrigin+Path)] to each other and not simply Urls // --> this however requires a rather big refactoring of the [MappingManager] including persistance final Uri uri = fromUri( uri: origin!.userEncodedDomainRoot, path: webDavFile.path.path, ); final NcFile file = webDavFile.isDirectory ? NcFile.directory(uri, webDavFile.name) : NcFile.file(uri, webDavFile.name, webDavFile.mimeType); file.lastModified = webDavFile.lastModified; file.favorite = webDavFile.favorite ?? false; return file; }).doOnError((error, stacktrace) { _logError(error, stacktrace: stacktrace); }) ?? const Stream.empty(); //.toList --> todo: should this return a Future since the data is actually allready downloaded? } Future getAvatar() => _client?.core.avatar .getAvatar(userId: origin!.username, size: 100) .catchError(_logAndRethrow) .then((value) => value.body) ?? Future.error("Not logged in!"); Future getPreview(Uri file) { final String path = Uri.decodeComponent(file.path); logger.fine("Fetching preview $path"); //todo: think about image sizes vs in code scaling return _client?.core.preview .getPreview( file: path, x: 128, y: 128, a: 1, mode: 'cover', ) .then((value) => value.body) ?? Future.error("Not logged in!"); //todo: implement proper error handling // .catchError((err) { // print("Could not load preview for $path"); // return err; // }); } Future downloadImage(Uri file) => _client?.webdav.get(_prepUriForLib(file)).catchError(_logAndRethrow) ?? Future.error("Not logged in!"); NcOrigin? get origin => _origin; //todo: should we consider adding an [isLocal] property to NcOrigin? bool isUriOfService(Uri uri) => uri.scheme == scheme; Future deleteFile(NcFile file) => _client?.webdav .delete(_prepUriForLib(file.uri)) .catchError(_logAndRethrow) .then((_) => file) ?? Future.error("Not logged in!"); Future copyFile(NcFile file, Uri destination, {bool overwrite = false}) => _client?.webdav .copy( _prepUriForLib(file.uri), _prepUriForLib(destination.resolve(file.name)), overwrite: overwrite, ) .catchError(_logAndRethrow) .then((_) => file) ?? Future.error("Not logged in!"); Future moveFile(NcFile file, Uri destination, {bool overwrite = false}) => _client?.webdav .move( _prepUriForLib(file.uri), _prepUriForLib(destination.resolve(file.name)), overwrite: overwrite, ) .catchError(_logAndRethrow) .then((_) => file) ?? Future.error("Not logged in!"); void _logAndRethrow(Object err) { _logError(err); throw err; } Future toggleFavorite(NcFile file) => _client?.webdav .proppatch( _prepUriForLib(file.uri), set: WebDavProp(ocfavorite: file.favorite ? 0 : 1), ) .catchError(_logAndRethrow) .then((_) => file..favorite = !file.favorite) ?? Future.error("Not logged in!"); void _logError(dynamic err, {StackTrace? stacktrace}) { logger.severe(err, err, stacktrace); } } ================================================ FILE: lib/services/isolateable/system_location_service.dart ================================================ import 'dart:io'; import 'dart:isolate'; import 'package:path_provider/path_provider.dart'; import 'package:yaga/model/system_location.dart'; import 'package:yaga/services/service.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/uri_utils.dart'; class SystemLocationService extends Service implements Isolateable { static final _internalOrigin = Uri(scheme: "file", host: "device.local", path: "/"); static final _tmpOrigin = Uri(scheme: "file", host: "device.tmp", path: "/"); static const _externalHost = "device.ext"; final Map _locations = {}; List get externals => _locations.values .where((element) => element.origin != _internalOrigin) .where((element) => element.origin != _tmpOrigin) .toList(); @override Future init() async { _init( (await getExternal())!, await getCacheDir(), (await getExternals())!, ); return this; } Future getCacheDir() => getApplicationCacheDirectory(); Future getExternal() => Platform.isAndroid ? getExternalStorageDirectory() : getApplicationSupportDirectory(); Future?> getExternals() async { if(Platform.isAndroid) { return getExternalStorageDirectories(); } return [await getApplicationSupportDirectory()]; } @override Future initIsolated( InitMsg init, SendPort isolateToMain, ) async { _init(init.externalPath, init.tmpPath, init.externalPaths); return this; } void _init( Directory externalDir, Directory tmpDir, List external) { _locations[_internalOrigin.authority] = Platform.isAndroid ? SystemLocation.fromSplitter(externalDir, _internalOrigin, "/Android") : SystemLocation(externalDir, _internalOrigin); _locations[_tmpOrigin.authority] = Platform.isAndroid ? SystemLocation.fromSplitter(tmpDir, _tmpOrigin, "/cache") : SystemLocation(tmpDir, _tmpOrigin); external .where((element) => element.toString() != externalDir.toString()) .forEach((element) { final Uri origin = Uri( scheme: "file", userInfo: element.uri.pathSegments[1], host: _externalHost, path: "/", ); _locations[origin.authority] = Platform.isAndroid ? SystemLocation.fromSplitter(element, origin, "/Android") : SystemLocation(element, origin); }); } //todo: think about this -> there are two ways of solving this //todo: first, we can infer the host by matching the starting part of the URI, advantage: self-contained, disadvantage: will require checking for every file //todo: second, we can require passing the host from the calling manager which should know if we are dealing with a local or tmp file Uri internalUriFromAbsolute(Uri absolute) { Uri? res; _locations.forEach((key, value) { if (absolute.path.startsWith(value.privatePath)) { res = fromUri( uri: value.origin, path: _internalUriNormalizePath(absolute, value), ); } }); if (res == null) { throw ArgumentError("Unknown system location!"); } return res!; } String _internalUriNormalizePath(Uri absolute, SystemLocation location) { return absolute.path.replaceFirst(location.privatePath, ""); } Uri absoluteUriFromInternal(Uri internal) { // already absolute if (internal.host == "") { return internal; } //todo: add a test when a local folder contain uri encoded chars //--> this happens when a server is behind a subpath cloud.com/nc //--> then NC Files App will create a local folder like cloud.com%2Fnc return fromPathList( uri: _locations[internal.authority]!.absoluteUri, paths: [ _locations[internal.authority]!.privatePath, internal.path, ], ); } SystemLocation get internalStorage => _locations[_internalOrigin.authority]!; SystemLocation get internalCache => _locations[_tmpOrigin.authority]!; } ================================================ FILE: lib/services/media_file_service.dart ================================================ import 'dart:io'; import 'package:photo_manager/photo_manager.dart'; import 'package:rxdart/rxdart.dart'; import 'package:yaga/model/local_file.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/services/service.dart'; import 'package:yaga/services/uri_name_resolver.dart'; import 'package:yaga/utils/ncfile_stream_extensions.dart'; import 'package:yaga/utils/uri_utils.dart'; class MediaFileService extends Service implements UriNameResolver { final SystemLocationService _systemLocationService; Map albums = {}; MediaFileService(this._systemLocationService); Stream listFiles(Uri uri) { if (uri.path == "/") { return _fetchAlbums(uri); } //todo: this is a POC state; clean everything up! if (albums.containsKey(getNameFromUri(uri))) { return _fetchAlbum(uri); } return _fetchAlbums(getRootFromUri(uri)) .collectToList() .flatMap((value) => _fetchAlbum(uri)); } Stream _fetchAlbums(Uri uri) { return PhotoManager.getAssetPathList(type: RequestType.image) .asStream() .doOnData((event) => albums = {}) .flatMap((value) => Stream.fromIterable(value)) .doOnData((event) => albums.putIfAbsent(event.id, () => event)) .map( (event) => NcFile.directory( fromUri(uri: uri, path: "/${event.id}"), event.name, upstreamId: event.id, ), ); } Stream _fetchAlbum(Uri uri) { final album = albums[getNameFromUri(uri)]; if (album == null) { return const Stream.empty(); } // todo: here we fetch all assets, this probably can be improved by making better use of MediaStore API regarding sorting and performance return album.assetCountAsync.asStream().flatMap( (count) => album .getAssetListRange(start: 0, end: count) .asStream() .flatMap((files) => Stream.fromIterable(files)) .asyncMap( (event) async { final file = NcFile.file( fromUri(uri: uri, path: "${event.relativePath}${event.title!}"), event.title!, event.mimeType, ); file.upstreamId = event.id; file.lastModified = event.modifiedDateTime; file.localFile = await _createLocalFile(file.uri); return file; }, ), ); } Future _createLocalFile(Uri uri) async { Uri internal = _systemLocationService.absoluteUriFromInternal(uri); File file = File.fromUri(internal); return LocalFile(file, file.existsSync()); } @override Uri getHumanReadableForm(Uri uri) { var id = getNameFromUri(uri); if (albums.containsKey(id)) { return fromUri(uri: uri, path: "/${albums[id]!.name}"); } return uri; } @override String get scheme => _systemLocationService.internalStorage.origin.scheme; Future> deleteFile(List files) { return PhotoManager.editor .deleteWithIds(files.map((file) => file.upstreamId!).toList()) .then( (deletedIds) => files .where((file) => deletedIds.contains(file.upstreamId)) .toList(), ); } } ================================================ FILE: lib/services/name_exchange_service.dart ================================================ import 'package:yaga/services/media_file_service.dart'; import 'package:yaga/services/service.dart'; import 'package:yaga/services/uri_name_resolver.dart'; class NameExchangeService extends Service { Map resolvers = {}; NameExchangeService(MediaFileService mediaFileService) { resolvers[mediaFileService.scheme] = mediaFileService; } Uri convertUriToHumanReadableUri(Uri uri) { if(resolvers.containsKey(uri.scheme)) { return resolvers[uri.scheme]!.getHumanReadableForm(uri); } return uri; } } ================================================ FILE: lib/services/secure_storage_service.dart ================================================ import 'package:flutter/services.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:yaga/services/service.dart'; class SecureStorageService extends Service { final FlutterSecureStorage _storage = const FlutterSecureStorage(); Future savePreference(String key, String value) { return _storage.write(key: key, value: value).catchError(_logAndRethrow); } Future loadPreference(String key) { return _storage .read(key: key) .catchError(_logAndRethrow) .then((value) => value ?? ""); } Future deletePreference(String key) { return _storage.delete(key: key).catchError(_logAndRethrow); } void _logAndRethrow(Object err) { if (err is PlatformException) { logger.severe("SecureStorage: ${err.code}"); logger.severe("SecureStorage: ${err.message}"); logger.severe("SecureStorage: ${err.details}"); logger.severe("SecureStorage: ${err.stacktrace}"); } else { logger.severe(err); } throw err; } } ================================================ FILE: lib/services/service.dart ================================================ import 'package:flutter/foundation.dart'; import 'package:yaga/utils/logger.dart'; mixin class Service> { @protected final logger = YagaLogger.getLogger(T); Future init() async => this as T; } ================================================ FILE: lib/services/shared_preferences_service.dart ================================================ import 'package:shared_preferences/shared_preferences.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/preferences/serializable_preference.dart'; import 'package:yaga/services/service.dart'; class SharedPreferencesService extends Service { late SharedPreferences _instance; @override Future init() async { _instance = await SharedPreferences.getInstance(); return this; } Future removePreference(Preference pref) => _instance.remove(pref.key!); Future savePreferenceToString( SerializablePreference pref) => _instance.setString(pref.key!, pref.serialize()); P loadPreferenceFromString< P extends SerializablePreference>(P pref) => pref.deserialize(_instance.getString(pref.key!)) as P; Future savePreferenceToBool( SerializablePreference pref) => _instance.setBool(pref.key!, pref.serialize()); P loadPreferenceFromBool< P extends SerializablePreference>(P pref) => pref.deserialize(_instance.getBool(pref.key!)) as P; Future savePreferenceToInt( SerializablePreference pref) => _instance.setInt(pref.key!, pref.serialize()); P loadPreferenceFromInt< P extends SerializablePreference>(P pref) => pref.deserialize(_instance.getInt(pref.key!)) as P; Future savePreferenceToStringList( SerializablePreference, dynamic, dynamic> pref) => _instance.setStringList(pref.key!, pref.serialize()); P loadPreferenceFromStringList< P extends SerializablePreference, dynamic, dynamic>>( P pref) => pref.deserialize(_instance.getStringList(pref.key!)) as P; } ================================================ FILE: lib/services/uri_name_resolver.dart ================================================ abstract class UriNameResolver { String get scheme; Uri getHumanReadableForm(Uri uri); } ================================================ FILE: lib/utils/background_worker/background_channel.dart ================================================ import 'package:flutter_background_service_android/flutter_background_service_android.dart'; import 'package:yaga/utils/background_worker/background_commands.dart'; import 'package:yaga/utils/background_worker/json_convertable.dart'; class BackgroundChannel{ final AndroidServiceInstance service; BackgroundChannel(this.service); void send(JsonConvertable msg) => service.invoke(BackgroundCommands.workerToMain, msg.toJson()); } ================================================ FILE: lib/utils/background_worker/background_commands.dart ================================================ class BackgroundCommands { static const String started = "started"; static const String init = "init"; static const String initDone = "initDone"; static const String stopped = "stopped"; static const String mainToWorker = "mainToWorker"; static const String workerToMain = "workerToMain"; } ================================================ FILE: lib/utils/background_worker/background_worker.dart ================================================ import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:flutter_background_service_android/flutter_background_service_android.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/file_manager/isolateable/file_action_manager.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/model/fetched_file.dart'; import 'package:yaga/utils/background_worker/background_channel.dart'; import 'package:yaga/utils/background_worker/background_commands.dart'; import 'package:yaga/utils/background_worker/json_convertable.dart'; import 'package:yaga/utils/background_worker/messages/background_downloaded_request.dart'; import 'package:yaga/utils/background_worker/messages/background_init_msg.dart'; import 'package:yaga/utils/background_worker/work_tracker.dart'; import 'package:yaga/utils/forground_worker/messages/download_file_request.dart'; import 'package:yaga/utils/forground_worker/messages/file_update_msg.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/delete_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/destination_action_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/favorite_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_done.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_request.dart'; import 'package:yaga/utils/forground_worker/messages/image_update_msg.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/self_signed_cert_handler.dart'; import 'package:yaga/utils/service_locator.dart'; class BackgroundWorker { final _logger = YagaLogger.getLogger(BackgroundWorker); final NextCloudManager _nextCloudManager; final SelfSignedCertHandler _selfSignedCertHandler; final service = FlutterBackgroundService(); Completer _isolateReady = Completer(); final RxCommand isolateResponseCommand = RxCommand.createSync((param) => param); BackgroundWorker(this._nextCloudManager, this._selfSignedCertHandler); Future init() async { if (Platform.isAndroid) { await Permission.notification.request(); await Permission.scheduleExactAlarm.request(); await Permission.photos.request(); await service.configure( androidConfiguration: AndroidConfiguration( // this will be executed when app is in foreground or background in separated isolate onStart: _workerMain, // auto start service autoStart: false, isForegroundMode: true, ), iosConfiguration: IosConfiguration( // auto start service autoStart: false, // this will be executed when app is in foreground in separated isolate onForeground: _workerMain, // you have to enable background fetch capability on xcode project onBackground: _onIosBackground, ), ); service.on(BackgroundCommands.workerToMain).listen((json) async { if (json != null && json[JsonConvertable.jsonTypeField] != null) { final type = json[JsonConvertable.jsonTypeField] as String; switch (type) { case BackgroundDownloadedRequest.jsonTypeConst: _fileFetchedHandler(json); break; case FileUpdateMsg.jsonTypeConst: isolateResponseCommand(FileUpdateMsg.fromJson(json)); break; case ImageUpdateMsg.jsonTypeConst: isolateResponseCommand(ImageUpdateMsg.fromJson(json)); break; case FilesActionDone.jsonTypeConst: isolateResponseCommand(FilesActionDone.fromJson(json)); break; default: //todo: handle error return; } } }); service.on(BackgroundCommands.started).listen((event) { _logger.info("Started Message"); service.invoke( BackgroundCommands.init, BackgroundInitMsg( _nextCloudManager.updateLoginStateCommand.lastResult!, _selfSignedCertHandler.fingerprint, ).toJson()); }); service.on(BackgroundCommands.initDone).listen( (event) { _logger.info("Init Done Message"); _isolateReady.complete(this); }, ); service.on(BackgroundCommands.stopped).listen((event) { _isolateReady = Completer(); }); } return this; } Future sendRequest(JsonConvertable message) async { _logger.info("Worker Request: ${message.jsonType}"); if (await service.isRunning() && _isolateReady.isCompleted) { service.invoke( BackgroundCommands.mainToWorker, message.toJson(), ); return; } _isolateReady.future.then( (value) => service.invoke( BackgroundCommands.mainToWorker, message.toJson(), ), ); await service.startService(); } Future _fileFetchedHandler(Map json) async { final event = BackgroundDownloadedRequest.fromJson(json); _logger.info( "Fetched Message: success=${event.success} ${event.file.uri.toString()}", ); if (!event.success) { //todo: Background: add notification or something return; } isolateResponseCommand( FetchedFile( event.file, await (event.file.localFile!.file as File).readAsBytes(), ), ); } static bool _onIosBackground(ServiceInstance service) { return true; } @pragma('vm:entry-point') static Future _workerMain(ServiceInstance service) async { // Only available for flutter 3.0.0 and later DartPluginRegistrant.ensureInitialized(); final ser = service as AndroidServiceInstance; service.on(BackgroundCommands.init).listen((event) { if (event == null) { return; } final init = BackgroundInitMsg.fromJson(event); final channel = BackgroundChannel(ser); setupBackgroundServiceLocator(init, channel); getIt.allReady().then( (_) { getIt.get().filesActionDoneCommand.listen( (value) => service.invoke(BackgroundCommands.workerToMain, value.toJson()), ); getIt.get().fileUpdateMessage.listen( (value) => service.invoke(BackgroundCommands.workerToMain, value.toJson()), ); service.invoke(BackgroundCommands.initDone); }, ); }); service.on(BackgroundCommands.mainToWorker).listen((event) { if (event == null || event[JsonConvertable.jsonTypeField] == null) { //todo: check for stop condition return; } final type = event[JsonConvertable.jsonTypeField] as String; switch (type) { case DownloadFileRequest.jsonTypeConst: _handleDownload(ser, DownloadFileRequest.fromJson(event)); case DestinationActionFilesRequest.jsonTypeConst: _handleFileAction( ser, DestinationActionFilesRequest.fromJson(event), getIt.get().copyMoveRequest, ); case DeleteFilesRequest.jsonTypeConst: _handleFileAction( ser, DeleteFilesRequest.fromJson(event), getIt.get().deleteFiles, ); case FavoriteFilesRequest.jsonTypeConst: _handleFileAction( ser, FavoriteFilesRequest.fromJson(event), (msg) => getIt.get().toggleFavorites(msg), ); default: //todo: log error //todo: check for stop condition return; } }); service.invoke(BackgroundCommands.started); } static Future _handleFileAction( AndroidServiceInstance service, T message, Future Function(T) handler, ) async { //todo: not unique enough; just temp getIt.get().activeTasks[message.sourceDir.toString()] = message; return handler(message).whenComplete( () => _checkAndStopService( service, message.sourceDir.toString(), ), ); } static Future _checkAndStopService( AndroidServiceInstance service, String taskId, ) async { getIt.get().activeTasks.remove(taskId); if (getIt.get().activeTasks.isEmpty) { service.invoke(BackgroundCommands.stopped); await service.stopSelf(); } } static Future _handleDownload( AndroidServiceInstance service, DownloadFileRequest request, ) async { getIt.get().activeTasks[request.file.uri.toString()] = request; await _updateNotification(service); return getIt .get() .downloadFile(request.file, persist: request.persist) .then((value) => _handleResult( service: service, request: request, success: true, )) .onError((error, stackTrace) => _handleResult(service: service, request: request, success: false)); } static Future _handleResult({ required AndroidServiceInstance service, required DownloadFileRequest request, required bool success, }) async { service.invoke( BackgroundCommands.workerToMain, BackgroundDownloadedRequest( success: success, file: request.file, ).toJson(), ); await _updateNotification(service); return _checkAndStopService(service, request.file.uri.toString()); } static Future _updateNotification( AndroidServiceInstance service, ) { String names = "..."; //todo: fix message return service.setForegroundNotificationInfo( title: "Nextcloud Yaga", content: "Downloading $names", ); } } ================================================ FILE: lib/utils/background_worker/json_convertable.dart ================================================ import 'package:yaga/utils/forground_worker/messages/message.dart'; abstract class JsonConvertable extends Message { static const String _jsonKey = "key"; static const String jsonTypeField = "jsonType"; final String jsonType; JsonConvertable(String key, this.jsonType) : super(key); JsonConvertable.fromJson(Map json) : jsonType = json[jsonTypeField] as String, super(json[_jsonKey] as String); Map toJson() { return { jsonTypeField: jsonType, _jsonKey: key, }; } } ================================================ FILE: lib/utils/background_worker/messages/background_downloaded_request.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/single_file_message.dart'; class BackgroundDownloadedRequest extends SingleFileMessage { static const String jsonTypeConst = "BackgroundDownloadedRequest"; static const String _jsonSuccess = "success"; final bool success; BackgroundDownloadedRequest({required NcFile file, required this.success}) : super(jsonTypeConst, jsonTypeConst, file); BackgroundDownloadedRequest.fromJson(Map json) : success = json[_jsonSuccess] as bool, super.fromJson(json); @override Map toJson() { final map = super.toJson(); map[_jsonSuccess] = success; return map; } } ================================================ FILE: lib/utils/background_worker/messages/background_init_msg.dart ================================================ import 'package:yaga/model/nc_login_data.dart'; class BackgroundInitMsg { static const String _jsonLastLoginData = "lastLoginData"; static const String _jsonFingerprint = "fingerprint"; final NextCloudLoginData lastLoginData; final String fingerprint; BackgroundInitMsg(this.lastLoginData, this.fingerprint); BackgroundInitMsg.fromJson(Map json) : lastLoginData = NextCloudLoginData.fromJson( json[_jsonLastLoginData] as Map, ), fingerprint = json[_jsonFingerprint] as String; Map toJson() { return { _jsonLastLoginData: lastLoginData.toJson(), _jsonFingerprint: fingerprint, }; } } ================================================ FILE: lib/utils/background_worker/work_tracker.dart ================================================ import 'package:yaga/utils/background_worker/json_convertable.dart'; class WorkTracker { final Map activeTasks = {}; } ================================================ FILE: lib/utils/download_file_image.dart ================================================ import 'dart:async'; import 'dart:io'; import 'dart:ui' as ui show Codec, ImmutableBuffer; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:yaga/model/fetched_file.dart'; typedef _SimpleDecoderCallback = Future Function(ui.ImmutableBuffer buffer); // this entire class is a copy of the respective FileImage functions // with the addition of an await for the localFileAvailable // proper solution would probably be to write an own ImageProvider class DownloadFileImage extends FileImage { final Future localFileAvailable; const DownloadFileImage(File file, this.localFileAvailable) : super(file); /// this function is copied from parent without changes @override ImageStreamCompleter loadBuffer(FileImage key, DecoderBufferCallback decode) { return MultiFrameImageStreamCompleter( codec: _loadAsync(key, decode: decode), scale: key.scale, debugLabel: key.file.path, informationCollector: () => [ ErrorDescription('Path: ${file.path}'), ], ); } @override @protected ImageStreamCompleter loadImage(FileImage key, ImageDecoderCallback decode) { return MultiFrameImageStreamCompleter( codec: _loadAsync(key, decode: decode), scale: key.scale, debugLabel: key.file.path, informationCollector: () => [ ErrorDescription('Path: ${file.path}'), ], ); } /// this function is copied from the parent /// await localFileAvailable was added and Uint8List result is reused Future _loadAsync( FileImage key, { required _SimpleDecoderCallback decode, }) async { final fetchedFile = await localFileAvailable; assert(key == this); // TODO(jonahwilliams): making this sync caused test failures that seem to // indicate that we can fail to call evict unless at least one await has // occurred in the test. // https://github.com/flutter/flutter/issues/113044 final int lengthInBytes = fetchedFile.data.length; if (lengthInBytes == 0) { // The file may become available later. PaintingBinding.instance.imageCache.evict(key); throw StateError('$file is empty and cannot be loaded as an image.'); } return decode(await ui.ImmutableBuffer.fromUint8List(fetchedFile.data)); } } ================================================ FILE: lib/utils/forground_worker/bridges/file_manager_bridge.dart ================================================ import 'package:rx_command/rx_command.dart'; import 'package:rxdart/rxdart.dart'; import 'package:yaga/managers/file_manager/file_manager.dart'; import 'package:yaga/managers/file_service_manager/media_file_manager.dart'; import 'package:yaga/utils/background_worker/background_worker.dart'; import 'package:yaga/utils/forground_worker/foreground_worker.dart'; import 'package:yaga/utils/forground_worker/messages/image_update_msg.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; //todo: slowly deprecate bridges; this is logic which belongs into the fileManager class FileManagerBridge { final FileManager _fileManager; final ForegroundWorker _worker; final MediaFileManager _mediaFileManager; final BackgroundWorker _backgroundWorker; FileManagerBridge( this._fileManager, this._worker, this._mediaFileManager, this._backgroundWorker, ) { _registerWorkerMessageWithTransformation( (ImageUpdateMsg msg) => msg.file, _fileManager.updateImageCommand, ); _registerWorkerMessage(_fileManager.fetchedFileCommand); _registerWorkerMessage(_fileManager.filesActionDoneCommand); _registerWorkerMessage(_fileManager.updateFilesCommand); _registerWorkerMessage(_fileManager.fileUpdateMessage); _fileManager.fetchFileListCommand .where((event) => !_mediaFileManager.isRelevant(event.uri.scheme)) .listen((event) => _worker.sendRequest(event)); _fileManager.sortFilesListCommand .listen((value) => _worker.sendRequest(value)); } _registerWorkerMessageWithTransformation( P Function(T) transformation, RxCommand command) { _worker.isolateResponseCommand .mergeWith([_backgroundWorker.isolateResponseCommand]) .where((event) => event is T) .map((event) => event as T) .map(transformation) .listen((msg) => command(msg)); } _registerWorkerMessage(RxCommand command) { _registerWorkerMessageWithTransformation((T msg) => msg, command); } } ================================================ FILE: lib/utils/forground_worker/bridges/nextcloud_manager_bridge.dart ================================================ import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/file_service_manager/isolateable/nextcloud_file_manger.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/foreground_worker.dart'; import 'package:yaga/utils/forground_worker/messages/download_preview_complete.dart'; import 'package:yaga/utils/forground_worker/messages/download_preview_request.dart'; import 'package:yaga/utils/forground_worker/messages/login_state_msg.dart'; class NextcloudManagerBridge { final NextCloudManager _nextCloudManager; final ForegroundWorker _worker; final NextcloudFileManager _nextcloudFileManager; RxCommand downloadPreviewCommand = RxCommand.createSync((param) => param); NextcloudManagerBridge( this._nextCloudManager, this._worker, this._nextcloudFileManager, ) { //todo: update loginStateCommand has no logout values... see todo in ncManager _nextCloudManager.updateLoginStateCommand.listen((value) { _worker.sendRequest(LoginStateMsg("", value)); }); _worker.isolateResponseCommand .where((event) => event is DownloadPreviewComplete) .map((event) => event as DownloadPreviewComplete) .listen( (value) => value.success ? _nextcloudFileManager.updatePreviewCommand(value.file) : _nextcloudFileManager.downloadPreviewFaildCommand(value.file), ); downloadPreviewCommand.listen((ncFile) { _worker.sendRequest(DownloadPreviewRequest("", ncFile)); }); } } ================================================ FILE: lib/utils/forground_worker/bridges/settings_manager_bridge.dart ================================================ import 'package:rxdart/rxdart.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/utils/forground_worker/foreground_worker.dart'; import 'package:yaga/utils/forground_worker/messages/preference_msg.dart'; import 'package:yaga/utils/logger.dart'; class SettingsManagerBridge { final _logger = YagaLogger.getLogger(SettingsManagerBridge); final SettingsManager _settingsManager; final ForegroundWorker _worker; SettingsManagerBridge(this._settingsManager, this._worker); Future init() async { _settingsManager.updateSettingCommand.doOnData((event) { _logger.warning(event); }).listen((event) => _worker.sendRequest(PreferenceMsg("", event))); return this; } } ================================================ FILE: lib/utils/forground_worker/foreground_worker.dart ================================================ import 'dart:async'; import 'dart:isolate'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/global_settings_manager.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/forground_worker/isolate_handler_regestry.dart'; import 'package:yaga/utils/forground_worker/messages/flush_logs_message.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/self_signed_cert_handler.dart'; import 'package:yaga/utils/service_locator.dart'; class ForegroundWorker { final _logger = YagaLogger.getLogger(ForegroundWorker); Isolate? _isolate; SendPort? _mainToIsolate; Completer _isolateReady = Completer(); final NextCloudManager _nextCloudManager; final GlobalSettingsManager _globalSettingsManager; final SelfSignedCertHandler _selfSignedCertHandler; final SharedPreferencesService _sharedPreferencesService; final SystemLocationService _systemLocationService; RxCommand isolateResponseCommand = RxCommand.createSync((param) => param); ForegroundWorker( this._nextCloudManager, this._globalSettingsManager, this._selfSignedCertHandler, this._sharedPreferencesService, this._systemLocationService, ); Future get isolateReadyFuture => _isolateReady.future; Future init() async { final isolateToMain = ReceivePort(); isolateToMain.listen((message) { if (message is SendPort) { _mainToIsolate = message; _isolateReady.complete(this); return; } if (message is List) { _logger.severe("Error in forground worker: ${message[0]}", null, StackTrace.fromString(message[1].toString())); } if (message is Message) { _logger.info("Main received: $message"); isolateResponseCommand(message); } }); _isolate = await Isolate.spawn( _workerMain, InitMsg( isolateToMain.sendPort, (await _systemLocationService.getExternal())!, await _systemLocationService.getCacheDir(), (await _systemLocationService.getExternals())!, _nextCloudManager.updateLoginStateCommand.lastResult!, _globalSettingsManager.updateRootMappingPreference.lastResult, _selfSignedCertHandler.fingerprint, _sharedPreferencesService.loadPreferenceFromBool( GlobalSettingsManager.autoPersist, ), ), errorsAreFatal: false, onError: isolateToMain.sendPort, ); return isolateReadyFuture; } void dispose() { _isolateReady = Completer(); _isolate?.kill(); } void sendRequest(Message request) { if(_isolateReady.isCompleted) { _mainToIsolate?.send(request); } else { isolateReadyFuture.then((value) => _mainToIsolate?.send(request)); } } static Future _workerMain(dynamic message) async { SendPort? isolateToMain; final mainToIsolate = ReceivePort(); final handlerRegistry = IsolateHandlerRegistry(); final _logger = YagaLogger.getLogger(ForegroundWorker); if (message is InitMsg) { isolateToMain = message.sendPort; await YagaLogger.init(isolate: true); setupIsolatedServiceLocator(message, isolateToMain, handlerRegistry); getIt.allReady().then((value) { isolateToMain?.send(mainToIsolate.sendPort); }); } mainToIsolate.listen((message) async { if (message is FlushLogsMessage) { await YagaLogger.fileHandler.flushFile(); isolateToMain?.send(FlushLogsMessage(flushed: true)); return; } if (message is Message) { _logger.info("Isolate received: $message"); handlerRegistry.handleMessage(message); } }); } } ================================================ FILE: lib/utils/forground_worker/handlers/file_list_request_handler.dart ================================================ import 'dart:async'; import 'dart:isolate'; import 'package:yaga/managers/file_manager/isolateable/isolated_file_manager.dart'; import 'package:yaga/managers/isolateable/sort_manager.dart'; import 'package:yaga/model/sorted_file_list.dart'; import 'package:yaga/utils/forground_worker/isolate_handler_regestry.dart'; import 'package:yaga/utils/forground_worker/isolate_msg_handler.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_done.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_request.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_response.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/forground_worker/messages/merge_sort_done.dart'; import 'package:yaga/utils/forground_worker/messages/merge_sort_request.dart'; import 'package:yaga/utils/forground_worker/messages/sort_request.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/utils/uri_utils.dart'; class FileListRequestHandler implements IsolateMsgHandler { @override Future initIsolated( InitMsg init, SendPort isolateToMain, IsolateHandlerRegistry registry, ) async { registry.registerHandler( (msg) => handle(msg, isolateToMain), ); registry.registerHandler( (msg) => handleMergeSort(msg, isolateToMain), ); registry.registerHandler((msg) => handleSort(msg, isolateToMain),); return this; } void handle(FileListRequest message, SendPort isolateToMain) { getIt .get() .listFileLists( message.key, message.uri, message.config, recursive: message.recursive, favorites: message.favorites, ) .then( (_) => isolateToMain.send( FileListDone( message.key, message.uri, recursive: message.recursive, ), ), ); } void handleMergeSort( MergeSortRequest message, SendPort isolateToMain, ) { SortedFileList addition = message.addition; if (message.uri != null && !message.recursive) { addition = addition.applyFilter( (file) => compareFilePathToTargetFilePath(file, message.uri!), ); } if (getIt.get().mergeSort(message.main, addition)) { isolateToMain.send(MergeSortDone( message.key, message.main, updateLoading: message.updateLoading, )); } } void handleSort(SortRequest message, SendPort isolateToMain,) { var sorted = getIt.get().sortList(message.files, message.fileListRequest.config); isolateToMain.send( FileListResponse(message.key, message.fileListRequest.uri, sorted, recursive: message.fileListRequest.recursive), ); isolateToMain.send( FileListDone(message.key, message.fileListRequest.uri), ); } } ================================================ FILE: lib/utils/forground_worker/handlers/nextcloud_file_manager_handler.dart ================================================ import 'dart:isolate'; import 'package:yaga/managers/file_manager/isolateable/isolated_file_manager.dart'; import 'package:yaga/managers/file_service_manager/isolateable/nextcloud_file_manger.dart'; import 'package:yaga/model/fetched_file.dart'; import 'package:yaga/utils/forground_worker/isolate_handler_regestry.dart'; import 'package:yaga/utils/forground_worker/isolate_msg_handler.dart'; import 'package:yaga/utils/forground_worker/messages/download_file_request.dart'; import 'package:yaga/utils/forground_worker/messages/download_preview_complete.dart'; import 'package:yaga/utils/forground_worker/messages/download_preview_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/delete_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/destination_action_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/favorite_files_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_done.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/service_locator.dart'; class NextcloudFileManagerHandler implements IsolateMsgHandler { @override Future initIsolated( InitMsg init, SendPort isolateToMain, IsolateHandlerRegistry registry, ) async { registry.registerHandler( (msg) => getIt.get().deleteFiles(msg), ); registry.registerHandler( (msg) => getIt.get().toggleFavorites(msg), ); registry.registerHandler( (msg) => getIt.get().copyMoveRequest(msg), ); registry.registerHandler( (msg) => getIt.get().cancelActionCommand(true), ); registry.registerHandler( (msg) => getIt.get().downloadPreviewCommand(msg.file), ); registry.registerHandler( (msg) => handleDownload(msg, isolateToMain), ); getIt.get().filesActionDoneCommand.listen((value) => isolateToMain.send(value)); getIt.get().fileUpdateMessage.listen((value) => isolateToMain.send(value)); return this; } NextcloudFileManagerHandler( NextcloudFileManager nextcloudFileManager, SendPort isolateToMain, ) { nextcloudFileManager.updatePreviewCommand.listen((file) { isolateToMain.send(DownloadPreviewComplete("", file)); }); nextcloudFileManager.downloadPreviewFaildCommand.listen( (file) => isolateToMain.send( DownloadPreviewComplete("", file, success: false), ), ); } Future handleDownload( DownloadFileRequest request, SendPort isolateToMain, ) async { getIt.get().downloadFile(request.file, persist: request.persist).then((value) async { isolateToMain.send(FetchedFile(request.file, value)); }); } } ================================================ FILE: lib/utils/forground_worker/handlers/user_handler.dart ================================================ import 'dart:async'; import 'dart:isolate'; import 'package:yaga/managers/isolateable/isolated_settings_manager.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/utils/forground_worker/isolate_handler_regestry.dart'; import 'package:yaga/utils/forground_worker/isolate_msg_handler.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/forground_worker/messages/login_state_msg.dart'; import 'package:yaga/utils/forground_worker/messages/preference_msg.dart'; import 'package:yaga/utils/self_signed_cert_handler.dart'; import 'package:yaga/utils/service_locator.dart'; class UserHandler implements IsolateMsgHandler { @override Future initIsolated(InitMsg init, SendPort isolateToMain, IsolateHandlerRegistry registry) async { registry .registerHandler((msg) => handleLoginStateChanged(msg)); registry.registerHandler( (msg) => getIt .get() .updateSettingCommand(msg.preference), ); return this; } void handleLoginStateChanged(LoginStateMsg message) { final NextCloudService ncService = getIt.get(); if (message.loginData.server == null) { getIt.get().revokeCert(); return ncService.logout(); } ncService.login(message.loginData); return; } } ================================================ FILE: lib/utils/forground_worker/isolate_handler_regestry.dart ================================================ import 'package:yaga/utils/forground_worker/messages/message.dart'; import 'package:yaga/utils/logger.dart'; class IsolateHandlerRegistry { final logger = YagaLogger.getLogger(IsolateHandlerRegistry); final Map> handlers = {}; void registerHandler(Function(M) handler) { handlers.putIfAbsent(M, () => []); handlers[M]!.add((Message msg) => handler(msg as M)); } void handleMessage(Message msg) { if (handlers.containsKey(msg.runtimeType)) { for (final handler in handlers[msg.runtimeType]!) { handler(msg); } } else { logger.shout("No handler registered for ${msg.runtimeType}"); } } } ================================================ FILE: lib/utils/forground_worker/isolate_msg_handler.dart ================================================ import 'dart:isolate'; import 'package:yaga/utils/forground_worker/isolate_handler_regestry.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; abstract class IsolateMsgHandler> { Future initIsolated( InitMsg init, SendPort isolateToMain, IsolateHandlerRegistry registry, ); } ================================================ FILE: lib/utils/forground_worker/isolateable.dart ================================================ import 'dart:isolate'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; mixin Isolateable> { Future initIsolated(InitMsg init, SendPort isolateToMain) async => this as T; } ================================================ FILE: lib/utils/forground_worker/messages/download_file_request.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/single_file_message.dart'; class DownloadFileRequest extends SingleFileMessage { static const String jsonTypeConst = "DownloadFileRequest"; static const String _jsonForceDownload = "forceDownload"; static const String _jsonPersist = "persist"; bool forceDownload; bool persist; DownloadFileRequest( NcFile file, { this.forceDownload = false, this.persist = false, }) : super(jsonTypeConst, jsonTypeConst, file); DownloadFileRequest.fromJson(Map json) : forceDownload = json[_jsonForceDownload] as bool, persist = json[_jsonPersist] as bool, super.fromJson(json); @override Map toJson() { final superMap = super.toJson(); superMap[_jsonForceDownload] = forceDownload; superMap[_jsonPersist] = persist; return superMap; } } ================================================ FILE: lib/utils/forground_worker/messages/download_preview_complete.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; class DownloadPreviewComplete extends Message { final NcFile file; final bool success; DownloadPreviewComplete( String key, this.file, { this.success = true, }) : super(key); } ================================================ FILE: lib/utils/forground_worker/messages/download_preview_request.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; class DownloadPreviewRequest extends Message { final NcFile file; DownloadPreviewRequest(String key, this.file) : super(key); } ================================================ FILE: lib/utils/forground_worker/messages/file_list_done.dart ================================================ import 'package:yaga/utils/forground_worker/messages/file_list_message.dart'; class FileListDone extends FileListMessage { FileListDone(String key, Uri uri, {bool recursive = false}) : super(key, uri, recursive: recursive); } ================================================ FILE: lib/utils/forground_worker/messages/file_list_message.dart ================================================ import 'package:yaga/utils/forground_worker/messages/message.dart'; abstract class FileListMessage extends Message { final Uri uri; final bool recursive; FileListMessage(String key, this.uri, {this.recursive = false}) : super(key); } ================================================ FILE: lib/utils/forground_worker/messages/file_list_request.dart ================================================ import 'package:yaga/model/sort_config.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; class FileListRequest extends Message { final Uri uri; final bool recursive; final bool favorites; final SortConfig config; FileListRequest( String key, this.uri, this.config, { this.recursive = false, this.favorites = false, }) : super(key); } ================================================ FILE: lib/utils/forground_worker/messages/file_list_response.dart ================================================ import 'package:yaga/model/sorted_file_list.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_message.dart'; class FileListResponse extends FileListMessage { final SortedFileList files; FileListResponse(String key, Uri uri, this.files, {bool recursive = false}) : super(key, uri, recursive: recursive); } ================================================ FILE: lib/utils/forground_worker/messages/file_update_msg.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/single_file_message.dart'; class FileUpdateMsg extends SingleFileMessage { static const String jsonTypeConst = "FileUpdateMsg"; FileUpdateMsg(String key, NcFile file) : super(key, jsonTypeConst, file); FileUpdateMsg.fromJson(Map json) : super.fromJson(json); } ================================================ FILE: lib/utils/forground_worker/messages/files_action/delete_files_request.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_request.dart'; class DeleteFilesRequest extends FilesActionRequest { static const String jsonTypeConst = "DeleteFilesRequest"; static const String _jsonLocal = "local"; final bool local; DeleteFilesRequest({required super.key, required super.files, required super.sourceDir, required this.local}) : super(jsonType: jsonTypeConst); DeleteFilesRequest.fromJson(super.json) : local = json[_jsonLocal] as bool, super.fromJson(); @override Map toJson() { return super.toJson() ..[_jsonLocal] = local; } } ================================================ FILE: lib/utils/forground_worker/messages/files_action/destination_action_files_request.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_request.dart'; enum DestinationAction { copy, move } class DestinationActionFilesRequest extends FilesActionRequest { static const String jsonTypeConst = "DestinationActionFilesRequest"; static const String _jsonDestination = "destination"; static const String _jsonAction = "action"; static const String _jsonOverwrite = "overwrite"; final Uri destination; final DestinationAction action; final bool overwrite; DestinationActionFilesRequest({ required super.key, required super.files, required this.destination, required super.sourceDir, this.action = DestinationAction.copy, this.overwrite = false, }) : super(jsonType: jsonTypeConst); DestinationActionFilesRequest.fromJson(super.json) : destination = Uri.parse(json[_jsonDestination] as String), action = DestinationAction.values.firstWhere((element) => (json[_jsonAction] as String) == element.name), overwrite = json[_jsonOverwrite] as bool, super.fromJson(); @override Map toJson() { final map = super.toJson(); map[_jsonDestination] = destination.toString(); map[_jsonAction] = action.name; map[_jsonOverwrite] = overwrite; return map; } } ================================================ FILE: lib/utils/forground_worker/messages/files_action/favorite_files_request.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/files_action_request.dart'; class FavoriteFilesRequest extends FilesActionRequest { static const String jsonTypeConst = "FavoriteFilesRequest"; FavoriteFilesRequest({required super.key, required super.files, required super.sourceDir}) : super(jsonType: jsonTypeConst); FavoriteFilesRequest.fromJson(super.json) : super.fromJson(); } ================================================ FILE: lib/utils/forground_worker/messages/files_action/files_action_done.dart ================================================ import 'package:yaga/utils/background_worker/json_convertable.dart'; class FilesActionDone extends JsonConvertable { static const String jsonTypeConst = "FilesActionDone"; static const String _jsonDestination = "destination"; final Uri destination; //todo: background: not sure adding destination was the best solution; it only matters for actionDone follow up FilesActionDone(String key, this.destination) : super(key, jsonTypeConst); FilesActionDone.fromJson(Map json) : destination = Uri.parse(json[_jsonDestination] as String), super.fromJson(json); @override Map toJson() { return super.toJson()..[_jsonDestination] = destination.toString(); } } ================================================ FILE: lib/utils/forground_worker/messages/files_action/files_action_request.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/background_worker/json_convertable.dart'; abstract class FilesActionRequest extends JsonConvertable { static const String _jsonSourceDir = "sourceDir"; final Uri sourceDir; static const String _jsonFiles = "files"; final List files; FilesActionRequest({ required String key, required String jsonType, required this.sourceDir, required this.files, }) : super(key, jsonType); FilesActionRequest.fromJson(super.json) : sourceDir = Uri.parse(json[_jsonSourceDir] as String), files = (json[_jsonFiles] as List).map((e) => NcFile.fromJson(e as Map)).toList(), super.fromJson(); @override Map toJson() { final map = super.toJson(); map[_jsonSourceDir] = sourceDir.toString(); map[_jsonFiles] = files.map((e) => e.toJson()).toList(); return map; } } ================================================ FILE: lib/utils/forground_worker/messages/flush_logs_message.dart ================================================ import 'package:yaga/utils/forground_worker/messages/message.dart'; class FlushLogsMessage extends Message { final bool flushed; FlushLogsMessage({this.flushed = false}) : super("flush-log"); } ================================================ FILE: lib/utils/forground_worker/messages/image_update_msg.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/single_file_message.dart'; class ImageUpdateMsg extends SingleFileMessage { static const String jsonTypeConst = "ImageUpdateMsg"; ImageUpdateMsg(String key, NcFile file) : super(key, jsonTypeConst, file); ImageUpdateMsg.fromJson(Map json) : super.fromJson(json); } ================================================ FILE: lib/utils/forground_worker/messages/init_msg.dart ================================================ import 'dart:io'; import 'dart:isolate'; import 'package:yaga/model/nc_login_data.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/model/preferences/mapping_preference.dart'; import 'package:yaga/utils/background_worker/messages/background_init_msg.dart'; class InitMsg extends BackgroundInitMsg { final SendPort sendPort; final Directory externalPath; final Directory tmpPath; final List externalPaths; final MappingPreference? mapping; final BoolPreference autoPersist; InitMsg( this.sendPort, this.externalPath, this.tmpPath, this.externalPaths, NextCloudLoginData lastLoginData, this.mapping, String fingerprint, this.autoPersist, ): super(lastLoginData, fingerprint); } ================================================ FILE: lib/utils/forground_worker/messages/login_state_msg.dart ================================================ import 'package:yaga/model/nc_login_data.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; class LoginStateMsg extends Message { final NextCloudLoginData loginData; LoginStateMsg(String key, this.loginData) : super(key); } ================================================ FILE: lib/utils/forground_worker/messages/merge_sort_done.dart ================================================ import 'package:yaga/model/sorted_file_list.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; class MergeSortDone extends Message { final SortedFileList sorted; final bool updateLoading; MergeSortDone( String key, this.sorted, { this.updateLoading = false, }) : super(key); } ================================================ FILE: lib/utils/forground_worker/messages/merge_sort_request.dart ================================================ import 'package:yaga/model/sorted_file_list.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; class MergeSortRequest extends Message { final SortedFileList main; final SortedFileList addition; final Uri? uri; final bool recursive; final bool updateLoading; MergeSortRequest( String key, this.main, this.addition, { this.uri, this.recursive = false, this.updateLoading = false, }) : super(key); } ================================================ FILE: lib/utils/forground_worker/messages/message.dart ================================================ abstract class Message { final String key; Message(this.key); } ================================================ FILE: lib/utils/forground_worker/messages/preference_msg.dart ================================================ import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; class PreferenceMsg extends Message { final Preference preference; PreferenceMsg(String key, this.preference) : super(key); } ================================================ FILE: lib/utils/forground_worker/messages/single_file_message.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/background_worker/json_convertable.dart'; abstract class SingleFileMessage extends JsonConvertable { static const String _jsonFile = "file"; final NcFile file; SingleFileMessage(String key, String type, this.file) : super(key, type); SingleFileMessage.fromJson(Map json) : file = NcFile.fromJson(json[_jsonFile] as Map), super.fromJson(json); @override Map toJson() { final superMap = super.toJson(); superMap[_jsonFile] = file.toJson(); return superMap; } } ================================================ FILE: lib/utils/forground_worker/messages/sort_request.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/utils/forground_worker/messages/file_list_request.dart'; import 'package:yaga/utils/forground_worker/messages/message.dart'; class SortRequest extends Message { final List files; final FileListRequest fileListRequest; SortRequest(String key, this.files, this.fileListRequest) : super(key); } ================================================ FILE: lib/utils/log_error_file_handler.dart ================================================ import 'dart:convert'; import 'dart:io'; import 'package:catcher_2/catcher_2.dart'; import 'package:catcher_2/core/application_profile_manager.dart'; import 'package:catcher_2/model/platform_type.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:yaga/utils/logger.dart'; import 'package:device_info_plus/device_info_plus.dart'; class LogErrorFileHandler extends ReportHandler { final File file; final bool enableDeviceParameters; final bool enableApplicationParameters; final bool enableStackTrace; final bool enableCustomParameters; final bool printLogs; //emergency logger for when errors occure in LogErrorFileHandler final _logger = YagaLogger.getEmergencyLogger(LogErrorFileHandler); IOSink? _sink; bool _fileValidationResult = false; LogErrorFileHandler(this.file, {this.enableDeviceParameters = false, this.enableApplicationParameters = false, this.enableStackTrace = true, this.enableCustomParameters = true, this.printLogs = false}) : assert(file != null, "File can't be null"), assert(enableDeviceParameters != null, "enableDeviceParameters can't be null"), assert(enableApplicationParameters != null, "enableApplicationParameters can't be null"), assert(enableStackTrace != null, "enableStackTrace can't be null"), assert(enableCustomParameters != null, "enableCustomParameters can't be null"), assert(printLogs != null, "printLogs can't be null"); @override Future handle(Report report, BuildContext? context) async { try { if (_sink == null) { await init(); } return await _processReport(report); } catch (exc, stackTrace) { _logger.severe("Exception occured: $exc stack: $stackTrace"); return false; } } Future _processReport(Report report) async { if (_fileValidationResult) { _writeReportToFile(report); return true; } else { return false; } } Future _checkFile() async { try { final bool exists = await file.exists(); if (!exists) { file.createSync(); } final IOSink sink = file.openWrite(mode: FileMode.append); sink.write(""); await sink.flush(); await sink.close(); return true; } catch (exc, stackTrace) { _logger.severe("Exception occured: $exc stack: $stackTrace"); return false; } } void _openFile() { if (_sink == null) { _sink = file.openWrite(mode: FileMode.writeOnly); _printLog("Opened file"); } } void _writeLineToFile(String text) { _logger.shout(text); } void writeLineToFile(String text) { _sink?.add(utf8.encode('$text\n')); } Future flushFile() async => _sink?.flush(); Future _closeFile() async { _printLog("Closing file"); await _sink?.flush(); await _sink?.close(); _sink = null; } Future _writeReportToFile(Report report) async { _printLog("Writing report to file"); _writeLineToFile( "============================== CATCHER LOG =============================="); _writeLineToFile("Crash occured on ${report.dateTime}"); _writeLineToFile(""); if (enableDeviceParameters) { _logDeviceParametersFormatted(report.deviceParameters); _writeLineToFile(""); } if (enableApplicationParameters) { _logApplicationParametersFormatted(report.applicationParameters); _writeLineToFile(""); } _writeLineToFile("---------- ERROR ----------"); _writeLineToFile("${report.error}"); _writeLineToFile(""); if (enableStackTrace) { _writeLineToFile("------- STACK TRACE -------"); _writeLineToFile("${report.stackTrace}"); } if (enableCustomParameters) { _logCustomParametersFormatted(report.customParameters); } _writeLineToFile( "======================================================================"); } void _logDeviceParametersFormatted(Map deviceParameters) { _writeLineToFile("------- DEVICE INFO -------"); for (final entry in deviceParameters.entries) { _writeLineToFile("${entry.key}: ${entry.value}"); } _writeLineToFile("------- END DEVICE INFO -------"); } void _logApplicationParametersFormatted( Map applicationParameters) { _writeLineToFile("------- APP INFO -------"); for (final entry in applicationParameters.entries) { _writeLineToFile("${entry.key}: ${entry.value}"); } _writeLineToFile("------- END APP INFO -------"); } void _logCustomParametersFormatted(Map customParameters) { _writeLineToFile("------- CUSTOM INFO -------"); for (final entry in customParameters.entries) { _writeLineToFile("${entry.key}: ${entry.value}"); } } Future printDeviceInfo() async { final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); if (Platform.isAndroid) { await deviceInfo.androidInfo.then((androidInfo) { _logDeviceParametersFormatted(_loadAndroidParameters(androidInfo)); }); } } Future printApplicationInfo() async { final Map _applicationParameters = {}; _applicationParameters["environment"] = describeEnum(ApplicationProfileManager.getApplicationProfile()); ///There is no package info web implementation if (!ApplicationProfileManager.isWeb()) { await PackageInfo.fromPlatform().then((packageInfo) { _applicationParameters["version"] = packageInfo.version; _applicationParameters["appName"] = packageInfo.appName; _applicationParameters["buildNumber"] = packageInfo.buildNumber; _applicationParameters["packageName"] = packageInfo.packageName; }); } _logApplicationParametersFormatted(_applicationParameters); } Map _loadAndroidParameters( AndroidDeviceInfo androidDeviceInfo) { final Map deviceParameters = {}; deviceParameters["id"] = androidDeviceInfo.id; deviceParameters["board"] = androidDeviceInfo.board; deviceParameters["bootloader"] = androidDeviceInfo.bootloader; deviceParameters["brand"] = androidDeviceInfo.brand; deviceParameters["device"] = androidDeviceInfo.device; deviceParameters["display"] = androidDeviceInfo.display; deviceParameters["fingerprint"] = androidDeviceInfo.fingerprint; deviceParameters["hardware"] = androidDeviceInfo.hardware; deviceParameters["host"] = androidDeviceInfo.host; deviceParameters["isPhysicalDevice"] = androidDeviceInfo.isPhysicalDevice; deviceParameters["manufacturer"] = androidDeviceInfo.manufacturer; deviceParameters["model"] = androidDeviceInfo.model; deviceParameters["product"] = androidDeviceInfo.product; deviceParameters["tags"] = androidDeviceInfo.tags; deviceParameters["type"] = androidDeviceInfo.type; deviceParameters["versionBaseOs"] = androidDeviceInfo.version.baseOS; deviceParameters["versionCodename"] = androidDeviceInfo.version.codename; deviceParameters["versionIncremental"] = androidDeviceInfo.version.incremental; deviceParameters["versionPreviewSdk"] = androidDeviceInfo.version.previewSdkInt; deviceParameters["versionRelease"] = androidDeviceInfo.version.release; deviceParameters["versionSdk"] = androidDeviceInfo.version.sdkInt; deviceParameters["versionSecurityPatch"] = androidDeviceInfo.version.securityPatch; return deviceParameters; } void _printLog(String log) { if (printLogs) { _logger.info(log); } } @override List getSupportedPlatforms() => [PlatformType.android, PlatformType.iOS]; Future destroy() async { await _closeFile(); } Future init() async { if (_sink != null) { return; } _fileValidationResult = await _checkFile(); _openFile(); } } ================================================ FILE: lib/utils/logger.dart ================================================ import 'dart:async'; import 'dart:io'; import 'package:ansicolor/ansicolor.dart'; import 'package:logging/logging.dart'; import 'package:share_plus/share_plus.dart'; import 'package:yaga/utils/log_error_file_handler.dart'; import 'package:yaga/utils/forground_worker/foreground_worker.dart'; import 'package:yaga/utils/forground_worker/messages/flush_logs_message.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/utils/uri_utils.dart'; class YagaLogger { const YagaLogger(); static final _logUri = fromPathList(uri: Directory.systemTemp.uri, paths: [ Directory.systemTemp.uri.path, "yaga.log.txt", ]); static final _isolateLogUri = fromPathList(uri: Directory.systemTemp.uri, paths: [ Directory.systemTemp.uri.path, "yaga.isolate.log.txt", ]); static late LogErrorFileHandler _fileHandler; static LogErrorFileHandler get fileHandler => YagaLogger._fileHandler; static Logger getLogger(Type className) { return _getLogger( className, ); } static Logger getEmergencyLogger(Type className) { return _getLogger(className); } static Logger _getLogger(Type className) { return Logger(className.toString()); } static final levelColors = { Level.FINEST: AnsiPen()..xterm(8), Level.FINER: AnsiPen()..xterm(8), Level.FINE: AnsiPen()..xterm(8), Level.INFO: AnsiPen()..xterm(12), Level.WARNING: AnsiPen()..xterm(208), Level.SEVERE: AnsiPen()..xterm(196), Level.SHOUT: AnsiPen()..xterm(199), }; static Future init({bool isolate = false}) async { YagaLogger._fileHandler = LogErrorFileHandler( File.fromUri(isolate ? YagaLogger._isolateLogUri : YagaLogger._logUri), printLogs: true, ); await YagaLogger._fileHandler.init(); ansiColorDisabled = false; Logger.root.level = Level.INFO; Logger.root.onRecord.listen((record) { final List logs = [ '${record.time} ${record.level} ${record.loggerName} - ${record.message}', ]; if (record.stackTrace != null) { logs.add( '${record.time} ${record.level} ${record.loggerName} - ${record.stackTrace}', ); } for (final log in logs) { print(levelColors[record.level]!(log)); YagaLogger._fileHandler.writeLineToFile(log); } }); } static Future printBaseLog() async { await YagaLogger._fileHandler.printDeviceInfo(); await YagaLogger._fileHandler.printApplicationInfo(); } static Future shareLogs() async { StreamSubscription? sub; sub = getIt .get() .isolateResponseCommand .where((msg) => msg is FlushLogsMessage && msg.flushed) .listen( (msg) async { try { await _fileHandler.flushFile(); Share.shareFiles([ YagaLogger._logUri.path, YagaLogger._isolateLogUri.path, ]); } finally { sub?.cancel(); } }, cancelOnError: true, ); getIt.get().sendRequest(FlushLogsMessage()); } } ================================================ FILE: lib/utils/navigation/yaga_route_information_parser.dart ================================================ import 'package:flutter/material.dart'; class YagaRouteInformationParser extends RouteInformationParser { @override Future parseRouteInformation(RouteInformation routeInformation) async { return Uri.parse(routeInformation.location??''); } } ================================================ FILE: lib/utils/navigation/yaga_router.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/route_args/choice_selector_screen_arguments.dart'; import 'package:yaga/model/route_args/focus_view_arguments.dart'; import 'package:yaga/model/route_args/image_screen_arguments.dart'; import 'package:yaga/model/route_args/path_selector_screen_arguments.dart'; import 'package:yaga/model/route_args/settings_screen_arguments.dart'; import 'package:yaga/views/screens/choice_selector_screen.dart'; import 'package:yaga/views/screens/focus_view.dart'; import 'package:yaga/views/screens/image_screen.dart'; import 'package:yaga/views/screens/nc_address_screen.dart'; import 'package:yaga/views/screens/nc_login_screen.dart'; import 'package:yaga/views/screens/path_selector_screen.dart'; import 'package:yaga/views/screens/settings_screen.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; Route generateRoute(RouteSettings settings) { switch (settings.name) { case SettingsScreen.route: final SettingsScreenArguments args = settings.arguments as SettingsScreenArguments; return MaterialPageRoute( settings: settings, builder: (context) => SettingsScreen( args.preferences, onCancel: args.onCancel, onCommit: args.onCommit, onPreferenceChangedCommand: args.onSettingChangedCommand, )); case PathSelectorScreen.route: final PathSelectorScreenArguments pathSelectorScreenArguments = settings.arguments as PathSelectorScreenArguments; return MaterialPageRoute( settings: settings, builder: (context) => PathSelectorScreen( pathSelectorScreenArguments.uri, pathSelectorScreenArguments.onSelect, onFileTap: pathSelectorScreenArguments.onFileTap, title: pathSelectorScreenArguments.title, fixedOrigin: pathSelectorScreenArguments.fixedOrigin, schemeFilter: pathSelectorScreenArguments.schemeFilter, )); // case DirectoryNavigationScreen.route: // DirectoryNavigationScreenArguments args = // settings.arguments as DirectoryNavigationScreenArguments; // return MaterialPageRoute( // settings: settings, // builder: (context) => DirectoryNavigator( // args.uri, // args.title, // args.bottomBarBuilder, // args.viewConfig, // )); case NextCloudAddressScreen.route: return MaterialPageRoute( settings: settings, builder: (context) => const NextCloudAddressScreen()); case NextCloudLoginScreen.route: return MaterialPageRoute( settings: settings, builder: (context) => NextCloudLoginScreen(settings.arguments as Uri)); case ImageScreen.route: final ImageScreenArguments args = settings.arguments as ImageScreenArguments; return MaterialPageRoute( settings: settings, builder: (context) => ImageScreen( args.images, args.index, title: args.title, ), ); case ChoiceSelectorScreen.route: final ChoiceSelectorScreenArguments args = settings.arguments as ChoiceSelectorScreenArguments; return MaterialPageRoute( settings: settings, builder: (context) => ChoiceSelectorScreen( args.choicePreference, args.onSelect, args.onCancel)); case FocusView.route: final FocusViewArguments args = settings.arguments as FocusViewArguments; return MaterialPageRoute( settings: settings, builder: (context) => FocusView( args.path, args.favorites, args.selected, args.prefPrefix, )); default: return MaterialPageRoute( settings: settings, builder: (context) => YagaHomeScreen(), ); } } ================================================ FILE: lib/utils/navigation/yaga_router_delegate.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/navigation_manager.dart'; import 'package:yaga/managers/tab_manager.dart'; import 'package:yaga/model/route_args/directory_navigation_screen_arguments.dart'; import 'package:yaga/services/intent_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/utils/navigation/yaga_router.dart'; import 'package:yaga/views/screens/directory_traversal_screen.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; class YagaRouterDelegate extends RouterDelegate with ChangeNotifier, PopNavigatorRouterDelegateMixin { @override final GlobalKey navigatorKey = GlobalKey(); final NavigationManager _navigationManager = getIt.get(); IntentService intentService = getIt.get(); YagaRouterDelegate() { _navigationManager.showDirectoryNavigation.listen((value) { notifyListeners(); }); getIt .get() .tabChangedCommand .listen((value) => _navigationManager.showDirectoryNavigation(null)); } @override Widget build(BuildContext context) { return Navigator( key: navigatorKey, onGenerateRoute: generateRoute, pages: [getInitialPage(), ..._buildDirectoryNavigationPage()], onPopPage: (route, result) { if (!route.didPop(result)) { return false; } _navigationManager.showDirectoryNavigation(null); return true; }, ); } @override Future setNewRoutePath(Uri configuration) async { //todo: we are not yet handling roots from the system } List _buildDirectoryNavigationPage() { final DirectoryNavigationScreenArguments? args = _navigationManager.showDirectoryNavigation.lastResult; if (args == null) { return []; } return [ MaterialPage( key: ValueKey(args.uri.toString()), child: DirectoryTraversalScreen(args), ) ]; } Page getInitialPage() { return MaterialPage( key: const ValueKey(YagaHomeScreen.route), child: YagaHomeScreen(), ); } } ================================================ FILE: lib/utils/ncfile_stream_extensions.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:rxdart/rxdart.dart'; extension NcFileStreamExtensions on Stream { Stream> collectToList() { return toList().asStream().onErrorReturn([]); } Stream recursively(Stream Function(Uri, {bool favorites}) listFilesFromUpstream, {required bool recursive, bool favorites = false}) { return flatMap( (file) => Rx.merge([ Stream.value(file), Stream.value(file) .where((file) => file.isDirectory) .where((_) => recursive) .flatMap( (file) => listFilesFromUpstream( file.uri, favorites: favorites, ).recursively( listFilesFromUpstream, recursive: recursive, favorites: favorites, ), ) ]), ); } } ================================================ FILE: lib/utils/nextcloud_client_factory.dart ================================================ import 'package:nextcloud/nextcloud.dart'; import 'package:yaga/utils/self_signed_cert_handler.dart'; class NextCloudClientFactory { // we do not actually need the SelfSignedCertHandler, // however we have to make sure it was initialized // before allowing anyone to create Nextcloud clients // ignore: avoid_unused_constructor_parameters NextCloudClientFactory(SelfSignedCertHandler handler); //todo: is this really the right place for this? String get userAgent => "Nextcloud Yaga"; NextcloudClient createNextCloudClient( Uri host, String username, String password, ) => NextcloudClient( host, loginName: username, password: password, userAgentOverride: userAgent, ); NextcloudClient createUnauthenticatedClient(Uri host) => NextcloudClient( host, userAgentOverride: userAgent, ); } ================================================ FILE: lib/utils/nextcloud_colors.dart ================================================ import 'package:flutter/rendering.dart'; class NextcloudColors { NextcloudColors._(); static const Color darkBlue = Color(0xFF0082C9); static const Color lightBlue = Color(0xFF1CAFFF); } ================================================ FILE: lib/utils/self_signed_cert_handler.dart ================================================ import 'dart:io'; import 'dart:isolate'; import 'package:yaga/services/secure_storage_service.dart'; import 'package:yaga/utils/forground_worker/isolateable.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/logger.dart'; class SelfSignedCertHandler extends HttpOverrides implements Isolateable { final _logger = YagaLogger.getLogger(SelfSignedCertHandler); final String _fingerprintKey = "cert.fingerprint"; String? _fingerprint; /// Expects a callback function if the cert is to be accepted and null otherwise. /// This callback function is then used to notify the caller when cert has been accepted. Future Function(String subject, String issuer, String fingerprint)? badCertificateCallback; SecureStorageService? _secureStorageService; Future init(SecureStorageService secStorage) async { _secureStorageService = secStorage; _fingerprint = await _secureStorageService?.loadPreference( _fingerprintKey, ); HttpOverrides.global = this; return this; } @override Future initIsolated( InitMsg init, SendPort isolateToMain, ) async { _fingerprint = init.fingerprint; HttpOverrides.global = this; return this; } Future initBackgroundable(String fingerprint) async { _fingerprint = fingerprint; HttpOverrides.global = this; return this; } String get fingerprint => _fingerprint ?? ''; @override HttpClient createHttpClient(SecurityContext? context) { final HttpClient client = super.createHttpClient(context); client.badCertificateCallback = (X509Certificate cert, String host, int port) { final String certFingerprint = cert.sha1.toString(); if (_fingerprint == certFingerprint) { return true; } _logger.warning("Fingerprint Cert: $certFingerprint"); _logger.warning("Saved Fingerprint: $_fingerprint"); _logger.warning("Host: $host"); _logger.warning("Cert-Subject: ${cert.subject}"); badCertificateCallback ?.call( cert.subject, cert.issuer, certFingerprint, ) .then((certAcceptedCallback) { if (certAcceptedCallback != null) { // we are here temporarily accepting the cert but not persisting until a successfull login _fingerprint = certFingerprint; certAcceptedCallback(); } }); return false; }; return client; } Future persistCert() { return _secureStorageService?.savePreference( _fingerprintKey, fingerprint) ?? Future.value(); } void revokeCert() { _fingerprint = null; _secureStorageService?.deletePreference(_fingerprintKey); } } ================================================ FILE: lib/utils/service_locator.dart ================================================ import 'dart:isolate'; import 'package:get_it/get_it.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:yaga/managers/file_manager/file_manager.dart'; import 'package:yaga/managers/file_manager/isolateable/file_action_manager.dart'; import 'package:yaga/managers/file_manager/isolateable/isolated_file_manager.dart'; import 'package:yaga/managers/file_service_manager/isolateable/local_file_manager.dart'; import 'package:yaga/managers/file_service_manager/isolateable/nextcloud_background_file_manager.dart'; import 'package:yaga/managers/file_service_manager/isolateable/nextcloud_file_manger.dart'; import 'package:yaga/managers/file_service_manager/media_file_manager.dart'; import 'package:yaga/managers/global_settings_manager.dart'; import 'package:yaga/managers/isolateable/isolated_global_settings_manager.dart'; import 'package:yaga/managers/isolateable/isolated_settings_manager.dart'; import 'package:yaga/managers/isolateable/mapping_manager.dart'; import 'package:yaga/managers/isolateable/sort_manager.dart'; import 'package:yaga/managers/isolateable/sync_manager.dart'; import 'package:yaga/managers/navigation_manager.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/managers/tab_manager.dart'; import 'package:yaga/services/intent_service.dart'; import 'package:yaga/services/isolateable/local_file_service.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/services/media_file_service.dart'; import 'package:yaga/services/name_exchange_service.dart'; import 'package:yaga/services/secure_storage_service.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/background_worker/background_channel.dart'; import 'package:yaga/utils/background_worker/background_worker.dart'; import 'package:yaga/utils/background_worker/messages/background_init_msg.dart'; import 'package:yaga/utils/background_worker/work_tracker.dart'; import 'package:yaga/utils/forground_worker/bridges/file_manager_bridge.dart'; import 'package:yaga/utils/forground_worker/bridges/nextcloud_manager_bridge.dart'; import 'package:yaga/utils/forground_worker/bridges/settings_manager_bridge.dart'; import 'package:yaga/utils/forground_worker/foreground_worker.dart'; import 'package:yaga/utils/forground_worker/handlers/file_list_request_handler.dart'; import 'package:yaga/utils/forground_worker/handlers/nextcloud_file_manager_handler.dart'; import 'package:yaga/utils/forground_worker/handlers/user_handler.dart'; import 'package:yaga/utils/forground_worker/isolate_handler_regestry.dart'; import 'package:yaga/utils/forground_worker/messages/init_msg.dart'; import 'package:yaga/utils/nextcloud_client_factory.dart'; import 'package:yaga/utils/self_signed_cert_handler.dart'; GetIt getIt = GetIt.instance; void setupServiceLocator() { //setup HTTP overrides getIt.registerSingletonAsync( () => SecureStorageService().init(), ); getIt.registerSingletonAsync( () async => SelfSignedCertHandler().init( await getIt.getAsync(), ), ); // Factories getIt.registerSingletonAsync( () async => NextCloudClientFactory( await getIt.getAsync(), ), ); // Services getIt.registerSingletonAsync( () => SystemLocationService().init()); getIt.registerSingletonAsync( () async => LocalFileService().init()); getIt.registerSingletonAsync( () => SharedPreferencesService().init()); getIt.registerSingletonAsync(() async => NextCloudService( await getIt.getAsync(), ).init()); getIt.registerSingletonAsync( () async => IntentService().init()); //todo: re-check if we still need everything in the main thread (bridge strategy) // Managers getIt.registerSingletonAsync(() async => TabManager()); getIt.registerSingletonAsync(() async => SettingsManager( await getIt.getAsync(), )); getIt.registerSingletonAsync( () async => NextCloudManager( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), ).init(), ); getIt.registerSingletonAsync(() async => MappingManager( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync())); getIt.registerSingletonAsync(() async => SyncManager()); getIt.registerSingletonAsync( () async => MediaFileService( await getIt.getAsync(), ).init(), ); getIt.registerSingletonAsync(() async => MediaFileManager( await getIt.getAsync(), )); getIt.registerSingletonAsync(() async => NameExchangeService( await getIt.getAsync(), )); getIt.registerSingletonAsync(() async => FileManager( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), )); getIt.registerSingletonAsync(() async => NextcloudFileManager( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync())); getIt.registerSingletonAsync( () async => GlobalSettingsManager( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), ).init()); getIt.registerSingletonAsync(() async => ForegroundWorker( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync()) .init()); getIt.registerSingletonAsync( () async => NextcloudManagerBridge( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), )); getIt.registerSingletonAsync( () async => SettingsManagerBridge( await getIt.getAsync(), await getIt.getAsync(), ).init(), ); getIt.registerSingletonAsync( () async => BackgroundWorker( await getIt.getAsync(), await getIt.getAsync(), ).init(), ); getIt.registerSingletonAsync( () async => FileManagerBridge( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), ), ); getIt.registerSingletonAsync(() async => PackageInfo.fromPlatform()); getIt.registerSingletonAsync(() async => NavigationManager()); } //todo: Background: clean up service init for background worker void setupBackgroundServiceLocator( BackgroundInitMsg init, BackgroundChannel channel, ) { getIt.registerSingletonAsync( () async => SelfSignedCertHandler().initBackgroundable(init.fingerprint), ); // Factories getIt.registerSingletonAsync( () async => NextCloudClientFactory( await getIt.getAsync(), ), ); // Services getIt.registerSingletonAsync( () async => LocalFileService().initBackgroundable(), ); getIt.registerSingletonAsync( () async => NextCloudService( await getIt.getAsync(), ).initBackgroundable(init.lastLoginData), ); //Managers getIt.registerSingletonAsync( () async => FileActionManager().initBackground(channel), ); getIt.registerSingletonAsync( () async => NextcloudBackgroundFileManager( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), ).initBackground(), ); getIt.registerSingletonAsync( () async => WorkTracker(), ); } void setupIsolatedServiceLocator( InitMsg init, SendPort isolateToMain, IsolateHandlerRegistry registry, ) { getIt.registerSingletonAsync( () async => SelfSignedCertHandler().initIsolated(init, isolateToMain), ); // Factories getIt.registerSingletonAsync( () async => NextCloudClientFactory( await getIt.getAsync(), ), ); // Services getIt.registerSingletonAsync( () async => SystemLocationService().initIsolated(init, isolateToMain), ); getIt.registerSingletonAsync( () async => LocalFileService().initIsolated(init, isolateToMain), ); getIt.registerSingletonAsync( () async => NextCloudService( await getIt.getAsync(), ).initIsolated(init, isolateToMain), ); // Managers getIt.registerSingletonAsync( () async => SortManager().initIsolated(init, isolateToMain), ); getIt.registerSingletonAsync( () async => IsolatedFileManager( await getIt.getAsync(), ).initIsolated(init, isolateToMain), ); getIt.registerSingletonAsync( () async => IsolatedSettingsManager().initIsolated(init, isolateToMain)); getIt.registerSingletonAsync( () async => SyncManager().initIsolated(init, isolateToMain)); getIt.registerSingletonAsync(() async => MappingManager( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync()) .initIsolated(init, isolateToMain)); getIt.registerSingletonAsync(() async => LocalFileManager( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), ).initIsolated(init, isolateToMain)); getIt.registerSingletonAsync(() async => NextcloudFileManager( await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync(), await getIt.getAsync()) .initIsolated(init, isolateToMain)); getIt.registerSingletonAsync( () async => IsolatedGlobalSettingsManager( await getIt.getAsync(), ).initIsolated(init, isolateToMain), ); // Handlers getIt.registerSingletonAsync( () async => NextcloudFileManagerHandler( await getIt.getAsync(), isolateToMain, ).initIsolated( init, isolateToMain, registry, ), ); getIt.registerSingletonAsync( () async => FileListRequestHandler().initIsolated( init, isolateToMain, registry, ), ); getIt.registerSingletonAsync( () async => UserHandler().initIsolated( init, isolateToMain, registry, ), ); } ================================================ FILE: lib/utils/uri_utils.dart ================================================ import 'package:validators/sanitizers.dart'; import 'package:yaga/model/nc_file.dart'; //todo: refactor into non static functions in util class UriUtils Uri fromUri({ required Uri uri, String? scheme, String? userInfo, String? host, int? port, String? path, }) => Uri( scheme: scheme ?? uri.scheme, userInfo: userInfo ?? uri.userInfo, host: host ?? uri.host, port: port ?? uri.port, path: path ?? uri.path, ); Uri fromPathList({required Uri uri, required List paths}) { String path = ""; for (final element in paths) { path = chainPathSegments(path, element); } // do not double encode here because paths are already double encoded return fromUri(uri: uri, path: path); } bool compareFilePathToTargetFilePath(NcFile file, Uri destination) { return file.uri.path == chainPathSegments( destination.path, Uri.encodeComponent(file.name), ); } String chainPathSegments(String first, String second) { String firstNormalized = first; if (first.endsWith("/")) { firstNormalized = rtrim(first, "/"); } String secondNormalized = second; if (second.startsWith("/")) { secondNormalized = ltrim(second, "/"); } return "$firstNormalized/$secondNormalized"; } Uri getRootFromUri(Uri uri) => fromUri(uri: uri, path: "/"); Uri fromUriPathSegments(Uri uri, int index) { final buffer = StringBuffer(); buffer.write("/"); for (int i = 0; i <= index; i++) { // in cases where we have encoded chars in the folder name we have to re-encode // to make sure we do not change the meaning, since pathSegments does auto-decoding buffer.write("${Uri.encodeComponent(uri.pathSegments[i])}/"); } return fromUri(uri: uri, path: buffer.toString()); } String getNameFromUri(Uri uri) { if (uri.pathSegments.isEmpty) { return uri.host; } //resolving any encoded chars in the name of a file/folder to improve readability should be avoided //this would not correspond anymore to the displayed name in nextcloud //furthermore you get problems when trying to double decode DE chars if (uri.pathSegments.last.isNotEmpty) { return uri.pathSegments.last; } return uri.pathSegments[uri.pathSegments.length - 2]; } ================================================ FILE: lib/views/screens/browse_view.dart ================================================ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:yaga/managers/navigation_manager.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/nc_origin.dart'; import 'package:yaga/model/route_args/directory_navigation_screen_arguments.dart'; import 'package:yaga/model/route_args/image_screen_arguments.dart'; import 'package:yaga/model/system_location.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/services/intent_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/image_screen.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; import 'package:yaga/views/widgets/avatar_widget.dart'; import 'package:yaga/views/widgets/image_views/nc_list_view.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/views/widgets/yaga_bottom_nav_bar.dart'; import 'package:yaga/views/widgets/yaga_drawer.dart'; class BrowseView extends StatelessWidget { String get pref => "browse_tab"; final bool favorites; const BrowseView({super.key, this.favorites = false}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(_getTitle() ?? "Nextcloud Yaga"), ), drawer: YagaDrawer(), body: StreamBuilder( stream: getIt.get().updateLoginStateCommand, builder: (context, snapshot) { final List children = []; if (Platform.isAndroid && !favorites) { children.add(_buildLocalStorageTile(context)); getIt.get().externals.forEach((element) { children.add(_buildSDCardTile(context, element)); }); } if (getIt.get().isLoggedIn()) { final NcOrigin origin = getIt.get().origin!; children.add(_buildNextcloudTile(context, origin)); } return ListView( children: children, ); }), bottomNavigationBar: buildBottomNavBar(), ); } YagaBottomNavBar buildBottomNavBar() { return favorites ? const YagaBottomNavBar(YagaHomeTab.favorites) : const YagaBottomNavBar(YagaHomeTab.folder); } ListTile _buildLocalStorageTile(BuildContext context) { return ListTile( // isThreeLine: false, leading: const AvatarWidget.phone(), title: const Text("Internal Memory"), onTap: () => getIt.get().showDirectoryNavigation(_getArgs( context, getIt.get().internalStorage.origin, )), ); } ListTile _buildSDCardTile(BuildContext context, SystemLocation element) { return ListTile( // isThreeLine: false, leading: const AvatarWidget.sd(), title: Text(element.origin.userInfo), onTap: () => getIt.get().showDirectoryNavigation( _getArgs( context, element.origin, ), ), ); } ListTile _buildNextcloudTile(BuildContext context, NcOrigin origin) { return ListTile( isThreeLine: true, leading: AvatarWidget.command( getIt.get().updateAvatarCommand, ), title: Text(origin.displayName), subtitle: Text(origin.domain), onTap: () => getIt.get().showDirectoryNavigation( _getArgs(context, origin.userEncodedDomainRoot), ), ); } //todo: unify this String? _getTitle() { if (getIt.get().isOpenForSelect) { return "Selecte image..."; } return null; } DirectoryNavigationScreenArguments _getArgs(BuildContext context, Uri uri) { final ViewConfiguration viewConfig = ViewConfiguration.browse( route: pref, defaultView: NcListView.viewKey, favorites: favorites, //todo: implicit navigation onFileTap: (List files, int index) => Navigator.pushNamed( context, ImageScreen.route, arguments: ImageScreenArguments(files, index), ), ); return DirectoryNavigationScreenArguments( uri: uri, title: _getTitle() ?? (favorites ? "Favorites" : "Browse"), fixedOrigin: favorites, viewConfig: viewConfig, //todo: this can now be probably be removed and YagaBottomNavBar can be created directly in DirectoryNavigationScreen bottomBarBuilder: (context, uri) => buildBottomNavBar(), ); } } ================================================ FILE: lib/views/screens/category_view_screen.dart ================================================ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/category_view_config.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/preferences/uri_preference.dart'; import 'package:yaga/model/route_args/image_screen_arguments.dart'; import 'package:yaga/model/route_args/settings_screen_arguments.dart'; import 'package:yaga/services/intent_service.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/image_screen.dart'; import 'package:yaga/views/screens/settings_screen.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; import 'package:yaga/views/widgets/image_views/category_view_exp.dart'; import 'package:yaga/views/widgets/image_view_container.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/views/widgets/list_menu_entry.dart'; import 'package:yaga/views/widgets/selection_app_bar.dart'; import 'package:yaga/views/widgets/selection_title.dart'; import 'package:yaga/views/widgets/selection_will_pop_scope.dart'; import 'package:yaga/views/widgets/yaga_bottom_nav_bar.dart'; import 'package:yaga/views/widgets/yaga_drawer.dart'; import 'package:yaga/views/widgets/yaga_popup_menu_button.dart'; enum CategoryViewMenu { settings } abstract class CategoryViewScreen extends StatefulWidget { final CategoryViewConfig _categoryViewConfig; const CategoryViewScreen(this._categoryViewConfig); @override _CategoryViewScreenState createState() => _CategoryViewScreenState(); } class _CategoryViewScreenState extends State with AutomaticKeepAliveClientMixin { final List _defaultViewPreferences = []; late ViewConfiguration _viewConfig; // GeneralViewConfig _generalViewConfig; late StreamSubscription _updateUriSubscription; late FileListLocalManager _fileListLocalManager; @override void initState() { void onFileTap(List files, int index) => _fileListLocalManager.isInSelectionMode ? _fileListLocalManager.selectFileCommand(files[index]) //todo: replace navigation by navigation manager : Navigator.pushNamed( context, ImageScreen.route, arguments: ImageScreenArguments(files, index), ); _viewConfig = ViewConfiguration( route: widget._categoryViewConfig.pref, defaultView: CategoryViewExp.viewKey, onFolderTap: null, onFileTap: onFileTap, onSelect: getIt.get().isOpenForSelect ? onFileTap : (files, index) => _fileListLocalManager.selectFileCommand(files[index]), favorites: widget._categoryViewConfig.favorites ); _defaultViewPreferences .add(widget._categoryViewConfig.generalViewConfig.general); _defaultViewPreferences .add(widget._categoryViewConfig.generalViewConfig.path); _defaultViewPreferences.add(_viewConfig.section); _defaultViewPreferences.add(_viewConfig.recursive); _defaultViewPreferences.add(_viewConfig.view); //todo: refactor getIt.get().logoutCommand.listen((value) => getIt .get() .persistStringSettingCommand( widget._categoryViewConfig.generalViewConfig.path.rebuild( (b) => b..value = getIt.get().internalStorage.uri, ))); //todo: is it still necessary for tab to be a stateful widget? //image state wrapper is a widget local manager _fileListLocalManager = FileListLocalManager( getIt .get() .loadPreferenceFromString( widget._categoryViewConfig.generalViewConfig.path) .value, getIt .get() .loadPreferenceFromBool(_viewConfig.recursive), ViewConfiguration.getSortConfigFromViewChoice( getIt .get() .loadPreferenceFromString(_viewConfig.view), ), favorites: _viewConfig.favorites, ); //todo: this could be moved into imageStateWrapper _updateUriSubscription = getIt .get() .updateSettingCommand .where((event) => event.key == widget._categoryViewConfig.generalViewConfig.path.key) .map((event) => event as UriPreference) .listen((event) { _fileListLocalManager.refetch(uri: event.value); }); _fileListLocalManager.initState(); super.initState(); } @override void dispose() { _updateUriSubscription.cancel(); _fileListLocalManager.dispose(); super.dispose(); } @override Widget build(BuildContext context) { super.build(context); return SelectionWillPopScope( fileListLocalManager: _fileListLocalManager, child: Scaffold( appBar: SelectionAppBar( fileListLocalManager: _fileListLocalManager, viewConfig: _viewConfig, appBarBuilder: _buildAppBar, ), drawer: widget._categoryViewConfig.hasDrawer! ? YagaDrawer() : null, body: ImageViewContainer( fileListLocalManager: _fileListLocalManager, viewConfig: _viewConfig), bottomNavigationBar: YagaBottomNavBar(widget._categoryViewConfig.selectedTab!), ), ); } AppBar _buildAppBar(BuildContext context, List actions) { if (!_fileListLocalManager.isInSelectionMode) { actions.add(YagaPopupMenuButton( _buildPopupMenu, _popupMenuHandler, )); } return AppBar( title: SelectionTitle( _fileListLocalManager, defaultTitel: Text( widget._categoryViewConfig.title!, overflow: TextOverflow.fade, ), ), actions: actions, leading: _fileListLocalManager.isInSelectionMode ? IconButton( icon: const Icon(Icons.arrow_back), onPressed: () => _fileListLocalManager.deselectAll(), ) : null, ); } void _popupMenuHandler(BuildContext context, CategoryViewMenu result) { if (result == CategoryViewMenu.settings) { Navigator.pushNamed( context, SettingsScreen.route, arguments: SettingsScreenArguments( preferences: _defaultViewPreferences, ), ); } } List> _buildPopupMenu(BuildContext context) { return [ const PopupMenuItem( value: CategoryViewMenu.settings, child: ListMenuEntry(Icons.settings, "Settings"), ), ]; } @override bool get wantKeepAlive => true; } ================================================ FILE: lib/views/screens/choice_selector_screen.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/preferences/choice_preference.dart'; import 'package:yaga/views/widgets/select_cancel_bottom_navigation.dart'; class ChoiceSelectorScreen extends StatefulWidget { static const String route = "/choiceSelectorScreen"; final ChoicePreference _choicePreference; final void Function() _onCancel; final void Function(String) _onSelect; const ChoiceSelectorScreen( this._choicePreference, this._onSelect, this._onCancel); @override _ChoiceSelectorScreenState createState() => _ChoiceSelectorScreenState(); } class _ChoiceSelectorScreenState extends State { late String _choice; @override void initState() { super.initState(); _choice = widget._choicePreference.value; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget._choicePreference.title!), ), body: ListView.separated( itemBuilder: (context, index) => RadioListTile( title: Text(widget._choicePreference.choices[ widget._choicePreference.choices.keys.elementAt(index)]!), value: widget._choicePreference.choices.keys.elementAt(index), groupValue: _choice, onChanged: (String? value) => setState(() => _choice = value ?? _choice)), separatorBuilder: (context, index) => const Divider(), itemCount: widget._choicePreference.choices.length), bottomNavigationBar: SelectCancelBottomNavigation( onCommit: () { widget._onSelect(_choice); }, onCancel: widget._onCancel), ); } } ================================================ FILE: lib/views/screens/directory_screen.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/route_args/directory_navigation_screen_arguments.dart'; import 'package:yaga/model/route_args/focus_view_arguments.dart'; import 'package:yaga/model/route_args/navigatable_screen_arguments.dart'; import 'package:yaga/model/route_args/settings_screen_arguments.dart'; import 'package:yaga/services/intent_service.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/focus_view.dart'; import 'package:yaga/views/screens/settings_screen.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; import 'package:yaga/views/widgets/image_view_container.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/views/widgets/list_menu_entry.dart'; import 'package:yaga/views/widgets/path_widget.dart'; import 'package:yaga/views/widgets/selection_app_bar.dart'; import 'package:yaga/views/widgets/selection_title.dart'; import 'package:yaga/views/widgets/selection_will_pop_scope.dart'; import 'package:yaga/views/widgets/yaga_popup_menu_button.dart'; enum BrowseViewMenu { settings, focus } //todo: rename this since it is also used for browse view... maybe clean up a little class DirectoryScreen extends StatefulWidget { static const String route = "/directoryNavigationScreen"; static const double appBarBottomHeight = 40; final ViewConfiguration viewConfig; final Uri uri; final String? title; final Widget Function(BuildContext, Uri)? bottomBarBuilder; final String? navigationRoute; final NavigatableScreenArguments Function(DirectoryNavigationScreenArguments)? getNavigationArgs; final bool leading; final bool fixedOrigin; final String schemeFilter; final YagaHomeTab _selectedTab; DirectoryScreen({ required this.uri, required this.viewConfig, this.title, this.bottomBarBuilder, this.navigationRoute, this.getNavigationArgs, required this.leading, this.fixedOrigin = false, this.schemeFilter = "", required YagaHomeTab selectedTab, }) : _selectedTab = selectedTab, super(key: ValueKey(uri.toString())); @override _DirectoryScreenState createState() => _DirectoryScreenState(uri, viewConfig); } class _DirectoryScreenState extends State { final FileListLocalManager _fileListLocalManager; final ViewConfiguration _viewConfig; final List _defaultViewPreferences = []; factory _DirectoryScreenState(Uri uri, ViewConfiguration viewConfig) { final fileListLocalManager = FileListLocalManager( uri, viewConfig.recursive, ViewConfiguration.getSortConfigFromViewChoice( getIt .get() .loadPreferenceFromString(viewConfig.view), ), allowSelecting: viewConfig.onFileTap != null, favorites: viewConfig.favorites, ); dynamic onFileTap(List files, int index) { if (fileListLocalManager.isInSelectionMode) { return fileListLocalManager.selectFileCommand(files[index]); } if (viewConfig.onFileTap != null) { return viewConfig.onFileTap!(files, index); } } dynamic onFolderTap(NcFile folder) { if (fileListLocalManager.isInSelectionMode) { return fileListLocalManager.selectFileCommand(folder); } if (viewConfig.onFolderTap != null) { return viewConfig.onFolderTap!(folder); } } return _DirectoryScreenState._internal( fileListLocalManager, ViewConfiguration.fromViewConfig( viewConfig: viewConfig, onFolderTap: onFolderTap, onSelect: getIt.get().isOpenForSelect ? onFileTap : (files, index) => fileListLocalManager.selectFileCommand(files[index]), onFileTap: onFileTap, ), ); } _DirectoryScreenState._internal(this._fileListLocalManager, this._viewConfig); @override void initState() { _defaultViewPreferences.add(widget.viewConfig.section); _defaultViewPreferences.add(widget.viewConfig.view); _fileListLocalManager.initState(); super.initState(); } @override void dispose() { _fileListLocalManager.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return SelectionWillPopScope( fileListLocalManager: _fileListLocalManager, child: Scaffold( key: ValueKey(_fileListLocalManager.uri.toString()), appBar: SelectionAppBar( fileListLocalManager: _fileListLocalManager, viewConfig: _viewConfig, appBarBuilder: _buildAppBar, bottomHeight: DirectoryScreen.appBarBottomHeight, searchResultHandler: (file) { if (file != null && file.isDirectory && widget.viewConfig.onFolderTap != null) { widget.viewConfig.onFolderTap!(file); } }, ), //todo: is it possible to directly pass the folder.uri? body: ImageViewContainer( fileListLocalManager: _fileListLocalManager, viewConfig: _viewConfig, ), bottomNavigationBar: widget.bottomBarBuilder == null ? null : widget.bottomBarBuilder!(context, _fileListLocalManager.uri), ), ); } AppBar _buildAppBar(BuildContext context, List actions) { if (!_fileListLocalManager.isInSelectionMode) { actions.add(YagaPopupMenuButton( _buildPopupMenu, _handleMenuSelection, )); } return AppBar( title: SelectionTitle( _fileListLocalManager, defaultTitel: Text(widget.title ?? _fileListLocalManager.uri.pathSegments.last), ), //todo: remove widget.leading argument it is always true leading: widget.leading ? IconButton( icon: const Icon(Icons.arrow_back), onPressed: () => _fileListLocalManager.isInSelectionMode ? _fileListLocalManager.deselectAll() : Navigator.of(context).pop()) : null, actions: actions, bottom: PreferredSize( preferredSize: const Size.fromHeight(DirectoryScreen.appBarBottomHeight), child: SizedBox( height: DirectoryScreen.appBarBottomHeight, child: Align( alignment: Alignment.topLeft, child: PathWidget( _fileListLocalManager.uri, (Uri subPath) => Navigator.of(context).pop(subPath), fixedOrigin: widget.fixedOrigin, schemeFilter: widget.schemeFilter, ), ), )), ); } void _handleMenuSelection(BuildContext context, BrowseViewMenu result) { if (result == BrowseViewMenu.settings) { Navigator.pushNamed( context, SettingsScreen.route, arguments: SettingsScreenArguments(preferences: _defaultViewPreferences), ); } if (result == BrowseViewMenu.focus) { Navigator.pushNamed( context, FocusView.route, arguments: FocusViewArguments( _fileListLocalManager.uri, _viewConfig.favorites, widget._selectedTab, _viewConfig.route, ), ); } } List> _buildPopupMenu(BuildContext context) { return [ const PopupMenuItem( value: BrowseViewMenu.settings, child: ListMenuEntry(Icons.settings, "Settings"), ), const PopupMenuItem( value: BrowseViewMenu.focus, child: ListMenuEntry(Icons.remove_red_eye, "Focus"), ), ]; } } ================================================ FILE: lib/views/screens/directory_traversal_screen.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/route_args/directory_navigation_screen_arguments.dart'; import 'package:yaga/utils/uri_utils.dart'; import 'package:yaga/utils/navigation/yaga_router.dart'; import 'package:yaga/views/screens/directory_screen.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; enum DirectoryTraversalScreenNavActions { cancel } class DirectoryTraversalScreen extends StatefulWidget { final DirectoryNavigationScreenArguments args; const DirectoryTraversalScreen(this.args); @override _DirectoryTraversalScreenState createState() => _DirectoryTraversalScreenState(); } class _DirectoryTraversalScreenState extends State { final _navigatorKey = GlobalKey(); Uri? uri; late ViewConfiguration viewConfig; @override void initState() { viewConfig = ViewConfiguration.fromViewConfig( viewConfig: widget.args.viewConfig, onFolderTap: (NcFile file) => _navigate(file.uri), ); uri = widget.args.uri; super.initState(); } void _navigate(Uri? target) { //this is so we can find out which use case sets null assert(target != null, "Target is null!"); setState(() { uri = target == null ? null : fromUri(uri: target); }); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async => !(await _navigatorKey.currentState?.maybePop(context) ?? true), child: Navigator( key: _navigatorKey, reportsRouteUpdateToEngine: true, pages: _buildPages(context, viewConfig, uri!), onGenerateRoute: generateRoute, onPopPage: (route, result) { if (!route.didPop(result)) { return false; } return _handlePagePop(context, result); }, ), ); } bool _handlePagePop(BuildContext context, dynamic result) { if (result is Uri) { _navigate(result); return true; } //in case we are poping the root element we need to inform the parent navigatort if (result == DirectoryTraversalScreenNavActions.cancel || uri == null || //todo: in which case is the uri == null?! uri == getRootFromUri(uri!)) { Navigator.of(context).pop(); return true; } //in case we are poping a non root element create the new page list setState(() { //todo: solve this better uri = fromUriPathSegments( uri!, uri!.pathSegments.length - 3, ); }); return true; } List _buildPages( BuildContext context, ViewConfiguration viewConfig, Uri uri, ) { final List pages = []; pages.add(_buildPage(getRootFromUri(uri), viewConfig)); int index = 0; uri.pathSegments.where((element) => element.isNotEmpty).forEach((segment) { pages.add( _buildPage( fromUriPathSegments(uri, index++), ViewConfiguration.fromViewConfig( viewConfig: viewConfig, favorites: false, ), ), ); }); return pages; } Page _buildPage(Uri uri, ViewConfiguration viewConfig) { return MaterialPage( key: ValueKey(uri.toString()), child: DirectoryScreen( uri: uri, bottomBarBuilder: widget.args.bottomBarBuilder, viewConfig: viewConfig, title: widget.args.title, fixedOrigin: widget.args.fixedOrigin, schemeFilter: widget.args.schemeFilter, leading: widget.args.leadingBackArrow, selectedTab: this.viewConfig.favorites ? YagaHomeTab.favorites : YagaHomeTab.folder, ), ); } } ================================================ FILE: lib/views/screens/favorites_view.dart ================================================ import 'package:yaga/views/screens/browse_view.dart'; class FavoritesView extends BrowseView { @override String get pref => "favorites"; const FavoritesView() : super(favorites: true); } ================================================ FILE: lib/views/screens/focus_view.dart ================================================ import 'package:yaga/model/category_view_config.dart'; import 'package:yaga/utils/uri_utils.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; import 'package:yaga/views/screens/category_view_screen.dart'; class FocusView extends CategoryViewScreen { static const String route = "/focus"; FocusView(Uri path, bool favorites, YagaHomeTab selectedTab, String prefPrefix) : super( CategoryViewConfig( defaultPath: path, pref: "$prefPrefix/focus", pathEnabled: false, hasDrawer: false, selectedTab: selectedTab, title: getNameFromUri(path), favorites: favorites, ), ); } ================================================ FILE: lib/views/screens/home_view.dart ================================================ import 'package:yaga/model/category_view_config.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/services/intent_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; import 'package:yaga/views/screens/category_view_screen.dart'; class HomeView extends CategoryViewScreen { static const String pref = "category"; HomeView() : super( CategoryViewConfig( defaultPath: getIt.get().internalStorage.uri, pref: pref, pathEnabled: true, hasDrawer: true, selectedTab: YagaHomeTab.grid, title: _getTitle()), ); //todo: unify this static String _getTitle() { if (getIt.get().isOpenForSelect) { return "Selecte image..."; } return "Nextcloud Yaga"; } } ================================================ FILE: lib/views/screens/image_screen.dart ================================================ import 'dart:async'; import 'dart:io'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:photo_view/photo_view.dart'; import 'package:photo_view/photo_view_gallery.dart'; import 'package:share_plus/share_plus.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; import 'package:yaga/managers/file_manager/file_manager.dart'; import 'package:yaga/managers/global_settings_manager.dart'; import 'package:yaga/model/fetched_file.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/intent_service.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/download_file_image.dart'; import 'package:yaga/utils/forground_worker/messages/download_file_request.dart'; import 'package:yaga/utils/forground_worker/messages/files_action/favorite_files_request.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/widgets/list_menu_entry.dart'; import 'package:yaga/views/widgets/yaga_popup_menu_button.dart'; class ImageScreen extends StatefulWidget { static const String route = "/image"; final List _images; final int index; final String? title; const ImageScreen( this._images, this.index, { this.title, }); @override State createState() => ImageScreenState(); } enum ImageViewMenu { share, fav, wallpaper, download, slideshow_start, slideshow_stop } class ImageScreenState extends State { final _logger = YagaLogger.getLogger(ImageScreenState); late String _title; late int _currentIndex; late PageController pageController; var _showAppBar = true; Timer? _timer; final rng = Random(); @override void initState() { pageController = PageController(initialPage: widget.index); _currentIndex = pageController.initialPage; _title = widget._images[_currentIndex].name; super.initState(); } void _onPageChanged(int index) { setState(() { _currentIndex = index; _title = widget._images[index].name; }); } @override void dispose() { _stopSlideShow(); SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values); super.dispose(); } void _stopSlideShow() { WakelockPlus.disable(); _timer?.cancel(); } @override Widget build(BuildContext context) { return Scaffold( appBar: _showAppBar ? AppBar( title: Text(widget.title ?? _title), actions: _buildMainAction(context), ) : null, body: GestureDetector( onTap: () => setState(() { _showAppBar = !_showAppBar; _showAppBar ? SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values) : SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive); }), child: CallbackShortcuts( bindings: { const SingleActivator(LogicalKeyboardKey.arrowRight): navigateRight, const SingleActivator(LogicalKeyboardKey.pageDown): navigateRight, const SingleActivator(LogicalKeyboardKey.arrowLeft): navigateLeft, const SingleActivator(LogicalKeyboardKey.pageUp): navigateLeft, const SingleActivator(LogicalKeyboardKey.keyF): () => _handlePopupMenu(context, ImageViewMenu.fav), }, child: Focus( autofocus: true, child: Stack( children: [ PhotoViewGallery.builder( pageController: pageController, onPageChanged: _onPageChanged, itemCount: widget._images.length, builder: (BuildContext context, int index) { final NcFile image = widget._images[index]; _logger.fine("Building view for index $index"); final Future localFileAvailable = getIt .get() .fetchedFileCommand .where((event) => event.file.uri.path == image.uri.path) .first; getIt.get().downloadImageCommand( DownloadFileRequest(image), ); return PhotoViewGalleryPageOptions( key: ValueKey(image.uri.path), minScale: PhotoViewComputedScale.contained, imageProvider: DownloadFileImage( image.localFile!.file as File, localFileAvailable, ), ); }, loadingBuilder: (context, event) { final bool previewExists = widget._images[_currentIndex].previewFile != null && widget._images[_currentIndex].previewFile!.exists; return Stack(children: [ Container( color: Colors.black, child: previewExists ? Image.file( widget._images[_currentIndex].previewFile!.file as File, width: double.infinity, height: double.infinity, fit: BoxFit.contain, ) : null, ), const LinearProgressIndicator(), ]); }, ), ]..addAll( _buildDesktopButtons(context), ), ), ), ), ), ); } List _buildDesktopButtons(BuildContext context) { if (Platform.isAndroid) { return []; } return [ _buildDesktopNavButton( context: context, child: const Icon(Icons.arrow_forward), onPressed: navigateRight, alignment: Alignment.centerRight, key: LogicalKeyboardKey.arrowRight, ), _buildDesktopNavButton( context: context, child: const Icon(Icons.arrow_back), onPressed: navigateLeft, alignment: Alignment.centerLeft, key: LogicalKeyboardKey.arrowLeft, ), ]; } void navigateLeft() => pageController.previousPage( duration: const Duration(milliseconds: 500), curve: Curves.linear, ); void navigateRight() => pageController.nextPage( duration: const Duration(milliseconds: 500), curve: Curves.linear, ); Widget _buildDesktopNavButton({ required BuildContext context, required Widget child, required Function() onPressed, required Alignment alignment, required LogicalKeyboardKey key, }) { return Align( alignment: alignment, child: Padding( padding: const EdgeInsets.only(left: 8.0, right: 8.0), child: FloatingActionButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), onPressed: onPressed, child: child, ), ), ); } int _calculatePage(BuildContext context) { if (getIt.get().loadPreferenceFromBool(GlobalSettingsManager.slideShowRandom).value) { return rng.nextInt(widget._images.length); } if (widget._images.length == _currentIndex + 1) { if (getIt.get().loadPreferenceFromBool(GlobalSettingsManager.slideShowAutoStop).value) { _stopSlideShow(); Navigator.pop(context); } return 0; } return _currentIndex + 1; } List _buildMainAction(BuildContext context) { if (getIt.get().isOpenForSelect) { return [ IconButton( icon: const Icon(Icons.check), onPressed: () async { await getIt.get().setSelectedFile(widget._images[_currentIndex]); }, ), ]; } return [ _addFavButton(context), if (_timer != null) ...[ IconButton( icon: const Icon(Icons.stop_circle_outlined), onPressed: () => _handlePopupMenu(context, ImageViewMenu.slideshow_stop), ) ], YagaPopupMenuButton(_buildPopupMenu, _handlePopupMenu), ]; } List> _buildPopupMenu(BuildContext context) { return [ if (_timer == null) const PopupMenuItem( value: ImageViewMenu.slideshow_start, child: ListMenuEntry(Icons.play_circle_outlined, "Start slideshow"), ) else const PopupMenuItem( value: ImageViewMenu.slideshow_stop, child: ListMenuEntry(Icons.stop_circle_outlined, "Stop slideshow"), ), const PopupMenuItem(value: ImageViewMenu.download, child: ListMenuEntry(Icons.download, "Download")), if (Platform.isAndroid) ...[ const PopupMenuItem(value: ImageViewMenu.wallpaper, child: ListMenuEntry(Icons.wallpaper, "Use as")), const PopupMenuItem(value: ImageViewMenu.share, child: ListMenuEntry(Icons.share, "Share")), ], ]; } void _handlePopupMenu(BuildContext context, ImageViewMenu item) { switch (item) { case ImageViewMenu.share: Share.shareFiles([widget._images[_currentIndex].localFile!.file.path]); case ImageViewMenu.fav: final image = widget._images[_currentIndex]; final req = FavoriteFilesRequest(key: "imageScreenRequest", files: [image], sourceDir: image.uri); getIt.get().filesActionCommand(req); case ImageViewMenu.wallpaper: getIt.get().attachData(widget._images[_currentIndex]); case ImageViewMenu.download: getIt.get().downloadImageCommand( DownloadFileRequest(widget._images[_currentIndex], forceDownload: true), ); case ImageViewMenu.slideshow_start: WakelockPlus.enable(); setState( () => _timer = Timer.periodic( Duration( seconds: getIt .get() .loadPreferenceFromInt(GlobalSettingsManager.slideShowInterval) .value, ), (Timer t) => pageController.jumpToPage(_calculatePage(context)), ), ); case ImageViewMenu.slideshow_stop: _stopSlideShow(); setState(() => _timer = null); } } Widget _addFavButton(BuildContext context) { return StreamBuilder( stream: getIt .get() .updateImageCommand .where((event) => event.uri.path == widget._images[_currentIndex].uri.path), initialData: widget._images[_currentIndex], builder: (context, snapshot) => IconButton( icon: snapshot.data!.favorite ? const Icon(Icons.star) : const Icon(Icons.star_border), onPressed: () => _handlePopupMenu(context, ImageViewMenu.fav), ), ); } } ================================================ FILE: lib/views/screens/nc_address_screen.dart ================================================ import 'dart:async'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:nextcloud/core.dart'; import 'package:nextcloud/nextcloud.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/model/nc_login_data.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/utils/nextcloud_client_factory.dart'; import 'package:yaga/utils/self_signed_cert_handler.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/nc_login_screen.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; import 'package:yaga/views/widgets/action_danger_dialog.dart'; import 'package:yaga/views/widgets/address_form_advanced.dart'; import 'package:yaga/views/widgets/address_form_simple.dart'; import 'package:yaga/views/widgets/select_cancel_bottom_navigation.dart'; class NextCloudAddressScreen extends StatefulWidget { static const route = "/nc/address"; const NextCloudAddressScreen({Key? key}) : super(key: key); @override State createState() => _NextCloudAddressScreenState(); } class _NextCloudAddressScreenState extends State { final _logger = YagaLogger.getLogger(_NextCloudAddressScreenState); GlobalKey _formKey = GlobalKey(); bool validation = true; bool _inBrowser = false; bool _disposing = false; @override void dispose() { _logger.fine("Disposing"); _disposing = true; super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Server Address"), actions: [ IconButton( icon: validation ? const Icon(Icons.report) : const Icon(Icons.report_off), onPressed: () => setState(() { validation = !validation; _formKey = GlobalKey(); }), ), ], ), body: Center( child: Container( padding: const EdgeInsets.symmetric(horizontal: 10), child: validation ? AddressFormSimple(_formKey, _onSave) : AddressFormAdvanced(_formKey, _onSave), ), ), resizeToAvoidBottomInset: true, bottomNavigationBar: SelectCancelBottomNavigation( onCommit: () { _inBrowser = false; _validateAndSaveForm(); }, //todo: why does this cause a refetch?! onCancel: () => Navigator.popUntil( context, ModalRoute.withName(YagaHomeScreen.route), ), labelSelect: "Continue", iconSelect: Icons.chevron_right, betweenItems: const [ BottomNavigationBarItem( icon: Icon(Icons.open_in_browser), label: "Open in browser", ), ], betweenItemsCallbacks: [ () { _inBrowser = true; _validateAndSaveForm(); } ], ), ); } void _validateAndSaveForm() { if (!(_formKey.currentState?.validate()??false)) { return; } _formKey.currentState?.save(); } Future _onSave(Uri uri) async { final client = getIt.get().createUnauthenticatedClient(uri); // check if we detect a self-signed cert, if yes, enforce browser flow if (!_inBrowser) { try { await client.httpClient.getUrl(uri); _logger.info("Proper HTTPS detected."); } on HandshakeException { _inBrowser = true; } } if (_inBrowser) { getIt.get().badCertificateCallback = _askForCertApprovalBuilder(uri); //todo: should we move this into the manager/service? //todo: is canLaunch/launch a UI component? LoginFlowV2 init; try { init = await client.core.clientFlowLoginV2.init().then((value) => value.body); } catch (e) { _logger.severe("Could not init login flow", e); getIt.get().revokeCert(); getIt.get().badCertificateCallback = null; return; } try { // final res = await client.core.clientFlowLoginV2.poll(token: init.poll.token).then((value) => value.body); if(await launchUrl(Uri.parse(init.login), mode: LaunchMode.externalApplication,)) { // await launchUrlString(init.login, mode: LaunchMode.externalApplication); LoginFlowV2Credentials? res; while (res == null) { _logger.fine("Requesting"); try { res = await client.core.clientFlowLoginV2.poll(token: init.poll.token) .then((value) => value.body); } on DynamiteApiException catch (e) { if (e.statusCode != 404) { throw e; } } } if (_disposing) { // revoke tmp granted cert if login is aborted getIt.get().revokeCert(); return; } getIt.get().loginCommand( NextCloudLoginData( Uri.parse(res!.server), res.loginName, res.appPassword, ), ); getIt .get() .badCertificateCallback = null; if (!mounted) return; Navigator.popUntil( context, ModalRoute.withName(YagaHomeScreen.route), ); } } on Exception catch (e) { //todo: show message to user _logger.severe('Could not launch $uri', e); } return; } if (!mounted) return; Navigator.pushNamed( context, NextCloudLoginScreen.route, arguments: uri, ); } Future Function( String subject, String issuer, String fingerprint, ) _askForCertApprovalBuilder(Uri uri) { return ( String subject, String issuer, String fingerprint, ) { final completer = Completer(); showDialog( context: context, builder: (context) => ActionDangerDialog( title: "Untrusted Certificate", cancelButton: "Cancel", aggressiveAction: "Trust", action: (agg) { if (agg) { completer.complete(() => _onSave(uri)); } else { completer.complete(null); } }, bodyBuilder: (context) => [ const Text('Do you trust this certificate?'), const Text(''), Text('Subject: $subject'), Text('Issuer: $issuer'), Text('Fingerprint: $fingerprint'), const Text(''), const Text( 'Please note that Nextcloud Yaga only performs fingerprint comparison on self-signed certificates!', ), ], ), ).whenComplete( () => getIt.get().badCertificateCallback = null, ); return completer.future; }; } } ================================================ FILE: lib/views/screens/nc_login_screen.dart ================================================ import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/model/nc_login_data.dart'; import 'package:yaga/utils/nextcloud_client_factory.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; class NextCloudLoginScreen extends StatelessWidget { static const String route = "/nc/login"; final Uri _url; const NextCloudLoginScreen(this._url); @override Widget build(BuildContext context) { final WebViewController controller = WebViewController() ..setUserAgent(getIt.get().userAgent) ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setNavigationDelegate( NavigationDelegate( onNavigationRequest: (NavigationRequest request) async { if (request.url.startsWith("nc")) { //string of type: nc://login/server:&user:&password: final Map ncParas = request.url .split("nc://login/")[1] .split("&") .map((e) => e.split(":")) .map((e) => {e.removeAt(0): e.join(":")}) .reduce((value, element) { value.addAll(element); return value; }); getIt.get().loginCommand(NextCloudLoginData( Uri.parse(ncParas[NextCloudLoginDataKeys.server]!), Uri.decodeComponent(ncParas[NextCloudLoginDataKeys.user]!), ncParas[NextCloudLoginDataKeys.password]!, )); Navigator.popUntil( context, ModalRoute.withName(YagaHomeScreen.route)); return NavigationDecision.prevent; } return NavigationDecision.navigate; }, ), ) ..loadRequest( Uri.parse("$_url/index.php/login/flow"), headers: {"OCS-APIREQUEST": "true"}, ); return Scaffold( appBar: AppBar( title: const Text("Sign in..."), ), body: WebViewWidget( controller: controller, ), ); } } ================================================ FILE: lib/views/screens/path_selector_screen.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/route_args/directory_navigation_screen_arguments.dart'; import 'package:yaga/views/screens/directory_traversal_screen.dart'; import 'package:yaga/views/widgets/image_views/nc_list_view.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/views/widgets/select_cancel_bottom_navigation.dart'; //todo: is it a good idea to merge PathSelectorScreen and DirectoryTraversalScreen? class PathSelectorScreen extends StatelessWidget { static const String route = "/pathSelector"; final Uri _uri; final void Function(Uri)? _onSelect; final void Function(List, int)? onFileTap; final String? title; final bool fixedOrigin; final String schemeFilter; const PathSelectorScreen( this._uri, this._onSelect, { this.onFileTap, this.title, this.fixedOrigin = false, this.schemeFilter = "", }); @override Widget build(BuildContext context) { return DirectoryTraversalScreen(_getArgs(context)); } DirectoryNavigationScreenArguments _getArgs(BuildContext context) { Widget Function(BuildContext, Uri)? bottomBarBuilder; //todo: can't we simply build the bottomBar every time in this screen? if (_onSelect != null) { bottomBarBuilder = (BuildContext context, Uri uri) => SelectCancelBottomNavigation( onCommit: () { Navigator.of(context) .pop(DirectoryTraversalScreenNavActions.cancel); _onSelect!(uri); }, onCancel: () => Navigator.of(context) .pop(DirectoryTraversalScreenNavActions.cancel), ); } final ViewConfiguration viewConfig = ViewConfiguration.browse( route: route, defaultView: NcListView.viewKey, onFolderTap: null, onFileTap: onFileTap, onSelect: null, ); return DirectoryNavigationScreenArguments( uri: _uri, title: title ?? "Select path...", viewConfig: viewConfig, fixedOrigin: fixedOrigin, schemeFilter: schemeFilter, bottomBarBuilder: bottomBarBuilder); } } ================================================ FILE: lib/views/screens/settings_screen.dart ================================================ import 'package:flutter/material.dart'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/model/preferences/action_preference.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/model/preferences/choice_preference.dart'; import 'package:yaga/model/preferences/int_preference.dart'; import 'package:yaga/model/preferences/mapping_preference.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/preferences/uri_preference.dart'; import 'package:yaga/views/widgets/preferences/action_preference_widget.dart'; import 'package:yaga/views/widgets/preferences/bool_preference_widget.dart'; import 'package:yaga/views/widgets/preferences/choice_preference_widget.dart'; import 'package:yaga/views/widgets/preferences/int_preference_widget.dart'; import 'package:yaga/views/widgets/preferences/mapping_preference_widget.dart'; import 'package:yaga/views/widgets/preferences/section_preference_widget.dart'; import 'package:yaga/views/widgets/preferences/uri_preference_widget.dart'; import 'package:yaga/views/widgets/select_cancel_bottom_navigation.dart'; class SettingsScreen extends StatelessWidget { static const String route = "/settings"; final List _defaultPreferences; final RxCommand? onPreferenceChangedCommand; final Function? onCommit; final Function? onCancel; const SettingsScreen( this._defaultPreferences, { this.onPreferenceChangedCommand, this.onCancel, this.onCommit, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Settings"), ), body: ListView.separated( itemBuilder: (context, index) { final Preference defaultPref = _defaultPreferences[index]; if (defaultPref is UriPreference) { return UriPreferenceWidget( defaultPref, onChangeCommand: onPreferenceChangedCommand, ); } if (defaultPref is MappingPreference) { return MappingPreferenceWidget(defaultPref, SettingsScreen.route); } if (defaultPref is BoolPreference) { return BoolPreferenceWidget( defaultPref, onChangeCommand: onPreferenceChangedCommand, ); } if (defaultPref is ChoicePreference) { return ChoicePreferenceWidget( defaultPref, onPreferenceChangedCommand, ); } if(defaultPref is IntPreference) { return IntPreferenceWidget(defaultPref, onPreferenceChangedCommand); } if (defaultPref is ActionPreference) { return ActionPreferenceWidget(defaultPref); } return SectionPreferenceWidget(defaultPref); }, separatorBuilder: (context, index) => const Divider(), itemCount: _defaultPreferences.length, ), bottomNavigationBar: onCommit == null ? null : SelectCancelBottomNavigation( onCommit: onCommit!, onCancel: onCancel!, ), ); } } ================================================ FILE: lib/views/screens/splash_screen.dart ================================================ import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:yaga/utils/nextcloud_colors.dart'; class SplashScreen extends StatelessWidget { @override Widget build(BuildContext context) { final scaffold = Scaffold( backgroundColor: Colors.transparent, body: Row( mainAxisAlignment: MainAxisAlignment.center, // mainAxisSize: MainAxisSize.max, children: [ Align( // alignment: Alignment.center, child: SvgPicture.asset( "assets/icon/foreground.svg", semanticsLabel: 'Yaga Logo', // alignment: Alignment.center, width: 108, ), ), ], ), ); return Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topRight, end: Alignment.bottomLeft, colors: [ NextcloudColors.lightBlue, NextcloudColors.darkBlue, ], ), ), child: scaffold, ); } } ================================================ FILE: lib/views/screens/yaga_home_screen.dart ================================================ import 'package:flutter/material.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:yaga/managers/global_settings_manager.dart'; import 'package:yaga/managers/tab_manager.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/forground_worker/foreground_worker.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/favorites_view.dart'; import 'package:yaga/views/screens/home_view.dart'; import 'package:yaga/views/screens/browse_view.dart'; import 'package:yaga/views/widgets/yaga_about_dialog.dart'; //todo: this has to be renamed enum YagaHomeTab { grid, folder, favorites } class YagaHomeScreen extends StatefulWidget { static const String route = "home://"; @override _YagaHomeScreenState createState() => _YagaHomeScreenState(); } class _YagaHomeScreenState extends State with WidgetsBindingObserver { @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.paused) { getIt.get().dispose(); } if (state == AppLifecycleState.resumed) { getIt.get().init(); } } @override Widget build(BuildContext context) { _showNewsDialog(context); return StreamBuilder( initialData: YagaHomeTab.grid, stream: getIt.get().tabChangedCommand, builder: (context, snapshot) { return IndexedStack( index: _getCurrentIndex(snapshot.data), children: [HomeView(), FavoritesView(), BrowseView()], ); }, ); } int _getCurrentIndex(YagaHomeTab? tab) { switch (tab) { case YagaHomeTab.folder: return 2; case YagaHomeTab.favorites: return 1; default: return 0; } } void _showNewsDialog(BuildContext context) { Future.delayed(Duration.zero, () async { final sharedPrefService = getIt.get(); final version = getIt.get().version; if (sharedPrefService .loadPreferenceFromString(GlobalSettingsManager.newsSeenVersion) .value != version) { await showDialog( context: context, builder: (BuildContext context) => YagaAboutDialog(), ).whenComplete( () => sharedPrefService.savePreferenceToString( GlobalSettingsManager.newsSeenVersion .rebuild((b) => b..value = version), ), ); } }); } } ================================================ FILE: lib/views/widgets/action_danger_dialog.dart ================================================ import 'package:flutter/material.dart'; class ActionDangerDialog extends StatelessWidget { final String title; final String cancelButton; final String? normalAction; final String aggressiveAction; final Function(bool) action; final List Function(BuildContext) bodyBuilder; const ActionDangerDialog({ required this.title, required this.cancelButton, this.normalAction, required this.aggressiveAction, required this.action, required this.bodyBuilder, }); @override Widget build(BuildContext context) { final actions = []; actions.add( TextButton( onPressed: () { Navigator.pop(context); }, child: Text(cancelButton), ), ); if (normalAction != null) { actions.add( TextButton( onPressed: () { Navigator.pop(context); action(false); }, child: Text(normalAction!), ), ); } actions.add( TextButton( style: TextButton.styleFrom(primary: Colors.red), onPressed: () { Navigator.pop(context); action(true); }, child: Text(aggressiveAction), ), ); return AlertDialog( title: Text(title), content: SingleChildScrollView( child: ListBody( children: bodyBuilder(context), ), ), actions: actions, ); } } ================================================ FILE: lib/views/widgets/address_form_advanced.dart ================================================ import 'package:flutter/material.dart'; import 'package:validators/sanitizers.dart'; class AddressFormAdvanced extends StatelessWidget { final GlobalKey _formKey; final Function(Uri) _onSave; const AddressFormAdvanced(this._formKey, this._onSave); @override Widget build(BuildContext context) { return Form( key: _formKey, autovalidateMode: AutovalidateMode.onUserInteraction, child: TextFormField( decoration: const InputDecoration( labelText: "Fully qualified Nextcloud Server address...", icon: Icon(Icons.cloud_queue), helperStyle: TextStyle(color: Colors.orange), helperText: "Validation is disabled."), onSaved: (value) => _onSave( Uri.parse(rtrim(value?.trim()??'', "/")), ), initialValue: "https://", ), ); } } ================================================ FILE: lib/views/widgets/address_form_simple.dart ================================================ import 'package:flutter/material.dart'; import 'package:validators/sanitizers.dart'; import 'package:validators/validators.dart'; class AddressFormSimple extends StatelessWidget { final GlobalKey _formKey; final Function(Uri) _onSave; const AddressFormSimple(this._formKey, this._onSave); @override Widget build(BuildContext context) { return Form( key: _formKey, autovalidateMode: AutovalidateMode.onUserInteraction, child: TextFormField( decoration: const InputDecoration( labelText: "Nextcloud Server address https://...", icon: Icon(Icons.cloud_queue)), onSaved: (value) => _onSave( Uri.parse('https://${rtrim(value?.trim()??"", "/")}'), ), validator: (value) { value = value?.trim()??""; if (value.startsWith("https://") || value.startsWith("http://")) { return "Https will be added automaically."; } return isURL("https://$value") ? null : "Please enter a valid URL."; }, ), ); } } ================================================ FILE: lib/views/widgets/avatar_widget.dart ================================================ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:rx_command/rx_command.dart'; class AvatarWidget extends StatelessWidget { final File? _avatar; final RxCommand? _command; final IconData? _iconData; final double _radius; final bool border; const AvatarWidget(this._avatar, {double radius = 14, this.border = true}) : _command = null, _iconData = null, _radius = radius; const AvatarWidget.command(this._command, {double radius = 14, this.border = true}) : _avatar = null, _iconData = null, _radius = radius; const AvatarWidget.icon(this._iconData, {double radius = 14, this.border = true}) : _avatar = null, _command = null, _radius = radius; const AvatarWidget.phone({double radius = 14, this.border = true}) : _avatar = null, _iconData = Icons.phone_android, _command = null, _radius = radius; const AvatarWidget.sd({double radius = 14, this.border = true}) : _avatar = null, _iconData = Icons.sd_card_outlined, _command = null, _radius = radius; Widget _buildAvatar(BuildContext context, File? data) { if (border) { return CircleAvatar( radius: _radius + 1, backgroundColor: Theme.of(context).primaryColor, child: _getInnerAvatar(context, data), ); } return _getInnerAvatar(context, data); } Widget _getInnerAvatar(BuildContext context, File? data) { if (data != null && data.existsSync()) { return CircleAvatar( radius: _radius, backgroundImage: FileImage(data), ); } if (_iconData != null) { return _getIconAvatar(context, _iconData!); } return _getIconAvatar(context, Icons.cloud); } Widget _getIconAvatar(BuildContext context, IconData iconData) { return CircleAvatar( radius: _radius, backgroundColor: Theme.of(context).primaryIconTheme.color, child: Icon( iconData, size: _radius + 10, color: Colors.black, ), ); } Widget _buildAvatarFromStream(BuildContext context) { return StreamBuilder( stream: _command, initialData: _command!.lastResult, builder: (context, snapshot) => _buildAvatar(context, snapshot.data), ); } @override Widget build(BuildContext context) { return _command == null ? _buildAvatar(context, _avatar) : _buildAvatarFromStream(context); } } ================================================ FILE: lib/views/widgets/circle_avatar_icon.dart ================================================ import 'package:flutter/material.dart'; class CircleAvatarIcon extends StatelessWidget { final Icon icon; final double radius; const CircleAvatarIcon({ required this.icon, this.radius = 13, }); @override Widget build(BuildContext context) { return Stack( alignment: Alignment.center, children: [ CircleAvatar( radius: radius, backgroundColor: Colors.white, ), icon, ], ); } } ================================================ FILE: lib/views/widgets/favorite_icon.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/views/widgets/circle_avatar_icon.dart'; class FavoriteIcon extends StatelessWidget { @override Widget build(BuildContext context) { return const Align( alignment: Alignment.bottomLeft, child: CircleAvatarIcon( icon: Icon( Icons.stars, color: Colors.amber, ), ), ); } } ================================================ FILE: lib/views/widgets/folder_icon.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/views/widgets/favorite_icon.dart'; class FolderIcon extends StatelessWidget { final NcFile dir; final double size; const FolderIcon({super.key, required this.dir, this.size = 48}); @override Widget build(BuildContext context) { Stack stack = Stack(children: [ Icon( Icons.folder, size: size, ), ]); if (dir.favorite) { stack.children.add(FavoriteIcon()); } return SizedBox( height: size, width: size, child: stack, ); } } ================================================ FILE: lib/views/widgets/image_search.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; import 'package:yaga/views/widgets/image_view_container.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; class ImageSearch extends SearchDelegate { final FileListLocalManager _fileListLocalManager; final ViewConfiguration _viewConfig; ImageSearch(this._fileListLocalManager, this._viewConfig); @override ThemeData appBarTheme(BuildContext context) { //todo: keep track of this issue and improve: https://github.com/flutter/flutter/issues/45498 assert(context != null); final ThemeData theme = Theme.of(context); assert(theme != null); return theme.copyWith( inputDecorationTheme: InputDecorationTheme( hintStyle: TextStyle(color: theme.primaryTextTheme.headline5?.color)), textTheme: theme.textTheme.copyWith( headline5: theme.textTheme.headline5 ?.copyWith(color: theme.primaryTextTheme.headline5?.color), headline6: const TextStyle( color: Colors.white, fontWeight: FontWeight.normal, fontSize: 18, ), )); } @override List buildActions(BuildContext context) { return [ IconButton(icon: const Icon(Icons.close), onPressed: () => query = "") ]; } @override Widget buildLeading(BuildContext context) { return IconButton( icon: const Icon(Icons.arrow_back), onPressed: () => Navigator.pop(context)); } @override Widget buildResults(BuildContext context) { return ImageViewContainer( fileListLocalManager: _fileListLocalManager, viewConfig: ViewConfiguration.fromViewConfig( viewConfig: _viewConfig, onFolderTap: (NcFile file) => close(context, file), ), filter: (NcFile file) => file.name.toLowerCase().contains(query.toLowerCase()) || file.lastModified.toString().contains(query), ); } @override Widget buildSuggestions(BuildContext context) { return ListView( //children: [], ); } } ================================================ FILE: lib/views/widgets/image_view_container.dart ================================================ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/preferences/choice_preference.dart'; import 'package:yaga/model/sorted_category_list.dart'; import 'package:yaga/model/sorted_file_folder_list.dart'; import 'package:yaga/model/sorted_file_list.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/widgets/image_views/category_view.dart'; import 'package:yaga/views/widgets/image_views/category_view_exp.dart'; import 'package:yaga/views/widgets/image_views/nc_grid_view.dart'; import 'package:yaga/views/widgets/image_views/nc_list_view.dart'; class ImageViewContainer extends StatelessWidget { final FileListLocalManager fileListLocalManager; final ViewConfiguration viewConfig; final bool Function(NcFile)? _filter; const ImageViewContainer({ required this.fileListLocalManager, required this.viewConfig, bool Function(NcFile)? filter, }) : _filter = filter; Widget _buildImageView(ChoicePreference choice, SortedFileList files) { SortedFileList filteredFiles = files; if (_filter != null) { filteredFiles = files.applyFilter(_filter!); } if (choice.value == NcGridView.viewKey) { return NcGridView(filteredFiles as SortedFileFolderList, viewConfig); } if (choice.value == CategoryView.viewKey) { return CategoryView(filteredFiles as SortedCategoryList, viewConfig); } if (choice.value == NcListView.viewKey) { return NcListView( sorted: filteredFiles as SortedFileFolderList, viewConfig: viewConfig, ); } return CategoryViewExp(filteredFiles as SortedCategoryList, viewConfig); } @override Widget build(BuildContext context) { return Stack(children: [ //todo: generalize stream builder for preferences StreamBuilder( initialData: getIt .get() .loadPreferenceFromString(viewConfig.view), stream: getIt .get() .updateSettingCommand .where((event) => event.key == viewConfig.view.key) .map((event) => event as ChoicePreference), builder: (context, choice) { final bool sortChanged = fileListLocalManager.setSortConfig( ViewConfiguration.getSortConfigFromViewChoice(choice.data!), ); return _buildImageContainterStreamBuilder( context, choice.data!, sortChanged, ); }, ), StreamBuilder( initialData: fileListLocalManager.loadingChangedCommand.lastResult, stream: fileListLocalManager.loadingChangedCommand, builder: (context, snapshot) => snapshot.data! ? const LinearProgressIndicator() : Container(), ) ]); } Widget _buildImageContainterStreamBuilder( BuildContext context, ChoicePreference choice, bool sortChanged, ) { return StreamBuilder( key: ValueKey(fileListLocalManager.sortConfig.sortType), initialData: sortChanged ? fileListLocalManager.emptyFileList : fileListLocalManager.filesChangedCommand.lastResult, stream: fileListLocalManager.filesChangedCommand.where( // this filter makes sure that if viewType is changed while loading we do not run into trouble (event) => event.config.sortType == fileListLocalManager.sortConfig.sortType, ), builder: (context, files) => RefreshIndicator( onRefresh: () async => fileListLocalManager.updateFilesAndFolders(), child: _buildImageView(choice, files.data!), ), ); } } ================================================ FILE: lib/views/widgets/image_views/category_view.dart ================================================ import 'package:flutter/material.dart'; import 'package:flutter_sticky_header/flutter_sticky_header.dart'; import 'package:yaga/model/sorted_category_list.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/views/widgets/image_views/utils/grid_delegate.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/views/widgets/remote_image_widget.dart'; class CategoryView extends StatelessWidget with GridDelegate { final _logger = YagaLogger.getLogger(CategoryView); static const String viewKey = "category"; final ViewConfiguration viewConfig; final SortedCategoryList sorted; CategoryView(this.sorted, this.viewConfig); Widget _buildHeader(String key, BuildContext context) { return Container( height: 30.0, color: Theme.of(context).colorScheme.secondary, padding: const EdgeInsets.symmetric(horizontal: 16.0), alignment: Alignment.centerLeft, child: Text( key, style: const TextStyle(color: Colors.white), ), ); } SliverStickyHeader _buildCategory(String key, BuildContext context) { return SliverStickyHeader( key: ValueKey(key), header: _buildHeader(key, context), sliver: SliverGrid( key: ValueKey("${key}_grid"), delegate: SliverChildBuilderDelegate((BuildContext context, int index) { return _buildImage(key, index, context); }, childCount: sorted.categorizedFiles[key]!.length), gridDelegate: buildImageGridDelegate(context), ), ); } Widget _buildImage(String key, int itemIndex, BuildContext context) { return InkWell( onTap: () => viewConfig.onFileTap?.call(sorted.categorizedFiles[key]!, itemIndex), onLongPress: () => viewConfig.onSelect?.call(sorted.categorizedFiles[key]!, itemIndex), child: RemoteImageWidget( sorted.categorizedFiles[key]![itemIndex], key: ValueKey(sorted.categorizedFiles[key]![itemIndex].uri.path), cacheWidth: 512, ), ); } Widget _buildStickyList(BuildContext context) { final List slivers = []; //todo: the actual issue behind the performance problems is that for many categorise we are keepint all headers in memory at once and also a tone of images //--> it seems the headerSliver is not cleaning up properly //--> long terme we need to find a solution for this! for (final key in sorted.categories) { print("rebuilding list"); slivers.add(_buildCategory(key, context)); } final DefaultStickyHeaderController sticky = DefaultStickyHeaderController( key: const ValueKey("mainGrid"), child: CustomScrollView( key: const ValueKey("mainGridView"), slivers: slivers, physics: const AlwaysScrollableScrollPhysics(), )); return sticky; } @override Widget build(BuildContext context) { _logger.finer("drawing list"); return _buildStickyList(context); } } ================================================ FILE: lib/views/widgets/image_views/category_view_exp.dart ================================================ import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; import 'package:sticky_infinite_list/sticky_infinite_list.dart'; import 'package:yaga/model/sorted_category_list.dart'; import 'package:yaga/utils/logger.dart'; import 'package:yaga/views/widgets/image_views/utils/grid_delegate.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/views/widgets/remote_image_widget.dart'; class CategoryViewExp extends StatelessWidget with GridDelegate { final _logger = YagaLogger.getLogger(CategoryViewExp); static const String viewKey = "category_exp"; final ViewConfiguration viewConfig; final SortedCategoryList sorted; CategoryViewExp(this.sorted, this.viewConfig); Widget _buildHeader(String key, BuildContext context) { return Container( height: 30.0, color: Theme.of(context).colorScheme.secondary, padding: const EdgeInsets.symmetric(horizontal: 16.0), alignment: Alignment.centerLeft, child: Text( key, style: const TextStyle(color: Colors.white), ), ); } Widget _buildImage(String key, int itemIndex, BuildContext context) { return InkWell( onTap: () => viewConfig.onFileTap?.call(sorted.categorizedFiles[key]!, itemIndex), onLongPress: () => viewConfig.onSelect?.call(sorted.categorizedFiles[key]!, itemIndex), child: RemoteImageWidget( sorted.categorizedFiles[key]![itemIndex], key: ValueKey(sorted.categorizedFiles[key]![itemIndex].uri.path), cacheWidth: 512, ), ); } Widget _buildExperimental() { final ScrollController scrollController = ScrollController(); final InfiniteList infiniteList = InfiniteList( posChildCount: sorted.categories.length, controller: scrollController, physics: const AlwaysScrollableScrollPhysics(), builder: (BuildContext context, int indexCategory) { final String key = sorted.categories[indexCategory]; /// Builder requires [InfiniteList] to be returned return InfiniteListItem( /// Header builder headerBuilder: (BuildContext context) { return _buildHeader(key, context); }, /// Content builder contentBuilder: (BuildContext context) { return GridView.builder( key: ValueKey("${key}_grid"), controller: scrollController, shrinkWrap: true, itemCount: sorted.categorizedFiles[key]!.length, gridDelegate: buildImageGridDelegate(context), itemBuilder: (context, itemIndex) { return _buildImage(key, itemIndex, context); }, ); }, ); }, ); return infiniteList; } @override Widget build(BuildContext context) { _logger.finer("drawing list"); return _buildExperimental(); } } ================================================ FILE: lib/views/widgets/image_views/nc_grid_view.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/sorted_file_folder_list.dart'; import 'package:yaga/views/widgets/image_views/utils/grid_delegate.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/views/widgets/remote_folder_widget.dart'; import 'package:yaga/views/widgets/remote_image_widget.dart'; class NcGridView extends StatelessWidget with GridDelegate { static const String viewKey = "grid"; final SortedFileFolderList sorted; final ViewConfiguration viewConfig; const NcGridView(this.sorted, this.viewConfig); Widget _buildImage(int key, BuildContext context) { return InkWell( onTap: () => viewConfig.onFileTap?.call(sorted.files, key), onLongPress: () => viewConfig.onSelect?.call(sorted.files, key), child: RemoteImageWidget( sorted.files[key], key: ValueKey(sorted.files[key].uri.path), cacheWidth: 256, // cacheHeight: 256, ), ); } Widget _buildFolder(int key, BuildContext context) { return Card( borderOnForeground: true, elevation: 2.0, child: Center( child: RemoteFolderWidget(index: key, sorted: sorted, viewConfig: viewConfig,) ), ); } @override Widget build(BuildContext context) { final SliverGrid folderGrid = SliverGrid( delegate: SliverChildBuilderDelegate( (context, index) => _buildFolder(index, context), childCount: sorted.folders.length, ), gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 300.0, crossAxisSpacing: 2, mainAxisSpacing: 2, mainAxisExtent: 70, ), ); final SliverPadding paddedFolders = SliverPadding( padding: const EdgeInsets.all(5), sliver: folderGrid, ); final SliverGrid fileGrid = SliverGrid( gridDelegate: buildImageGridDelegate(context), delegate: SliverChildBuilderDelegate( (context, index) => _buildImage(index, context), childCount: sorted.files.length, ), ); final SliverPadding paddedFiles = SliverPadding( padding: const EdgeInsets.all(5), sliver: fileGrid, ); return CustomScrollView( physics: const AlwaysScrollableScrollPhysics(), slivers: viewConfig.showFolders.value ? [paddedFolders, paddedFiles] : [paddedFiles], ); } } ================================================ FILE: lib/views/widgets/image_views/nc_list_view.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/sorted_file_folder_list.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/views/widgets/remote_folder_widget.dart'; import 'package:yaga/views/widgets/remote_image_widget.dart'; class NcListView extends StatelessWidget { static const String viewKey = "list"; final SortedFileFolderList sorted; final ViewConfiguration viewConfig; const NcListView({ required this.sorted, required this.viewConfig, }); @override Widget build(BuildContext context) { final slivers = []; const Widget divider = Divider( thickness: 2, ); if (viewConfig.showFolders.value) { slivers.add( SliverList.separated( separatorBuilder: (context, index) => divider, itemBuilder: (context, index) => RemoteFolderWidget(sorted: sorted, index: index, viewConfig: viewConfig), itemCount: sorted.folders.length, ), ); } slivers.add( SliverList.list( children: const [ divider, ], ), ); slivers.add( SliverList.separated( separatorBuilder: (context, index) => divider, itemBuilder: (context, index) => ListTile( leading: SizedBox( width: 64, height: 64, child: RemoteImageWidget( sorted.files[index], key: ValueKey(sorted.files[index].uri.path), cacheWidth: 128, showFileEnding: false, ), ), title: Text(sorted.files[index].name), onTap: () => viewConfig.onFileTap?.call(sorted.files, index), onLongPress: () => viewConfig.onSelect?.call(sorted.files, index), ), itemCount: sorted.files.length, ), ); return CustomScrollView( physics: const AlwaysScrollableScrollPhysics(), slivers: slivers, ); } } ================================================ FILE: lib/views/widgets/image_views/utils/grid_delegate.dart ================================================ import 'package:flutter/material.dart'; mixin class GridDelegate { SliverGridDelegate buildImageGridDelegate(BuildContext context) { return const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 175.0, crossAxisSpacing: 2, mainAxisSpacing: 2, ); } } ================================================ FILE: lib/views/widgets/image_views/utils/view_configuration.dart ================================================ import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/model/preferences/choice_preference.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/preferences/section_preference.dart'; import 'package:yaga/model/sort_config.dart'; import 'package:yaga/views/widgets/image_views/category_view.dart'; import 'package:yaga/views/widgets/image_views/category_view_exp.dart'; import 'package:yaga/views/widgets/image_views/nc_grid_view.dart'; import 'package:yaga/views/widgets/image_views/nc_list_view.dart'; class ViewConfiguration { final SectionPreference section; final ChoicePreference view; final BoolPreference recursive; final BoolPreference showFolders; final bool favorites; final String route; //todo: not sure if moving the onTap handler to this objects is a good idea final Function(NcFile)? onFolderTap; final Function(List, int)? onFileTap; final Function(List, int)? onSelect; factory ViewConfiguration({ required String route, required String defaultView, required Function(NcFile)? onFolderTap, required Function(List, int)? onFileTap, required final Function(List, int)? onSelect, required bool favorites, }) { final SectionPreference section = SectionPreference((b) => b ..key = Preference.prefixKey(route, "view") ..title = "View"); final ChoicePreference view = ChoicePreference((b) => b ..key = section.prepareKey("view") ..title = "View Type" ..value = defaultView ..choices = { NcListView.viewKey: "List View", NcGridView.viewKey: "Grid View", CategoryView.viewKey: "Category View", CategoryViewExp.viewKey: "Category View (experimental)" }); final BoolPreference recursive = BoolPreference((b) => b ..key = section.prepareKey("recursive") ..title = "Load Recursively" ..value = false); final BoolPreference showFolders = BoolPreference((b) => b ..key = section.prepareKey("folders") ..title = "Show Folders" ..value = false); return ViewConfiguration._internal( section, view, recursive, showFolders, onFileTap, onFolderTap, onSelect, route, favorites: favorites ); } factory ViewConfiguration.browse({ required String route, required String defaultView, Function(NcFile)? onFolderTap, Function(List, int)? onFileTap, Function(List, int)? onSelect, bool favorites = false, }) { final SectionPreference section = SectionPreference((b) => b ..key = Preference.prefixKey(route, "view") ..title = "View"); final ChoicePreference view = ChoicePreference((b) => b ..key = section.prepareKey("view") ..title = "View Type" ..value = defaultView ..choices = { NcListView.viewKey: "List View", NcGridView.viewKey: "Grid View" }); final BoolPreference recursive = BoolPreference((b) => b ..key = section.prepareKey("recursive") ..title = "Load Recursively" ..value = false); final BoolPreference showFolders = BoolPreference((b) => b ..key = section.prepareKey("folders") ..title = "Show Folders" ..value = true); return ViewConfiguration._internal( section, view, recursive, showFolders, onFileTap, onFolderTap, onSelect, route, favorites: favorites, ); } factory ViewConfiguration.fromViewConfig({ required ViewConfiguration viewConfig, Function(NcFile)? onFolderTap, Function(List, int)? onFileTap, Function(List, int)? onSelect, bool? favorites, }) { return ViewConfiguration._internal( viewConfig.section, viewConfig.view, viewConfig.recursive, viewConfig.showFolders, onFileTap ?? viewConfig.onFileTap, onFolderTap ?? viewConfig.onFolderTap, onSelect ?? viewConfig.onSelect, viewConfig.route, favorites: favorites ?? viewConfig.favorites, ); } static SortConfig getSortConfigFromViewChoice(ChoicePreference pref) { if (pref.value == CategoryView.viewKey || pref.value == CategoryViewExp.viewKey) { return const SortConfig( SortType.category, SortProperty.dateModified, SortProperty.name, ); } if (pref.value == NcGridView.viewKey) { return const SortConfig( SortType.list, SortProperty.dateModified, SortProperty.name, ); } return const SortConfig( SortType.list, SortProperty.name, SortProperty.name, ); } ViewConfiguration._internal(this.section, this.view, this.recursive, this.showFolders, this.onFileTap, this.onFolderTap, this.onSelect, this.route, {this.favorites = false}); ViewConfiguration clone() { return ViewConfiguration._internal(section, view, recursive, showFolders, onFileTap, onFolderTap, onSelect, route, favorites: favorites); } } ================================================ FILE: lib/views/widgets/list_menu_entry.dart ================================================ import 'package:flutter/material.dart'; class ListMenuEntry extends StatelessWidget { final IconData _iconData; final String _text; const ListMenuEntry(this._iconData, this._text); @override Widget build(BuildContext context) { return ListTile( leading: Icon(_iconData), title: Text(_text), // isThreeLine: false, contentPadding: const EdgeInsets.all(0), ); } } ================================================ FILE: lib/views/widgets/path_widget.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/services/name_exchange_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/utils/uri_utils.dart'; import 'package:yaga/views/widgets/avatar_widget.dart'; class PathWidget extends StatelessWidget { final Uri _uri; final Function(Uri) _onTap; final bool fixedOrigin; final String schemeFilter; const PathWidget( this._uri, this._onTap, { this.fixedOrigin = false, this.schemeFilter = "", }); @override Widget build(BuildContext context) { return ButtonTheme( minWidth: 20, padding: const EdgeInsets.symmetric(horizontal: 2), child: ListView.separated( shrinkWrap: true, padding: const EdgeInsets.symmetric(horizontal: 20), scrollDirection: Axis.horizontal, itemCount: _uri.pathSegments.isEmpty ? 1 : _uri.pathSegments.length, itemBuilder: (context, index) { if (index == 0) { final Uri selected = getRootFromUri(_uri); if (fixedOrigin) { return _getDisabledAvatar(selected); } List> items = []; final SystemLocationService systemLocationService = getIt.get(); items.add(_getMenuItem( systemLocationService.internalStorage.origin, )); getIt.get().externals.forEach((element) { items.add(_getMenuItem( element.origin, )); }); if (getIt.get().isLoggedIn()) { items.add( _getMenuItem( getIt.get().origin!.userEncodedDomainRoot, ), ); } if (schemeFilter.isNotEmpty) { items = items .where((element) => element.value!.scheme == schemeFilter) .toList(); } return DropdownButtonHideUnderline( child: DropdownButton( value: selected, onChanged: (Uri? value) => _onTap(value!), items: items, ), ); } final Uri subUri = fromUriPathSegments(_uri, index - 1); final Uri readableUri = getIt.get().convertUriToHumanReadableUri(subUri); return TextButton( style: TextButton.styleFrom( primary: Colors.white, ), onPressed: () => _onTap(subUri), child: Text(getNameFromUri(readableUri)), ); }, separatorBuilder: (context, index) => const Icon(Icons.keyboard_arrow_right, color: Colors.white), ), ); } DropdownMenuItem _getMenuItem(Uri origin) { return DropdownMenuItem( value: origin, child: _getAvatarForOrigin(origin), ); } Widget _getDisabledAvatar(Uri origin) { return InkWell( onTap: () => _onTap(origin), child: _getAvatarForOrigin(origin), ); } Widget _getAvatarForOrigin(Uri origin) { if (getIt.get().internalStorage.origin == origin) { return const AvatarWidget.phone(); } if (origin.scheme == getIt.get().scheme) { return AvatarWidget.command( getIt.get().updateAvatarCommand, ); } return const AvatarWidget.sd(); } } ================================================ FILE: lib/views/widgets/preferences/action_preference_widget.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/preferences/action_preference.dart'; class ActionPreferenceWidget extends StatelessWidget { final ActionPreference _pref; const ActionPreferenceWidget(this._pref); @override Widget build(BuildContext context) { return ListTile( title: Text( _pref.title!, ), onTap: _pref.action, enabled: _pref.enabled!, ); } } ================================================ FILE: lib/views/widgets/preferences/bool_preference_widget.dart ================================================ import 'package:flutter/material.dart'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/widgets/preferences/preference_list_tile_widget.dart'; class BoolPreferenceWidget extends StatelessWidget { final BoolPreference _defaultPreference; final RxCommand? onChangeCommand; const BoolPreferenceWidget(this._defaultPreference, {this.onChangeCommand}); //todo: generalize this for all preferences void _notifyChange(BoolPreference pref) { if (onChangeCommand != null) { onChangeCommand!(pref); return; } getIt.get().persistBoolSettingCommand(pref); } @override Widget build(BuildContext context) { return PreferenceListTileWidget( initData: getIt .get() .loadPreferenceFromBool(_defaultPreference), listTileBuilder: (context, pref) => SwitchListTile( title: Text(pref.title!), value: pref.value, onChanged: pref.enabled! ? (value) => _notifyChange(pref.rebuild((b) => b..value = value)) : null, ), ); } } ================================================ FILE: lib/views/widgets/preferences/choice_preference_widget.dart ================================================ import 'package:flutter/material.dart'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/preferences/choice_preference.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/route_args/choice_selector_screen_arguments.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/choice_selector_screen.dart'; import 'package:yaga/views/widgets/preferences/preference_list_tile_widget.dart'; class ChoicePreferenceWidget extends StatelessWidget { final ChoicePreference _choicePreference; final RxCommand? onChangeCommand; const ChoicePreferenceWidget(this._choicePreference, this.onChangeCommand); //todo: generalize this for all preferences void _notifyChange(ChoicePreference pref) { if (onChangeCommand != null) { onChangeCommand!(pref); return; } getIt.get().persistStringSettingCommand(pref); } @override Widget build(BuildContext context) { return PreferenceListTileWidget( initData: getIt .get() .loadPreferenceFromString(_choicePreference), listTileBuilder: (context, pref) => ListTile( title: Text(pref.title!), subtitle: Text(pref.choices[pref.value]!), onTap: () => Navigator.pushNamed( context, ChoiceSelectorScreen.route, arguments: ChoiceSelectorScreenArguments(pref, (String value) { Navigator.pop(context); _notifyChange(pref.rebuild((b) => b..value = value)); }, () => Navigator.pop(context))), )); } } ================================================ FILE: lib/views/widgets/preferences/int_preference_widget.dart ================================================ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/preferences/int_preference.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/widgets/preferences/preference_list_tile_widget.dart'; class IntPreferenceWidget extends StatefulWidget { final IntPreference _defaultPreference; final RxCommand? _onChangeCommand; const IntPreferenceWidget(this._defaultPreference, this._onChangeCommand); @override State createState() => _IntPreferenceWidgetState(); } class _IntPreferenceWidgetState extends State { GlobalKey _formKey = GlobalKey(); //todo: generalize this for all preferences void _notifyChange(IntPreference pref) { if (widget._onChangeCommand != null) { widget._onChangeCommand!(pref); return; } getIt.get().persistIntSettingCommand(pref); } bool _validate(String interval) { return (int.tryParse(interval) ?? 0) > 0; } @override Widget build(BuildContext context) { return PreferenceListTileWidget( initData: getIt .get() .loadPreferenceFromInt(widget._defaultPreference), listTileBuilder: (context, pref) => ListTile( title: Text(pref.title!), subtitle: Text(pref.value.toString()), onTap: () => showDialog( context: context, builder: (context) => AlertDialog( title: Text(pref.title!), content: Form( key: _formKey, autovalidateMode: AutovalidateMode.onUserInteraction, child: TextFormField( keyboardType: TextInputType.number, initialValue: pref.value.toString(), onSaved: (newValue) => _notifyChange( pref.rebuild( (b) => b..value = int.parse(newValue!), ), ), inputFormatters: [ FilteringTextInputFormatter.digitsOnly ], validator: (v) => _validate(v ?? "") ? null : "Number has to be bigger than 0.", ), ), actions: [ TextButton( onPressed: () { if(_formKey.currentState?.validate()??false) { _formKey.currentState?.save(); Navigator.pop(context); } }, child: Text("Ok"), ), TextButton( onPressed: () { Navigator.pop(context); }, child: Text("Cancel"), ), ], ), ), ), ); } } ================================================ FILE: lib/views/widgets/preferences/mapping_preference_widget.dart ================================================ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/preferences/bool_preference.dart'; import 'package:yaga/model/preferences/mapping_preference.dart'; import 'package:yaga/model/preferences/uri_preference.dart'; import 'package:yaga/model/route_args/settings_screen_arguments.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/settings_screen.dart'; import 'package:yaga/views/widgets/action_danger_dialog.dart'; import 'package:yaga/views/widgets/preferences/preference_list_tile_widget.dart'; class MappingPreferenceWidget extends StatefulWidget { final MappingPreference pref; final String route; const MappingPreferenceWidget(this.pref, this.route); @override State createState() => _MappingPreferenceState(); } class _MappingPreferenceState extends State { late SystemLocationService _systemLocationService; late UriPreference _remote; late UriPreference _local; late BoolPreference _syncDeletes; @override void initState() { _systemLocationService = getIt.get(); final _settingsManager = getIt.get(); final prefService = getIt.get(); _remote = prefService.loadPreferenceFromString(widget.pref.remote); _local = prefService.loadPreferenceFromString(widget.pref.local); _syncDeletes = prefService.loadPreferenceFromBool( widget.pref.syncDeletes, ); _settingsManager.updateSettingCommand .where( (event) => event.key == widget.pref.remote.key || event.key == widget.pref.local.key || event.key == widget.pref.syncDeletes.key, ) .listen((pref) { if (pref.key == _remote.key) { _remote = pref as UriPreference; } if (pref.key == _local.key) { _local = pref as UriPreference; _settingsManager.updateSettingCommand( _syncDeletes.rebuild((b) => b..value = false), ); } if (pref.key == _syncDeletes.key) { _syncDeletes = pref as BoolPreference; } }); super.initState(); } @override Widget build(BuildContext context) { return PreferenceListTileWidget( initData: widget.pref, listTileBuilder: (context, pref) => ListTile( enabled: pref.enabled!, title: Text(pref.title!), onTap: () => Navigator.pushNamed( context, SettingsScreen.route, arguments: SettingsScreenArguments( onSettingChangedCommand: getIt.get().updateSettingCommand, preferences: [pref.remote, pref.local, pref.syncDeletes], onCancel: () => Navigator.pop(context), //todo: onCommit should return a list of all preferences then we do not need to listen here to the UriPref changes onCommit: () => _checkDirectory(context, pref), ), ), ), ); } void _checkDirectory(BuildContext context, MappingPreference pref) { if (_syncDeletes.value && Directory(_systemLocationService .absoluteUriFromInternal(_local.value) .path) .listSync() .isNotEmpty) { showDialog( context: context, builder: (context) => ActionDangerDialog( title: "Danger of losing data", cancelButton: "Cancel", aggressiveAction: "Continue", action: (agg) { Navigator.pop(context); if (agg) { _persist(context, pref); } }, bodyBuilder: (context) => [ const Text( 'The choosen local directory is not empty. Any files which do not exist on the Nextcloud side of the mapping will be erased from your phone!', ), ], ), ); } else { _persist(context, pref); } } void _persist(BuildContext context, MappingPreference pref) { Navigator.pop(context); getIt.get().persistMappingPreferenceCommand( pref.rebuild( (b) => b ..local = _local.toBuilder() ..remote = _remote.toBuilder() ..syncDeletes = _syncDeletes.toBuilder(), ), ); } } ================================================ FILE: lib/views/widgets/preferences/preference_list_tile_widget.dart ================================================ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/utils/service_locator.dart'; class PreferenceListTileWidget extends StatelessWidget { final T initData; final Widget Function(BuildContext, T) listTileBuilder; const PreferenceListTileWidget({ required this.initData, required this.listTileBuilder, }); @override Widget build(BuildContext context) { return StreamBuilder( stream: getIt .get() .updateSettingCommand .where((event) => event.key == initData.key) .map((event) => event as T), initialData: initData, builder: (BuildContext context, AsyncSnapshot snapshot) { return listTileBuilder(context, snapshot.data!); }, ); } } ================================================ FILE: lib/views/widgets/preferences/section_preference_widget.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/preferences/preference.dart'; class SectionPreferenceWidget extends StatelessWidget { final Preference _pref; const SectionPreferenceWidget(this._pref); @override Widget build(BuildContext context) { return ListTile( title: Text( _pref.title!, style: TextStyle( color: Theme.of(context).colorScheme.secondary, fontWeight: FontWeight.bold), ), ); } } ================================================ FILE: lib/views/widgets/preferences/string_preference_widget.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/model/preferences/string_preference.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/widgets/preferences/preference_list_tile_widget.dart'; class StringPreferenceWidget extends StatelessWidget { final StringPreference _defaultPreference; final Function(StringPreference) _onTap; const StringPreferenceWidget(this._defaultPreference, this._onTap); @override Widget build(BuildContext context) { return PreferenceListTileWidget( initData: getIt .get() .loadPreferenceFromString(_defaultPreference), listTileBuilder: (context, pref) => ListTile( title: Text(pref.title!), subtitle: Text(pref.value), onTap: () => _onTap(pref), )); } } ================================================ FILE: lib/views/widgets/preferences/uri_preference_widget.dart ================================================ import 'package:flutter/material.dart'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/settings_manager.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/preferences/uri_preference.dart'; import 'package:yaga/model/route_args/path_selector_screen_arguments.dart'; import 'package:yaga/services/name_exchange_service.dart'; import 'package:yaga/services/shared_preferences_service.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/path_selector_screen.dart'; import 'package:yaga/views/widgets/preferences/preference_list_tile_widget.dart'; class UriPreferenceWidget extends StatelessWidget { final UriPreference _defaultPref; final RxCommand? onChangeCommand; const UriPreferenceWidget(this._defaultPref, {this.onChangeCommand}); void _notifyChange(UriPreference pref) { if (onChangeCommand != null) { onChangeCommand!(pref); return; } getIt.get().persistStringSettingCommand(pref); } void _pushToNavigation(BuildContext context, UriPreference pref, Uri uri) { Navigator.pushNamed( context, PathSelectorScreen.route, arguments: PathSelectorScreenArguments( uri: uri, onSelect: (Uri path) => _notifyChange( pref.rebuild((b) => b..value = path), ), fixedOrigin: pref.fixedOrigin, schemeFilter: pref.schemeFilter, ), ); } @override Widget build(BuildContext context) { return PreferenceListTileWidget( initData: getIt .get() .loadPreferenceFromString(_defaultPref), listTileBuilder: (context, pref) => ListTile( enabled: pref.enabled!, title: Text(pref.title!), subtitle: Text(Uri.decodeComponent(getIt.get().convertUriToHumanReadableUri(pref.value).toString())), onTap: () => _pushToNavigation(context, pref, pref.value), ), ); } } ================================================ FILE: lib/views/widgets/remote_folder_widget.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/file_manager/file_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/model/sorted_file_folder_list.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/widgets/folder_icon.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; class RemoteFolderWidget extends StatelessWidget { final SortedFileFolderList sorted; final int index; final ViewConfiguration viewConfig; const RemoteFolderWidget({super.key, required this.sorted, required this.index, required this.viewConfig}); @override Widget build(BuildContext context) { final folder = sorted.folders[index]; return StreamBuilder(stream: getIt.get().updateImageCommand .where((event) => event.uri.path == folder.uri.path), initialData: folder, builder: (context, snapshot) => ListTile( onLongPress: () => viewConfig.onSelect?.call(sorted.folders, index), onTap: () => viewConfig.onFolderTap?.call(snapshot.data!), leading: FolderIcon(dir: snapshot.data!), trailing: snapshot.data!.selected ? const Icon(Icons.check_circle) : null, title: Text( folder.name, ), ), ); } } ================================================ FILE: lib/views/widgets/remote_image_widget.dart ================================================ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:rxdart/rxdart.dart'; import 'package:yaga/managers/file_manager/file_manager.dart'; import 'package:yaga/managers/file_service_manager/isolateable/nextcloud_file_manger.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/utils/forground_worker/bridges/nextcloud_manager_bridge.dart'; import 'package:yaga/utils/nextcloud_colors.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/widgets/circle_avatar_icon.dart'; import 'package:yaga/views/widgets/favorite_icon.dart'; class RemoteImageWidget extends StatelessWidget { final NcFile _file; final int cacheWidth; final int? cacheHeight; final bool showFileEnding; const RemoteImageWidget( this._file, { Key? key, required this.cacheWidth, this.cacheHeight, this.showFileEnding = true, }) : super(key: key); Widget _createIconOverlay(BuildContext context, Ink mainWidget) { final List children = [ mainWidget, Align( alignment: Alignment.bottomRight, child: CircleAvatarIcon(icon: _getLocalIcon(context)), ), ]; if (_file.favorite) { children.add(FavoriteIcon()); } if (_file.selected) { children.add(const Align( alignment: Alignment.center, child: CircleAvatarIcon( icon: Icon( Icons.check, color: NextcloudColors.lightBlue, ), radius: 20, ), )); } return Stack( fit: StackFit.expand, children: children, ); } Ink _inkFromImage(FileSystemEntity file) => Ink.image( image: ResizeImage.resizeIfNeeded( cacheWidth, cacheHeight, FileImage(file as File), ), fit: BoxFit.cover, ); Icon _getLocalIcon(BuildContext context) { if (getIt.get().isUriOfService(_file.uri)) { if (_file.localFile!.exists) { return const Icon( Icons.check_circle, color: Colors.green, ); } return Icon( Icons.cloud_circle, color: Theme.of(context).colorScheme.secondary, ); } return const Icon( Icons.phone_android, color: Colors.black, ); } @override Widget build(BuildContext context) { return StreamBuilder( stream: Rx.merge([ getIt .get() .updatePreviewCommand .where((event) => event.uri.path == _file.uri.path) //here we are backpropagating the existing flag to the local file list //this is okay since we do not need to do any imediate action upon this change just have the value in case of resorting .doOnData( (event) => _file.previewFile = event.previewFile, ), getIt .get() .updateImageCommand .where((event) => event.uri.path == _file.uri.path) //here we are backpropagating the existing flag to the local file list //this is okay since we do not need to do any imediate action upon this change just have the value in case of resorting .doOnData( (event) => _file.localFile = event.localFile, ) ]), initialData: _file, builder: (context, snapshot) { if(_file.favorite != snapshot.data!.favorite) { _file.favorite = snapshot.data!.favorite; } if (_file.previewFile != null && _file.previewFile!.exists) { return _createIconOverlay( context, _inkFromImage(snapshot.data!.previewFile!.file), ); } _requestPreviewDownload(); if (_file.localFile != null && _file.localFile!.exists) { return _createIconOverlay( context, _inkFromImage(snapshot.data!.localFile!.file), ); } return _createDefaultIconPreview(context); }, ); } Widget _createDefaultIconPreview(BuildContext context) { final children = [ SvgPicture.asset( "assets/icon/foreground_no_border.svg", semanticsLabel: 'Yaga Logo', // alignment: Alignment.center, width: 48, ), ]; if (showFileEnding) { children.add(Text(_file.fileExtension)); } return _createIconOverlay( context, Ink( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: children, ), ), ); } void _requestPreviewDownload() { if (getIt.get().isUriOfService(_file.uri)) { getIt.get().downloadPreviewCommand(_file); } } } ================================================ FILE: lib/views/widgets/search_icon_button.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/views/widgets/image_search.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; class SearchIconButton extends StatelessWidget { final FileListLocalManager fileListLocalManager; final ViewConfiguration viewConfig; final Function(NcFile?)? searchResultHandler; const SearchIconButton({ required this.fileListLocalManager, required this.viewConfig, this.searchResultHandler, }); @override Widget build(BuildContext context) { return IconButton( icon: const Icon(Icons.search), onPressed: () async { final NcFile? file = await showSearch( context: context, delegate: ImageSearch(fileListLocalManager, viewConfig), ); searchResultHandler?.call(file); }, ); } } ================================================ FILE: lib/views/widgets/select_cancel_bottom_navigation.dart ================================================ import 'package:flutter/material.dart'; class SelectCancelBottomNavigation extends StatelessWidget { final Function onCommit; final Function onCancel; final String labelSelect; final String labelCancel; final IconData iconSelect; final List betweenItems; final List betweenItemsCallbacks; const SelectCancelBottomNavigation({ required this.onCommit, required this.onCancel, this.labelSelect = "Select", this.labelCancel = "Cancel", this.iconSelect = Icons.check, this.betweenItems = const [], this.betweenItemsCallbacks = const [], }); @override Widget build(BuildContext context) { final List items = []; items.add(BottomNavigationBarItem( icon: const Icon(Icons.close), label: labelCancel, )); items.addAll(betweenItems); items.add(BottomNavigationBarItem( icon: Icon(iconSelect), label: labelSelect, )); return BottomNavigationBar( currentIndex: items.length - 1, onTap: (index) { if (index == items.length - 1) { onCommit(); return; } if (index == 0) { onCancel(); return; } final betweenItemsIndex = index - 1; if (betweenItemsIndex >= 0) { betweenItemsCallbacks[betweenItemsIndex].call(); return; } }, items: items, ); } } ================================================ FILE: lib/views/widgets/selection_action_cancel_dialog.dart ================================================ import 'package:flutter/material.dart'; class SelectionActionCancelDialog extends StatelessWidget { final String title; final Function() cancelAction; const SelectionActionCancelDialog(this.title, this.cancelAction); @override Widget build(BuildContext context) { return AlertDialog( title: Text(title), content: const SingleChildScrollView( child: Center( child: CircularProgressIndicator(), ), ), actions: [ TextButton( onPressed: () => cancelAction(), child: const Text('Cancel'), ), ], ); } } ================================================ FILE: lib/views/widgets/selection_app_bar.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; import 'package:yaga/model/nc_file.dart'; import 'package:yaga/views/widgets/image_views/utils/view_configuration.dart'; import 'package:yaga/views/widgets/search_icon_button.dart'; import 'package:yaga/views/widgets/selection_popup_menu_button.dart'; import 'package:yaga/views/widgets/selection_select_all.dart'; class SelectionAppBar extends PreferredSize { factory SelectionAppBar({ required FileListLocalManager fileListLocalManager, required ViewConfiguration viewConfig, required Widget Function(BuildContext, List) appBarBuilder, double bottomHeight = 0, Function(NcFile?)? searchResultHandler, }) { final Widget child = StreamBuilder( initialData: fileListLocalManager.selectionModeChanged.lastResult, stream: fileListLocalManager.selectionModeChanged, builder: (context, snapshot) { final List actions = []; if (fileListLocalManager.isInSelectionMode) { actions.add(SelectionSelectAll(fileListLocalManager)); } actions.add(SearchIconButton( fileListLocalManager: fileListLocalManager, viewConfig: viewConfig, searchResultHandler: searchResultHandler, )); if (fileListLocalManager.isInSelectionMode) { actions.add(SelectionPopupMenuButton( fileListLocalManager: fileListLocalManager, )); } return appBarBuilder(context, actions); }, ); return SelectionAppBar._internal( preferredSize: Size.fromHeight(kToolbarHeight + bottomHeight), child: child, ); } const SelectionAppBar._internal({ required Size preferredSize, required Widget child, }) : super(preferredSize: preferredSize, child: child); } ================================================ FILE: lib/views/widgets/selection_popup_menu_button.dart ================================================ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:share_plus/share_plus.dart'; import 'package:yaga/managers/file_manager/file_manager.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; import 'package:yaga/model/route_args/path_selector_screen_arguments.dart'; import 'package:yaga/utils/forground_worker/messages/download_file_request.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/path_selector_screen.dart'; import 'package:yaga/views/widgets/action_danger_dialog.dart'; import 'package:yaga/views/widgets/list_menu_entry.dart'; import 'package:yaga/views/widgets/selection_action_cancel_dialog.dart'; import 'package:yaga/views/widgets/yaga_popup_menu_button.dart'; enum SelectionViewMenu { share, delete, copy, move, download, favorite } class SelectionPopupMenuButton extends StatelessWidget { final FileListLocalManager fileListLocalManager; const SelectionPopupMenuButton({required this.fileListLocalManager}); @override Widget build(BuildContext context) { return YagaPopupMenuButton( _buildSelectionPopupMenu, _popupMenuHandler, ); } List> _buildSelectionPopupMenu(BuildContext context) { final hasSelectedFolders = fileListLocalManager.hasSelectedFolders; final entries = _buildAndroidSpecificItems(hasSelectedFolders); if (fileListLocalManager.isRemoteUri) { if (!hasSelectedFolders) { entries.addAll( [ const PopupMenuItem(value: SelectionViewMenu.delete, child: ListMenuEntry(Icons.delete, "Delete")), const PopupMenuItem(value: SelectionViewMenu.copy, child: ListMenuEntry(Icons.copy, "Copy")), const PopupMenuItem(value: SelectionViewMenu.move, child: ListMenuEntry(Icons.forward, "Move")), const PopupMenuItem( value: SelectionViewMenu.download, child: ListMenuEntry(Icons.file_download, "Download"), ), ], ); } return entries ..addAll([ const PopupMenuItem(value: SelectionViewMenu.favorite, child: ListMenuEntry(Icons.star, "Favorite")), ]); } // do not allow folder delete on local storage for now if (hasSelectedFolders) { return entries; } return entries ..addAll([ const PopupMenuItem( value: SelectionViewMenu.delete, child: ListMenuEntry(Icons.delete, "Delete"), ), ]); } List> _buildAndroidSpecificItems(bool hasSelectedFolders) { if (!Platform.isAndroid || hasSelectedFolders) { return []; } return [ const PopupMenuItem( value: SelectionViewMenu.share, child: ListMenuEntry(Icons.share, "Share"), ), ]; } void _popupMenuHandler(BuildContext context, SelectionViewMenu result) { if (result == SelectionViewMenu.share) { if (fileListLocalManager.selected.where((element) => !element.localFile!.exists).toList().isNotEmpty) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text( "Currently sharing supports only already downloaded files.", ), behavior: SnackBarBehavior.floating, ), ); return; } Share.shareFiles(fileListLocalManager.selected.map((e) => e.localFile!.file.path).toList()); return; } //todo: background: check behavior if dialog gets closed while background action still running if (result == SelectionViewMenu.delete) { showDialog( context: context, useRootNavigator: false, builder: (contextDialog) => fileListLocalManager.isRemoteUri ? ActionDangerDialog( title: "Delete location", cancelButton: 'Keep', normalAction: 'Delete locally', aggressiveAction: 'Delete remotely', action: (agg) => _openDeletingDialog(context, agg), bodyBuilder: (builderContext) => [ const Text( "If you delete your images locally, they will be deleted from your phone only.", ), const Text( "If you delete them remotely they will be deleted from your phone and server.", ), ], ) : ActionDangerDialog( title: "Delete", cancelButton: 'Keep', aggressiveAction: 'Delete', action: (agg) => _openDeletingDialog(context, false), bodyBuilder: (builderContext) => [ const Text( "This images seem to be local to your phone. Do you really want to delete them?", ), ], ), ); } if (result == SelectionViewMenu.copy || result == SelectionViewMenu.move) { Navigator.pushNamed( context, PathSelectorScreen.route, arguments: PathSelectorScreenArguments( uri: fileListLocalManager.uri, fixedOrigin: true, onSelect: (uri) => showDialog( context: context, useRootNavigator: false, builder: (contextDialog) => ActionDangerDialog( title: "Overwrite Existing", cancelButton: 'Cancel', normalAction: 'Skip existing', aggressiveAction: 'Overwrite existing', action: (agg) => _openCancelableDialog( context, result == SelectionViewMenu.copy ? "Copying..." : "Moving...", result == SelectionViewMenu.copy ? () => fileListLocalManager.copySelected(uri, overwrite: agg) : () => fileListLocalManager.moveSelected(uri, overwrite: agg), ), bodyBuilder: (builderContext) => [ const Text( "Do you want to overwrite existing files, if any?", ), ], ), ), ), ); } if (result == SelectionViewMenu.download) { for (final file in fileListLocalManager.selected) { getIt.get().downloadImageCommand( DownloadFileRequest(file, forceDownload: true), ); } fileListLocalManager.deselectAll(); } if (result == SelectionViewMenu.favorite) { fileListLocalManager.favoriteSelected(); fileListLocalManager.deselectAll(); } } void _openDeletingDialog(BuildContext context, bool aggressive) => _openCancelableDialog( context, "Deleting...", () => fileListLocalManager.deleteSelected(local: !aggressive), ); void _openCancelableDialog( BuildContext context, String text, Future Function() actionCallback, ) { bool dialogOpen = true; showDialog( context: context, useRootNavigator: false, builder: (context) => SelectionActionCancelDialog( text, fileListLocalManager.cancelSelectionAction, ), ).whenComplete(() => dialogOpen = false); actionCallback().whenComplete(() { if (dialogOpen) { Navigator.pop(context); } }); } } ================================================ FILE: lib/views/widgets/selection_select_all.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; class SelectionSelectAll extends StatelessWidget { final FileListLocalManager _fileListLocalManager; const SelectionSelectAll(this._fileListLocalManager); @override Widget build(BuildContext context) { return IconButton( icon: const Icon(Icons.select_all), onPressed: _fileListLocalManager.toggleSelect, ); } } ================================================ FILE: lib/views/widgets/selection_title.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; class SelectionTitle extends StatelessWidget { final FileListLocalManager _fileListLocalManager; final Widget? defaultTitel; const SelectionTitle(this._fileListLocalManager, {this.defaultTitel}); @override Widget build(BuildContext context) { return StreamBuilder( stream: _fileListLocalManager.selectionChangedCommand, builder: (context, snapshot) { if (defaultTitel != null && !_fileListLocalManager.isInSelectionMode) { return defaultTitel!; } return Text( "${_fileListLocalManager.selected.length}/${_fileListLocalManager.sorted.length}", overflow: TextOverflow.fade, ); }, ); } } ================================================ FILE: lib/views/widgets/selection_will_pop_scope.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/widget_local/file_list_local_manager.dart'; class SelectionWillPopScope extends StatelessWidget { final Widget child; final FileListLocalManager fileListLocalManager; const SelectionWillPopScope({ required this.child, required this.fileListLocalManager, }); @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { if (fileListLocalManager.selectionModeChanged.lastResult!) { fileListLocalManager.deselectAll(); return false; } return true; }, child: child, ); } } ================================================ FILE: lib/views/widgets/yaga_about_dialog.dart ================================================ import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_svg/svg.dart'; import 'package:markdown/markdown.dart' as mk; import 'package:package_info_plus/package_info_plus.dart'; import 'package:url_launcher/url_launcher_string.dart'; import 'package:yaga/utils/service_locator.dart'; class YagaAboutDialog extends StatelessWidget { @override Widget build(BuildContext context) { return AboutDialog( applicationVersion: "v${getIt.get().version}", applicationIcon: SvgPicture.asset( "assets/icon/icon.svg", semanticsLabel: 'Yaga Logo', width: 56, ), children: [ FutureBuilder( future: DefaultAssetBundle.of(context).loadString("assets/news.md"), builder: (context, snapshot) { final sc = ScrollController(); return SizedBox( height: 300, width: 400, child: Scrollbar( thumbVisibility: true, controller: sc, child: Markdown( padding: const EdgeInsets.fromLTRB(0.0, 0.0, 5.0, 0.0), data: snapshot.data?.toString() ?? "", shrinkWrap: true, controller: sc, extensionSet: mk.ExtensionSet( mk.ExtensionSet.gitHubFlavored.blockSyntaxes, [ mk.EmojiSyntax(), ...mk.ExtensionSet.gitHubFlavored.inlineSyntaxes ], ), ), ), ); }, ), Align( alignment: Alignment.topLeft, child: TextButton.icon( onPressed: () => launchUrlString("https://vauvenal5.github.io/yaga-docs/"), icon: const Icon(Icons.book_outlined), label: const Text("Read the docs"), ), ), Align( alignment: Alignment.topLeft, child: TextButton.icon( onPressed: () => launchUrlString( "https://vauvenal5.github.io/yaga-docs/privacy/", ), icon: const Icon(Icons.policy_outlined), label: const Text("Privacy Policy"), ), ), Align( alignment: Alignment.topLeft, child: TextButton.icon( onPressed: () => launchUrlString("https://github.com/vauvenal5/yaga/issues"), icon: const Icon(Icons.bug_report_outlined), label: const Text("Report a bug"), ), ), ], ); } } ================================================ FILE: lib/views/widgets/yaga_bottom_nav_bar.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/tab_manager.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/yaga_home_screen.dart'; class YagaBottomNavBar extends StatelessWidget { final YagaHomeTab _selectedTab; const YagaBottomNavBar(this._selectedTab); @override Widget build(BuildContext context) { return BottomNavigationBar( currentIndex: _getCurrentIndex(), onTap: (index) { switch (index) { case 2: getIt.get().tabChangedCommand(YagaHomeTab.folder); return; case 1: getIt.get().tabChangedCommand(YagaHomeTab.favorites); return; default: getIt.get().tabChangedCommand(YagaHomeTab.grid); } }, items: const [ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.star), label: 'Favorites', ), BottomNavigationBarItem( icon: Icon(Icons.folder), label: 'Browse', ), ], ); } int _getCurrentIndex() { switch (_selectedTab) { case YagaHomeTab.folder: return 2; case YagaHomeTab.favorites: return 1; default: return 0; } } } ================================================ FILE: lib/views/widgets/yaga_drawer.dart ================================================ import 'package:flutter/material.dart'; import 'package:yaga/managers/global_settings_manager.dart'; import 'package:yaga/managers/nextcloud_manager.dart'; import 'package:yaga/model/nc_login_data.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/route_args/settings_screen_arguments.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/utils/nextcloud_colors.dart'; import 'package:yaga/utils/service_locator.dart'; import 'package:yaga/views/screens/nc_address_screen.dart'; import 'package:yaga/views/screens/settings_screen.dart'; import 'package:yaga/views/widgets/action_danger_dialog.dart'; import 'package:yaga/views/widgets/avatar_widget.dart'; import 'package:yaga/views/widgets/yaga_about_dialog.dart'; class YagaDrawer extends StatelessWidget { @override Widget build(BuildContext context) { return Drawer( child: ListView( children: [ DrawerHeader( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topRight, end: Alignment.bottomLeft, colors: [ NextcloudColors.lightBlue, NextcloudColors.darkBlue, ], ), ), child: StreamBuilder( stream: getIt.get().updateLoginStateCommand, initialData: getIt .get() .updateLoginStateCommand .lastResult, builder: (context, snapshot) { final ncService = getIt.get(); return Align( alignment: Alignment.centerLeft, child: ListTile( leading: AvatarWidget.command( getIt.get().updateAvatarCommand, radius: 25, ), title: Text( ncService.isLoggedIn() ? ncService.origin!.displayName : "", style: const TextStyle(color: Colors.white), ), subtitle: Text( ncService.isLoggedIn() ? ncService.origin!.domain : "", style: const TextStyle(color: Colors.white), ), ), ); }, ), ), StreamBuilder>( initialData: getIt .get() .updateGlobalSettingsCommand .lastResult, stream: getIt.get().updateGlobalSettingsCommand, builder: (context, snapshot) => ListTile( leading: const Icon(Icons.settings_outlined), title: const Text("Global Settings"), onTap: () => Navigator.pushNamed( context, SettingsScreen.route, arguments: SettingsScreenArguments(preferences: snapshot.data!), ), ), ), StreamBuilder( stream: getIt.get().updateLoginStateCommand, initialData: getIt .get() .updateLoginStateCommand .lastResult, builder: (context, snapshot) { if (getIt.get().isLoggedIn()) { return ListTile( leading: const Icon(Icons.power_settings_new), title: const Text("Logout"), onTap: () => _logout(context), ); } return ListTile( leading: const Icon(Icons.add_to_home_screen), title: const Text("Login"), onTap: () => Navigator.pushNamed( context, NextCloudAddressScreen.route, ), ); }, ), //todo: improve this (fill text and move to bottom) ListTile( title: Text( MaterialLocalizations.of(context).aboutListTileTitle( context.findAncestorWidgetOfExactType()?.title ?? "Yaga", ), ), leading: const Icon(Icons.info_outline), onTap: () => showDialog( context: context, builder: (BuildContext context) => YagaAboutDialog(), ), ), ], ), ); } void _logout(BuildContext context) { showDialog( context: context, builder: (dialogContext) => ActionDangerDialog( title: "Logout", cancelButton: "Cancel", aggressiveAction: "Logout", action: getIt.get<NextCloudManager>().logoutCommand, bodyBuilder: (builderContext) => <Widget>[ const Text( "Logging out will reset your local preferences.", ), ], ), ); } } ================================================ FILE: lib/views/widgets/yaga_popup_menu_button.dart ================================================ import 'package:flutter/material.dart'; class YagaPopupMenuButton<T> extends StatelessWidget { final List<PopupMenuEntry<T>> Function(BuildContext context) itemBuilder; final void Function(BuildContext context, T result) handler; const YagaPopupMenuButton(this.itemBuilder, this.handler); @override Widget build(BuildContext context) { return PopupMenuButton<T>( offset: const Offset(0, 10), onSelected: (T result) => handler(context, result), itemBuilder: itemBuilder, ); } } ================================================ FILE: linux/.gitignore ================================================ flutter/ephemeral ================================================ FILE: linux/CMakeLists.txt ================================================ # Project-level configuration. cmake_minimum_required(VERSION 3.10) project(runner LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. set(BINARY_NAME "yaga") # The unique GTK application identifier for this application. See: # https://wiki.gnome.org/HowDoI/ChooseApplicationID set(APPLICATION_ID "com.github.vauvenal5.yaga") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. cmake_policy(SET CMP0063 NEW) # Load bundled libraries from the lib/ directory relative to the binary. set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") # Root filesystem for cross-building. if(FLUTTER_TARGET_PLATFORM_SYSROOT) set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endif() # Define build configuration options. if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() # Compilation settings that should be applied to most targets. # # Be cautious about adding new options here, as plugins use this function by # default. In most cases, you should add new options to specific targets instead # of modifying this function. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>") target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>") endfunction() # Flutter library and tool build rules. set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Define the application target. To change its name, change BINARY_NAME above, # not the value here, or `flutter run` will no longer work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) # Only the install-generated bundle's copy of the executable will launch # correctly, since the resources must in the right relative locations. To avoid # people trying to run the unbundled copy, put it in a subdirectory instead of # the default top-level location. set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ================================================ FILE: linux/flutter/CMakeLists.txt ================================================ # This file controls Flutter-level build steps. It should not be edited. cmake_minimum_required(VERSION 3.10) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. # Serves the same purpose as list(TRANSFORM ... PREPEND ...), # which isn't available in 3.10. function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() # === Flutter Library === # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "fl_basic_message_channel.h" "fl_binary_codec.h" "fl_binary_messenger.h" "fl_dart_project.h" "fl_engine.h" "fl_json_message_codec.h" "fl_json_method_codec.h" "fl_message_codec.h" "fl_method_call.h" "fl_method_channel.h" "fl_method_codec.h" "fl_method_response.h" "fl_plugin_registrar.h" "fl_plugin_registry.h" "fl_standard_message_codec.h" "fl_standard_method_codec.h" "fl_string_codec.h" "fl_value.h" "fl_view.h" "flutter_linux.h" ) list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO ) add_dependencies(flutter flutter_assemble) # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ================================================ FILE: linux/flutter/generated_plugin_registrant.cc ================================================ // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include <flutter_secure_storage_linux/flutter_secure_storage_linux_plugin.h> #include <url_launcher_linux/url_launcher_plugin.h> void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); } ================================================ FILE: linux/flutter/generated_plugin_registrant.h ================================================ // // Generated file. Do not edit. // // clang-format off #ifndef GENERATED_PLUGIN_REGISTRANT_ #define GENERATED_PLUGIN_REGISTRANT_ #include <flutter_linux/flutter_linux.h> // Registers Flutter plugins. void fl_register_plugins(FlPluginRegistry* registry); #endif // GENERATED_PLUGIN_REGISTRANT_ ================================================ FILE: linux/flutter/generated_plugins.cmake ================================================ # # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST flutter_secure_storage_linux url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $<TARGET_FILE:${plugin}_plugin>) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) endforeach(ffi_plugin) ================================================ FILE: linux/main.cc ================================================ #include "my_application.h" int main(int argc, char** argv) { g_autoptr(MyApplication) app = my_application_new(); return g_application_run(G_APPLICATION(app), argc, argv); } ================================================ FILE: linux/my_application.cc ================================================ #include "my_application.h" #include <flutter_linux/flutter_linux.h> #ifdef GDK_WINDOWING_X11 #include <gdk/gdkx.h> #endif #include "flutter/generated_plugin_registrant.h" struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) // Implements GApplication::activate. static void my_application_activate(GApplication* application) { MyApplication* self = MY_APPLICATION(application); GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); // Use a header bar when running in GNOME as this is the common style used // by applications and is the setup most users will be using (e.g. Ubuntu // desktop). // If running on X and not using GNOME then just use a traditional title bar // in case the window manager does more exotic layout, e.g. tiling. // If running on Wayland assume the header bar will work (may need changing // if future cases occur). gboolean use_header_bar = TRUE; #ifdef GDK_WINDOWING_X11 GdkScreen* screen = gtk_window_get_screen(window); if (GDK_IS_X11_SCREEN(screen)) { const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); if (g_strcmp0(wm_name, "GNOME Shell") != 0) { use_header_bar = FALSE; } } #endif if (use_header_bar) { GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); gtk_widget_show(GTK_WIDGET(header_bar)); gtk_header_bar_set_title(header_bar, "yaga"); gtk_header_bar_set_show_close_button(header_bar, TRUE); gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); } else { gtk_window_set_title(window, "yaga"); } gtk_window_set_default_size(window, 1280, 720); gtk_widget_show(GTK_WIDGET(window)); // code taken from https://github.com/flutter/flutter/issues/53229 if (g_file_test("assets", G_FILE_TEST_IS_DIR)) { gtk_window_set_icon_from_file(window, "assets/icon/icon.svg", NULL); // For debug mode } else { gtk_window_set_icon_from_file(window, "data/flutter_assets/assets/icon/icon.svg", NULL); // For release mode } g_autoptr(FlDartProject) project = fl_dart_project_new(); fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); FlView* view = fl_view_new(project); gtk_widget_show(GTK_WIDGET(view)); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); gtk_widget_grab_focus(GTK_WIDGET(view)); } // Implements GApplication::local_command_line. static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { MyApplication* self = MY_APPLICATION(application); // Strip out the first argument as it is the binary name. self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); g_autoptr(GError) error = nullptr; if (!g_application_register(application, nullptr, &error)) { g_warning("Failed to register: %s", error->message); *exit_status = 1; return TRUE; } g_application_activate(application); *exit_status = 0; return TRUE; } // Implements GObject::dispose. static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; G_OBJECT_CLASS(klass)->dispose = my_application_dispose; } static void my_application_init(MyApplication* self) {} MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", G_APPLICATION_NON_UNIQUE, nullptr)); } ================================================ FILE: linux/my_application.h ================================================ #ifndef FLUTTER_MY_APPLICATION_H_ #define FLUTTER_MY_APPLICATION_H_ #include <gtk/gtk.h> G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, GtkApplication) /** * my_application_new: * * Creates a new Flutter-based application. * * Returns: a new #MyApplication. */ MyApplication* my_application_new(); #endif // FLUTTER_MY_APPLICATION_H_ ================================================ FILE: pubspec.yaml ================================================ name: yaga description: A Nextcloud gallary app. # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2.43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # In Android, build-name is used as versionName while build-number used as versionCode. # Read more about Android versioning at https://developer.android.com/studio/publish/versioning # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 0.43.1+4301 environment: sdk: '>=3.1.0 <4.0.0' dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. # cupertino_icons: ^1.0.0 ansicolor: ^2.0.1 built_value: ^8.0.5 catcher_2: ^1.0.3 device_info_plus: ^9.0.1 equatable: ^2.0.0 flutter_secure_storage: ^8.0.0 flutter_sticky_header: ^0.6.0 flutter_svg: ^1.0.3 get_it: ^7.2.0 image: ^3.0.2 logging: ^1.0.1 mime: ^1.0.0 package_info_plus: ^4.2.0 path_provider: ^2.1.2 permission_handler: ^11.0.1 photo_view: ^0.14.0 rx_command: ^6.0.1 rxdart: ^0.27.2 share_plus: ^7.2.1 shared_preferences: ^2.0.5 sticky_infinite_list: ^4.0.1 url_launcher: ^6.0.3 uuid: ^3.0.4 validators: ^3.0.0 webview_flutter: ^4.2.2 photo_manager: ^3.0.0-dev.5 photo_manager_image_provider: ^2.1.0 flutter_markdown: ^0.6.10+3 markdown: ^7.1.1 flutter_background_service: ^5.0.1 flutter_background_service_android: ^6.0.1 wakelock_plus: ^1.1.3 # pointing to forked repo to support NC26 nextcloud: git: # url: https://github.com/vauvenal5/neon url: https://github.com/nextcloud/neon path: packages/nextcloud ref: 06e2eef # ref: a9e43b8f dependency_overrides: dynamite_runtime: git: url: https://github.com/nextcloud/neon path: packages/dynamite/dynamite_runtime ref: bd408bc # dependency_overrides: # analyzer: "0.40.6" dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter build_runner: ^2.4.6 built_value_generator: ^8.0.5 flutter_launcher_icons: ^0.11.0 lint: ^2.1.2 mockito: ^5.0.5 # dev_dependency_overrides: # petitparser: ^3.0.0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - assets/icon/icon.svg - assets/icon/foreground.svg - assets/icon/foreground_no_border.svg - assets/news.md # - images/a_dot_ham.jpeg # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.dev/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, # see https://flutter.dev/custom-fonts/#from-packages flutter_icons: android: true ios: false image_path: assets/icon/icon.png ================================================ FILE: test/managers/isolateable/mapping_manager_test.dart ================================================ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:rx_command/rx_command.dart'; import 'package:yaga/managers/isolateable/mapping_manager.dart'; import 'package:yaga/managers/settings_manager_base.dart'; import 'package:yaga/model/nc_origin.dart'; import 'package:yaga/model/preferences/mapping_preference.dart'; import 'package:yaga/model/preferences/preference.dart'; import 'package:yaga/model/system_location.dart'; import 'package:yaga/services/isolateable/nextcloud_service.dart'; import 'package:yaga/services/isolateable/system_location_service.dart'; import 'mapping_manager_test.mocks.dart'; @GenerateMocks([SettingsManagerBase, NextCloudService, SystemLocationService]) void main() { final MockSettingsManagerBase settingsManagerBaseMock = MockSettingsManagerBase(); final MockNextCloudService nextCloudServiceMock = MockNextCloudService(); final MockSystemLocationService systemLocationServiceMock = MockSystemLocationService(); const userInfo = "yaga"; const host = "cloud.test.com"; const userDomain = "$userInfo@$host"; final ncRoot = Uri(host: host, pathSegments: []); final ncOrigin = NcOrigin(ncRoot, userInfo, userInfo, userInfo); final command = MockCommand<Preference, Preference>(); final origin = Uri(scheme: 'file', host: 'device.local', path: '/'); final SystemLocation internalAppDirStorage = SystemLocation.fromSplitter( Directory('/system/path/Android/app/path'), origin, 'Android'); final internalAppDirCache = SystemLocation.fromSplitter( Directory('/system/path/Android/cache/path'), origin, 'Android'); const localPath = "/some/local/path"; late MappingManager uut; setUp(() async { when(settingsManagerBaseMock.updateSettingCommand).thenAnswer((_) => command); when(nextCloudServiceMock.origin).thenReturn(ncOrigin); when(systemLocationServiceMock.internalStorage).thenReturn(internalAppDirStorage); when(systemLocationServiceMock.internalCache).thenReturn(internalAppDirCache); when(systemLocationServiceMock.absoluteUriFromInternal(any)).thenAnswer((realInvocation) => realInvocation.positionalArguments[0] as Uri); uut = MappingManager( settingsManagerBaseMock, nextCloudServiceMock, systemLocationServiceMock, ); }); void setUpMapping(String localPath, String remotePath) { final MappingPreference pref = MappingPreference((b) => b ..key = "testKey" ..title = "Root Mapping" ..value = false ..local.value = Uri(host: "local", path: localPath) ..remote.value = Uri(host: "remote", path: remotePath)); uut.handleMappingUpdate(pref); } group("map to tmp path", () { Future<void> mapToTmpPathTest(String remotePath) async { await uut.mapToTmpUri(Uri(host: "remote", path: remotePath)); final Uri captured = verify(systemLocationServiceMock.absoluteUriFromInternal(captureAny)) .captured .single as Uri; expect(captured.path, "${internalAppDirCache.uri.path}/$userDomain$remotePath"); } test("default mapps to cache dir", () async { const String remote = "/test/1.png"; mapToTmpPathTest(remote); }); test("mappings do not influence tmp", () async { const String remote = "/test/1.png"; setUpMapping(localPath, "/"); mapToTmpPathTest(remote); }); }); group("map to local path", () { Future<void> mapToLocalPathTest({ required String remotePath, String? remoteTargetFolderPath, required String expectedPath, }) async { if (remoteTargetFolderPath != null) { setUpMapping(localPath, remoteTargetFolderPath); } await uut.mapToLocalUri(Uri(host: "remote", path: remotePath)); final Uri captured = verify(systemLocationServiceMock.absoluteUriFromInternal(captureAny)) .captured .single as Uri; expect(captured.path, expectedPath); } Future<void> mapRootToLocalPathTest(String remotePath) async { mapToLocalPathTest( remotePath: remotePath, remoteTargetFolderPath: "/", expectedPath: localPath + remotePath, ); } Future<void> mapPicturesToLocalPathTest(String remotePath, {String? expectedPath}) async { const String targetPath = "/Pictures/"; mapToLocalPathTest( remotePath: remotePath, remoteTargetFolderPath: targetPath, expectedPath: expectedPath ?? localPath + remotePath.replaceFirst(targetPath, "/"), ); } test("file with root mapping", () async { const String remote = "/test/1.png"; mapRootToLocalPathTest(remote); }); test("dir with root mapping", () async { const String remote = "/test/"; mapRootToLocalPathTest(remote); }); test("file with sub mapping", () async { const String remote = "/Pictures/1.png"; mapPicturesToLocalPathTest(remote); }); test("dir with sub mapping", () async { const String remote = "/Pictures/test/"; mapPicturesToLocalPathTest(remote); }); test("none sub mapping paths are mapped to app dir", () async { const String remote = "/test/1.png"; mapPicturesToLocalPathTest(remote, expectedPath: "${internalAppDirStorage.uri.path}/$userDomain$remote"); }); test("default mapps to app dir", () async { const String remote = "/test/1.png"; mapToLocalPathTest( remotePath: remote, expectedPath: "${internalAppDirStorage.uri.path}/$userDomain$remote"); }); }); group("map tmp to remote uri", () { Future<void> mapTmpToRemoteUriTest(String relativePath) async { final Uri tmp = Uri( host: "local", path: "${internalAppDirCache.uri.path}/$userDomain$relativePath", ); final Uri remote = Uri( scheme: "nc", userInfo: userInfo, host: host, pathSegments: [], ); final Uri result = await uut.mapTmpToRemoteUri(tmp, remote); expect(result.scheme, "nc"); expect(result.userInfo, userInfo); expect(result.host, host); expect(result.path, relativePath); } test("map tmp file", () async { mapTmpToRemoteUriTest("/test/1.png"); }); test("map tmp dir", () async { mapTmpToRemoteUriTest("/test/"); }); }); group("map to remote uri", () { Future<void> mapToRemoteUriTest({ required String localFilePath, required String remotePath, required String expectedPath, String? mappingPath, }) async { final Uri file = Uri( host: "local", path: localFilePath, ); final Uri remote = Uri( scheme: "nc", userInfo: userInfo, host: host, path: remotePath, ); if (mappingPath != null) { setUpMapping(localPath, mappingPath); } final Uri result = await uut.mapToRemoteUri(file, remote); expect(result.scheme, "nc"); expect(result.userInfo, userInfo); expect(result.host, host); expect(result.path, expectedPath); } test("map file with default mapping", () async { mapToRemoteUriTest( localFilePath: "${internalAppDirStorage.uri.path}/$userDomain/test/1.png", remotePath: "/", expectedPath: "/test/1.png", ); }); test("map file with root mapping", () async { mapToRemoteUriTest( localFilePath: "$localPath/test/1.png", remotePath: "/", expectedPath: "/test/1.png", mappingPath: "/", ); }); test("map file with sub mapping", () async { mapToRemoteUriTest( localFilePath: "$localPath/test/1.png", remotePath: "/Pictures/", expectedPath: "/Pictures/test/1.png", mappingPath: "/Pictures/", ); }); test("map file on different path than sub mapping", () async { mapToRemoteUriTest( localFilePath: "${internalAppDirStorage.uri.path}/$userDomain/test/1.png", remotePath: "/", expectedPath: "/test/1.png", mappingPath: "/Pictures/", ); }); }); } ================================================ FILE: test/utils/uri_utils_test.dart ================================================ import 'package:flutter_test/flutter_test.dart'; import 'package:yaga/utils/uri_utils.dart'; void main() { group("fromUri", () { final Uri originalUri = Uri( scheme: "https", userInfo: "user", host: "cloud.nextcloud.com", port: 8443, path: "/original/path", ); test("should override nothing", () { expect( fromUri(uri: originalUri).toString(), originalUri.toString(), ); }); test("should override everything", () { final Uri expected = Uri( scheme: "http", userInfo: "user2", host: "cloud.nc.com", port: 443, path: "/other/path", ); expect( fromUri( uri: originalUri, scheme: expected.scheme, userInfo: expected.userInfo, host: expected.host, port: expected.port, path: expected.path, ).toString(), expected.toString(), ); }); }); group("fromPathSegments", () { final Uri uri = Uri(host: "cloud.nextcloud.com", path: "/original/path"); test("should ignore original uri path", () { const String firstPath = "/first/part"; const String secondPath = "/second/part/"; final Uri actual = fromPathList( uri: uri, paths: [firstPath, secondPath], ); expect(actual.host, uri.host); expect(actual.path, "$firstPath$secondPath"); }); test("should not double encode special chars", () { const String firstPath = "/first/part/with%2Fspecial%2Fchar"; const String secondPath = "/second/part/"; final Uri actual = fromPathList( uri: uri, paths: [firstPath, secondPath], ); expect(actual.host, uri.host); expect(actual.path, "$firstPath$secondPath"); }); }); group("chainPathSegments", () { const String expected = "/first/part/second/part/"; test("should correctly unite path with leading and trailing slash", () { const String first = "/first/part/"; const String second = "/second/part/"; expect(chainPathSegments(first, second), expected); }); test("should correctly unite path with leading slash", () { const String first = "/first/part"; const String second = "/second/part/"; expect(chainPathSegments(first, second), expected); }); test("should correctly unite path with trailing slash", () { const String first = "/first/part/"; const String second = "second/part/"; expect(chainPathSegments(first, second), expected); }); test("should correctly unite path without slash", () { const String first = "/first/part"; const String second = "second/part/"; expect(chainPathSegments(first, second), expected); }); }); group("getRootFromUri", () { test("should return root uri from current uri", () { final Uri uri = Uri(host: "cloud.nextcloud.com", path: "/some/path"); final Uri actual = getRootFromUri(uri); expect(actual.host, uri.host); expect(actual.path, "/"); }); }); group("fromUriPathSegments", () { test("should not change meaning of special chars", () { const String expectedPath = "/test/path%2Fwith%2Fspecial/"; final Uri uri = Uri(path: "${expectedPath}chars"); expect(fromUriPathSegments(uri, 1).path, expectedPath); }); test("should not change meaning of double encoded chars", () { const String expectedPath = "/test/path%252Fwith%252Fspecial/t%C3%B6st/"; final Uri uri = Uri(path: "${expectedPath}chars"); expect(fromUriPathSegments(uri, 2).path, expectedPath); }); }); group("getNameFromUri", () { test("should return file name from uri", () { const String fileName = "file.png"; final Uri fileUri = Uri(pathSegments: ["test", "path", "to", fileName]); expect(getNameFromUri(fileUri), fileName); }); test("should return folder name from uri", () { const String folder = "folder"; final Uri folderUri = Uri(pathSegments: ["test", "path", "to", folder, ""]); expect(getNameFromUri(folderUri), folder); }); test("should return host name from empty uri", () { const String host = "testHost"; final Uri emptyUri = Uri(host: host); expect(getNameFromUri(emptyUri), host.toLowerCase()); }); }); } ================================================ FILE: test/widget_test.dart ================================================ // This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:yaga/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }