diff --git a/Makefile b/Makefile index 3dcdf0806f..8f119c257b 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ dev: rm -rf ./server/dist && docker-compose -f ./docker/docker-compose.dev.yml up --remove-orphans dev-new: - rm -rf ./server/dist && docker compose -f ./docker/docker-compose.dev.yml up --remove-orphans + rm -rf ./server/dist && docker-compose -f ./docker/docker-compose.dev.yml up --remove-orphans dev-update: rm -rf ./server/dist && docker-compose -f ./docker/docker-compose.dev.yml up --build -V --remove-orphans @@ -26,4 +26,4 @@ prod-scale: docker-compose -f ./docker/docker-compose.yml up --build -V --scale immich-server=3 --scale immich-microservices=3 --remove-orphans api: - cd ./server && npm run api:generate \ No newline at end of file + cd ./server && npm run api:generate diff --git a/README.md b/README.md index 8c5bca08be..ab12842568 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,9 @@ Spec: Free-tier Oracle VM - Amsterdam - 2.4Ghz quad-core ARM64 CPU, 24GB RAM | Search by metadata, objects and image tags | Yes | No | | Administrative functions (user management) | N/A | Yes | | Background backup | Android | N/A | -| Virtual scroll | N/A | Yes | +| Virtual scroll | Yes | Yes | +| OAuth Support | Yes | Yes | +| LivePhotos Backup and Playback (iOS only) | Yes | Yes | # Support the project diff --git a/docker/.env.example b/docker/.env.example index a594f9c0bf..a2053e29af 100644 --- a/docker/.env.example +++ b/docker/.env.example @@ -23,7 +23,9 @@ REDIS_HOSTNAME=immich_redis # REDIS_SOCKET= ################################################################################### -# Upload File Config +# Upload File Location +# +# This is the location where uploaded files are stored. ################################################################################### UPLOAD_LOCATION=absolute_location_on_your_machine_where_you_want_to_store_the_backup @@ -36,19 +38,17 @@ LOG_LEVEL=simple ################################################################################### # JWT SECRET -################################################################################### - +# # This JWT_SECRET is used to sign the authentication keys for user login # You should set it to a long randomly generated value # You can use this command to generate one: openssl rand -base64 128 +################################################################################### + JWT_SECRET= ################################################################################### # Reverse Geocoding -#################################################################################### - -# DISABLE_REVERSE_GEOCODING=false - +# # Reverse geocoding is done locally which has a small impact on memory usage # This memory usage can be altered by changing the REVERSE_GEOCODING_PRECISION variable # This ranges from 0-3 with 3 being the most precise @@ -56,25 +56,44 @@ JWT_SECRET= # 2 - Cities > 1000 population: ~150MB RAM # 1 - Cities > 5000 population: ~80MB RAM # 0 - Cities > 15000 population: ~40MB RAM +#################################################################################### +# DISABLE_REVERSE_GEOCODING=false # REVERSE_GEOCODING_PRECISION=3 #################################################################################### # WEB - Optional -#################################################################################### - +# # Custom message on the login page, should be written in HTML form. -# For example PUBLIC_LOGIN_PAGE_MESSAGE="This is a demo instance of Immich.

Email: demo@demo.de
Password: demo" +# For example: +# PUBLIC_LOGIN_PAGE_MESSAGE="This is a demo instance of Immich.

Email: demo@demo.de
Password: demo" +#################################################################################### PUBLIC_LOGIN_PAGE_MESSAGE= #################################################################################### # Alternative Service Addresses - Optional -#################################################################################### - -# This is an advanced feature for users who may be running their immich services on different hosts. It will not change which address or port that services bind to within their containers, but it will change where other services look for their peers. +# +# This is an advanced feature for users who may be running their immich services on different hosts. +# It will not change which address or port that services bind to within their containers, but it will change where other services look for their peers. # Note: immich-microservices is bound to 3002, but no references are made +#################################################################################### # IMMICH_WEB_URL=http://immich-web:3000 # IMMICH_SERVER_URL=http://immich-server:3001 # IMMICH_MACHINE_LEARNING_URL=http://immich-machine-learning:3003 + +#################################################################################### +# OAuth Setting - Optional +# +# These setting will enable OAuth login for your instance of Immich +# Folow the instructions in the page https://immich.app/docs/usage/oauth to set up your OAuth provider +#################################################################################### + +# OAUTH_ENABLED=false +# OAUTH_ISSUER_URL= +# OAUTH_CLIENT_ID= +# OAUTH_CLIENT_SECRET= +# OAUTH_BUTTON_TEXT=Login with OAuth +# OAUTH_AUTO_REGISTER=true +# OAUTH_SCOPE="openid profile email" diff --git a/docs/blog/2019-05-28-first-blog-post.md b/docs/blog/2019-05-28-first-blog-post.md deleted file mode 100644 index 02f3f81bd2..0000000000 --- a/docs/blog/2019-05-28-first-blog-post.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -slug: first-blog-post -title: First Blog Post -authors: - name: Gao Wei - title: Docusaurus Core Team - url: https://github.com/wgao19 - image_url: https://github.com/wgao19.png -tags: [hola, docusaurus] ---- - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet diff --git a/docs/blog/2019-05-29-long-blog-post.md b/docs/blog/2019-05-29-long-blog-post.md deleted file mode 100644 index 26ffb1b1f6..0000000000 --- a/docs/blog/2019-05-29-long-blog-post.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -slug: long-blog-post -title: Long Blog Post -authors: endi -tags: [hello, docusaurus] ---- - -This is the summary of a very long blog post, - -Use a `` comment to limit blog post size in the list view. - - - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet - -Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet diff --git a/docs/blog/2021-08-01-mdx-blog-post.mdx b/docs/blog/2021-08-01-mdx-blog-post.mdx deleted file mode 100644 index c04ebe323e..0000000000 --- a/docs/blog/2021-08-01-mdx-blog-post.mdx +++ /dev/null @@ -1,20 +0,0 @@ ---- -slug: mdx-blog-post -title: MDX Blog Post -authors: [slorber] -tags: [docusaurus] ---- - -Blog posts support [Docusaurus Markdown features](https://docusaurus.io/docs/markdown-features), such as [MDX](https://mdxjs.com/). - -:::tip - -Use the power of React to create interactive blog posts. - -```js - -``` - - - -::: diff --git a/docs/blog/2021-08-26-welcome/docusaurus-plushie-banner.jpeg b/docs/blog/2021-08-26-welcome/docusaurus-plushie-banner.jpeg deleted file mode 100644 index 11bda09284..0000000000 Binary files a/docs/blog/2021-08-26-welcome/docusaurus-plushie-banner.jpeg and /dev/null differ diff --git a/docs/blog/2021-08-26-welcome/index.md b/docs/blog/2021-08-26-welcome/index.md deleted file mode 100644 index 9455168f17..0000000000 --- a/docs/blog/2021-08-26-welcome/index.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -slug: welcome -title: Welcome -authors: [slorber, yangshun] -tags: [facebook, hello, docusaurus] ---- - -[Docusaurus blogging features](https://docusaurus.io/docs/blog) are powered by the [blog plugin](https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-content-blog). - -Simply add Markdown files (or folders) to the `blog` directory. - -Regular blog authors can be added to `authors.yml`. - -The blog post date can be extracted from filenames, such as: - -- `2019-05-30-welcome.md` -- `2019-05-30-welcome/index.md` - -A blog post folder can be convenient to co-locate blog post images: - -![Docusaurus Plushie](./docusaurus-plushie-banner.jpeg) - -The blog supports tags as well! - -**And if you don't want a blog**: just delete this directory, and use `blog: false` in your Docusaurus config. diff --git a/docs/blog/authors.yml b/docs/blog/authors.yml index bcb2991563..f331efa927 100644 --- a/docs/blog/authors.yml +++ b/docs/blog/authors.yml @@ -1,17 +1,5 @@ -endi: - name: Endilie Yacop Sucipto - title: Maintainer of Docusaurus - url: https://github.com/endiliey - image_url: https://github.com/endiliey.png - -yangshun: - name: Yangshun Tay - title: Front End Engineer @ Facebook - url: https://github.com/yangshun - image_url: https://github.com/yangshun.png - -slorber: - name: Sébastien Lorber - title: Docusaurus maintainer - url: https://sebastienlorber.com - image_url: https://github.com/slorber.png +alextran: + name: Alex Tran + title: Maintainer of Immich + url: https://github.com/alextran1502 + image_url: https://github.com/alextran1502.png diff --git a/docs/blog/release-1.36/index.mdx b/docs/blog/release-1.36/index.mdx new file mode 100644 index 0000000000..9a9c6a5263 --- /dev/null +++ b/docs/blog/release-1.36/index.mdx @@ -0,0 +1,114 @@ +--- +slug: release-1-36 +title: Release v1.36.0 +authors: [alextran] +tags: [release] +date: 2022-11-10 +--- + +Hello everyone, it is my pleasure to deliver the new release of Immich to you. The team has been working hard to bring you the new features and improvements. This release includes some big features that the community has been asking since the beginning of Immich. We hope you will enjoy it. + +Some notable features are: + +- [OAuth integration](#livephoto-ios-support-) +- [LivePhoto support on iOS](#oauth-integration-) +- User config system + + + +## LivePhoto iOS Support 🎉 + +LivePhoto on iOS is now supported in Immich. + +The motion part will now be uploaded and can be played on the mobile app and the web. + +:::caution + +- The server and the app has to be on version **1.36.x** for the application to work correctly. +- Previous uploaded photos will not be updated automatically, you will have to remove and reupload them if you want to keep the LivePhoto functionality. + +::: + + + +## OAuth Integration 🎉 + +I want to borrow this chance to express my gratitude to [@EnricoBilla](https://github.com/EnricoBilla), who has been the trailblazer for this feature since the beginning days of Immich. His PR has sparked ideas, suggestions, and discussion among the team member on how to integrate this feature successfully into the app. Thank you so much for your work and your time. + +OAuth is now integrated into the system. Please follow the guide [here](https://immich.app/docs/usage/oauth) to set up your OAuth integration + +After setting up the correct environment variables in the `.env` file, as shown below + +| Key | Type | Default | Description | +| ------------------- | ------- | -------------------- | ------------------------------------------------------------------------- | +| OAUTH_ENABLED | boolean | false | Enable/disable OAuth2 | +| OAUTH_ISSUER_URL | URL | (required) | Required. Self-discovery URL for client | +| OAUTH_CLIENT_ID | string | (required) | Required. Client ID | +| OAUTH_CLIENT_SECRET | string | (required) | Required. Client Secret | +| OAUTH_SCOPE | string | openid email profile | Full list of scopes to send with the request (space delimited) | +| OAUTH_AUTO_REGISTER | boolean | true | When true, will automatically register a user the first time they sign in | +| OAUTH_BUTTON_TEXT | string | Login with OAuth | Text for the OAuth button on the web | + +```bash title="Authentik Example" +OAUTH_ENABLED=true +OAUTH_ISSUER_URL=http://10.1.15.216:9000/application/o/immich-test/ +OAUTH_CLIENT_ID=30596v8f78a4b6a97d5985c3076b6b4c4d12ddc33 +OAUTH_CLIENT_SECRET=50f1eafdec353b95b1c638db390db4ab67ef035a51212dbec2f56175e2eb272b5d572c099176e6fe116ecf47ffdd544bgdb9e2edc588307ee0339d25eeccd88 +OAUTH_BUTTON_TEXT=Login with Authentik +``` + +The web will have the option to sign in with OAuth. + + + +The mobile app will check if the server has OAuth enabled before displaying the OAuth +sign-in button. + + + +## Support + + + +If you find the project helpful and it helps you in some ways, you can support the project [one time](https://github.com/sponsors/alextran1502?frequency=one-time&sponsor=alextran1502) or [monthly](https://github.com/sponsors/alextran1502) from GitHub Sponsor + +It is a great way to let me know that you want me to continue developing and working on this project for years to come. + +## Details + +For more details, please check out the [release note](https://github.com/immich-app/immich/releases/tag/v1.36.0_55-dev) diff --git a/docs/docs/usage/img/authentik-redirect.png b/docs/docs/usage/img/authentik-redirect.png new file mode 100644 index 0000000000..6cae28bbfe Binary files /dev/null and b/docs/docs/usage/img/authentik-redirect.png differ diff --git a/docs/docs/usage/oauth.md b/docs/docs/usage/oauth.md index c8dff35908..78eb47aed5 100644 --- a/docs/docs/usage/oauth.md +++ b/docs/docs/usage/oauth.md @@ -28,9 +28,17 @@ Before enabling OAuth in Immich, a new client application needs to be configured 2. Configure Redirect URIs/Origins - 1. The **Sign-in redirect URIs** should include: + The **Sign-in redirect URIs** should include: - - All URLs that will be used to access the login page of the Immich web client (eg. `http://localhost:2283/auth/login`, `http://192.168.0.200:2283/auth/login`, `https://immich.example.com/auth/login`) + * All URLs that will be used to access the login page of the Immich web client (eg. `http://localhost:2283/auth/login`, `http://192.168.0.200:2283/auth/login`, `https://immich.example.com/auth/login`) + * Mobile app redirect URL `app.immich:/` + +:::caution +You **MUST** include `app.immich:/` as the redirect URI for iOS and Android mobile app to work properly. + +**Authentik example** + +::: ## Enable OAuth @@ -41,7 +49,7 @@ Once you have a new OAuth client application configured, Immich can be configure | OAUTH_ENABLED | boolean | false | Enable/disable OAuth2 | | OAUTH_ISSUER_URL | URL | (required) | Required. Self-discovery URL for client (from previous step) | | OAUTH_CLIENT_ID | string | (required) | Required. Client ID (from previous step) | -| OAUTH_CLIENT_SECRET | string | (required) | Required. Client Secret (previous step | +| OAUTH_CLIENT_SECRET | string | (required) | Required. Client Secret (previous step) | | OAUTH_SCOPE | string | openid email profile | Full list of scopes to send with the request (space delimited) | | OAUTH_AUTO_REGISTER | boolean | true | When true, will automatically register a user the first time they sign in | | OAUTH_BUTTON_TEXT | string | Login with OAuth | Text for the OAuth button on the web | diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index d1094f50aa..afb5d61b16 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -80,7 +80,7 @@ const config = { position: "right", label: "Documentation", }, - // { to: "/blog", label: "Blog", position: "right" }, + { to: "/blog", label: "Blog", position: "right" }, { href: "https://github.com/immich-app/immich", label: "GitHub", diff --git a/mobile/android/app/build.gradle b/mobile/android/app/build.gradle index 54234e4b08..cc0de01bad 100644 --- a/mobile/android/app/build.gradle +++ b/mobile/android/app/build.gradle @@ -33,7 +33,7 @@ if (keystorePropertiesFile.exists()) { android { - compileSdkVersion flutter.compileSdkVersion + compileSdkVersion 33 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 @@ -52,7 +52,7 @@ android { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "app.alextran.immich" minSdkVersion 23 - targetSdkVersion flutter.targetSdkVersion + targetSdkVersion 33 versionCode flutterVersionCode.toInteger() versionName flutterVersionName } diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml index 36a967da6c..b6bf0b4459 100644 --- a/mobile/android/app/src/main/AndroidManifest.xml +++ b/mobile/android/app/src/main/AndroidManifest.xml @@ -12,21 +12,35 @@ + + + + + + + + + + - + android:name="androidx.startup.InitializationProvider" + android:authorities="${applicationId}.androidx-startup" + tools:node="remove"> + + + diff --git a/mobile/android/fastlane/Fastfile b/mobile/android/fastlane/Fastfile index ed9e512b54..188807cc37 100644 --- a/mobile/android/fastlane/Fastfile +++ b/mobile/android/fastlane/Fastfile @@ -35,8 +35,8 @@ platform :android do task: 'bundle', build_type: 'Release', properties: { - "android.injected.version.code" => 54, - "android.injected.version.name" => "1.35.0", + "android.injected.version.code" => 58, + "android.injected.version.name" => "1.37.0", } ) upload_to_play_store(skip_upload_apk: true, skip_upload_images: true, skip_upload_screenshots: true, aab: '../build/app/outputs/bundle/release/app-release.aab') diff --git a/mobile/android/fastlane/metadata/android/en-US/changelogs/55.txt b/mobile/android/fastlane/metadata/android/en-US/changelogs/55.txt new file mode 100644 index 0000000000..ea6099549b --- /dev/null +++ b/mobile/android/fastlane/metadata/android/en-US/changelogs/55.txt @@ -0,0 +1,3 @@ +* Added OAuth login option +* Tidy-up dependencies, remove unused, replace rarely used ones +* Added view LivePhotos feature \ No newline at end of file diff --git a/mobile/android/fastlane/metadata/android/en-US/changelogs/56.txt b/mobile/android/fastlane/metadata/android/en-US/changelogs/56.txt new file mode 100644 index 0000000000..f90fc5722b --- /dev/null +++ b/mobile/android/fastlane/metadata/android/en-US/changelogs/56.txt @@ -0,0 +1,2 @@ +* Fixed freezed splash screen +* Fixed OIDC redirect but not logging in \ No newline at end of file diff --git a/mobile/android/fastlane/metadata/android/en-US/changelogs/57.txt b/mobile/android/fastlane/metadata/android/en-US/changelogs/57.txt new file mode 100644 index 0000000000..ff056558b8 --- /dev/null +++ b/mobile/android/fastlane/metadata/android/en-US/changelogs/57.txt @@ -0,0 +1,2 @@ +* Show human readable file size in detail view +* Fix permission issue on Android 33 \ No newline at end of file diff --git a/mobile/android/fastlane/metadata/android/en-US/changelogs/58.txt b/mobile/android/fastlane/metadata/android/en-US/changelogs/58.txt new file mode 100644 index 0000000000..ba269eb4fd --- /dev/null +++ b/mobile/android/fastlane/metadata/android/en-US/changelogs/58.txt @@ -0,0 +1,6 @@ +* Use binary prefixes for data sizes +* Fix not able to show device asset on Android 13 +* Use cached asset info if unchanged instead of downloading all assets +* Add in-app logging +* Add search mechanism to album selection page +* Improve UI \ No newline at end of file diff --git a/mobile/android/fastlane/report.xml b/mobile/android/fastlane/report.xml index 35596dd5e1..52da1b7299 100644 --- a/mobile/android/fastlane/report.xml +++ b/mobile/android/fastlane/report.xml @@ -5,17 +5,17 @@ - + - + - + diff --git a/mobile/assets/i18n/en-US.json b/mobile/assets/i18n/en-US.json index 826f5d017f..5e072b84d4 100644 --- a/mobile/assets/i18n/en-US.json +++ b/mobile/assets/i18n/en-US.json @@ -17,7 +17,7 @@ "backup_album_selection_page_albums_device": "Albums on device ({})", "backup_album_selection_page_albums_tap": "Tap to include, double tap to exclude", "backup_album_selection_page_assets_scatter": "Assets can scatter across multiple albums. Thus, albums can be included or excluded during the backup process.", - "backup_album_selection_page_select_albums": "Select Albums", + "backup_album_selection_page_select_albums": "Select albums", "backup_album_selection_page_selection_info": "Selection Info", "backup_album_selection_page_total_assets": "Total unique assets", "backup_all": "All", @@ -109,7 +109,9 @@ "login_form_err_invalid_email": "Invalid Email", "login_form_err_leading_whitespace": "Leading whitespace", "login_form_err_trailing_whitespace": "Trailing whitespace", - "login_form_failed_login": "Error logging you in, check server url, email and password", + "login_form_failed_login": "Error logging you in, check server URL, email and password", + "login_form_failed_get_oauth_server_config": "Error logging using OAuth, check server URL", + "login_form_failed_get_oauth_server_disable": "OAuth feature is not available on this server", "login_form_label_email": "Email", "login_form_label_password": "Password", "login_form_password_hint": "password", @@ -118,6 +120,7 @@ "profile_drawer_client_server_up_to_date": "Client and Server are up-to-date", "profile_drawer_settings": "Settings", "profile_drawer_sign_out": "Sign Out", + "profile_drawer_app_logs": "Logs", "search_bar_hint": "Search your photos", "search_page_no_objects": "No Objects Info Available", "search_page_no_places": "No Places Info Available", diff --git a/mobile/fonts/Inconsolata-Regular.ttf b/mobile/fonts/Inconsolata-Regular.ttf new file mode 100644 index 0000000000..0d879bf3a4 Binary files /dev/null and b/mobile/fonts/Inconsolata-Regular.ttf differ diff --git a/mobile/ios/Podfile.lock b/mobile/ios/Podfile.lock index 7310ec8756..ffa1e57887 100644 --- a/mobile/ios/Podfile.lock +++ b/mobile/ios/Podfile.lock @@ -3,6 +3,8 @@ PODS: - flutter_udid (0.0.1): - Flutter - SAMKeychain + - flutter_web_auth (0.5.0): + - Flutter - fluttertoast (0.0.2): - Flutter - Toast @@ -37,6 +39,7 @@ PODS: DEPENDENCIES: - Flutter (from `Flutter`) - flutter_udid (from `.symlinks/plugins/flutter_udid/ios`) + - flutter_web_auth (from `.symlinks/plugins/flutter_web_auth/ios`) - fluttertoast (from `.symlinks/plugins/fluttertoast/ios`) - image_picker_ios (from `.symlinks/plugins/image_picker_ios/ios`) - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) @@ -60,6 +63,8 @@ EXTERNAL SOURCES: :path: Flutter flutter_udid: :path: ".symlinks/plugins/flutter_udid/ios" + flutter_web_auth: + :path: ".symlinks/plugins/flutter_web_auth/ios" fluttertoast: :path: ".symlinks/plugins/fluttertoast/ios" image_picker_ios: @@ -86,6 +91,7 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: Flutter: f04841e97a9d0b0a8025694d0796dd46242b2854 flutter_udid: 0848809dbed4c055175747ae6a45a8b4f6771e1c + flutter_web_auth: c25208760459cec375a3c39f6a8759165ca0fa4d fluttertoast: 16fbe6039d06a763f3533670197d01fc73459037 FMDB: 2ce00b547f966261cd18927a3ddb07cb6f3db82a image_picker_ios: b786a5dcf033a8336a657191401bfdf12017dabb diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj index 37e0c55524..95c7de92f2 100644 --- a/mobile/ios/Runner.xcodeproj/project.pbxproj +++ b/mobile/ios/Runner.xcodeproj/project.pbxproj @@ -360,7 +360,7 @@ CODE_SIGN_ENTITLEMENTS = Runner/RunnerProfile.entitlements; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 68; + CURRENT_PROJECT_VERSION = 73; DEVELOPMENT_TEAM = 2F67MQ8R79; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; @@ -495,7 +495,7 @@ CLANG_ENABLE_MODULES = YES; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 68; + CURRENT_PROJECT_VERSION = 73; DEVELOPMENT_TEAM = 2F67MQ8R79; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; @@ -522,7 +522,7 @@ CLANG_ENABLE_MODULES = YES; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 68; + CURRENT_PROJECT_VERSION = 73; DEVELOPMENT_TEAM = 2F67MQ8R79; ENABLE_BITCODE = NO; INFOPLIST_FILE = Runner/Info.plist; diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plist index 9e13c18b48..73f4b0779e 100644 --- a/mobile/ios/Runner/Info.plist +++ b/mobile/ios/Runner/Info.plist @@ -17,11 +17,11 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.34.0 + 1.37.0 CFBundleSignature ???? CFBundleVersion - 68 + 73 LSRequiresIPhoneOS MGLMapboxMetricsEnabledSettingShownInApp diff --git a/mobile/ios/ci_scripts/ci_post_clone.sh b/mobile/ios/ci_scripts/ci_post_clone.sh new file mode 100755 index 0000000000..1a4f0cd169 --- /dev/null +++ b/mobile/ios/ci_scripts/ci_post_clone.sh @@ -0,0 +1,23 @@ +#!/bin/sh + +# The default execution directory of this script is the ci_scripts directory. +cd $CI_WORKSPACE/mobile + +# Install Flutter using git. +git clone https://github.com/flutter/flutter.git --depth 1 -b stable $HOME/flutter +export PATH="$PATH:$HOME/flutter/bin" + +# Install Flutter artifacts for iOS (--ios), or macOS (--macos) platforms. +flutter precache --ios + +# Install Flutter dependencies. +flutter pub get + +# Install CocoaPods using Homebrew. +HOMEBREW_NO_AUTO_UPDATE=1 # disable homebrew's automatic updates. +brew install cocoapods + +# Install CocoaPods dependencies. +cd ios && pod install # run `pod install` in the `ios` directory. + +exit 0 diff --git a/mobile/ios/fastlane/Fastfile b/mobile/ios/fastlane/Fastfile index c40114ef93..66600efe51 100644 --- a/mobile/ios/fastlane/Fastfile +++ b/mobile/ios/fastlane/Fastfile @@ -19,7 +19,7 @@ platform :ios do desc "iOS Beta" lane :beta do increment_version_number( - version_number: "1.35.0" + version_number: "1.37.0" ) increment_build_number( build_number: latest_testflight_build_number + 1, diff --git a/mobile/ios/fastlane/report.xml b/mobile/ios/fastlane/report.xml index cccb701b0a..c40a2fb5fe 100644 --- a/mobile/ios/fastlane/report.xml +++ b/mobile/ios/fastlane/report.xml @@ -5,32 +5,32 @@ - + - + - + - + - + - + diff --git a/mobile/lib/constants/hive_box.dart b/mobile/lib/constants/hive_box.dart index 5a65c248aa..704be3586e 100644 --- a/mobile/lib/constants/hive_box.dart +++ b/mobile/lib/constants/hive_box.dart @@ -4,6 +4,7 @@ const String accessTokenKey = "immichBoxAccessTokenKey"; // Key 1 const String deviceIdKey = 'immichBoxDeviceIdKey'; // Key 2 const String isLoggedInKey = 'immichIsLoggedInKey'; // Key 3 const String serverEndpointKey = 'immichBoxServerEndpoint'; // Key 4 +const String assetEtagKey = 'immichAssetEtagKey'; // Key 5 // Login Info const String hiveLoginInfoBox = "immichLoginInfoBox"; // Box @@ -29,3 +30,6 @@ const String backupRequireCharging = "immichBackupRequireCharging"; // Key 3 // Duplicate asset const String duplicatedAssetsBox = "immichDuplicatedAssetsBox"; // Box const String duplicatedAssetsKey = "immichDuplicatedAssetsKey"; // Key 1 + +// In app logger +const String immichLoggerBox = "immichInAppLogger"; // Box \ No newline at end of file diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart index d1148df360..811dca7cff 100644 --- a/mobile/lib/main.dart +++ b/mobile/lib/main.dart @@ -16,11 +16,13 @@ import 'package:immich_mobile/modules/login/models/hive_saved_login_info.model.d import 'package:immich_mobile/modules/login/providers/authentication.provider.dart'; import 'package:immich_mobile/routing/router.dart'; import 'package:immich_mobile/routing/tab_navigation_observer.dart'; +import 'package:immich_mobile/shared/models/immich_logger_message.model.dart'; import 'package:immich_mobile/shared/providers/app_state.provider.dart'; import 'package:immich_mobile/shared/providers/asset.provider.dart'; import 'package:immich_mobile/shared/providers/release_info.provider.dart'; import 'package:immich_mobile/shared/providers/server_info.provider.dart'; import 'package:immich_mobile/shared/providers/websocket.provider.dart'; +import 'package:immich_mobile/shared/services/immich_logger.service.dart'; import 'package:immich_mobile/shared/views/immich_loading_overlay.dart'; import 'package:immich_mobile/shared/views/version_announcement_overlay.dart'; import 'package:immich_mobile/utils/immich_app_theme.dart'; @@ -31,8 +33,10 @@ void main() async { Hive.registerAdapter(HiveSavedLoginInfoAdapter()); Hive.registerAdapter(HiveBackupAlbumsAdapter()); Hive.registerAdapter(HiveDuplicatedAssetsAdapter()); + Hive.registerAdapter(ImmichLoggerMessageAdapter()); await Future.wait([ + Hive.openBox(immichLoggerBox), Hive.openBox(userInfoBox), Hive.openBox(hiveLoginInfoBox), Hive.openBox(hiveGithubReleaseInfoBox), @@ -58,6 +62,9 @@ void main() async { } } + // Initialize Immich Logger Service + ImmichLogger().init(); + runApp( EasyLocalization( supportedLocales: locales, diff --git a/mobile/lib/modules/album/services/album.service.dart b/mobile/lib/modules/album/services/album.service.dart index 5e53399e35..fd82cd06fc 100644 --- a/mobile/lib/modules/album/services/album.service.dart +++ b/mobile/lib/modules/album/services/album.service.dart @@ -69,7 +69,10 @@ class AlbumService { Iterable assets, ) async { return createAlbum( - _getNextAlbumName(await getAlbums(isShared: false)), assets, []); + _getNextAlbumName(await getAlbums(isShared: false)), + assets, + [], + ); } Future getAlbumDetail(String albumId) async { diff --git a/mobile/lib/modules/album/ui/album_thumbnail_card.dart b/mobile/lib/modules/album/ui/album_thumbnail_card.dart index 5530b37ddb..87d2f45d59 100644 --- a/mobile/lib/modules/album/ui/album_thumbnail_card.dart +++ b/mobile/lib/modules/album/ui/album_thumbnail_card.dart @@ -21,8 +21,39 @@ class AlbumThumbnailCard extends StatelessWidget { @override Widget build(BuildContext context) { var box = Hive.box(userInfoBox); + var cardSize = MediaQuery.of(context).size.width / 2 - 18; + var isDarkMode = Theme.of(context).brightness == Brightness.dark; - final cardSize = MediaQuery.of(context).size.width / 2 - 18; + buildEmptyThumbnail() { + return Container( + decoration: BoxDecoration( + color: isDarkMode ? Colors.grey[800] : Colors.grey[200], + ), + child: SizedBox( + height: cardSize, + width: cardSize, + child: const Center( + child: Icon(Icons.no_photography), + ), + ), + ); + } + + buildAlbumThumbnail() { + return CachedNetworkImage( + memCacheHeight: max(400, cardSize.toInt() * 3), + width: cardSize, + height: cardSize, + fit: BoxFit.cover, + fadeInDuration: const Duration(milliseconds: 200), + imageUrl: getAlbumThumbnailUrl( + album, + type: ThumbnailFormat.JPEG, + ), + httpHeaders: {"Authorization": "Bearer ${box.get(accessTokenKey)}"}, + cacheKey: "${album.albumThumbnailAssetId}", + ); + } return GestureDetector( onTap: () { @@ -35,19 +66,9 @@ class AlbumThumbnailCard extends StatelessWidget { children: [ ClipRRect( borderRadius: BorderRadius.circular(8), - child: CachedNetworkImage( - memCacheHeight: max(400, cardSize.toInt() * 3), - width: cardSize, - height: cardSize, - fit: BoxFit.cover, - fadeInDuration: const Duration(milliseconds: 200), - imageUrl: - getAlbumThumbnailUrl(album, type: ThumbnailFormat.JPEG), - httpHeaders: { - "Authorization": "Bearer ${box.get(accessTokenKey)}" - }, - cacheKey: "${album.albumThumbnailAssetId}", - ), + child: album.albumThumbnailAssetId == null + ? buildEmptyThumbnail() + : buildAlbumThumbnail(), ), Padding( padding: const EdgeInsets.only(top: 8.0), diff --git a/mobile/lib/modules/album/ui/album_viewer_appbar.dart b/mobile/lib/modules/album/ui/album_viewer_appbar.dart index ccc23ca72f..f49082559a 100644 --- a/mobile/lib/modules/album/ui/album_viewer_appbar.dart +++ b/mobile/lib/modules/album/ui/album_viewer_appbar.dart @@ -34,7 +34,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { final newAlbumTitle = ref.watch(albumViewerProvider).editTitleText; final isEditAlbum = ref.watch(albumViewerProvider).isEditAlbum; - void _onDeleteAlbumPressed(String albumId) async { + void onDeleteAlbumPressed(String albumId) async { ImmichLoadingOverlayController.appLoader.show(); bool isSuccess = @@ -62,7 +62,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { ImmichLoadingOverlayController.appLoader.hide(); } - void _onLeaveAlbumPressed(String albumId) async { + void onLeaveAlbumPressed(String albumId) async { ImmichLoadingOverlayController.appLoader.show(); bool isSuccess = @@ -84,7 +84,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { ImmichLoadingOverlayController.appLoader.hide(); } - void _onRemoveFromAlbumPressed(String albumId) async { + void onRemoveFromAlbumPressed(String albumId) async { ImmichLoadingOverlayController.appLoader.show(); bool isSuccess = @@ -110,7 +110,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { ImmichLoadingOverlayController.appLoader.hide(); } - _buildBottomSheetActionButton() { + buildBottomSheetActionButton() { if (isMultiSelectionEnable) { if (albumInfo.ownerId == userId) { return ListTile( @@ -119,7 +119,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { 'album_viewer_appbar_share_remove', style: TextStyle(fontWeight: FontWeight.bold), ).tr(), - onTap: () => _onRemoveFromAlbumPressed(albumId), + onTap: () => onRemoveFromAlbumPressed(albumId), ); } else { return const SizedBox(); @@ -132,7 +132,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { 'album_viewer_appbar_share_delete', style: TextStyle(fontWeight: FontWeight.bold), ).tr(), - onTap: () => _onDeleteAlbumPressed(albumId), + onTap: () => onDeleteAlbumPressed(albumId), ); } else { return ListTile( @@ -141,13 +141,13 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { 'album_viewer_appbar_share_leave', style: TextStyle(fontWeight: FontWeight.bold), ).tr(), - onTap: () => _onLeaveAlbumPressed(albumId), + onTap: () => onLeaveAlbumPressed(albumId), ); } } } - void _buildBottomSheet() { + void buildBottomSheet() { showModalBottomSheet( backgroundColor: Theme.of(context).scaffoldBackgroundColor, isScrollControlled: false, @@ -157,7 +157,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { child: Column( mainAxisSize: MainAxisSize.min, children: [ - _buildBottomSheetActionButton(), + buildBottomSheetActionButton(), ], ), ); @@ -165,7 +165,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { ); } - _buildLeadingButton() { + buildLeadingButton() { if (isMultiSelectionEnable) { return IconButton( onPressed: () => ref @@ -204,7 +204,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { return AppBar( elevation: 0, - leading: _buildLeadingButton(), + leading: buildLeadingButton(), title: isMultiSelectionEnable ? Text('${selectedAssetsInAlbum.length}') : null, @@ -212,7 +212,7 @@ class AlbumViewerAppbar extends HookConsumerWidget with PreferredSizeWidget { actions: [ IconButton( splashRadius: 25, - onPressed: _buildBottomSheet, + onPressed: buildBottomSheet, icon: const Icon(Icons.more_horiz_rounded), ), ], diff --git a/mobile/lib/modules/album/ui/album_viewer_thumbnail.dart b/mobile/lib/modules/album/ui/album_viewer_thumbnail.dart index 6566e76434..e34060def9 100644 --- a/mobile/lib/modules/album/ui/album_viewer_thumbnail.dart +++ b/mobile/lib/modules/album/ui/album_viewer_thumbnail.dart @@ -27,7 +27,7 @@ class AlbumViewerThumbnail extends HookConsumerWidget { final isMultiSelectionEnable = ref.watch(assetSelectionProvider).isMultiselectEnable; - _viewAsset() { + viewAsset() { AutoRouter.of(context).push( GalleryViewerRoute( asset: asset, @@ -47,18 +47,18 @@ class AlbumViewerThumbnail extends HookConsumerWidget { } } - _enableMultiSelection() { + enableMultiSelection() { ref.watch(assetSelectionProvider.notifier).enableMultiselection(); ref .watch(assetSelectionProvider.notifier) .addAssetsInAlbumViewer([asset]); } - _disableMultiSelection() { + disableMultiSelection() { ref.watch(assetSelectionProvider.notifier).disableMultiselection(); } - _buildVideoLabel() { + buildVideoLabel() { return Positioned( top: 5, right: 5, @@ -80,7 +80,7 @@ class AlbumViewerThumbnail extends HookConsumerWidget { ); } - _buildAssetStoreLocationIcon() { + buildAssetStoreLocationIcon() { return Positioned( right: 10, bottom: 5, @@ -94,7 +94,7 @@ class AlbumViewerThumbnail extends HookConsumerWidget { ); } - _buildAssetSelectionIcon() { + buildAssetSelectionIcon() { bool isSelected = selectedAssetsInAlbumViewer.contains(asset); return Positioned( @@ -112,21 +112,21 @@ class AlbumViewerThumbnail extends HookConsumerWidget { ); } - _buildThumbnailImage() { + buildThumbnailImage() { return Container( decoration: BoxDecoration(border: drawBorderColor()), child: ImmichImage(asset, width: 300, height: 300), ); } - _handleSelectionGesture() { + handleSelectionGesture() { if (selectedAssetsInAlbumViewer.contains(asset)) { ref .watch(assetSelectionProvider.notifier) .removeAssetsInAlbumViewer([asset]); if (selectedAssetsInAlbumViewer.isEmpty) { - _disableMultiSelection(); + disableMultiSelection(); } } else { ref @@ -136,14 +136,14 @@ class AlbumViewerThumbnail extends HookConsumerWidget { } return GestureDetector( - onTap: isMultiSelectionEnable ? _handleSelectionGesture : _viewAsset, - onLongPress: _enableMultiSelection, + onTap: isMultiSelectionEnable ? handleSelectionGesture : viewAsset, + onLongPress: enableMultiSelection, child: Stack( children: [ - _buildThumbnailImage(), - if (showStorageIndicator) _buildAssetStoreLocationIcon(), - if (!asset.isImage) _buildVideoLabel(), - if (isMultiSelectionEnable) _buildAssetSelectionIcon(), + buildThumbnailImage(), + if (showStorageIndicator) buildAssetStoreLocationIcon(), + if (!asset.isImage) buildVideoLabel(), + if (isMultiSelectionEnable) buildAssetSelectionIcon(), ], ), ); diff --git a/mobile/lib/modules/album/ui/month_group_title.dart b/mobile/lib/modules/album/ui/month_group_title.dart index e3a772d287..5d33d44ab0 100644 --- a/mobile/lib/modules/album/ui/month_group_title.dart +++ b/mobile/lib/modules/album/ui/month_group_title.dart @@ -21,7 +21,7 @@ class MonthGroupTitle extends HookConsumerWidget { ref.watch(assetSelectionProvider).selectedNewAssetsForAlbum; final isAlbumExist = ref.watch(assetSelectionProvider).isAlbumExist; - _handleTitleIconClick() { + handleTitleIconClick() { HapticFeedback.heavyImpact(); if (isAlbumExist) { @@ -61,7 +61,7 @@ class MonthGroupTitle extends HookConsumerWidget { } } - _getSimplifiedMonth() { + getSimplifiedMonth() { var monthAndYear = month.split(','); var yearText = monthAndYear[1].trim(); var monthText = monthAndYear[0].trim(); @@ -85,7 +85,7 @@ class MonthGroupTitle extends HookConsumerWidget { child: Row( children: [ GestureDetector( - onTap: _handleTitleIconClick, + onTap: handleTitleIconClick, child: selectedDateGroup.contains(month) ? Icon( Icons.check_circle_rounded, @@ -97,11 +97,11 @@ class MonthGroupTitle extends HookConsumerWidget { ), ), GestureDetector( - onTap: _handleTitleIconClick, + onTap: handleTitleIconClick, child: Padding( padding: const EdgeInsets.only(left: 8.0), child: Text( - _getSimplifiedMonth(), + getSimplifiedMonth(), style: TextStyle( fontSize: 24, color: Theme.of(context).primaryColor, diff --git a/mobile/lib/modules/album/ui/selection_thumbnail_image.dart b/mobile/lib/modules/album/ui/selection_thumbnail_image.dart index 09b3160b62..25d8c01de0 100644 --- a/mobile/lib/modules/album/ui/selection_thumbnail_image.dart +++ b/mobile/lib/modules/album/ui/selection_thumbnail_image.dart @@ -18,7 +18,7 @@ class SelectionThumbnailImage extends HookConsumerWidget { ref.watch(assetSelectionProvider).selectedAdditionalAssetsForAlbum; var isAlbumExist = ref.watch(assetSelectionProvider).isAlbumExist; - Widget _buildSelectionIcon(Asset asset) { + Widget buildSelectionIcon(Asset asset) { var isSelected = selectedAsset.map((item) => item.id).contains(asset.id); var isNewlySelected = newAssetsForAlbum.map((item) => item.id).contains(asset.id); @@ -111,7 +111,7 @@ class SelectionThumbnailImage extends HookConsumerWidget { padding: const EdgeInsets.all(3.0), child: Align( alignment: Alignment.topLeft, - child: _buildSelectionIcon(asset), + child: buildSelectionIcon(asset), ), ), if (!asset.isImage) diff --git a/mobile/lib/modules/album/views/album_viewer_page.dart b/mobile/lib/modules/album/views/album_viewer_page.dart index 9e9c4af41a..65db82eb6b 100644 --- a/mobile/lib/modules/album/views/album_viewer_page.dart +++ b/mobile/lib/modules/album/views/album_viewer_page.dart @@ -37,7 +37,7 @@ class AlbumViewerPage extends HookConsumerWidget { /// Find out if the assets in album exist on the device /// If they exist, add to selected asset state to show they are already selected. - void _onAddPhotosPressed(AlbumResponseDto albumInfo) async { + void onAddPhotosPressed(AlbumResponseDto albumInfo) async { if (albumInfo.assets.isNotEmpty == true) { ref.watch(assetSelectionProvider.notifier).addNewAssets( albumInfo.assets.map((e) => Asset.remote(e)).toList(), @@ -60,7 +60,8 @@ class AlbumViewerPage extends HookConsumerWidget { albumId, ); - if (addAssetsResult != null && addAssetsResult.successfullyAdded > 0) { + if (addAssetsResult != null && + addAssetsResult.successfullyAdded > 0) { ref.refresh(sharedAlbumDetailProvider(albumId)); } @@ -73,7 +74,7 @@ class AlbumViewerPage extends HookConsumerWidget { } } - void _onAddUsersPressed(AlbumResponseDto albumInfo) async { + void onAddUsersPressed(AlbumResponseDto albumInfo) async { List? sharedUserIds = await AutoRouter.of(context).push?>( SelectAdditionalUserForSharingRoute(albumInfo: albumInfo), @@ -94,7 +95,7 @@ class AlbumViewerPage extends HookConsumerWidget { } } - Widget _buildTitle(AlbumResponseDto albumInfo) { + Widget buildTitle(AlbumResponseDto albumInfo) { return Padding( padding: const EdgeInsets.only(left: 8, right: 8, top: 16), child: userId == albumInfo.ownerId @@ -115,7 +116,7 @@ class AlbumViewerPage extends HookConsumerWidget { ); } - Widget _buildAlbumDateRange(AlbumResponseDto albumInfo) { + Widget buildAlbumDateRange(AlbumResponseDto albumInfo) { String startDate = ""; DateTime parsedStartDate = DateTime.parse(albumInfo.assets.first.createdAt); @@ -148,14 +149,14 @@ class AlbumViewerPage extends HookConsumerWidget { ); } - Widget _buildHeader(AlbumResponseDto albumInfo) { + Widget buildHeader(AlbumResponseDto albumInfo) { return SliverToBoxAdapter( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - _buildTitle(albumInfo), + buildTitle(albumInfo), if (albumInfo.assets.isNotEmpty == true) - _buildAlbumDateRange(albumInfo), + buildAlbumDateRange(albumInfo), if (albumInfo.shared) SizedBox( height: 60, @@ -188,7 +189,7 @@ class AlbumViewerPage extends HookConsumerWidget { ); } - Widget _buildImageGrid(AlbumResponseDto albumInfo) { + Widget buildImageGrid(AlbumResponseDto albumInfo) { final appSettingService = ref.watch(appSettingsServiceProvider); final bool showStorageIndicator = appSettingService.getSetting(AppSettingsEnum.storageIndicator); @@ -220,7 +221,7 @@ class AlbumViewerPage extends HookConsumerWidget { return const SliverToBoxAdapter(); } - Widget _buildControlButton(AlbumResponseDto albumInfo) { + Widget buildControlButton(AlbumResponseDto albumInfo) { return Padding( padding: const EdgeInsets.only(left: 16.0, top: 8, bottom: 8), child: SizedBox( @@ -230,13 +231,13 @@ class AlbumViewerPage extends HookConsumerWidget { children: [ AlbumActionOutlinedButton( iconData: Icons.add_photo_alternate_outlined, - onPressed: () => _onAddPhotosPressed(albumInfo), + onPressed: () => onAddPhotosPressed(albumInfo), labelText: "share_add_photos".tr(), ), if (userId == albumInfo.ownerId) AlbumActionOutlinedButton( iconData: Icons.person_add_alt_rounded, - onPressed: () => _onAddUsersPressed(albumInfo), + onPressed: () => onAddUsersPressed(albumInfo), labelText: "album_viewer_page_share_add_users".tr(), ), ], @@ -245,7 +246,7 @@ class AlbumViewerPage extends HookConsumerWidget { ); } - Widget _buildBody(AlbumResponseDto albumInfo) { + Widget buildBody(AlbumResponseDto albumInfo) { return GestureDetector( onTap: () { titleFocusNode.unfocus(); @@ -257,7 +258,7 @@ class AlbumViewerPage extends HookConsumerWidget { child: CustomScrollView( controller: scrollController, slivers: [ - _buildHeader(albumInfo), + buildHeader(albumInfo), SliverPersistentHeader( pinned: true, delegate: ImmichSliverPersistentAppBarDelegate( @@ -265,11 +266,11 @@ class AlbumViewerPage extends HookConsumerWidget { maxHeight: 50, child: Container( color: Theme.of(context).scaffoldBackgroundColor, - child: _buildControlButton(albumInfo), + child: buildControlButton(albumInfo), ), ), ), - _buildImageGrid(albumInfo) + buildImageGrid(albumInfo) ], ), ), @@ -293,7 +294,7 @@ class AlbumViewerPage extends HookConsumerWidget { ), body: albumInfo.when( data: (albumInfo) => albumInfo != null - ? _buildBody(albumInfo) + ? buildBody(albumInfo) : const Center( child: CircularProgressIndicator(), ), diff --git a/mobile/lib/modules/album/views/asset_selection_page.dart b/mobile/lib/modules/album/views/asset_selection_page.dart index 226d6b0285..3654545179 100644 --- a/mobile/lib/modules/album/views/asset_selection_page.dart +++ b/mobile/lib/modules/album/views/asset_selection_page.dart @@ -25,7 +25,7 @@ class AssetSelectionPage extends HookConsumerWidget { List imageGridGroup = []; - String _buildAssetCountText() { + String buildAssetCountText() { if (isAlbumExist) { return (selectedAssets.length + newAssetsForAlbum.length).toString(); } else { @@ -33,7 +33,7 @@ class AssetSelectionPage extends HookConsumerWidget { } } - Widget _buildBody() { + Widget buildBody() { assetGroupMonthYear.forEach((monthYear, assetGroup) { imageGridGroup .add(MonthGroupTitle(month: monthYear, assetGroup: assetGroup)); @@ -71,7 +71,7 @@ class AssetSelectionPage extends HookConsumerWidget { style: TextStyle(fontSize: 18), ).tr() : Text( - _buildAssetCountText(), + buildAssetCountText(), style: const TextStyle(fontSize: 18), ), centerTitle: false, @@ -94,7 +94,7 @@ class AssetSelectionPage extends HookConsumerWidget { ), ], ), - body: _buildBody(), + body: buildBody(), ); } } diff --git a/mobile/lib/modules/album/views/create_album_page.dart b/mobile/lib/modules/album/views/create_album_page.dart index 374d8fb12f..18d3d978a8 100644 --- a/mobile/lib/modules/album/views/create_album_page.dart +++ b/mobile/lib/modules/album/views/create_album_page.dart @@ -29,11 +29,11 @@ class CreateAlbumPage extends HookConsumerWidget { ref.watch(assetSelectionProvider).selectedNewAssetsForAlbum; final isDarkTheme = Theme.of(context).brightness == Brightness.dark; - _showSelectUserPage() { + showSelectUserPage() { AutoRouter.of(context).push(const SelectUserForSharingRoute()); } - void _onBackgroundTapped() { + void onBackgroundTapped() { albumTitleTextFieldFocusNode.unfocus(); isAlbumTitleTextFieldFocus.value = false; @@ -45,7 +45,7 @@ class CreateAlbumPage extends HookConsumerWidget { } } - _onSelectPhotosButtonPressed() async { + onSelectPhotosButtonPressed() async { ref.watch(assetSelectionProvider.notifier).setIsAlbumExist(false); AssetSelectionPageResult? selectedAsset = await AutoRouter.of(context) @@ -56,7 +56,7 @@ class CreateAlbumPage extends HookConsumerWidget { } } - _buildTitleInputField() { + buildTitleInputField() { return Padding( padding: const EdgeInsets.only( right: 10, @@ -71,7 +71,7 @@ class CreateAlbumPage extends HookConsumerWidget { ); } - _buildTitle() { + buildTitle() { if (selectedAssets.isEmpty) { return SliverToBoxAdapter( child: Padding( @@ -90,7 +90,7 @@ class CreateAlbumPage extends HookConsumerWidget { return const SliverToBoxAdapter(); } - _buildSelectPhotosButton() { + buildSelectPhotosButton() { if (selectedAssets.isEmpty) { return SliverToBoxAdapter( child: Padding( @@ -109,7 +109,7 @@ class CreateAlbumPage extends HookConsumerWidget { borderRadius: BorderRadius.circular(5), ), ), - onPressed: _onSelectPhotosButtonPressed, + onPressed: onSelectPhotosButtonPressed, icon: Icon( Icons.add_rounded, color: Theme.of(context).primaryColor, @@ -132,7 +132,7 @@ class CreateAlbumPage extends HookConsumerWidget { return const SliverToBoxAdapter(); } - _buildControlButton() { + buildControlButton() { return Padding( padding: const EdgeInsets.only(left: 12.0, top: 16, bottom: 16), child: SizedBox( @@ -142,7 +142,7 @@ class CreateAlbumPage extends HookConsumerWidget { children: [ AlbumActionOutlinedButton( iconData: Icons.add_photo_alternate_outlined, - onPressed: _onSelectPhotosButtonPressed, + onPressed: onSelectPhotosButtonPressed, labelText: "share_add_photos".tr(), ), ], @@ -151,7 +151,7 @@ class CreateAlbumPage extends HookConsumerWidget { ); } - _buildSelectedImageGrid() { + buildSelectedImageGrid() { if (selectedAssets.isNotEmpty) { return SliverPadding( padding: const EdgeInsets.only(top: 16), @@ -164,7 +164,7 @@ class CreateAlbumPage extends HookConsumerWidget { delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return GestureDetector( - onTap: _onBackgroundTapped, + onTap: onBackgroundTapped, child: SharedAlbumThumbnailImage( asset: selectedAssets.elementAt(index), ), @@ -179,7 +179,7 @@ class CreateAlbumPage extends HookConsumerWidget { return const SliverToBoxAdapter(); } - _createNonSharedAlbum() async { + createNonSharedAlbum() async { var newAlbum = await ref.watch(albumProvider.notifier).createAlbum( ref.watch(albumTitleProvider), ref.watch(assetSelectionProvider).selectedNewAssetsForAlbum, @@ -216,7 +216,7 @@ class CreateAlbumPage extends HookConsumerWidget { if (isSharedAlbum) TextButton( onPressed: albumTitleController.text.isNotEmpty - ? _showSelectUserPage + ? showSelectUserPage : null, child: Text( 'create_shared_album_page_share'.tr(), @@ -230,7 +230,7 @@ class CreateAlbumPage extends HookConsumerWidget { TextButton( onPressed: albumTitleController.text.isNotEmpty && selectedAssets.isNotEmpty - ? _createNonSharedAlbum + ? createNonSharedAlbum : null, child: Text( 'create_shared_album_page_create'.tr(), @@ -242,7 +242,7 @@ class CreateAlbumPage extends HookConsumerWidget { ], ), body: GestureDetector( - onTap: _onBackgroundTapped, + onTap: onBackgroundTapped, child: CustomScrollView( slivers: [ SliverAppBar( @@ -255,15 +255,15 @@ class CreateAlbumPage extends HookConsumerWidget { preferredSize: const Size.fromHeight(66.0), child: Column( children: [ - _buildTitleInputField(), - if (selectedAssets.isNotEmpty) _buildControlButton(), + buildTitleInputField(), + if (selectedAssets.isNotEmpty) buildControlButton(), ], ), ), ), - _buildTitle(), - _buildSelectPhotosButton(), - _buildSelectedImageGrid(), + buildTitle(), + buildSelectPhotosButton(), + buildSelectedImageGrid(), ], ), ), diff --git a/mobile/lib/modules/album/views/select_additional_user_for_sharing_page.dart b/mobile/lib/modules/album/views/select_additional_user_for_sharing_page.dart index 61ee9a6e6a..553a4daa87 100644 --- a/mobile/lib/modules/album/views/select_additional_user_for_sharing_page.dart +++ b/mobile/lib/modules/album/views/select_additional_user_for_sharing_page.dart @@ -19,12 +19,12 @@ class SelectAdditionalUserForSharingPage extends HookConsumerWidget { ref.watch(suggestedSharedUsersProvider); final sharedUsersList = useState>({}); - _addNewUsersHandler() { + addNewUsersHandler() { AutoRouter.of(context) .pop(sharedUsersList.value.map((e) => e.id).toList()); } - _buildTileIcon(UserResponseDto user) { + buildTileIcon(UserResponseDto user) { if (sharedUsersList.value.contains(user)) { return CircleAvatar( backgroundColor: Theme.of(context).primaryColor, @@ -42,7 +42,7 @@ class SelectAdditionalUserForSharingPage extends HookConsumerWidget { } } - _buildUserList(List users) { + buildUserList(List users) { List usersChip = []; for (var user in sharedUsersList.value) { @@ -84,7 +84,7 @@ class SelectAdditionalUserForSharingPage extends HookConsumerWidget { shrinkWrap: true, itemBuilder: ((context, index) { return ListTile( - leading: _buildTileIcon(users[index]), + leading: buildTileIcon(users[index]), title: Text( users[index].email, style: const TextStyle( @@ -131,7 +131,7 @@ class SelectAdditionalUserForSharingPage extends HookConsumerWidget { actions: [ TextButton( onPressed: - sharedUsersList.value.isEmpty ? null : _addNewUsersHandler, + sharedUsersList.value.isEmpty ? null : addNewUsersHandler, child: const Text( "share_add", style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold), @@ -147,7 +147,7 @@ class SelectAdditionalUserForSharingPage extends HookConsumerWidget { ); } - return _buildUserList(users); + return buildUserList(users); }, error: (e, _) => Text("Error loading suggested users $e"), loading: () => const Center( diff --git a/mobile/lib/modules/album/views/select_user_for_sharing_page.dart b/mobile/lib/modules/album/views/select_user_for_sharing_page.dart index 19f007b35b..cbccbb1b3d 100644 --- a/mobile/lib/modules/album/views/select_user_for_sharing_page.dart +++ b/mobile/lib/modules/album/views/select_user_for_sharing_page.dart @@ -20,7 +20,7 @@ class SelectUserForSharingPage extends HookConsumerWidget { AsyncValue> suggestedShareUsers = ref.watch(suggestedSharedUsersProvider); - _createSharedAlbum() async { + createSharedAlbum() async { var newAlbum = await ref.watch(sharedAlbumProvider.notifier).createSharedAlbum( ref.watch(albumTitleProvider), @@ -44,7 +44,7 @@ class SelectUserForSharingPage extends HookConsumerWidget { ); } - _buildTileIcon(UserResponseDto user) { + buildTileIcon(UserResponseDto user) { if (sharedUsersList.value.contains(user)) { return CircleAvatar( backgroundColor: Theme.of(context).primaryColor, @@ -62,7 +62,7 @@ class SelectUserForSharingPage extends HookConsumerWidget { } } - _buildUserList(List users) { + buildUserList(List users) { List usersChip = []; for (var user in sharedUsersList.value) { @@ -104,7 +104,7 @@ class SelectUserForSharingPage extends HookConsumerWidget { shrinkWrap: true, itemBuilder: ((context, index) { return ListTile( - leading: _buildTileIcon(users[index]), + leading: buildTileIcon(users[index]), title: Text( users[index].email, style: const TextStyle( @@ -153,8 +153,7 @@ class SelectUserForSharingPage extends HookConsumerWidget { style: TextButton.styleFrom( foregroundColor: Theme.of(context).primaryColor, ), - onPressed: - sharedUsersList.value.isEmpty ? null : _createSharedAlbum, + onPressed: sharedUsersList.value.isEmpty ? null : createSharedAlbum, child: const Text( "share_create_album", style: TextStyle( @@ -168,7 +167,7 @@ class SelectUserForSharingPage extends HookConsumerWidget { ), body: suggestedShareUsers.when( data: (users) { - return _buildUserList(users); + return buildUserList(users); }, error: (e, _) => Text("Error loading suggested users $e"), loading: () => const Center( diff --git a/mobile/lib/modules/album/views/sharing_page.dart b/mobile/lib/modules/album/views/sharing_page.dart index cb04ebf759..492e141468 100644 --- a/mobile/lib/modules/album/views/sharing_page.dart +++ b/mobile/lib/modules/album/views/sharing_page.dart @@ -28,7 +28,7 @@ class SharingPage extends HookConsumerWidget { [], ); - _buildAlbumList() { + buildAlbumList() { return SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { @@ -71,7 +71,7 @@ class SharingPage extends HookConsumerWidget { ); } - _buildEmptyListIndication() { + buildEmptyListIndication() { return SliverToBoxAdapter( child: Padding( padding: const EdgeInsets.all(8.0), @@ -136,8 +136,8 @@ class SharingPage extends HookConsumerWidget { ), ), sharedAlbums.isNotEmpty - ? _buildAlbumList() - : _buildEmptyListIndication() + ? buildAlbumList() + : buildEmptyListIndication() ], ), ); diff --git a/mobile/lib/modules/asset_viewer/providers/image_viewer_page_state.provider.dart b/mobile/lib/modules/asset_viewer/providers/image_viewer_page_state.provider.dart index 6d3ae83842..8bedafc762 100644 --- a/mobile/lib/modules/asset_viewer/providers/image_viewer_page_state.provider.dart +++ b/mobile/lib/modules/asset_viewer/providers/image_viewer_page_state.provider.dart @@ -64,5 +64,7 @@ class ImageViewerStateNotifier extends StateNotifier { final imageViewerStateProvider = StateNotifierProvider( ((ref) => ImageViewerStateNotifier( - ref.watch(imageViewerServiceProvider), ref.watch(shareServiceProvider))), + ref.watch(imageViewerServiceProvider), + ref.watch(shareServiceProvider), + )), ); diff --git a/mobile/lib/modules/asset_viewer/ui/exif_bottom_sheet.dart b/mobile/lib/modules/asset_viewer/ui/exif_bottom_sheet.dart index bb88d54e60..23dd1ccb0d 100644 --- a/mobile/lib/modules/asset_viewer/ui/exif_bottom_sheet.dart +++ b/mobile/lib/modules/asset_viewer/ui/exif_bottom_sheet.dart @@ -6,6 +6,7 @@ import 'package:immich_mobile/shared/models/asset.dart'; import 'package:openapi/api.dart'; import 'package:path/path.dart' as p; import 'package:latlong2/latlong.dart'; +import 'package:immich_mobile/utils/bytes_units.dart'; class ExifBottomSheet extends ConsumerWidget { final Asset assetDetail; @@ -15,7 +16,7 @@ class ExifBottomSheet extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - _buildMap() { + buildMap() { return Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Container( @@ -66,7 +67,7 @@ class ExifBottomSheet extends ConsumerWidget { ExifResponseDto? exifInfo = assetDetail.remote?.exifInfo; - _buildLocationText() { + buildLocationText() { return Text( "${exifInfo?.city}, ${exifInfo?.state}", style: TextStyle( @@ -120,11 +121,11 @@ class ExifBottomSheet extends ConsumerWidget { ).tr(), if (assetDetail.latitude != null && assetDetail.longitude != null) - _buildMap(), + buildMap(), if (exifInfo != null && exifInfo.city != null && exifInfo.state != null) - _buildLocationText(), + buildLocationText(), Text( "${assetDetail.latitude?.toStringAsFixed(4)}, ${assetDetail.longitude?.toStringAsFixed(4)}", style: TextStyle(fontSize: 12, color: Colors.grey[400]), @@ -162,7 +163,7 @@ class ExifBottomSheet extends ConsumerWidget { ), subtitle: exifInfo.exifImageHeight != null ? Text( - "${exifInfo.exifImageHeight} x ${exifInfo.exifImageWidth} ${exifInfo.fileSizeInByte!}B ", + "${exifInfo.exifImageHeight} x ${exifInfo.exifImageWidth} ${formatBytes(exifInfo.fileSizeInByte!)} ", ) : null, ), @@ -178,7 +179,7 @@ class ExifBottomSheet extends ConsumerWidget { style: const TextStyle(fontWeight: FontWeight.bold), ), subtitle: Text( - "ƒ/${exifInfo.fNumber} 1/${(1 / (exifInfo.exposureTime ?? 1)).toStringAsFixed(0)} ${exifInfo.focalLength}mm ISO${exifInfo.iso} ", + "ƒ/${exifInfo.fNumber} 1/${(1 / (exifInfo.exposureTime ?? 1)).toStringAsFixed(0)} ${exifInfo.focalLength} mm ISO${exifInfo.iso} ", ), ), ], diff --git a/mobile/lib/modules/backup/background_service/background.service.dart b/mobile/lib/modules/backup/background_service/background.service.dart index 69000c3ba5..8b48934917 100644 --- a/mobile/lib/modules/backup/background_service/background.service.dart +++ b/mobile/lib/modules/backup/background_service/background.service.dart @@ -349,7 +349,6 @@ class BackgroundService { Hive.openBox(duplicatedAssetsBox), Hive.openBox(hiveBackupInfoBox), ]); - ApiService apiService = ApiService(); apiService.setEndpoint(Hive.box(userInfoBox).get(serverEndpointKey)); apiService.setAccessToken(Hive.box(userInfoBox).get(accessTokenKey)); diff --git a/mobile/lib/modules/backup/background_service/localization.dart b/mobile/lib/modules/backup/background_service/localization.dart index 1e8c9142ed..a0c1610ece 100644 --- a/mobile/lib/modules/backup/background_service/localization.dart +++ b/mobile/lib/modules/backup/background_service/localization.dart @@ -1,3 +1,5 @@ +// ignore_for_file: implementation_imports + import 'package:flutter/foundation.dart'; import 'package:easy_localization/src/asset_loader.dart'; import 'package:easy_localization/src/easy_localization_controller.dart'; diff --git a/mobile/lib/modules/backup/providers/backup.provider.dart b/mobile/lib/modules/backup/providers/backup.provider.dart index ddf58fea84..aabad64c1e 100644 --- a/mobile/lib/modules/backup/providers/backup.provider.dart +++ b/mobile/lib/modules/backup/providers/backup.provider.dart @@ -1,7 +1,7 @@ import 'dart:io'; import 'package:cancellation_token_http/http.dart'; -import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:immich_mobile/constants/hive_box.dart'; @@ -18,6 +18,7 @@ import 'package:immich_mobile/modules/login/models/authentication_state.model.da import 'package:immich_mobile/modules/login/providers/authentication.provider.dart'; import 'package:immich_mobile/shared/providers/app_state.provider.dart'; import 'package:immich_mobile/shared/services/server_info.service.dart'; +import 'package:logging/logging.dart'; import 'package:openapi/api.dart'; import 'package:photo_manager/photo_manager.dart'; @@ -62,6 +63,7 @@ class BackupNotifier extends StateNotifier { getBackupInfo(); } + final log = Logger('BackupNotifier'); final BackupService _backupService; final ServerInfoService _serverInfoService; final AuthenticationState _authState; @@ -171,9 +173,10 @@ class BackupNotifier extends StateNotifier { /// Get all album on the device /// Get all selected and excluded album from the user's persistent storage /// If this is the first time performing backup - set the default selected album to be - /// the one that has all assets (Recent on Android, Recents on iOS) + /// the one that has all assets (`Recent` on Android, `Recents` on iOS) /// Future _getBackupAlbumsInfo() async { + Stopwatch stopwatch = Stopwatch()..start(); // Get all albums on the device List availableAlbums = []; List albums = await PhotoManager.getAssetPathList( @@ -181,6 +184,8 @@ class BackupNotifier extends StateNotifier { type: RequestType.common, ); + log.info('Found ${albums.length} local albums'); + for (AssetPathEntity album in albums) { AvailableAlbum availableAlbum = AvailableAlbum(albumEntity: album); @@ -218,13 +223,16 @@ class BackupNotifier extends StateNotifier { ); if (backupAlbumInfo == null) { - debugPrint("[ERROR] getting Hive backup album infomation"); + log.severe( + "backupAlbumInfo == null", + "Failed to get Hive backup album information", + ); return; } // First time backup - set isAll album is the default one for backup. if (backupAlbumInfo.selectedAlbumIds.isEmpty) { - debugPrint("First time backup setup recent album as default"); + log.info("First time backup; setup 'Recent(s)' album as default"); // Get album that contains all assets var list = await PhotoManager.getAssetPathList( @@ -286,9 +294,11 @@ class BackupNotifier extends StateNotifier { selectedBackupAlbums: selectedAlbums, excludedBackupAlbums: excludedAlbums, ); - } catch (e) { - debugPrint("[ERROR] Failed to generate album from id $e"); + } catch (e, stackTrace) { + log.severe("Failed to generate album from id", e, stackTrace); } + + debugPrint("_getBackupAlbumsInfo takes ${stopwatch.elapsedMilliseconds}ms"); } /// @@ -338,7 +348,7 @@ class BackupNotifier extends StateNotifier { ); if (allUniqueAssets.isEmpty) { - debugPrint("No Asset On Device"); + log.info("Not found albums or assets on the device to backup"); state = state.copyWith( backupProgress: BackUpProgressEnum.idle, allAssetsInDatabase: allAssetsInDatabase, @@ -360,14 +370,14 @@ class BackupNotifier extends StateNotifier { return; } - /// /// Get all necessary information for calculating the available albums, /// which albums are selected or excluded /// and then update the UI according to those information - /// Future getBackupInfo() async { - final bool isEnabled = await _backgroundService.isBackgroundBackupEnabled(); + var isEnabled = await _backgroundService.isBackgroundBackupEnabled(); + state = state.copyWith(backgroundBackup: isEnabled); + if (state.backupProgress != BackUpProgressEnum.inBackground) { await _getBackupAlbumsInfo(); await _updateServerInfo(); @@ -375,10 +385,8 @@ class BackupNotifier extends StateNotifier { } } - /// /// Save user selection of selected albums and excluded albums to /// Hive database - /// void _updatePersistentAlbumsSelection() { final epoch = DateTime.fromMillisecondsSinceEpoch(0, isUtc: true); Box backupAlbumInfoBox = @@ -398,10 +406,9 @@ class BackupNotifier extends StateNotifier { ); } - /// /// Invoke backup process - /// Future startBackupProcess() async { + debugPrint("Start backup process"); assert(state.backupProgress == BackUpProgressEnum.idle); state = state.copyWith(backupProgress: BackUpProgressEnum.inProgress); @@ -412,13 +419,12 @@ class BackupNotifier extends StateNotifier { await PhotoManager.clearFileCache(); if (state.allUniqueAssets.isEmpty) { - debugPrint("No Asset On Device - Abort Backup Process"); + log.info("No Asset On Device - Abort Backup Process"); state = state.copyWith(backupProgress: BackUpProgressEnum.idle); return; } Set assetsWillBeBackup = Set.from(state.allUniqueAssets); - // Remove item that has already been backed up for (var assetId in state.allAssetsInDatabase) { assetsWillBeBackup.removeWhere((e) => e.id == assetId); @@ -530,7 +536,7 @@ class BackupNotifier extends StateNotifier { // User has been logged out return if (accessKey == null || !_authState.isAuthenticated) { - debugPrint("[resumeBackup] not authenticated - abort"); + log.info("[_resumeBackup] not authenticated - abort"); return; } @@ -539,17 +545,17 @@ class BackupNotifier extends StateNotifier { _authState.deviceInfo.isAutoBackup) { // check if backup is alreayd in process - then return if (state.backupProgress == BackUpProgressEnum.inProgress) { - debugPrint("[resumeBackup] Backup is already in progress - abort"); + log.info("[_resumeBackup] Backup is already in progress - abort"); return; } if (state.backupProgress == BackUpProgressEnum.inBackground) { - debugPrint("[resumeBackup] Background backup is running - abort"); + log.info("[_resumeBackup] Background backup is running - abort"); return; } // Run backup - debugPrint("[resumeBackup] Start back up"); + log.info("[_resumeBackup] Start back up"); await startBackupProcess(); } @@ -565,7 +571,7 @@ class BackupNotifier extends StateNotifier { state = state.copyWith(backupProgress: BackUpProgressEnum.inBackground); final bool hasLock = await _backgroundService.acquireLock(); if (!hasLock) { - debugPrint("WARNING [resumeBackup] failed to acquireLock"); + log.warning("WARNING [resumeBackup] failed to acquireLock"); return; } await Future.wait([ @@ -612,7 +618,11 @@ class BackupNotifier extends StateNotifier { AvailableAlbum a = albums.firstWhere((e) => e.id == ids[i]); result.add(a.copyWith(lastBackup: times[i])); } on StateError { - debugPrint("[_updateAlbumBackupTime] failed to find album in state"); + log.severe( + "[_updateAlbumBackupTime] failed to find album in state", + "State Error", + StackTrace.current, + ); } } return result; @@ -631,21 +641,29 @@ class BackupNotifier extends StateNotifier { await Hive.box(hiveBackupInfoBox).close(); } } catch (error) { - debugPrint("[_notifyBackgroundServiceCanRun] failed to close box"); + log.info("[_notifyBackgroundServiceCanRun] failed to close box"); } try { if (Hive.isBoxOpen(duplicatedAssetsBox)) { await Hive.box(duplicatedAssetsBox).close(); } - } catch (error) { - debugPrint("[_notifyBackgroundServiceCanRun] failed to close box"); + } catch (error, stackTrace) { + log.severe( + "[_notifyBackgroundServiceCanRun] failed to close box", + error, + stackTrace, + ); } try { if (Hive.isBoxOpen(backgroundBackupInfoBox)) { await Hive.box(backgroundBackupInfoBox).close(); } - } catch (error) { - debugPrint("[_notifyBackgroundServiceCanRun] failed to close box"); + } catch (error, stackTrace) { + log.severe( + "[_notifyBackgroundServiceCanRun] failed to close box", + error, + stackTrace, + ); } _backgroundService.releaseLock(); } diff --git a/mobile/lib/modules/backup/ui/album_info_card.dart b/mobile/lib/modules/backup/ui/album_info_card.dart index 51b48f8fe2..952d4393ed 100644 --- a/mobile/lib/modules/backup/ui/album_info_card.dart +++ b/mobile/lib/modules/backup/ui/album_info_card.dart @@ -33,7 +33,7 @@ class AlbumInfoCard extends HookConsumerWidget { ColorFilter unselectedFilter = const ColorFilter.mode(Colors.black, BlendMode.color); - _buildSelectedTextBox() { + buildSelectedTextBox() { if (isSelected) { return Chip( visualDensity: VisualDensity.compact, @@ -67,7 +67,7 @@ class AlbumInfoCard extends HookConsumerWidget { return const SizedBox(); } - _buildImageFilter() { + buildImageFilter() { if (isSelected) { return selectedFilter; } else if (isExcluded) { @@ -163,7 +163,7 @@ class AlbumInfoCard extends HookConsumerWidget { topRight: Radius.circular(12), ), image: DecorationImage( - colorFilter: _buildImageFilter(), + colorFilter: buildImageFilter(), image: imageData != null ? MemoryImage(imageData!) : const AssetImage( @@ -177,7 +177,7 @@ class AlbumInfoCard extends HookConsumerWidget { Positioned( bottom: 10, left: 25, - child: _buildSelectedTextBox(), + child: buildSelectedTextBox(), ) ], ), diff --git a/mobile/lib/modules/backup/views/album_preview_page.dart b/mobile/lib/modules/backup/views/album_preview_page.dart index afca75be1f..27ca79082b 100644 --- a/mobile/lib/modules/backup/views/album_preview_page.dart +++ b/mobile/lib/modules/backup/views/album_preview_page.dart @@ -15,14 +15,16 @@ class AlbumPreviewPage extends HookConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final assets = useState>([]); - _getAssetsInAlbum() async { + getAssetsInAlbum() async { assets.value = await album.getAssetListRange( - start: 0, end: await album.assetCountAsync); + start: 0, + end: await album.assetCountAsync, + ); } useEffect( () { - _getAssetsInAlbum(); + getAssetsInAlbum(); return null; }, [], @@ -34,7 +36,7 @@ class AlbumPreviewPage extends HookConsumerWidget { title: Column( children: [ Text( - "${album.name} (${album.assetCountAsync})", + album.name, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold), ), Padding( diff --git a/mobile/lib/modules/backup/views/backup_album_selection_page.dart b/mobile/lib/modules/backup/views/backup_album_selection_page.dart index 59893117e2..3de7294742 100644 --- a/mobile/lib/modules/backup/views/backup_album_selection_page.dart +++ b/mobile/lib/modules/backup/views/backup_album_selection_page.dart @@ -5,6 +5,7 @@ import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:immich_mobile/constants/immich_colors.dart'; +import 'package:immich_mobile/modules/backup/models/available_album.model.dart'; import 'package:immich_mobile/modules/backup/providers/backup.provider.dart'; import 'package:immich_mobile/modules/backup/ui/album_info_card.dart'; import 'package:immich_mobile/shared/ui/immich_loading_indicator.dart'; @@ -14,10 +15,13 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { const BackupAlbumSelectionPage({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { - final availableAlbums = ref.watch(backupProvider).availableAlbums; + // final availableAlbums = ref.watch(backupProvider).availableAlbums; final selectedBackupAlbums = ref.watch(backupProvider).selectedBackupAlbums; final excludedBackupAlbums = ref.watch(backupProvider).excludedBackupAlbums; final isDarkTheme = Theme.of(context).brightness == Brightness.dark; + final albums = useState>( + ref.watch(backupProvider).availableAlbums, + ); useEffect( () { @@ -27,8 +31,8 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { [], ); - _buildAlbumSelectionList() { - if (availableAlbums.isEmpty) { + buildAlbumSelectionList() { + if (albums.value.isEmpty) { return const Center( child: ImmichLoadingIndicator(), ); @@ -38,17 +42,17 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { height: 265, child: ListView.builder( scrollDirection: Axis.horizontal, - itemCount: availableAlbums.length, + itemCount: albums.value.length, physics: const BouncingScrollPhysics(), itemBuilder: ((context, index) { - var thumbnailData = availableAlbums[index].thumbnailData; + var thumbnailData = albums.value[index].thumbnailData; return Padding( padding: index == 0 ? const EdgeInsets.only(left: 16.00) : const EdgeInsets.all(0), child: AlbumInfoCard( imageData: thumbnailData, - albumInfo: availableAlbums[index], + albumInfo: albums.value[index], ), ); }), @@ -56,7 +60,7 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { ); } - _buildSelectedAlbumNameChip() { + buildSelectedAlbumNameChip() { return selectedBackupAlbums.map((album) { void removeSelection() { if (ref.watch(backupProvider).selectedBackupAlbums.length == 1) { @@ -79,15 +83,13 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { child: Chip( visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(5), + borderRadius: BorderRadius.circular(10), ), label: Text( album.name, style: TextStyle( fontSize: 10, - color: Theme.of(context).brightness == Brightness.dark - ? Colors.black - : Colors.white, + color: isDarkTheme ? Colors.black : Colors.white, fontWeight: FontWeight.bold, ), ), @@ -104,7 +106,7 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { }).toSet(); } - _buildExcludedAlbumNameChip() { + buildExcludedAlbumNameChip() { return excludedBackupAlbums.map((album) { void removeSelection() { ref @@ -119,7 +121,7 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { child: Chip( visualDensity: VisualDensity.compact, shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(5), + borderRadius: BorderRadius.circular(10), ), label: Text( album.name, @@ -143,6 +145,46 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { }).toSet(); } + buildSearchBar() { + return Padding( + padding: const EdgeInsets.only(left: 16.0, right: 16, bottom: 8.0), + child: TextFormField( + onChanged: (searchValue) { + albums.value = ref + .watch(backupProvider) + .availableAlbums + .where( + (album) => album.name + .toLowerCase() + .contains(searchValue.toLowerCase()), + ) + .toList(); + }, + decoration: InputDecoration( + contentPadding: const EdgeInsets.symmetric( + horizontal: 8.0, + vertical: 8.0, + ), + hintText: "Search", + hintStyle: TextStyle( + color: isDarkTheme ? Colors.white : Colors.grey, + fontSize: 14.0, + ), + prefixIcon: const Icon( + Icons.search, + color: Colors.grey, + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide.none, + ), + filled: true, + fillColor: isDarkTheme ? Colors.white30 : Colors.grey[200], + ), + ), + ); + } + return Scaffold( appBar: AppBar( leading: IconButton( @@ -177,8 +219,8 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Wrap( children: [ - ..._buildSelectedAlbumNameChip(), - ..._buildExcludedAlbumNameChip() + ...buildSelectedAlbumNameChip(), + ...buildExcludedAlbumNameChip() ], ), ), @@ -188,7 +230,7 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { child: Card( margin: const EdgeInsets.all(0), shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(5), + borderRadius: BorderRadius.circular(10), side: BorderSide( color: isDarkTheme ? const Color.fromARGB(255, 0, 0, 0) @@ -225,8 +267,11 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { ListTile( title: Text( - "backup_album_selection_page_albums_device" - .tr(args: [availableAlbums.length.toString()]), + "backup_album_selection_page_albums_device".tr( + args: [ + ref.watch(backupProvider).availableAlbums.length.toString() + ], + ), style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 14), ), subtitle: Padding( @@ -254,7 +299,7 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), + borderRadius: BorderRadius.circular(10), ), elevation: 5, title: Text( @@ -284,9 +329,11 @@ class BackupAlbumSelectionPage extends HookConsumerWidget { ), ), + buildSearchBar(), + Padding( padding: const EdgeInsets.only(bottom: 16.0), - child: _buildAlbumSelectionList(), + child: buildAlbumSelectionList(), ), ], ), diff --git a/mobile/lib/modules/backup/views/backup_controller_page.dart b/mobile/lib/modules/backup/views/backup_controller_page.dart index a734de85f0..1ca866b0df 100644 --- a/mobile/lib/modules/backup/views/backup_controller_page.dart +++ b/mobile/lib/modules/backup/views/backup_controller_page.dart @@ -45,7 +45,7 @@ class BackupControllerPage extends HookConsumerWidget { [], ); - Widget _buildStorageInformation() { + Widget buildStorageInformation() { return ListTile( leading: Icon( Icons.storage_rounded, @@ -84,7 +84,7 @@ class BackupControllerPage extends HookConsumerWidget { ); } - ListTile _buildAutoBackupController() { + ListTile buildAutoBackupController() { var backUpOption = authenticationState.deviceInfo.isAutoBackup ? "backup_controller_page_status_on".tr() : "backup_controller_page_status_off".tr(); @@ -143,7 +143,7 @@ class BackupControllerPage extends HookConsumerWidget { ); } - void _showErrorToUser(String msg) { + void showErrorToUser(String msg) { final snackBar = SnackBar( content: Text( msg.tr(), @@ -153,7 +153,7 @@ class BackupControllerPage extends HookConsumerWidget { ScaffoldMessenger.of(context).showSnackBar(snackBar); } - void _showBatteryOptimizationInfoToUser() { + void showBatteryOptimizationInfoToUser() { showDialog( context: context, barrierDismissible: false, @@ -193,7 +193,7 @@ class BackupControllerPage extends HookConsumerWidget { ); } - ListTile _buildBackgroundBackupController() { + ListTile buildBackgroundBackupController() { final bool isBackgroundEnabled = backupState.backgroundBackup; final bool isWifiRequired = backupState.backupRequireWifi; final bool isChargingRequired = backupState.backupRequireCharging; @@ -238,8 +238,8 @@ class BackupControllerPage extends HookConsumerWidget { .read(backupProvider.notifier) .configureBackgroundBackup( requireWifi: isChecked, - onError: _showErrorToUser, - onBatteryInfo: _showBatteryOptimizationInfoToUser, + onError: showErrorToUser, + onBatteryInfo: showBatteryOptimizationInfoToUser, ) : null, ), @@ -259,8 +259,8 @@ class BackupControllerPage extends HookConsumerWidget { .read(backupProvider.notifier) .configureBackgroundBackup( requireCharging: isChecked, - onError: _showErrorToUser, - onBatteryInfo: _showBatteryOptimizationInfoToUser, + onError: showErrorToUser, + onBatteryInfo: showBatteryOptimizationInfoToUser, ) : null, ), @@ -268,8 +268,8 @@ class BackupControllerPage extends HookConsumerWidget { onPressed: () => ref.read(backupProvider.notifier).configureBackgroundBackup( enabled: !isBackgroundEnabled, - onError: _showErrorToUser, - onBatteryInfo: _showBatteryOptimizationInfoToUser, + onError: showErrorToUser, + onBatteryInfo: showBatteryOptimizationInfoToUser, ), child: Text( isBackgroundEnabled @@ -284,7 +284,7 @@ class BackupControllerPage extends HookConsumerWidget { ); } - Widget _buildSelectedAlbumName() { + Widget buildSelectedAlbumName() { var text = "backup_controller_page_backup_selected".tr(); var albums = ref.watch(backupProvider).selectedBackupAlbums; @@ -323,7 +323,7 @@ class BackupControllerPage extends HookConsumerWidget { } } - Widget _buildExcludedAlbumName() { + Widget buildExcludedAlbumName() { var text = "backup_controller_page_excluded".tr(); var albums = ref.watch(backupProvider).excludedBackupAlbums; @@ -348,7 +348,7 @@ class BackupControllerPage extends HookConsumerWidget { } } - _buildFolderSelectionTile() { + buildFolderSelectionTile() { return Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5), // if you need this @@ -374,8 +374,8 @@ class BackupControllerPage extends HookConsumerWidget { "backup_controller_page_to_backup", style: TextStyle(fontSize: 12), ).tr(), - _buildSelectedAlbumName(), - _buildExcludedAlbumName() + buildSelectedAlbumName(), + buildExcludedAlbumName() ], ), ), @@ -398,7 +398,7 @@ class BackupControllerPage extends HookConsumerWidget { ); } - _buildCurrentBackupAssetInfoCard() { + buildCurrentBackupAssetInfoCard() { return ListTile( leading: Icon( Icons.info_outline_rounded, @@ -606,7 +606,7 @@ class BackupControllerPage extends HookConsumerWidget { ), ), ), - _buildFolderSelectionTile(), + buildFolderSelectionTile(), BackupInfoCard( title: "backup_controller_page_total".tr(), subtitle: "backup_controller_page_total_sub".tr(), @@ -624,13 +624,13 @@ class BackupControllerPage extends HookConsumerWidget { "${backupState.allUniqueAssets.length - backupState.selectedAlbumsBackupAssetsIds.length}", ), const Divider(), - _buildAutoBackupController(), + buildAutoBackupController(), if (Platform.isAndroid) const Divider(), - if (Platform.isAndroid) _buildBackgroundBackupController(), + if (Platform.isAndroid) buildBackgroundBackupController(), const Divider(), - _buildStorageInformation(), + buildStorageInformation(), const Divider(), - _buildCurrentBackupAssetInfoCard(), + buildCurrentBackupAssetInfoCard(), Padding( padding: const EdgeInsets.only( top: 24, diff --git a/mobile/lib/modules/home/services/asset.service.dart b/mobile/lib/modules/home/services/asset.service.dart index 3dbf0e8d3e..0599d0c547 100644 --- a/mobile/lib/modules/home/services/asset.service.dart +++ b/mobile/lib/modules/home/services/asset.service.dart @@ -10,8 +10,10 @@ import 'package:immich_mobile/modules/backup/services/backup.service.dart'; import 'package:immich_mobile/shared/models/asset.dart'; import 'package:immich_mobile/shared/providers/api.provider.dart'; import 'package:immich_mobile/shared/services/api.service.dart'; +import 'package:immich_mobile/utils/openapi_extensions.dart'; +import 'package:immich_mobile/utils/tuple.dart'; +import 'package:logging/logging.dart'; import 'package:openapi/api.dart'; -import 'package:photo_manager/src/types/entity.dart'; final assetServiceProvider = Provider( (ref) => AssetService( @@ -25,42 +27,31 @@ class AssetService { final ApiService _apiService; final BackupService _backupService; final BackgroundService _backgroundService; + final log = Logger('AssetService'); AssetService(this._apiService, this._backupService, this._backgroundService); - /// Returns all local, remote assets in that order - Future> getAllAsset({bool urgent = false}) async { - final List assets = []; + /// Returns `null` if the server state did not change, else list of assets + Future?> getRemoteAssets({required bool hasCache}) async { try { - // not using `await` here to fetch local & remote assets concurrently - final Future?> remoteTask = - _apiService.assetApi.getAllAssets(); - final Iterable newLocalAssets; - final List localAssets = await _getLocalAssets(urgent); - final List remoteAssets = await remoteTask ?? []; - if (remoteAssets.isNotEmpty && localAssets.isNotEmpty) { - final String deviceId = Hive.box(userInfoBox).get(deviceIdKey); - final Set existingIds = remoteAssets - .where((e) => e.deviceId == deviceId) - .map((e) => e.deviceAssetId) - .toSet(); - newLocalAssets = localAssets.where((e) => !existingIds.contains(e.id)); - } else { - newLocalAssets = localAssets; + final Box box = Hive.box(userInfoBox); + final Pair, String?>? remote = await _apiService + .assetApi + .getAllAssetsWithETag(eTag: hasCache ? box.get(assetEtagKey) : null); + if (remote == null) { + return null; } - - assets.addAll(newLocalAssets.map((e) => Asset.local(e))); - // the order (first all local, then remote assets) is important! - assets.addAll(remoteAssets.map((e) => Asset.remote(e))); - } catch (e) { - debugPrint("Error [getAllAsset] ${e.toString()}"); + box.put(assetEtagKey, remote.second); + return remote.first.map(Asset.remote).toList(growable: false); + } catch (e, stack) { + log.severe('Error while getting remote assets', e, stack); + return null; } - return assets; } /// if [urgent] is `true`, do not block by waiting on the background service - /// to finish running. Returns an empty list instead after a timeout. - Future> _getLocalAssets(bool urgent) async { + /// to finish running. Returns `null` instead after a timeout. + Future?> getLocalAssets({bool urgent = false}) async { try { final Future hasAccess = urgent ? _backgroundService.hasAccess @@ -71,15 +62,16 @@ class AssetService { } final box = await Hive.openBox(hiveBackupInfoBox); final HiveBackupAlbums? backupAlbumInfo = box.get(backupInfoKey); - - return backupAlbumInfo != null - ? await _backupService - .buildUploadCandidates(backupAlbumInfo.deepCopy()) - : []; + if (backupAlbumInfo != null) { + return (await _backupService + .buildUploadCandidates(backupAlbumInfo.deepCopy())) + .map(Asset.local) + .toList(growable: false); + } } catch (e) { debugPrint("Error [_getLocalAssets] ${e.toString()}"); - return []; } + return null; } Future getAssetById(String assetId) async { diff --git a/mobile/lib/modules/home/ui/immich_sliver_appbar.dart b/mobile/lib/modules/home/ui/immich_sliver_appbar.dart index 63761c5783..aeac61c9dc 100644 --- a/mobile/lib/modules/home/ui/immich_sliver_appbar.dart +++ b/mobile/lib/modules/home/ui/immich_sliver_appbar.dart @@ -32,7 +32,9 @@ class ImmichSliverAppBar extends ConsumerWidget { snap: false, backgroundColor: Theme.of(context).appBarTheme.backgroundColor, shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(5)), + borderRadius: BorderRadius.all( + Radius.circular(5), + ), ), leading: Builder( builder: (BuildContext context) { diff --git a/mobile/lib/modules/home/ui/profile_drawer/profile_drawer.dart b/mobile/lib/modules/home/ui/profile_drawer/profile_drawer.dart index d8bb50c329..04e7e648e8 100644 --- a/mobile/lib/modules/home/ui/profile_drawer/profile_drawer.dart +++ b/mobile/lib/modules/home/ui/profile_drawer/profile_drawer.dart @@ -2,12 +2,12 @@ import 'package:auto_route/auto_route.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:immich_mobile/modules/backup/providers/backup.provider.dart'; import 'package:immich_mobile/modules/home/ui/profile_drawer/profile_drawer_header.dart'; import 'package:immich_mobile/modules/home/ui/profile_drawer/server_info_box.dart'; +import 'package:immich_mobile/modules/login/providers/authentication.provider.dart'; import 'package:immich_mobile/routing/router.dart'; import 'package:immich_mobile/shared/providers/asset.provider.dart'; -import 'package:immich_mobile/modules/login/providers/authentication.provider.dart'; -import 'package:immich_mobile/modules/backup/providers/backup.provider.dart'; import 'package:immich_mobile/shared/providers/websocket.provider.dart'; class ProfileDrawer extends HookConsumerWidget { @@ -15,7 +15,7 @@ class ProfileDrawer extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - _buildSignoutButton() { + buildSignoutButton() { return ListTile( horizontalTitleGap: 0, leading: SizedBox( @@ -46,7 +46,7 @@ class ProfileDrawer extends HookConsumerWidget { ); } - _buildSettingButton() { + buildSettingButton() { return ListTile( horizontalTitleGap: 0, leading: SizedBox( @@ -70,6 +70,30 @@ class ProfileDrawer extends HookConsumerWidget { ); } + buildAppLogButton() { + return ListTile( + horizontalTitleGap: 0, + leading: SizedBox( + height: double.infinity, + child: Icon( + Icons.assignment_outlined, + color: Theme.of(context).textTheme.labelMedium?.color, + size: 20, + ), + ), + title: Text( + "profile_drawer_app_logs", + style: Theme.of(context) + .textTheme + .labelLarge + ?.copyWith(fontWeight: FontWeight.bold), + ).tr(), + onTap: () { + AutoRouter.of(context).push(const AppLogRoute()); + }, + ); + } + return Drawer( child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -79,8 +103,9 @@ class ProfileDrawer extends HookConsumerWidget { padding: EdgeInsets.zero, children: [ const ProfileDrawerHeader(), - _buildSettingButton(), - _buildSignoutButton(), + buildSettingButton(), + buildAppLogButton(), + buildSignoutButton(), ], ), const ServerInfoBox() diff --git a/mobile/lib/modules/home/ui/profile_drawer/profile_drawer_header.dart b/mobile/lib/modules/home/ui/profile_drawer/profile_drawer_header.dart index d8187b8c5e..1c08cb7b71 100644 --- a/mobile/lib/modules/home/ui/profile_drawer/profile_drawer_header.dart +++ b/mobile/lib/modules/home/ui/profile_drawer/profile_drawer_header.dart @@ -25,7 +25,7 @@ class ProfileDrawerHeader extends HookConsumerWidget { var dummmy = Random().nextInt(1024); final isDarkMode = Theme.of(context).brightness == Brightness.dark; - _buildUserProfileImage() { + buildUserProfileImage() { if (authState.profileImagePath.isEmpty) { return const CircleAvatar( radius: 35, @@ -77,7 +77,7 @@ class ProfileDrawerHeader extends HookConsumerWidget { return const SizedBox(); } - _pickUserProfileImage() async { + pickUserProfileImage() async { final XFile? image = await ImagePicker().pickImage( source: ImageSource.gallery, maxHeight: 1024, @@ -98,7 +98,7 @@ class ProfileDrawerHeader extends HookConsumerWidget { useEffect( () { - _buildUserProfileImage(); + buildUserProfileImage(); return null; }, [], @@ -129,12 +129,12 @@ class ProfileDrawerHeader extends HookConsumerWidget { Stack( clipBehavior: Clip.none, children: [ - _buildUserProfileImage(), + buildUserProfileImage(), Positioned( bottom: 0, right: -5, child: GestureDetector( - onTap: _pickUserProfileImage, + onTap: pickUserProfileImage, child: Material( color: Colors.grey[100], elevation: 3, diff --git a/mobile/lib/modules/home/ui/profile_drawer/server_info_box.dart b/mobile/lib/modules/home/ui/profile_drawer/server_info_box.dart index 8cd84fdfce..04edfc5f79 100644 --- a/mobile/lib/modules/home/ui/profile_drawer/server_info_box.dart +++ b/mobile/lib/modules/home/ui/profile_drawer/server_info_box.dart @@ -17,7 +17,7 @@ class ServerInfoBox extends HookConsumerWidget { final appInfo = useState({}); - _getPackageInfo() async { + getPackageInfo() async { PackageInfo packageInfo = await PackageInfo.fromPlatform(); appInfo.value = { @@ -28,7 +28,7 @@ class ServerInfoBox extends HookConsumerWidget { useEffect( () { - _getPackageInfo(); + getPackageInfo(); return null; }, [], diff --git a/mobile/lib/modules/home/views/home_page.dart b/mobile/lib/modules/home/views/home_page.dart index 5b2fbbb416..1fafc63436 100644 --- a/mobile/lib/modules/home/views/home_page.dart +++ b/mobile/lib/modules/home/views/home_page.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:auto_route/auto_route.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; @@ -20,6 +22,7 @@ import 'package:immich_mobile/shared/providers/asset.provider.dart'; import 'package:immich_mobile/shared/providers/server_info.provider.dart'; import 'package:immich_mobile/shared/providers/websocket.provider.dart'; import 'package:immich_mobile/shared/services/share.service.dart'; +import 'package:immich_mobile/shared/ui/immich_loading_indicator.dart'; import 'package:immich_mobile/shared/ui/immich_toast.dart'; import 'package:openapi/api.dart'; @@ -37,6 +40,8 @@ class HomePage extends HookConsumerWidget { final albums = ref.watch(albumProvider); final albumService = ref.watch(albumServiceProvider); + final tipOneOpacity = useState(0.0); + useEffect( () { ref.read(websocketProvider.notifier).connect(); @@ -146,6 +151,49 @@ class HomePage extends HookConsumerWidget { } } + buildLoadingIndicator() { + Timer(const Duration(seconds: 2), () { + tipOneOpacity.value = 1; + }); + + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const ImmichLoadingIndicator(), + Padding( + padding: const EdgeInsets.only(top: 16.0), + child: Text( + 'Building the timeline', + style: TextStyle( + fontWeight: FontWeight.w600, + fontSize: 16, + color: Theme.of(context).primaryColor, + ), + ), + ), + AnimatedOpacity( + duration: const Duration(milliseconds: 500), + opacity: tipOneOpacity.value, + child: const SizedBox( + width: 250, + child: Padding( + padding: EdgeInsets.only(top: 8.0), + child: Text( + 'If this is your first time using the app, please make sure to choose a backup album(s) so that the timeline can populate photos and videos in the album(s).', + textAlign: TextAlign.justify, + style: TextStyle( + fontSize: 12, + ), + ), + ), + ), + ) + ], + ), + ); + } + return SafeArea( bottom: !multiselectEnabled.state, top: true, @@ -164,15 +212,17 @@ class HomePage extends HookConsumerWidget { top: selectionEnabledHook.value ? 0 : 60, bottom: 0.0, ), - child: ImmichAssetGrid( - renderList: renderList, - assetsPerRow: - appSettingService.getSetting(AppSettingsEnum.tilesPerRow), - showStorageIndicator: appSettingService - .getSetting(AppSettingsEnum.storageIndicator), - listener: selectionListener, - selectionActive: selectionEnabledHook.value, - ), + child: ref.watch(assetProvider).isEmpty + ? buildLoadingIndicator() + : ImmichAssetGrid( + renderList: renderList, + assetsPerRow: appSettingService + .getSetting(AppSettingsEnum.tilesPerRow), + showStorageIndicator: appSettingService + .getSetting(AppSettingsEnum.storageIndicator), + listener: selectionListener, + selectionActive: selectionEnabledHook.value, + ), ), if (selectionEnabledHook.value) ControlBottomAppBar( diff --git a/mobile/lib/modules/login/models/hive_saved_login_info.model.dart b/mobile/lib/modules/login/models/hive_saved_login_info.model.dart index 6d367d5978..e807fc4780 100644 --- a/mobile/lib/modules/login/models/hive_saved_login_info.model.dart +++ b/mobile/lib/modules/login/models/hive_saved_login_info.model.dart @@ -5,21 +5,25 @@ part 'hive_saved_login_info.model.g.dart'; @HiveType(typeId: 0) class HiveSavedLoginInfo { @HiveField(0) - String email; + String email; // DEPRECATED @HiveField(1) - String password; + String password; // DEPRECATED @HiveField(2) String serverUrl; - @HiveField(3) + @HiveField(3, defaultValue: false) bool isSaveLogin; + @HiveField(4, defaultValue: "") + String accessToken; + HiveSavedLoginInfo({ required this.email, required this.password, required this.serverUrl, required this.isSaveLogin, + required this.accessToken, }); } diff --git a/mobile/lib/modules/login/models/hive_saved_login_info.model.g.dart b/mobile/lib/modules/login/models/hive_saved_login_info.model.g.dart index 80e6f30a9d..27c1d19672 100644 Binary files a/mobile/lib/modules/login/models/hive_saved_login_info.model.g.dart and b/mobile/lib/modules/login/models/hive_saved_login_info.model.g.dart differ diff --git a/mobile/lib/modules/login/providers/authentication.provider.dart b/mobile/lib/modules/login/providers/authentication.provider.dart index f75fe3b544..db1c2343cd 100644 --- a/mobile/lib/modules/login/providers/authentication.provider.dart +++ b/mobile/lib/modules/login/providers/authentication.provider.dart @@ -74,15 +74,6 @@ class AuthenticationNotifier extends StateNotifier { return false; } - // Store device id to local storage - var deviceInfo = await _deviceInfoService.getDeviceInfo(); - Hive.box(userInfoBox).put(deviceIdKey, deviceInfo["deviceId"]); - - state = state.copyWith( - deviceId: deviceInfo["deviceId"], - deviceType: deviceInfo["deviceType"], - ); - // Make sign-in request try { var loginResponse = await _apiService.authenticationApi.login( @@ -97,73 +88,27 @@ class AuthenticationNotifier extends StateNotifier { return false; } - Hive.box(userInfoBox).put(accessTokenKey, loginResponse.accessToken); - - state = state.copyWith( - isAuthenticated: true, - userId: loginResponse.userId, - userEmail: loginResponse.userEmail, - firstName: loginResponse.firstName, - lastName: loginResponse.lastName, - profileImagePath: loginResponse.profileImagePath, - isAdmin: loginResponse.isAdmin, - shouldChangePassword: loginResponse.shouldChangePassword, + return setSuccessLoginInfo( + accessToken: loginResponse.accessToken, + serverUrl: serverEndpoint, + isSavedLoginInfo: isSavedLoginInfo, ); - - // Login Success - Set Access Token to API Client - _apiService.setAccessToken(loginResponse.accessToken); - - if (isSavedLoginInfo) { - // Save login info to local storage - Hive.box(hiveLoginInfoBox).put( - savedLoginInfoKey, - HiveSavedLoginInfo( - email: email, - password: password, - isSaveLogin: true, - serverUrl: Hive.box(userInfoBox).get(serverEndpointKey), - ), - ); - } else { - Hive.box(hiveLoginInfoBox) - .delete(savedLoginInfoKey); - } } catch (e) { HapticFeedback.vibrate(); debugPrint("Error logging in $e"); return false; } - - // Register device info - try { - DeviceInfoResponseDto? deviceInfo = - await _apiService.deviceInfoApi.createDeviceInfo( - CreateDeviceInfoDto( - deviceId: state.deviceId, - deviceType: state.deviceType, - ), - ); - - if (deviceInfo == null) { - debugPrint('Device Info Response is null'); - return false; - } - - state = state.copyWith(deviceInfo: deviceInfo); - } catch (e) { - debugPrint("ERROR Register Device Info: $e"); - return false; - } - - return true; } Future logout() async { - Hive.box(userInfoBox).delete(accessTokenKey); state = state.copyWith(isAuthenticated: false); - _assetCacheService.invalidate(); - _albumCacheService.invalidate(); - _sharedAlbumCacheService.invalidate(); + await Future.wait([ + Hive.box(userInfoBox).delete(accessTokenKey), + Hive.box(userInfoBox).delete(assetEtagKey), + _assetCacheService.invalidate(), + _albumCacheService.invalidate(), + _sharedAlbumCacheService.invalidate(), + ]); // Remove login info from local storage var loginInfo = @@ -173,7 +118,7 @@ class AuthenticationNotifier extends StateNotifier { loginInfo.password = ""; loginInfo.isSaveLogin = false; - Hive.box(hiveLoginInfoBox).put( + await Hive.box(hiveLoginInfoBox).put( savedLoginInfoKey, loginInfo, ); @@ -215,6 +160,76 @@ class AuthenticationNotifier extends StateNotifier { return false; } } + + Future setSuccessLoginInfo({ + required String accessToken, + required String serverUrl, + required bool isSavedLoginInfo, + }) async { + _apiService.setAccessToken(accessToken); + var userResponseDto = await _apiService.userApi.getMyUserInfo(); + + if (userResponseDto != null) { + var userInfoHiveBox = await Hive.openBox(userInfoBox); + var deviceInfo = await _deviceInfoService.getDeviceInfo(); + userInfoHiveBox.put(deviceIdKey, deviceInfo["deviceId"]); + userInfoHiveBox.put(accessTokenKey, accessToken); + userInfoHiveBox.put(serverEndpointKey, serverUrl); + + state = state.copyWith( + isAuthenticated: true, + userId: userResponseDto.id, + userEmail: userResponseDto.email, + firstName: userResponseDto.firstName, + lastName: userResponseDto.lastName, + profileImagePath: userResponseDto.profileImagePath, + isAdmin: userResponseDto.isAdmin, + shouldChangePassword: userResponseDto.shouldChangePassword, + deviceId: deviceInfo["deviceId"], + deviceType: deviceInfo["deviceType"], + ); + + if (isSavedLoginInfo) { + // Save login info to local storage + Hive.box(hiveLoginInfoBox).put( + savedLoginInfoKey, + HiveSavedLoginInfo( + email: "", + password: "", + isSaveLogin: true, + serverUrl: serverUrl, + accessToken: accessToken, + ), + ); + } else { + Hive.box(hiveLoginInfoBox) + .delete(savedLoginInfoKey); + } + } + + // Register device info + try { + DeviceInfoResponseDto? deviceInfo = + await _apiService.deviceInfoApi.createDeviceInfo( + CreateDeviceInfoDto( + deviceId: state.deviceId, + deviceType: state.deviceType, + ), + ); + + if (deviceInfo == null) { + debugPrint('Device Info Response is null'); + return false; + } + + state = state.copyWith(deviceInfo: deviceInfo); + } catch (e) { + debugPrint("ERROR Register Device Info: $e"); + return false; + } + + return true; + } } final authenticationProvider = diff --git a/mobile/lib/modules/login/providers/oauth.provider.dart b/mobile/lib/modules/login/providers/oauth.provider.dart new file mode 100644 index 0000000000..dc0b1e643d --- /dev/null +++ b/mobile/lib/modules/login/providers/oauth.provider.dart @@ -0,0 +1,6 @@ +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:immich_mobile/modules/login/services/oauth.service.dart'; +import 'package:immich_mobile/shared/providers/api.provider.dart'; + +final oAuthServiceProvider = + Provider((ref) => OAuthService(ref.watch(apiServiceProvider))); diff --git a/mobile/lib/modules/login/services/oauth.service.dart b/mobile/lib/modules/login/services/oauth.service.dart new file mode 100644 index 0000000000..995aef2757 --- /dev/null +++ b/mobile/lib/modules/login/services/oauth.service.dart @@ -0,0 +1,39 @@ +import 'package:immich_mobile/shared/services/api.service.dart'; +import 'package:openapi/api.dart'; +import 'package:flutter_web_auth/flutter_web_auth.dart'; + +// Redirect URL = app.immich:// + +class OAuthService { + final ApiService _apiService; + final callbackUrlScheme = 'app.immich'; + + OAuthService(this._apiService); + + Future getOAuthServerConfig( + String serverEndpoint, + ) async { + _apiService.setEndpoint(serverEndpoint); + + return await _apiService.oAuthApi.generateConfig( + OAuthConfigDto(redirectUri: '$callbackUrlScheme:/'), + ); + } + + Future oAuthLogin(String oauthUrl) async { + try { + var result = await FlutterWebAuth.authenticate( + url: oauthUrl, + callbackUrlScheme: callbackUrlScheme, + ); + + return await _apiService.oAuthApi.callback( + OAuthCallbackDto( + url: result, + ), + ); + } catch (e) { + return null; + } + } +} diff --git a/mobile/lib/modules/login/ui/login_form.dart b/mobile/lib/modules/login/ui/login_form.dart index ea741faf1e..13f53b8ff1 100644 --- a/mobile/lib/modules/login/ui/login_form.dart +++ b/mobile/lib/modules/login/ui/login_form.dart @@ -6,11 +6,14 @@ import 'package:hive/hive.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:immich_mobile/constants/hive_box.dart'; import 'package:immich_mobile/modules/login/models/hive_saved_login_info.model.dart'; +import 'package:immich_mobile/modules/login/providers/oauth.provider.dart'; import 'package:immich_mobile/routing/router.dart'; +import 'package:immich_mobile/shared/providers/api.provider.dart'; import 'package:immich_mobile/shared/providers/asset.provider.dart'; import 'package:immich_mobile/modules/login/providers/authentication.provider.dart'; import 'package:immich_mobile/modules/backup/providers/backup.provider.dart'; import 'package:immich_mobile/shared/ui/immich_toast.dart'; +import 'package:openapi/api.dart'; class LoginForm extends HookConsumerWidget { const LoginForm({Key? key}) : super(key: key); @@ -23,10 +26,47 @@ class LoginForm extends HookConsumerWidget { useTextEditingController.fromValue(TextEditingValue.empty); final serverEndpointController = useTextEditingController(text: 'login_form_endpoint_hint'.tr()); + final apiService = ref.watch(apiServiceProvider); + final serverEndpointFocusNode = useFocusNode(); final isSaveLoginInfo = useState(false); + final isLoading = useState(false); + final isOauthEnable = useState(false); + final oAuthButtonLabel = useState('OAuth'); + + getServeLoginConfig() async { + if (!serverEndpointFocusNode.hasFocus) { + var urlText = serverEndpointController.text.trim(); + + try { + var endpointUrl = Uri.tryParse(urlText); + + if (endpointUrl != null) { + isLoading.value = true; + apiService.setEndpoint(endpointUrl.toString()); + var loginConfig = await apiService.oAuthApi.generateConfig( + OAuthConfigDto(redirectUri: endpointUrl.toString()), + ); + + if (loginConfig != null) { + isOauthEnable.value = loginConfig.enabled; + oAuthButtonLabel.value = loginConfig.buttonText ?? 'OAuth'; + } else { + isOauthEnable.value = false; + } + + isLoading.value = false; + } + } catch (_) { + isLoading.value = false; + isOauthEnable.value = false; + } + } + } useEffect( () { + serverEndpointFocusNode.addListener(getServeLoginConfig); + var loginInfo = Hive.box(hiveLoginInfoBox) .get(savedLoginInfoKey); @@ -37,11 +77,19 @@ class LoginForm extends HookConsumerWidget { isSaveLoginInfo.value = loginInfo.isSaveLogin; } + getServeLoginConfig(); return null; }, [], ); + populateTestLoginInfo() { + usernameController.text = 'testuser@email.com'; + passwordController.text = 'password'; + serverEndpointController.text = 'http://10.1.15.216:2283/api'; + isSaveLoginInfo.value = true; + } + return Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 300), @@ -51,10 +99,13 @@ class LoginForm extends HookConsumerWidget { runSpacing: 16, alignment: WrapAlignment.center, children: [ - const Image( - image: AssetImage('assets/immich-logo-no-outline.png'), - width: 100, - filterQuality: FilterQuality.high, + GestureDetector( + onDoubleTap: () => populateTestLoginInfo(), + child: const Image( + image: AssetImage('assets/immich-logo-no-outline.png'), + width: 100, + filterQuality: FilterQuality.high, + ), ), Text( 'IMMICH', @@ -67,7 +118,10 @@ class LoginForm extends HookConsumerWidget { ), EmailInput(controller: usernameController), PasswordInput(controller: passwordController), - ServerEndpointInput(controller: serverEndpointController), + ServerEndpointInput( + controller: serverEndpointController, + focusNode: serverEndpointFocusNode, + ), CheckboxListTile( activeColor: Theme.of(context).primaryColor, contentPadding: const EdgeInsets.symmetric(horizontal: 8), @@ -92,12 +146,52 @@ class LoginForm extends HookConsumerWidget { } }, ), - LoginButton( - emailController: usernameController, - passwordController: passwordController, - serverEndpointController: serverEndpointController, - isSavedLoginInfo: isSaveLoginInfo.value, - ), + if (isLoading.value) + const SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ), + if (!isLoading.value) + Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + LoginButton( + emailController: usernameController, + passwordController: passwordController, + serverEndpointController: serverEndpointController, + isSavedLoginInfo: isSaveLoginInfo.value, + ), + if (isOauthEnable.value) ...[ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 16.0, + ), + child: Divider( + color: Brightness.dark == Theme.of(context).brightness + ? Colors.white + : Colors.black, + ), + ), + OAuthLoginButton( + serverEndpointController: serverEndpointController, + isSavedLoginInfo: isSaveLoginInfo.value, + buttonLabel: oAuthButtonLabel.value, + isLoading: isLoading, + onLoginSuccess: () { + isLoading.value = false; + ref.watch(backupProvider.notifier).resumeBackup(); + AutoRouter.of(context).replace( + const TabControllerRoute(), + ); + }, + ), + ], + ], + ) ], ), ), @@ -108,9 +202,12 @@ class LoginForm extends HookConsumerWidget { class ServerEndpointInput extends StatelessWidget { final TextEditingController controller; - - const ServerEndpointInput({Key? key, required this.controller}) - : super(key: key); + final FocusNode focusNode; + const ServerEndpointInput({ + Key? key, + required this.controller, + required this.focusNode, + }) : super(key: key); String? _validateInput(String? url) { if (url?.startsWith(RegExp(r'https?://')) == true) { @@ -131,6 +228,7 @@ class ServerEndpointInput extends StatelessWidget { ), validator: _validateInput, autovalidateMode: AutovalidateMode.always, + focusNode: focusNode, ); } } @@ -200,13 +298,9 @@ class LoginButton extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { - return ElevatedButton( + return ElevatedButton.icon( style: ElevatedButton.styleFrom( - visualDensity: VisualDensity.standard, - backgroundColor: Theme.of(context).primaryColor, - foregroundColor: Colors.grey[50], - elevation: 2, - padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 25), + padding: const EdgeInsets.symmetric(vertical: 12), ), onPressed: () async { // This will remove current cache asset state of previous user login. @@ -238,10 +332,102 @@ class LoginButton extends ConsumerWidget { ); } }, - child: const Text( + icon: const Icon(Icons.login_rounded), + label: const Text( "login_form_button_text", style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold), ).tr(), ); } } + +class OAuthLoginButton extends ConsumerWidget { + final TextEditingController serverEndpointController; + final bool isSavedLoginInfo; + final ValueNotifier isLoading; + final VoidCallback onLoginSuccess; + final String buttonLabel; + + const OAuthLoginButton({ + Key? key, + required this.serverEndpointController, + required this.isSavedLoginInfo, + required this.isLoading, + required this.onLoginSuccess, + required this.buttonLabel, + }) : super(key: key); + + @override + Widget build(BuildContext context, WidgetRef ref) { + var oAuthService = ref.watch(oAuthServiceProvider); + + void performOAuthLogin() async { + ref.watch(assetProvider.notifier).clearAllAsset(); + OAuthConfigResponseDto? oAuthServerConfig; + + try { + oAuthServerConfig = await oAuthService + .getOAuthServerConfig(serverEndpointController.text); + + isLoading.value = true; + } catch (e) { + ImmichToast.show( + context: context, + msg: "login_form_failed_get_oauth_server_config".tr(), + toastType: ToastType.error, + ); + isLoading.value = false; + return; + } + + if (oAuthServerConfig != null && oAuthServerConfig.enabled) { + var loginResponseDto = + await oAuthService.oAuthLogin(oAuthServerConfig.url!); + + if (loginResponseDto != null) { + var isSuccess = await ref + .watch(authenticationProvider.notifier) + .setSuccessLoginInfo( + accessToken: loginResponseDto.accessToken, + isSavedLoginInfo: isSavedLoginInfo, + serverUrl: serverEndpointController.text, + ); + + if (isSuccess) { + isLoading.value = false; + onLoginSuccess(); + } else { + ImmichToast.show( + context: context, + msg: "login_form_failed_login".tr(), + toastType: ToastType.error, + ); + } + } + + isLoading.value = false; + } else { + ImmichToast.show( + context: context, + msg: "login_form_failed_get_oauth_server_disable".tr(), + toastType: ToastType.info, + ); + isLoading.value = false; + return; + } + } + + return ElevatedButton.icon( + style: ElevatedButton.styleFrom( + backgroundColor: Theme.of(context).primaryColor.withAlpha(230), + padding: const EdgeInsets.symmetric(vertical: 12), + ), + onPressed: performOAuthLogin, + icon: const Icon(Icons.pin_rounded), + label: Text( + buttonLabel, + style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold), + ), + ); + } +} diff --git a/mobile/lib/modules/login/views/login_page.dart b/mobile/lib/modules/login/views/login_page.dart index 42c02a6eac..98778736e3 100644 --- a/mobile/lib/modules/login/views/login_page.dart +++ b/mobile/lib/modules/login/views/login_page.dart @@ -1,14 +1,65 @@ +import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:immich_mobile/modules/login/ui/login_form.dart'; +import 'package:immich_mobile/routing/router.dart'; +import 'package:package_info_plus/package_info_plus.dart'; class LoginPage extends HookConsumerWidget { const LoginPage({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { - return const Scaffold( - body: LoginForm(), + final appVersion = useState('0.0.0'); + + getAppInfo() async { + PackageInfo packageInfo = await PackageInfo.fromPlatform(); + appVersion.value = packageInfo.version; + } + + useEffect( + () { + getAppInfo(); + return null; + }, + ); + + return Scaffold( + body: const LoginForm(), + bottomNavigationBar: Padding( + padding: const EdgeInsets.only(bottom: 16.0), + child: SizedBox( + height: 50, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + 'v${appVersion.value}', + style: const TextStyle( + color: Colors.grey, + fontWeight: FontWeight.bold, + fontFamily: "Inconsolata", + ), + ), + const Text(' '), + GestureDetector( + child: Text( + 'Logs', + style: TextStyle( + color: Theme.of(context).primaryColor, + fontWeight: FontWeight.bold, + fontFamily: "Inconsolata", + ), + ), + onTap: () { + AutoRouter.of(context).push(const AppLogRoute()); + }, + ), + ], + ), + ), + ), ); } } diff --git a/mobile/lib/modules/search/views/search_page.dart b/mobile/lib/modules/search/views/search_page.dart index d80a18a353..14c8202d2e 100644 --- a/mobile/lib/modules/search/views/search_page.dart +++ b/mobile/lib/modules/search/views/search_page.dart @@ -39,14 +39,14 @@ class SearchPage extends HookConsumerWidget { [], ); - _onSearchSubmitted(String searchTerm) async { + onSearchSubmitted(String searchTerm) async { searchFocusNode.unfocus(); ref.watch(searchPageStateProvider.notifier).disableSearch(); AutoRouter.of(context).push(SearchResultRoute(searchTerm: searchTerm)); } - _buildPlaces() { + buildPlaces() { return curatedLocation.when( loading: () => SizedBox( height: imageSize, @@ -97,7 +97,7 @@ class SearchPage extends HookConsumerWidget { ); } - _buildThings() { + buildThings() { return curatedObjects.when( loading: () => SizedBox( height: imageSize, @@ -155,7 +155,7 @@ class SearchPage extends HookConsumerWidget { return Scaffold( appBar: SearchBar( searchFocusNode: searchFocusNode, - onSubmitted: _onSearchSubmitted, + onSubmitted: onSearchSubmitted, ), body: GestureDetector( onTap: () { @@ -174,7 +174,7 @@ class SearchPage extends HookConsumerWidget { style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14), ).tr(), ), - _buildPlaces(), + buildPlaces(), Padding( padding: const EdgeInsets.all(16.0), child: const Text( @@ -182,11 +182,11 @@ class SearchPage extends HookConsumerWidget { style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14), ).tr(), ), - _buildThings() + buildThings() ], ), if (isSearchEnabled) - SearchSuggestionList(onSubmitted: _onSearchSubmitted), + SearchSuggestionList(onSubmitted: onSearchSubmitted), ], ), ), diff --git a/mobile/lib/modules/search/views/search_result_page.dart b/mobile/lib/modules/search/views/search_result_page.dart index 048cf46b9f..4d20f87668 100644 --- a/mobile/lib/modules/search/views/search_result_page.dart +++ b/mobile/lib/modules/search/views/search_result_page.dart @@ -38,7 +38,7 @@ class SearchResultPage extends HookConsumerWidget { [], ); - _onSearchSubmitted(String newSearchTerm) { + onSearchSubmitted(String newSearchTerm) { debugPrint("Re-Search with $newSearchTerm"); searchFocusNode?.unfocus(); isNewSearch.value = false; @@ -46,7 +46,7 @@ class SearchResultPage extends HookConsumerWidget { ref.watch(searchResultPageProvider.notifier).search(newSearchTerm); } - _buildTextField() { + buildTextField() { return TextField( controller: searchTermController, focusNode: searchFocusNode, @@ -60,7 +60,7 @@ class SearchResultPage extends HookConsumerWidget { onSubmitted: (searchTerm) { if (searchTerm.isNotEmpty) { searchTermController.clear(); - _onSearchSubmitted(searchTerm); + onSearchSubmitted(searchTerm); } else { isNewSearch.value = false; } @@ -80,7 +80,7 @@ class SearchResultPage extends HookConsumerWidget { ); } - _buildChip() { + buildChip() { return Chip( label: Wrap( spacing: 5, @@ -108,7 +108,7 @@ class SearchResultPage extends HookConsumerWidget { ); } - _buildSearchResult() { + buildSearchResult() { var searchResultPageState = ref.watch(searchResultPageProvider); var searchResultRenderList = ref.watch(searchRenderListProvider); @@ -154,7 +154,7 @@ class SearchResultPage extends HookConsumerWidget { isNewSearch.value = true; searchFocusNode?.requestFocus(); }, - child: isNewSearch.value ? _buildTextField() : _buildChip(), + child: isNewSearch.value ? buildTextField() : buildChip(), ), centerTitle: false, ), @@ -168,9 +168,9 @@ class SearchResultPage extends HookConsumerWidget { }, child: Stack( children: [ - _buildSearchResult(), + buildSearchResult(), if (isNewSearch.value) - SearchSuggestionList(onSubmitted: _onSearchSubmitted), + SearchSuggestionList(onSubmitted: onSearchSubmitted), ], ), ), diff --git a/mobile/lib/modules/settings/views/settings_page.dart b/mobile/lib/modules/settings/views/settings_page.dart index 9a16793429..8422e201ab 100644 --- a/mobile/lib/modules/settings/views/settings_page.dart +++ b/mobile/lib/modules/settings/views/settings_page.dart @@ -4,7 +4,6 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:immich_mobile/modules/settings/ui/asset_list_settings/asset_list_settings.dart'; -import 'package:immich_mobile/modules/settings/ui/experimental_settings/experimental_settings.dart'; import 'package:immich_mobile/modules/settings/ui/image_viewer_quality_setting/image_viewer_quality_setting.dart'; import 'package:immich_mobile/modules/settings/ui/notification_setting/notification_setting.dart'; import 'package:immich_mobile/modules/settings/ui/theme_setting/theme_setting.dart'; diff --git a/mobile/lib/routing/router.dart b/mobile/lib/routing/router.dart index 3a00ae8c81..313a53e5fb 100644 --- a/mobile/lib/routing/router.dart +++ b/mobile/lib/routing/router.dart @@ -1,33 +1,34 @@ import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; -import 'package:immich_mobile/modules/album/views/library_page.dart'; -import 'package:immich_mobile/modules/asset_viewer/views/gallery_viewer.dart'; -import 'package:immich_mobile/modules/backup/views/album_preview_page.dart'; -import 'package:immich_mobile/modules/backup/views/backup_album_selection_page.dart'; -import 'package:immich_mobile/modules/backup/views/failed_backup_status_page.dart'; -import 'package:immich_mobile/modules/login/views/change_password_page.dart'; -import 'package:immich_mobile/modules/login/views/login_page.dart'; -import 'package:immich_mobile/modules/home/views/home_page.dart'; -import 'package:immich_mobile/modules/search/views/search_page.dart'; -import 'package:immich_mobile/modules/search/views/search_result_page.dart'; import 'package:immich_mobile/modules/album/models/asset_selection_page_result.model.dart'; import 'package:immich_mobile/modules/album/views/album_viewer_page.dart'; import 'package:immich_mobile/modules/album/views/asset_selection_page.dart'; import 'package:immich_mobile/modules/album/views/create_album_page.dart'; +import 'package:immich_mobile/modules/album/views/library_page.dart'; import 'package:immich_mobile/modules/album/views/select_additional_user_for_sharing_page.dart'; import 'package:immich_mobile/modules/album/views/select_user_for_sharing_page.dart'; import 'package:immich_mobile/modules/album/views/sharing_page.dart'; +import 'package:immich_mobile/modules/asset_viewer/views/gallery_viewer.dart'; +import 'package:immich_mobile/modules/asset_viewer/views/image_viewer_page.dart'; +import 'package:immich_mobile/modules/asset_viewer/views/video_viewer_page.dart'; +import 'package:immich_mobile/modules/backup/views/album_preview_page.dart'; +import 'package:immich_mobile/modules/backup/views/backup_album_selection_page.dart'; +import 'package:immich_mobile/modules/backup/views/backup_controller_page.dart'; +import 'package:immich_mobile/modules/backup/views/failed_backup_status_page.dart'; +import 'package:immich_mobile/modules/home/views/home_page.dart'; +import 'package:immich_mobile/modules/login/views/change_password_page.dart'; +import 'package:immich_mobile/modules/login/views/login_page.dart'; +import 'package:immich_mobile/modules/search/views/search_page.dart'; +import 'package:immich_mobile/modules/search/views/search_result_page.dart'; import 'package:immich_mobile/modules/settings/views/settings_page.dart'; import 'package:immich_mobile/routing/auth_guard.dart'; -import 'package:immich_mobile/modules/backup/views/backup_controller_page.dart'; -import 'package:immich_mobile/modules/asset_viewer/views/image_viewer_page.dart'; import 'package:immich_mobile/shared/models/asset.dart'; import 'package:immich_mobile/shared/providers/api.provider.dart'; import 'package:immich_mobile/shared/services/api.service.dart'; +import 'package:immich_mobile/shared/views/app_log_page.dart'; import 'package:immich_mobile/shared/views/splash_screen.dart'; import 'package:immich_mobile/shared/views/tab_controller_page.dart'; -import 'package:immich_mobile/modules/asset_viewer/views/video_viewer_page.dart'; import 'package:openapi/api.dart'; import 'package:photo_manager/photo_manager.dart'; @@ -80,6 +81,10 @@ part 'router.gr.dart'; transitionsBuilder: TransitionsBuilders.slideBottom, ), AutoRoute(page: SettingsPage, guards: [AuthGuard]), + CustomRoute( + page: AppLogPage, + transitionsBuilder: TransitionsBuilders.slideBottom, + ), ], ) class AppRouter extends _$AppRouter { diff --git a/mobile/lib/routing/router.gr.dart b/mobile/lib/routing/router.gr.dart index d280114915..bd266c00cd 100644 --- a/mobile/lib/routing/router.gr.dart +++ b/mobile/lib/routing/router.gr.dart @@ -142,6 +142,14 @@ class _$AppRouter extends RootStackRouter { return MaterialPageX( routeData: routeData, child: const SettingsPage()); }, + AppLogRoute.name: (routeData) { + return CustomPage( + routeData: routeData, + child: const AppLogPage(), + transitionsBuilder: TransitionsBuilders.slideBottom, + opaque: true, + barrierDismissible: false); + }, HomeRoute.name: (routeData) { return MaterialPageX( routeData: routeData, child: const HomePage()); @@ -218,7 +226,8 @@ class _$AppRouter extends RootStackRouter { RouteConfig(FailedBackupStatusRoute.name, path: '/failed-backup-status-page', guards: [authGuard]), RouteConfig(SettingsRoute.name, - path: '/settings-page', guards: [authGuard]) + path: '/settings-page', guards: [authGuard]), + RouteConfig(AppLogRoute.name, path: '/app-log-page') ]; } @@ -560,6 +569,14 @@ class SettingsRoute extends PageRouteInfo { static const String name = 'SettingsRoute'; } +/// generated route for +/// [AppLogPage] +class AppLogRoute extends PageRouteInfo { + const AppLogRoute() : super(AppLogRoute.name, path: '/app-log-page'); + + static const String name = 'AppLogRoute'; +} + /// generated route for /// [HomePage] class HomeRoute extends PageRouteInfo { diff --git a/mobile/lib/shared/models/immich_logger_message.model.dart b/mobile/lib/shared/models/immich_logger_message.model.dart new file mode 100644 index 0000000000..ae22d97809 --- /dev/null +++ b/mobile/lib/shared/models/immich_logger_message.model.dart @@ -0,0 +1,34 @@ +import 'package:hive/hive.dart'; + +part 'immich_logger_message.model.g.dart'; + +@HiveType(typeId: 3) +class ImmichLoggerMessage { + @HiveField(0) + String message; + + @HiveField(1, defaultValue: "INFO") + String level; + + @HiveField(2) + DateTime createdAt; + + @HiveField(3) + String? context1; + + @HiveField(4) + String? context2; + + ImmichLoggerMessage({ + required this.message, + required this.level, + required this.createdAt, + required this.context1, + required this.context2, + }); + + @override + String toString() { + return 'InAppLoggerMessage(message: $message, level: $level, createdAt: $createdAt)'; + } +} diff --git a/mobile/lib/shared/models/immich_logger_message.model.g.dart b/mobile/lib/shared/models/immich_logger_message.model.g.dart new file mode 100644 index 0000000000..314d165070 Binary files /dev/null and b/mobile/lib/shared/models/immich_logger_message.model.g.dart differ diff --git a/mobile/lib/shared/providers/asset.provider.dart b/mobile/lib/shared/providers/asset.provider.dart index 9de766439a..9250c33802 100644 --- a/mobile/lib/shared/providers/asset.provider.dart +++ b/mobile/lib/shared/providers/asset.provider.dart @@ -1,20 +1,22 @@ import 'dart:collection'; -import 'package:flutter/foundation.dart'; +import 'package:hive/hive.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:immich_mobile/constants/hive_box.dart'; import 'package:immich_mobile/modules/home/services/asset.service.dart'; import 'package:immich_mobile/modules/home/services/asset_cache.service.dart'; import 'package:immich_mobile/shared/models/asset.dart'; import 'package:immich_mobile/shared/services/device_info.service.dart'; import 'package:collection/collection.dart'; import 'package:intl/intl.dart'; +import 'package:logging/logging.dart'; import 'package:openapi/api.dart'; import 'package:photo_manager/photo_manager.dart'; class AssetNotifier extends StateNotifier> { final AssetService _assetService; final AssetCacheService _assetCacheService; - + final log = Logger('AssetNotifier'); final DeviceInfoService _deviceInfoService = DeviceInfoService(); bool _getAllAssetInProgress = false; bool _deleteInProgress = false; @@ -33,31 +35,61 @@ class AssetNotifier extends StateNotifier> { final stopwatch = Stopwatch(); try { _getAllAssetInProgress = true; - final bool isCacheValid = await _assetCacheService.isValid(); + stopwatch.start(); + final localTask = _assetService.getLocalAssets(urgent: !isCacheValid); + final remoteTask = _assetService.getRemoteAssets(hasCache: isCacheValid); if (isCacheValid && state.isEmpty) { - stopwatch.start(); state = await _assetCacheService.get(); - debugPrint( - "Reading assets from cache: ${stopwatch.elapsedMilliseconds}ms"); + log.info( + "Reading assets from cache: ${stopwatch.elapsedMilliseconds}ms", + ); stopwatch.reset(); } - stopwatch.start(); - var allAssets = await _assetService.getAllAsset(urgent: !isCacheValid); - debugPrint("Query assets from API: ${stopwatch.elapsedMilliseconds}ms"); + int remoteBegin = state.indexWhere((a) => a.isRemote); + remoteBegin = remoteBegin == -1 ? state.length : remoteBegin; + final List currentLocal = state.slice(0, remoteBegin); + List? newRemote = await remoteTask; + List? newLocal = await localTask; + log.info("Load assets: ${stopwatch.elapsedMilliseconds}ms"); stopwatch.reset(); - - state = allAssets; + if (newRemote == null && + (newLocal == null || currentLocal.equals(newLocal))) { + log.info("state is already up-to-date"); + return; + } + newRemote ??= state.slice(remoteBegin); + newLocal ??= []; + state = _combineLocalAndRemoteAssets(local: newLocal, remote: newRemote); + log.info("Combining assets: ${stopwatch.elapsedMilliseconds}ms"); } finally { _getAllAssetInProgress = false; } - debugPrint("[getAllAsset] setting new asset state"); + log.info("setting new asset state"); - stopwatch.start(); - _cacheState(); - debugPrint("Store assets in cache: ${stopwatch.elapsedMilliseconds}ms"); stopwatch.reset(); + _cacheState(); + log.info("Store assets in cache: ${stopwatch.elapsedMilliseconds}ms"); + } + + List _combineLocalAndRemoteAssets({ + required Iterable local, + required List remote, + }) { + final List assets = []; + if (remote.isNotEmpty && local.isNotEmpty) { + final String deviceId = Hive.box(userInfoBox).get(deviceIdKey); + final Set existingIds = remote + .where((e) => e.deviceId == deviceId) + .map((e) => e.deviceAssetId) + .toSet(); + local = local.where((e) => !existingIds.contains(e.id)); + } + assets.addAll(local); + // the order (first all local, then remote assets) is important! + assets.addAll(remote); + return assets; } clearAllAsset() { @@ -123,8 +155,8 @@ class AssetNotifier extends StateNotifier> { if (local.isNotEmpty) { try { return await PhotoManager.editor.deleteWithIds(local); - } catch (e) { - debugPrint("Delete asset from device failed: $e"); + } catch (e, stack) { + log.severe("Failed to delete asset from device", e, stack); } } return []; @@ -145,7 +177,9 @@ class AssetNotifier extends StateNotifier> { final assetProvider = StateNotifierProvider>((ref) { return AssetNotifier( - ref.watch(assetServiceProvider), ref.watch(assetCacheServiceProvider)); + ref.watch(assetServiceProvider), + ref.watch(assetCacheServiceProvider), + ); }); final assetGroupByDateTimeProvider = StateProvider((ref) { diff --git a/mobile/lib/shared/providers/release_info.provider.dart b/mobile/lib/shared/providers/release_info.provider.dart index da24505e98..d10a7a07a0 100644 --- a/mobile/lib/shared/providers/release_info.provider.dart +++ b/mobile/lib/shared/providers/release_info.provider.dart @@ -6,10 +6,11 @@ import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:http/http.dart'; import 'package:immich_mobile/constants/hive_box.dart'; import 'package:immich_mobile/shared/views/version_announcement_overlay.dart'; +import 'package:logging/logging.dart'; class ReleaseInfoNotifier extends StateNotifier { ReleaseInfoNotifier() : super(""); - + final log = Logger('ReleaseInfoNotifier'); void checkGithubReleaseInfo() async { final Client client = Client(); var box = Hive.box(hiveGithubReleaseInfoBox); @@ -17,19 +18,17 @@ class ReleaseInfoNotifier extends StateNotifier { try { String? localReleaseVersion = box.get(githubReleaseInfoKey); final res = await client.get( - Uri.parse( - "https://api.github.com/repos/immich-app/immich/releases/latest", - ), - headers: {"Accept": "application/vnd.github.v3+json"}); + Uri.parse( + "https://api.github.com/repos/immich-app/immich/releases/latest", + ), + headers: {"Accept": "application/vnd.github.v3+json"}, + ); if (res.statusCode == 200) { final data = jsonDecode(res.body); String latestTagVersion = data["tag_name"]; state = latestTagVersion; - debugPrint("Local release version $localReleaseVersion"); - debugPrint("Remote release veresion $latestTagVersion"); - if (localReleaseVersion == null && latestTagVersion.isNotEmpty) { VersionAnnouncementOverlayController.appLoader.show(); return; diff --git a/mobile/lib/shared/providers/websocket.provider.dart b/mobile/lib/shared/providers/websocket.provider.dart index bc48762768..e9f8db40ea 100644 --- a/mobile/lib/shared/providers/websocket.provider.dart +++ b/mobile/lib/shared/providers/websocket.provider.dart @@ -6,23 +6,24 @@ import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:immich_mobile/constants/hive_box.dart'; import 'package:immich_mobile/modules/login/providers/authentication.provider.dart'; import 'package:immich_mobile/shared/providers/asset.provider.dart'; +import 'package:logging/logging.dart'; import 'package:openapi/api.dart'; import 'package:socket_io_client/socket_io_client.dart'; -class WebscoketState { +class WebsocketState { final Socket? socket; final bool isConnected; - WebscoketState({ + WebsocketState({ this.socket, required this.isConnected, }); - WebscoketState copyWith({ + WebsocketState copyWith({ Socket? socket, bool? isConnected, }) { - return WebscoketState( + return WebsocketState( socket: socket ?? this.socket, isConnected: isConnected ?? this.isConnected, ); @@ -30,13 +31,13 @@ class WebscoketState { @override String toString() => - 'WebscoketState(socket: $socket, isConnected: $isConnected)'; + 'WebsocketState(socket: $socket, isConnected: $isConnected)'; @override bool operator ==(Object other) { if (identical(this, other)) return true; - return other is WebscoketState && + return other is WebsocketState && other.socket == socket && other.isConnected == isConnected; } @@ -45,12 +46,11 @@ class WebscoketState { int get hashCode => socket.hashCode ^ isConnected.hashCode; } -class WebsocketNotifier extends StateNotifier { +class WebsocketNotifier extends StateNotifier { WebsocketNotifier(this.ref) - : super(WebscoketState(socket: null, isConnected: false)) { - debugPrint("Init websocket instance"); - } + : super(WebsocketState(socket: null, isConnected: false)); + final log = Logger('WebsocketNotifier'); final Ref ref; connect() { @@ -60,8 +60,8 @@ class WebsocketNotifier extends StateNotifier { var accessToken = Hive.box(userInfoBox).get(accessTokenKey); var endpoint = Hive.box(userInfoBox).get(serverEndpointKey); try { - debugPrint("[WEBSOCKET] Attempting to connect to ws"); - // Configure socket transports must be sepecified + debugPrint("Attempting to connect to websocket"); + // Configure socket transports must be specified Socket socket = io( endpoint.toString().replaceAll('/api', ''), OptionBuilder() @@ -76,18 +76,18 @@ class WebsocketNotifier extends StateNotifier { ); socket.onConnect((_) { - debugPrint("[WEBSOCKET] Established Websocket Connection"); - state = WebscoketState(isConnected: true, socket: socket); + debugPrint("Established Websocket Connection"); + state = WebsocketState(isConnected: true, socket: socket); }); socket.onDisconnect((_) { - debugPrint("[WEBSOCKET] Disconnect to Websocket Connection"); - state = WebscoketState(isConnected: false, socket: null); + debugPrint("Disconnect to Websocket Connection"); + state = WebsocketState(isConnected: false, socket: null); }); socket.on('error', (errorMessage) { - debugPrint("Webcoket Error - $errorMessage"); - state = WebscoketState(isConnected: false, socket: null); + log.severe("Websocket Error - $errorMessage"); + state = WebsocketState(isConnected: false, socket: null); }); socket.on('on_upload_success', (data) { @@ -105,21 +105,22 @@ class WebsocketNotifier extends StateNotifier { } disconnect() { - debugPrint("[WEBSOCKET] Attempting to disconnect"); + debugPrint("Attempting to disconnect from websocket"); + var socket = state.socket?.disconnect(); if (socket?.disconnected == true) { - state = WebscoketState(isConnected: false, socket: null); + state = WebsocketState(isConnected: false, socket: null); } } stopListenToEvent(String eventName) { - debugPrint("[Websocket] Stop listening to event $eventName"); + debugPrint("Stop listening to event $eventName"); state.socket?.off(eventName); } listenUploadEvent() { - debugPrint("[Websocket] Start listening to event on_upload_success"); + debugPrint("Start listening to event on_upload_success"); state.socket?.on('on_upload_success', (data) { var jsonString = jsonDecode(data.toString()); AssetResponseDto? newAsset = AssetResponseDto.fromJson(jsonString); @@ -132,6 +133,6 @@ class WebsocketNotifier extends StateNotifier { } final websocketProvider = - StateNotifierProvider((ref) { + StateNotifierProvider((ref) { return WebsocketNotifier(ref); }); diff --git a/mobile/lib/shared/services/api.service.dart b/mobile/lib/shared/services/api.service.dart index c1b70a0e81..900e261e3a 100644 --- a/mobile/lib/shared/services/api.service.dart +++ b/mobile/lib/shared/services/api.service.dart @@ -5,6 +5,7 @@ class ApiService { late UserApi userApi; late AuthenticationApi authenticationApi; + late OAuthApi oAuthApi; late AlbumApi albumApi; late AssetApi assetApi; late ServerInfoApi serverInfoApi; @@ -14,6 +15,7 @@ class ApiService { _apiClient = ApiClient(basePath: endpoint); userApi = UserApi(_apiClient); authenticationApi = AuthenticationApi(_apiClient); + oAuthApi = OAuthApi(_apiClient); albumApi = AlbumApi(_apiClient); assetApi = AssetApi(_apiClient); serverInfoApi = ServerInfoApi(_apiClient); diff --git a/mobile/lib/shared/services/cache.service.dart b/mobile/lib/shared/services/cache.service.dart index a251c14495..72ca31f7d6 100644 --- a/mobile/lib/shared/services/cache.service.dart +++ b/mobile/lib/shared/services/cache.service.dart @@ -1,3 +1,4 @@ +// ignore: depend_on_referenced_packages import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:immich_mobile/modules/settings/providers/app_settings.provider.dart'; diff --git a/mobile/lib/shared/services/immich_logger.service.dart b/mobile/lib/shared/services/immich_logger.service.dart new file mode 100644 index 0000000000..4e7d3bf71c --- /dev/null +++ b/mobile/lib/shared/services/immich_logger.service.dart @@ -0,0 +1,95 @@ +import 'dart:io'; + +import 'package:flutter/widgets.dart'; +import 'package:hive/hive.dart'; +import 'package:immich_mobile/constants/hive_box.dart'; +import 'package:immich_mobile/shared/models/immich_logger_message.model.dart'; +import 'package:logging/logging.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:share_plus/share_plus.dart'; + +/// [ImmichLogger] is a custom logger that is built on top of the [logging] package. +/// The logs are written to a Hive box and onto console, using `debugPrint` method. +/// +/// The logs are deleted when exceeding the `maxLogEntries` (default 200) property +/// in the class. +/// +/// Logs can be shared by calling the `shareLogs` method, which will open a share dialog +/// and generate a csv file. +class ImmichLogger { + final maxLogEntries = 200; + final Box _box = Hive.box(immichLoggerBox); + + List get messages => + _box.values.toList().reversed.toList(); + + ImmichLogger() { + _removeOverflowMessages(); + } + + init() { + Logger.root.level = Level.INFO; + Logger.root.onRecord.listen(_writeLogToHiveBox); + } + + _removeOverflowMessages() { + if (_box.length > maxLogEntries) { + var numberOfEntryToBeDeleted = _box.length - maxLogEntries; + for (var i = 0; i < numberOfEntryToBeDeleted; i++) { + _box.deleteAt(0); + } + } + } + + _writeLogToHiveBox(LogRecord record) { + final Box box = Hive.box(immichLoggerBox); + var formattedMessage = record.message; + + debugPrint('[${record.level.name}] [${record.time}] ${record.message}'); + box.add( + ImmichLoggerMessage( + message: formattedMessage, + level: record.level.name, + createdAt: record.time, + context1: record.loggerName, + context2: record.stackTrace?.toString(), + ), + ); + } + + void clearLogs() { + _box.clear(); + } + + Future shareLogs() async { + final tempDir = await getTemporaryDirectory(); + final dateTime = DateTime.now().toIso8601String(); + final filePath = '${tempDir.path}/Immich_log_$dateTime.csv'; + final logFile = await File(filePath).create(); + final io = logFile.openWrite(); + try { + // Write header + io.write("created_at,level,context,message,stacktrace\n"); + + // Write messages + for (final m in messages) { + io.write( + '${m.createdAt},${m.level},"${m.context1 ?? ""}","${m.message}","${m.context2 ?? ""}"\n', + ); + } + } finally { + await io.flush(); + await io.close(); + } + + // Share file + await Share.shareFiles( + [filePath], + subject: "Immich logs $dateTime", + sharePositionOrigin: Rect.zero, + ); + + // Clean up temp file + await logFile.delete(); + } +} diff --git a/mobile/lib/shared/services/json_cache.dart b/mobile/lib/shared/services/json_cache.dart index b8a403abba..739d8931de 100644 --- a/mobile/lib/shared/services/json_cache.dart +++ b/mobile/lib/shared/services/json_cache.dart @@ -23,8 +23,12 @@ abstract class JsonCache { } Future invalidate() async { - final file = await _getCacheFile(); - await file.delete(); + try { + final file = await _getCacheFile(); + await file.delete(); + } on FileSystemException { + // file is already deleted + } } Future putRawData(dynamic data) async { @@ -46,4 +50,4 @@ abstract class JsonCache { void put(T data); Future get(); -} \ No newline at end of file +} diff --git a/mobile/lib/shared/ui/immich_loading_indicator.dart b/mobile/lib/shared/ui/immich_loading_indicator.dart index 84a33ba046..bd4ad0d3cb 100644 --- a/mobile/lib/shared/ui/immich_loading_indicator.dart +++ b/mobile/lib/shared/ui/immich_loading_indicator.dart @@ -15,7 +15,10 @@ class ImmichLoadingIndicator extends StatelessWidget { borderRadius: BorderRadius.circular(10), ), padding: const EdgeInsets.all(15), - child: const CircularProgressIndicator(color: Colors.white), + child: const CircularProgressIndicator( + color: Colors.white, + strokeWidth: 2, + ), ); } } diff --git a/mobile/lib/shared/ui/immich_toast.dart b/mobile/lib/shared/ui/immich_toast.dart index 80cac0ce96..3f15c13a2a 100644 --- a/mobile/lib/shared/ui/immich_toast.dart +++ b/mobile/lib/shared/ui/immich_toast.dart @@ -9,12 +9,13 @@ class ImmichToast { required String msg, ToastType toastType = ToastType.info, ToastGravity gravity = ToastGravity.TOP, + int durationInSecond = 3, }) { final isDarkTheme = Theme.of(context).brightness == Brightness.dark; final fToast = FToast(); fToast.init(context); - Color _getColor(ToastType type, BuildContext context) { + Color getColor(ToastType type, BuildContext context) { switch (type) { case ToastType.info: return Theme.of(context).primaryColor; @@ -25,7 +26,7 @@ class ImmichToast { } } - Icon _getIcon(ToastType type) { + Icon getIcon(ToastType type) { switch (type) { case ToastType.info: return Icon( @@ -59,7 +60,7 @@ class ImmichToast { child: Row( mainAxisSize: MainAxisSize.min, children: [ - _getIcon(toastType), + getIcon(toastType), const SizedBox( width: 12.0, ), @@ -67,7 +68,7 @@ class ImmichToast { child: Text( msg, style: TextStyle( - color: _getColor(toastType, context), + color: getColor(toastType, context), fontWeight: FontWeight.bold, fontSize: 15, ), @@ -77,7 +78,7 @@ class ImmichToast { ), ), gravity: gravity, - toastDuration: const Duration(seconds: 2), + toastDuration: Duration(seconds: durationInSecond), ); } } diff --git a/mobile/lib/shared/views/app_log_page.dart b/mobile/lib/shared/views/app_log_page.dart new file mode 100644 index 0000000000..ff3b2e71c2 --- /dev/null +++ b/mobile/lib/shared/views/app_log_page.dart @@ -0,0 +1,165 @@ +import 'package:auto_route/auto_route.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:immich_mobile/shared/services/immich_logger.service.dart'; +import 'package:intl/intl.dart'; + +class AppLogPage extends HookConsumerWidget { + const AppLogPage({ + Key? key, + }) : super(key: key); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final immichLogger = ImmichLogger(); + final logMessages = useState(immichLogger.messages); + + Widget colorStatusIndicator(Color color) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + width: 10, + height: 10, + decoration: BoxDecoration( + color: color, + shape: BoxShape.circle, + ), + ), + ], + ); + } + + Widget buildLeadingIcon(String level) { + switch (level) { + case "INFO": + return colorStatusIndicator(Theme.of(context).primaryColor); + case "SEVERE": + return colorStatusIndicator(Colors.redAccent); + + case "WARNING": + return colorStatusIndicator(Colors.orangeAccent); + default: + return colorStatusIndicator(Colors.grey); + } + } + + getTileColor(String level) { + switch (level) { + case "INFO": + return Colors.transparent; + case "SEVERE": + return Theme.of(context).brightness == Brightness.dark + ? Colors.redAccent.withOpacity(0.25) + : Colors.redAccent.withOpacity(0.075); + case "WARNING": + return Theme.of(context).brightness == Brightness.dark + ? Colors.orangeAccent.withOpacity(0.25) + : Colors.orangeAccent.withOpacity(0.075); + default: + return Theme.of(context).primaryColor.withOpacity(0.1); + } + } + + return Scaffold( + appBar: AppBar( + title: Text( + "Logs - ${logMessages.value.length}", + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16.0, + ), + ), + scrolledUnderElevation: 1, + elevation: 2, + actions: [ + IconButton( + icon: Icon( + Icons.delete_outline_rounded, + color: Theme.of(context).primaryColor, + semanticLabel: "Clear logs", + size: 20.0, + ), + onPressed: () { + immichLogger.clearLogs(); + logMessages.value = []; + }, + ), + IconButton( + icon: Icon( + Icons.share_rounded, + color: Theme.of(context).primaryColor, + semanticLabel: "Share logs", + size: 20.0, + ), + onPressed: () { + immichLogger.shareLogs(); + }, + ), + ], + leading: IconButton( + onPressed: () { + AutoRouter.of(context).pop(); + }, + icon: const Icon( + Icons.arrow_back_ios_new_rounded, + size: 20.0, + ), + ), + centerTitle: true, + ), + body: ListView.separated( + separatorBuilder: (context, index) { + return Divider( + height: 0, + color: Theme.of(context).brightness == Brightness.dark + ? Colors.white70 + : Colors.grey[600], + ); + }, + itemCount: logMessages.value.length, + itemBuilder: (context, index) { + var logMessage = logMessages.value[index]; + return ListTile( + visualDensity: VisualDensity.compact, + dense: true, + tileColor: getTileColor(logMessage.level), + minLeadingWidth: 10, + title: Text.rich( + TextSpan( + children: [ + TextSpan( + text: "#$index ", + style: TextStyle( + color: Theme.of(context).brightness == Brightness.dark + ? Colors.white70 + : Colors.grey[600], + fontSize: 14.0, + fontWeight: FontWeight.bold, + ), + ), + TextSpan( + text: logMessage.message, + style: const TextStyle( + fontSize: 14.0, + ), + ), + ], + ), + style: const TextStyle(fontSize: 14.0, fontFamily: "Inconsolata"), + ), + subtitle: Text( + "[${logMessage.context1}] Logged on ${DateFormat("HH:mm:ss.SSS").format(logMessage.createdAt)}", + style: TextStyle( + fontSize: 12.0, + color: Colors.grey[600], + ), + ), + leading: buildLeadingIcon(logMessage.level), + ); + }, + ), + ); + } +} diff --git a/mobile/lib/shared/views/splash_screen.dart b/mobile/lib/shared/views/splash_screen.dart index ead677582a..e659c1241a 100644 --- a/mobile/lib/shared/views/splash_screen.dart +++ b/mobile/lib/shared/views/splash_screen.dart @@ -8,29 +8,39 @@ import 'package:immich_mobile/modules/backup/providers/backup.provider.dart'; import 'package:immich_mobile/modules/login/models/hive_saved_login_info.model.dart'; import 'package:immich_mobile/modules/login/providers/authentication.provider.dart'; import 'package:immich_mobile/routing/router.dart'; +import 'package:immich_mobile/shared/providers/api.provider.dart'; class SplashScreenPage extends HookConsumerWidget { const SplashScreenPage({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { + final apiService = ref.watch(apiServiceProvider); HiveSavedLoginInfo? loginInfo = Hive.box(hiveLoginInfoBox).get(savedLoginInfoKey); void performLoggingIn() async { - var isAuthenticated = - await ref.read(authenticationProvider.notifier).login( - loginInfo!.email, - loginInfo.password, - loginInfo.serverUrl, - true, - ); + try { + if (loginInfo != null) { + // Make sure API service is initialized + apiService.setEndpoint(loginInfo.serverUrl); - if (isAuthenticated) { - // Resume backup (if enable) then navigate - ref.watch(backupProvider.notifier).resumeBackup(); - AutoRouter.of(context).replace(const TabControllerRoute()); - } else { + var isSuccess = await ref + .read(authenticationProvider.notifier) + .setSuccessLoginInfo( + accessToken: loginInfo.accessToken, + isSavedLoginInfo: true, + serverUrl: loginInfo.serverUrl, + ); + if (isSuccess) { + // Resume backup (if enable) then navigate + ref.watch(backupProvider.notifier).resumeBackup(); + AutoRouter.of(context).replace(const TabControllerRoute()); + } else { + AutoRouter.of(context).replace(const LoginRoute()); + } + } + } catch (_) { AutoRouter.of(context).replace(const LoginRoute()); } } diff --git a/mobile/lib/utils/bytes_units.dart b/mobile/lib/utils/bytes_units.dart index 78e9f17df7..be9ac13dcb 100644 --- a/mobile/lib/utils/bytes_units.dart +++ b/mobile/lib/utils/bytes_units.dart @@ -1,15 +1,17 @@ - String formatBytes(int bytes) { - if (bytes < 1000) { - return "$bytes B"; - } else if (bytes < 1000000) { - final kb = (bytes / 1000).toStringAsFixed(1); - return "$kb kB"; - } else if (bytes < 1000000000) { - final mb = (bytes / 1000000).toStringAsFixed(1); - return "$mb MB"; - } else { - final gb = (bytes / 1000000000).toStringAsFixed(1); - return "$gb GB"; + const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']; + + int magnitude = 0; + double remainder = bytes.toDouble(); + while (remainder >= 1024) { + if (magnitude + 1 < units.length) { + magnitude++; + remainder /= 1024; + } + else { + break; + } } -} \ No newline at end of file + + return "${remainder.toStringAsFixed(magnitude == 0 ? 0 : 1)} ${units[magnitude]}"; +} diff --git a/mobile/lib/utils/immich_cache_info_repository.dart b/mobile/lib/utils/immich_cache_info_repository.dart index 87a17ac0b4..699713a6bd 100644 --- a/mobile/lib/utils/immich_cache_info_repository.dart +++ b/mobile/lib/utils/immich_cache_info_repository.dart @@ -1,3 +1,5 @@ +// ignore_for_file: depend_on_referenced_packages, implementation_imports + import 'dart:io'; import 'dart:math'; diff --git a/mobile/lib/utils/openapi_extensions.dart b/mobile/lib/utils/openapi_extensions.dart new file mode 100644 index 0000000000..2959be3d10 --- /dev/null +++ b/mobile/lib/utils/openapi_extensions.dart @@ -0,0 +1,53 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart'; +import 'package:openapi/api.dart'; + +import 'tuple.dart'; + +/// Extension methods to retrieve ETag together with the API call +extension WithETag on AssetApi { + /// Get all AssetEntity belong to the user + /// + /// Parameters: + /// + /// * [String] eTag: + /// ETag of data already cached on the client + Future, String?>?> getAllAssetsWithETag({ + String? eTag, + }) async { + final response = await getAllAssetsWithHttpInfo( + ifNoneMatch: eTag, + ); + if (response.statusCode >= HttpStatus.badRequest) { + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); + } + // When a remote server returns no body with a status of 204, we shall not decode it. + // At the time of writing this, `dart:convert` will throw an "Unexpected end of input" + // FormatException when trying to decode an empty string. + if (response.body.isNotEmpty && + response.statusCode != HttpStatus.noContent) { + final responseBody = await _decodeBodyBytes(response); + final etag = response.headers[HttpHeaders.etagHeader]; + final data = (await apiClient.deserializeAsync( + responseBody, 'List') as List) + .cast() + .toList(); + return Pair(data, etag); + } + return null; + } +} + +/// Returns the decoded body as UTF-8 if the given headers indicate an 'application/json' +/// content type. Otherwise, returns the decoded body as decoded by dart:http package. +Future _decodeBodyBytes(Response response) async { + final contentType = response.headers['content-type']; + return contentType != null && + contentType.toLowerCase().startsWith('application/json') + ? response.bodyBytes.isEmpty + ? '' + : utf8.decode(response.bodyBytes) + : response.body; +} diff --git a/mobile/lib/utils/tuple.dart b/mobile/lib/utils/tuple.dart new file mode 100644 index 0000000000..5473e9ce43 --- /dev/null +++ b/mobile/lib/utils/tuple.dart @@ -0,0 +1,8 @@ +/// An immutable pair or 2-tuple +/// TODO replace with Record once Dart 2.19 is available +class Pair { + final T1 first; + final T2 second; + + const Pair(this.first, this.second); +} diff --git a/mobile/openapi/doc/AssetApi.md b/mobile/openapi/doc/AssetApi.md index b374febceb..9140b2d5e8 100644 Binary files a/mobile/openapi/doc/AssetApi.md and b/mobile/openapi/doc/AssetApi.md differ diff --git a/mobile/openapi/doc/AssetResponseDto.md b/mobile/openapi/doc/AssetResponseDto.md index f6e52a709e..3e80e12c3f 100644 Binary files a/mobile/openapi/doc/AssetResponseDto.md and b/mobile/openapi/doc/AssetResponseDto.md differ diff --git a/mobile/openapi/doc/UsageByUserDto.md b/mobile/openapi/doc/UsageByUserDto.md index 2e6a074c0c..ffdc2a88ec 100644 Binary files a/mobile/openapi/doc/UsageByUserDto.md and b/mobile/openapi/doc/UsageByUserDto.md differ diff --git a/mobile/openapi/doc/UserResponseDto.md b/mobile/openapi/doc/UserResponseDto.md index 99f2f5245b..4d6fb1c669 100644 Binary files a/mobile/openapi/doc/UserResponseDto.md and b/mobile/openapi/doc/UserResponseDto.md differ diff --git a/mobile/openapi/lib/api/asset_api.dart b/mobile/openapi/lib/api/asset_api.dart index eebbb99e30..73811beb63 100644 Binary files a/mobile/openapi/lib/api/asset_api.dart and b/mobile/openapi/lib/api/asset_api.dart differ diff --git a/mobile/openapi/lib/model/asset_response_dto.dart b/mobile/openapi/lib/model/asset_response_dto.dart index f916088ba2..44a41036ab 100644 Binary files a/mobile/openapi/lib/model/asset_response_dto.dart and b/mobile/openapi/lib/model/asset_response_dto.dart differ diff --git a/mobile/openapi/lib/model/usage_by_user_dto.dart b/mobile/openapi/lib/model/usage_by_user_dto.dart index 68b3324895..6657b946e3 100644 Binary files a/mobile/openapi/lib/model/usage_by_user_dto.dart and b/mobile/openapi/lib/model/usage_by_user_dto.dart differ diff --git a/mobile/openapi/lib/model/user_response_dto.dart b/mobile/openapi/lib/model/user_response_dto.dart index a6242d2c84..432ec9b159 100644 Binary files a/mobile/openapi/lib/model/user_response_dto.dart and b/mobile/openapi/lib/model/user_response_dto.dart differ diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index 8dcc4e87a9..2870a23466 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -266,7 +266,7 @@ packages: name: ffi url: "https://pub.dartlang.org" source: hosted - version: "1.2.1" + version: "2.0.1" file: dependency: transitive description: @@ -366,6 +366,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "2.0.0" + flutter_web_auth: + dependency: "direct main" + description: + name: flutter_web_auth + url: "https://pub.dartlang.org" + source: hosted + version: "0.5.0" flutter_web_plugins: dependency: transitive description: flutter @@ -547,12 +554,12 @@ packages: source: hosted version: "1.0.1" logging: - dependency: transitive + dependency: "direct main" description: name: logging url: "https://pub.dartlang.org" source: hosted - version: "1.0.2" + version: "1.1.0" matcher: dependency: transitive description: @@ -622,7 +629,7 @@ packages: name: package_info_plus url: "https://pub.dartlang.org" source: hosted - version: "1.4.2" + version: "1.4.3+1" package_info_plus_linux: dependency: transitive description: @@ -657,7 +664,7 @@ packages: name: package_info_plus_windows url: "https://pub.dartlang.org" source: hosted - version: "1.0.5" + version: "2.1.0" path: dependency: "direct main" description: @@ -692,7 +699,7 @@ packages: name: path_provider_linux url: "https://pub.dartlang.org" source: hosted - version: "2.1.6" + version: "2.1.7" path_provider_macos: dependency: transitive description: @@ -713,7 +720,7 @@ packages: name: path_provider_windows url: "https://pub.dartlang.org" source: hosted - version: "2.0.6" + version: "2.1.3" pedantic: dependency: transitive description: @@ -991,14 +998,14 @@ packages: name: sqflite url: "https://pub.dartlang.org" source: hosted - version: "2.0.2+1" + version: "2.2.0+3" sqflite_common: dependency: transitive description: name: sqflite_common url: "https://pub.dartlang.org" source: hosted - version: "2.2.1+1" + version: "2.4.0+2" stack_trace: dependency: transitive description: @@ -1250,7 +1257,7 @@ packages: name: win32 url: "https://pub.dartlang.org" source: hosted - version: "2.5.2" + version: "2.7.0" wkt_parser: dependency: transitive description: diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index 3e24dbf8f5..11f2f5ae35 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -2,7 +2,7 @@ name: immich_mobile description: Immich - selfhosted backup media file on mobile phone publish_to: "none" -version: 1.35.0+54 +version: 1.37.0+58 environment: sdk: ">=2.17.0 <3.0.0" @@ -40,12 +40,14 @@ dependencies: latlong2: ^0.8.1 collection: ^1.16.0 http_parser: ^4.0.1 + flutter_web_auth: ^0.5.0 openapi: path: openapi # easy to remove packages: image_picker: ^0.8.5+3 # only used to select user profile image from system gallery -> we can simply select an image from within immich? + logging: ^1.1.0 dev_dependencies: flutter_test: @@ -70,7 +72,9 @@ flutter: - family: SnowburstOne fonts: - asset: fonts/SnowburstOne.ttf - + - family: Inconsolata + fonts: + - asset: fonts/Inconsolata-Regular.ttf flutter_icons: image_path_android: "assets/immich-logo-no-outline.png" image_path_ios: "assets/immich-logo-no-outline.png" diff --git a/server/apps/immich/src/api-v1/album/response-dto/album-response.dto.ts b/server/apps/immich/src/api-v1/album/response-dto/album-response.dto.ts index dde9998e3e..71d4475430 100644 --- a/server/apps/immich/src/api-v1/album/response-dto/album-response.dto.ts +++ b/server/apps/immich/src/api-v1/album/response-dto/album-response.dto.ts @@ -18,7 +18,14 @@ export class AlbumResponseDto { } export function mapAlbum(entity: AlbumEntity): AlbumResponseDto { - const sharedUsers = entity.sharedUsers?.map((userAlbum) => mapUser(userAlbum.userInfo)) || []; + const sharedUsers: UserResponseDto[] = []; + + entity.sharedUsers?.forEach((userAlbum) => { + if (userAlbum.userInfo) { + const user = mapUser(userAlbum.userInfo); + sharedUsers.push(user); + } + }); return { albumName: entity.albumName, albumThumbnailAssetId: entity.albumThumbnailAssetId, @@ -33,7 +40,14 @@ export function mapAlbum(entity: AlbumEntity): AlbumResponseDto { } export function mapAlbumExcludeAssetInfo(entity: AlbumEntity): AlbumResponseDto { - const sharedUsers = entity.sharedUsers?.map((userAlbum) => mapUser(userAlbum.userInfo)) || []; + const sharedUsers: UserResponseDto[] = []; + + entity.sharedUsers?.forEach((userAlbum) => { + if (userAlbum.userInfo) { + const user = mapUser(userAlbum.userInfo); + sharedUsers.push(user); + } + }); return { albumName: entity.albumName, albumThumbnailAssetId: entity.albumThumbnailAssetId, diff --git a/server/apps/immich/src/api-v1/asset/asset.controller.ts b/server/apps/immich/src/api-v1/asset/asset.controller.ts index f070fe6415..83befba8b3 100644 --- a/server/apps/immich/src/api-v1/asset/asset.controller.ts +++ b/server/apps/immich/src/api-v1/asset/asset.controller.ts @@ -26,7 +26,7 @@ import { BackgroundTaskService } from '../../modules/background-task/background- import { DeleteAssetDto } from './dto/delete-asset.dto'; import { SearchAssetDto } from './dto/search-asset.dto'; import { CheckDuplicateAssetDto } from './dto/check-duplicate-asset.dto'; -import { ApiBearerAuth, ApiBody, ApiConsumes, ApiTags } from '@nestjs/swagger'; +import { ApiBearerAuth, ApiBody, ApiConsumes, ApiHeader, ApiTags } from '@nestjs/swagger'; import { CuratedObjectsResponseDto } from './response-dto/curated-objects-response.dto'; import { CuratedLocationsResponseDto } from './response-dto/curated-locations-response.dto'; import { AssetResponseDto } from './response-dto/asset-response.dto'; @@ -110,7 +110,7 @@ export class AssetController { } @Get('/file/:assetId') - @Header('Cache-Control', 'max-age=300') + @Header('Cache-Control', 'max-age=3600') async serveFile( @GetAuthUser() authUser: AuthUserDto, @Headers() headers: Record, @@ -123,15 +123,16 @@ export class AssetController { } @Get('/thumbnail/:assetId') - @Header('Cache-Control', 'max-age=300') + @Header('Cache-Control', 'max-age=3600') async getAssetThumbnail( @GetAuthUser() authUser: AuthUserDto, + @Headers() headers: Record, @Response({ passthrough: true }) res: Res, @Param('assetId') assetId: string, @Query(new ValidationPipe({ transform: true })) query: GetAssetThumbnailDto, ): Promise { await this.assetService.checkAssetsAccess(authUser, [assetId]); - return this.assetService.getAssetThumbnail(assetId, query, res); + return this.assetService.getAssetThumbnail(assetId, query, res, headers); } @Get('/curated-objects') @@ -174,8 +175,15 @@ export class AssetController { * Get all AssetEntity belong to the user */ @Get('/') + @ApiHeader({ + name: 'if-none-match', + description: 'ETag of data already cached on the client', + required: false, + schema: { type: 'string' }, + }) async getAllAssets(@GetAuthUser() authUser: AuthUserDto): Promise { - return await this.assetService.getAllAssets(authUser); + const assets = await this.assetService.getAllAssets(authUser); + return assets; } @Post('/time-bucket') diff --git a/server/apps/immich/src/api-v1/asset/asset.service.ts b/server/apps/immich/src/api-v1/asset/asset.service.ts index fb5dc20fdb..6c9d72a0d5 100644 --- a/server/apps/immich/src/api-v1/asset/asset.service.ts +++ b/server/apps/immich/src/api-v1/asset/asset.service.ts @@ -306,7 +306,12 @@ export class AssetService { } } - public async getAssetThumbnail(assetId: string, query: GetAssetThumbnailDto, res: Res) { + public async getAssetThumbnail( + assetId: string, + query: GetAssetThumbnailDto, + res: Res, + headers: Record, + ) { let fileReadStream: ReadStream; const asset = await this.assetRepository.findOne({ where: { id: assetId } }); @@ -316,28 +321,22 @@ export class AssetService { } try { - if (query.format == GetAssetThumbnailFormatEnum.JPEG) { + if (query.format == GetAssetThumbnailFormatEnum.WEBP && asset.webpPath && asset.webpPath.length > 0) { + if (await processETag(asset.webpPath, res, headers)) { + return; + } + await fs.access(asset.webpPath, constants.R_OK); + fileReadStream = createReadStream(asset.webpPath); + } else { if (!asset.resizePath) { throw new NotFoundException('resizePath not set'); } - - await fs.access(asset.resizePath, constants.R_OK | constants.W_OK); - fileReadStream = createReadStream(asset.resizePath); - } else { - if (asset.webpPath && asset.webpPath.length > 0) { - await fs.access(asset.webpPath, constants.R_OK | constants.W_OK); - fileReadStream = createReadStream(asset.webpPath); - } else { - if (!asset.resizePath) { - throw new NotFoundException('resizePath not set'); - } - - await fs.access(asset.resizePath, constants.R_OK | constants.W_OK); - fileReadStream = createReadStream(asset.resizePath); + if (await processETag(asset.resizePath, res, headers)) { + return; } + await fs.access(asset.resizePath, constants.R_OK); + fileReadStream = createReadStream(asset.resizePath); } - - res.header('Cache-Control', 'max-age=300'); return new StreamableFile(fileReadStream); } catch (e) { res.header('Cache-Control', 'none'); @@ -349,7 +348,7 @@ export class AssetService { } } - public async serveFile(assetId: string, query: ServeFileDto, res: Res, headers: any) { + public async serveFile(assetId: string, query: ServeFileDto, res: Res, headers: Record) { let fileReadStream: ReadStream; const asset = await this._assetRepository.getById(assetId); @@ -371,6 +370,9 @@ export class AssetService { Logger.error('Error serving IMAGE asset for web', 'ServeFile'); throw new InternalServerErrorException(`Failed to serve image asset for web`, 'ServeFile'); } + if (await processETag(asset.resizePath, res, headers)) { + return; + } await fs.access(asset.resizePath, constants.R_OK | constants.W_OK); fileReadStream = createReadStream(asset.resizePath); @@ -384,7 +386,9 @@ export class AssetService { res.set({ 'Content-Type': asset.mimeType, }); - + if (await processETag(asset.originalPath, res, headers)) { + return; + } await fs.access(asset.originalPath, constants.R_OK | constants.W_OK); fileReadStream = createReadStream(asset.originalPath); } else { @@ -392,7 +396,9 @@ export class AssetService { res.set({ 'Content-Type': 'image/webp', }); - + if (await processETag(asset.webpPath, res, headers)) { + return; + } await fs.access(asset.webpPath, constants.R_OK | constants.W_OK); fileReadStream = createReadStream(asset.webpPath); } else { @@ -403,6 +409,9 @@ export class AssetService { if (!asset.resizePath) { throw new Error('resizePath not set'); } + if (await processETag(asset.resizePath, res, headers)) { + return; + } await fs.access(asset.resizePath, constants.R_OK | constants.W_OK); fileReadStream = createReadStream(asset.resizePath); @@ -436,9 +445,9 @@ export class AssetService { if (range) { /** Extracting Start and End value from Range Header */ - let [start, end] = range.replace(/bytes=/, '').split('-'); - start = parseInt(start, 10); - end = end ? parseInt(end, 10) : size - 1; + const [startStr, endStr] = range.replace(/bytes=/, '').split('-'); + let start = parseInt(startStr, 10); + let end = endStr ? parseInt(endStr, 10) : size - 1; if (!isNaN(start) && isNaN(end)) { start = start; @@ -475,7 +484,9 @@ export class AssetService { res.set({ 'Content-Type': mimeType, }); - + if (await processETag(asset.originalPath, res, headers)) { + return; + } return new StreamableFile(createReadStream(videoPath)); } } catch (e) { @@ -651,3 +662,14 @@ export class AssetService { } } } + +async function processETag(path: string, res: Res, headers: Record): Promise { + const { size, mtimeNs } = await fs.stat(path, { bigint: true }); + const etag = `W/"${size}-${mtimeNs}"`; + res.setHeader('ETag', etag); + if (etag === headers['if-none-match']) { + res.status(304); + return true; + } + return false; +} diff --git a/server/apps/immich/src/api-v1/asset/response-dto/asset-response.dto.ts b/server/apps/immich/src/api-v1/asset/response-dto/asset-response.dto.ts index 4054d670aa..09d61aae51 100644 --- a/server/apps/immich/src/api-v1/asset/response-dto/asset-response.dto.ts +++ b/server/apps/immich/src/api-v1/asset/response-dto/asset-response.dto.ts @@ -19,10 +19,10 @@ export class AssetResponseDto { mimeType!: string | null; duration!: string; webpPath!: string | null; - encodedVideoPath!: string | null; + encodedVideoPath?: string | null; exifInfo?: ExifResponseDto; smartInfo?: SmartInfoResponseDto; - livePhotoVideoId!: string | null; + livePhotoVideoId?: string | null; } export function mapAsset(entity: AssetEntity): AssetResponseDto { diff --git a/server/apps/immich/src/api-v1/oauth/oauth.controller.ts b/server/apps/immich/src/api-v1/oauth/oauth.controller.ts index eb864a1cb3..13637acc0c 100644 --- a/server/apps/immich/src/api-v1/oauth/oauth.controller.ts +++ b/server/apps/immich/src/api-v1/oauth/oauth.controller.ts @@ -3,6 +3,7 @@ import { ApiTags } from '@nestjs/swagger'; import { Response } from 'express'; import { AuthType } from '../../constants/jwt.constant'; import { ImmichJwtService } from '../../modules/immich-jwt/immich-jwt.service'; +import { LoginResponseDto } from '../auth/response-dto/login-response.dto'; import { OAuthCallbackDto } from './dto/oauth-auth-code.dto'; import { OAuthConfigDto } from './dto/oauth-config.dto'; import { OAuthService } from './oauth.service'; @@ -19,7 +20,10 @@ export class OAuthController { } @Post('/callback') - public async callback(@Res({ passthrough: true }) response: Response, @Body(ValidationPipe) dto: OAuthCallbackDto) { + public async callback( + @Res({ passthrough: true }) response: Response, + @Body(ValidationPipe) dto: OAuthCallbackDto, + ): Promise { const loginResponse = await this.oauthService.callback(dto); response.setHeader('Set-Cookie', this.immichJwtService.getCookies(loginResponse, AuthType.OAUTH)); return loginResponse; diff --git a/server/apps/immich/src/api-v1/server-info/response-dto/server-stats-response.dto.ts b/server/apps/immich/src/api-v1/server-info/response-dto/server-stats-response.dto.ts index aef4acd118..615acfcf05 100644 --- a/server/apps/immich/src/api-v1/server-info/response-dto/server-stats-response.dto.ts +++ b/server/apps/immich/src/api-v1/server-info/response-dto/server-stats-response.dto.ts @@ -5,7 +5,6 @@ export class ServerStatsResponseDto { constructor() { this.photos = 0; this.videos = 0; - this.objects = 0; this.usageByUser = []; this.usageRaw = 0; this.usage = ''; @@ -34,7 +33,6 @@ export class ServerStatsResponseDto { { photos: 1, videos: 1, - objects: 1, diskUsageRaw: 1, }, ], diff --git a/server/apps/immich/src/api-v1/server-info/response-dto/usage-by-user-response.dto.ts b/server/apps/immich/src/api-v1/server-info/response-dto/usage-by-user-response.dto.ts index 863c77af9d..7502d63afd 100644 --- a/server/apps/immich/src/api-v1/server-info/response-dto/usage-by-user-response.dto.ts +++ b/server/apps/immich/src/api-v1/server-info/response-dto/usage-by-user-response.dto.ts @@ -3,16 +3,15 @@ import { ApiProperty } from '@nestjs/swagger'; export class UsageByUserDto { constructor(userId: string) { this.userId = userId; - this.objects = 0; this.videos = 0; this.photos = 0; + this.usageRaw = 0; + this.usage = '0B'; } @ApiProperty({ type: 'string' }) userId: string; @ApiProperty({ type: 'integer' }) - objects: number; - @ApiProperty({ type: 'integer' }) videos: number; @ApiProperty({ type: 'integer' }) photos: number; diff --git a/server/apps/immich/src/api-v1/server-info/server-info.service.ts b/server/apps/immich/src/api-v1/server-info/server-info.service.ts index f13688e6ec..db85a7038f 100644 --- a/server/apps/immich/src/api-v1/server-info/server-info.service.ts +++ b/server/apps/immich/src/api-v1/server-info/server-info.service.ts @@ -7,8 +7,6 @@ import { UsageByUserDto } from './response-dto/usage-by-user-response.dto'; import { AssetEntity } from '@app/database/entities/asset.entity'; import { Repository } from 'typeorm'; import { InjectRepository } from '@nestjs/typeorm'; -import path from 'path'; -import { readdirSync, statSync } from 'fs'; import { asHumanReadable } from '../../utils/human-readable.util'; @Injectable() @@ -35,59 +33,46 @@ export class ServerInfoService { } async getStats(): Promise { - const res = await this.assetRepository - .createQueryBuilder('asset') - .select(`COUNT(asset.id)`, 'count') - .addSelect(`asset.type`, 'type') - .addSelect(`asset.userId`, 'userId') - .groupBy('asset.type, asset.userId') - .addGroupBy('asset.type') + const serverStats = new ServerStatsResponseDto(); + + type UserStatsQueryResponse = { + assetType: string; + assetCount: string; + totalSizeInBytes: string; + userId: string; + }; + + const userStatsQueryResponse: UserStatsQueryResponse[] = await this.assetRepository + .createQueryBuilder('a') + .select('COUNT(a.id)', 'assetCount') + .addSelect('SUM(ei.fileSizeInByte)', 'totalSizeInBytes') + .addSelect('a."userId"') + .addSelect('a.type', 'assetType') + .where('a.isVisible = true') + .leftJoin('a.exifInfo', 'ei') + .groupBy('a."userId"') + .addGroupBy('a.type') .getRawMany(); - const serverStats = new ServerStatsResponseDto(); const tmpMap = new Map(); const getUsageByUser = (id: string) => tmpMap.get(id) || new UsageByUserDto(id); - res.map((item) => { - const usage: UsageByUserDto = getUsageByUser(item.userId); - if (item.type === 'IMAGE') { - usage.photos = parseInt(item.count); - serverStats.photos += usage.photos; - } else if (item.type === 'VIDEO') { - usage.videos = parseInt(item.count); - serverStats.videos += usage.videos; - } - tmpMap.set(item.userId, usage); + + userStatsQueryResponse.forEach((r) => { + const usageByUser = getUsageByUser(r.userId); + usageByUser.photos += r.assetType === 'IMAGE' ? parseInt(r.assetCount) : 0; + usageByUser.videos += r.assetType === 'VIDEO' ? parseInt(r.assetCount) : 0; + usageByUser.usageRaw += parseInt(r.totalSizeInBytes); + usageByUser.usage = asHumanReadable(usageByUser.usageRaw); + + serverStats.photos += r.assetType === 'IMAGE' ? parseInt(r.assetCount) : 0; + serverStats.videos += r.assetType === 'VIDEO' ? parseInt(r.assetCount) : 0; + serverStats.usageRaw += parseInt(r.totalSizeInBytes); + serverStats.usage = asHumanReadable(serverStats.usageRaw); + tmpMap.set(r.userId, usageByUser); }); - for (const userId of tmpMap.keys()) { - const usage = getUsageByUser(userId); - const userDiskUsage = await ServerInfoService.getDirectoryStats(path.join(APP_UPLOAD_LOCATION, userId)); - usage.usageRaw = userDiskUsage.size; - usage.objects = userDiskUsage.fileCount; - usage.usage = asHumanReadable(usage.usageRaw); - serverStats.usageRaw += usage.usageRaw; - serverStats.objects += usage.objects; - } - serverStats.usage = asHumanReadable(serverStats.usageRaw); serverStats.usageByUser = Array.from(tmpMap.values()); + return serverStats; } - - private static async getDirectoryStats(dirPath: string) { - let size = 0; - let fileCount = 0; - for (const filename of readdirSync(dirPath)) { - const absFilename = path.join(dirPath, filename); - const fileStat = statSync(absFilename); - if (fileStat.isFile()) { - size += fileStat.size; - fileCount += 1; - } else if (fileStat.isDirectory()) { - const subDirStat = await ServerInfoService.getDirectoryStats(absFilename); - size += subDirStat.size; - fileCount += subDirStat.fileCount; - } - } - return { size, fileCount }; - } } diff --git a/server/apps/immich/src/api-v1/user/response-dto/user-response.dto.ts b/server/apps/immich/src/api-v1/user/response-dto/user-response.dto.ts index 9308a3fead..145b068414 100644 --- a/server/apps/immich/src/api-v1/user/response-dto/user-response.dto.ts +++ b/server/apps/immich/src/api-v1/user/response-dto/user-response.dto.ts @@ -9,7 +9,7 @@ export class UserResponseDto { profileImagePath!: string; shouldChangePassword!: boolean; isAdmin!: boolean; - deletedAt!: Date | null; + deletedAt?: Date; } export function mapUser(entity: UserEntity): UserResponseDto { @@ -22,6 +22,6 @@ export function mapUser(entity: UserEntity): UserResponseDto { profileImagePath: entity.profileImagePath, shouldChangePassword: entity.shouldChangePassword, isAdmin: entity.isAdmin, - deletedAt: entity.deletedAt || null, + deletedAt: entity.deletedAt, }; } diff --git a/server/apps/immich/src/api-v1/user/user-repository.ts b/server/apps/immich/src/api-v1/user/user-repository.ts index 788b37db0c..e9bccf1e79 100644 --- a/server/apps/immich/src/api-v1/user/user-repository.ts +++ b/server/apps/immich/src/api-v1/user/user-repository.ts @@ -59,7 +59,6 @@ export class UserRepository implements IUserRepository { user.salt = await bcrypt.genSalt(); user.password = await this.hashPassword(user.password, user.salt); } - user.isAdmin = false; return this.userRepository.save(user); } diff --git a/server/apps/immich/src/api-v1/user/user.service.spec.ts b/server/apps/immich/src/api-v1/user/user.service.spec.ts index abed003833..8539e88f46 100644 --- a/server/apps/immich/src/api-v1/user/user.service.spec.ts +++ b/server/apps/immich/src/api-v1/user/user.service.spec.ts @@ -127,5 +127,16 @@ describe('UserService', () => { }); expect(result).rejects.toBeInstanceOf(NotFoundException); }); + + it('cannot delete admin user', () => { + const requestor = adminAuthUser; + + userRepositoryMock.get.mockImplementationOnce(() => Promise.resolve(adminUser)); + userRepositoryMock.get.mockImplementationOnce(() => Promise.resolve(adminUser)); + + const result = sui.deleteUser(requestor, adminAuthUser.id); + + expect(result).rejects.toBeInstanceOf(BadRequestException); + }); }); }); diff --git a/server/apps/immich/src/api-v1/user/user.service.ts b/server/apps/immich/src/api-v1/user/user.service.ts index 311561856f..6fe2aafefd 100644 --- a/server/apps/immich/src/api-v1/user/user.service.ts +++ b/server/apps/immich/src/api-v1/user/user.service.ts @@ -119,6 +119,11 @@ export class UserService { if (!user) { throw new BadRequestException('User not found'); } + + if (user.isAdmin) { + throw new BadRequestException('Cannot delete admin user'); + } + try { const deletedUser = await this.userRepository.delete(user); return mapUser(deletedUser); diff --git a/server/apps/immich/src/constants/server_version.constant.ts b/server/apps/immich/src/constants/server_version.constant.ts index 0131b25f49..8b7e5a2d54 100644 --- a/server/apps/immich/src/constants/server_version.constant.ts +++ b/server/apps/immich/src/constants/server_version.constant.ts @@ -10,7 +10,7 @@ export interface IServerVersion { export const serverVersion: IServerVersion = { major: 1, - minor: 35, + minor: 37, patch: 0, - build: 54, + build: 58, }; diff --git a/server/apps/immich/src/main.ts b/server/apps/immich/src/main.ts index c744c0422a..cd1cd22d23 100644 --- a/server/apps/immich/src/main.ts +++ b/server/apps/immich/src/main.ts @@ -14,6 +14,7 @@ async function bootstrap() { const app = await NestFactory.create(AppModule); app.set('trust proxy'); + app.set('etag', 'strong'); app.use(cookieParser()); app.use(json({ limit: '10mb' })); if (process.env.NODE_ENV === 'development') { diff --git a/server/apps/immich/src/modules/download/download.service.ts b/server/apps/immich/src/modules/download/download.service.ts index 191f9addca..0c47cce429 100644 --- a/server/apps/immich/src/modules/download/download.service.ts +++ b/server/apps/immich/src/modules/download/download.service.ts @@ -35,7 +35,7 @@ export class DownloadService { fileCount++; // for easier testing, can be changed before merging. - if (totalSize > HumanReadableSize.GB * 20) { + if (totalSize > HumanReadableSize.GiB * 20) { complete = false; this.logger.log( `Archive size exceeded after ${fileCount} files, capping at ${totalSize} bytes (${asHumanReadable( diff --git a/server/apps/immich/src/utils/human-readable.util.ts b/server/apps/immich/src/utils/human-readable.util.ts index 6c71d05e20..aa9bb04af8 100644 --- a/server/apps/immich/src/utils/human-readable.util.ts +++ b/server/apps/immich/src/utils/human-readable.util.ts @@ -1,31 +1,25 @@ -const KB = 1000; -const MB = KB * 1000; -const GB = MB * 1000; -const TB = GB * 1000; -const PB = TB * 1000; +const KiB = Math.pow(1024, 1); +const MiB = Math.pow(1024, 2); +const GiB = Math.pow(1024, 3); +const TiB = Math.pow(1024, 4); +const PiB = Math.pow(1024, 5); -export const HumanReadableSize = { KB, MB, GB, TB, PB }; +export const HumanReadableSize = { KiB, MiB, GiB, TiB, PiB }; -export function asHumanReadable(bytes: number, precision = 1) { - if (bytes >= PB) { - return `${(bytes / PB).toFixed(precision)}PB`; - } +export function asHumanReadable(bytes: number, precision = 1): string { + const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']; - if (bytes >= TB) { - return `${(bytes / TB).toFixed(precision)}TB`; - } + let magnitude = 0; + let remainder = bytes; + while (remainder >= 1024) { + if (magnitude + 1 < units.length) { + magnitude++; + remainder /= 1024; + } + else { + break; + } + } - if (bytes >= GB) { - return `${(bytes / GB).toFixed(precision)}GB`; - } - - if (bytes >= MB) { - return `${(bytes / MB).toFixed(precision)}MB`; - } - - if (bytes >= KB) { - return `${(bytes / KB).toFixed(precision)}KB`; - } - - return `${bytes}B`; + return `${remainder.toFixed( magnitude == 0 ? 0 : precision )} ${units[magnitude]}`; } diff --git a/server/immich-openapi-specs.json b/server/immich-openapi-specs.json index 66192c92e8..bee972c82f 100644 --- a/server/immich-openapi-specs.json +++ b/server/immich-openapi-specs.json @@ -1 +1 @@ -{"openapi":"3.0.0","paths":{"/user":{"get":{"operationId":"getAllUsers","parameters":[{"name":"isAll","required":true,"in":"query","schema":{"type":"boolean"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/UserResponseDto"}}}}}},"tags":["User"],"security":[{"bearer":[]}]},"post":{"operationId":"createUser","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateUserDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]},"put":{"operationId":"updateUser","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateUserDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/info/{userId}":{"get":{"operationId":"getUserById","parameters":[{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"]}},"/user/me":{"get":{"operationId":"getMyUserInfo","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/count":{"get":{"operationId":"getUserCount","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserCountResponseDto"}}}}},"tags":["User"]}},"/user/{userId}":{"delete":{"operationId":"deleteUser","parameters":[{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/{userId}/restore":{"post":{"operationId":"restoreUser","parameters":[{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/profile-image":{"post":{"operationId":"createProfileImage","parameters":[],"requestBody":{"required":true,"description":"A new avatar for the user","content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/CreateProfileImageDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateProfileImageResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/profile-image/{userId}":{"get":{"operationId":"getProfileImage","parameters":[{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["User"]}},"/asset/upload":{"post":{"operationId":"uploadFile","parameters":[],"requestBody":{"required":true,"description":"Asset Upload Information","content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/AssetFileUploadDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetFileUploadResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/download/{assetId}":{"get":{"operationId":"downloadFile","parameters":[{"name":"isThumb","required":false,"in":"query","schema":{"title":"Is serve thumbnail (resize) file","type":"boolean"}},{"name":"isWeb","required":false,"in":"query","schema":{"title":"Is request made from web","type":"boolean"}},{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/download-library":{"get":{"operationId":"downloadLibrary","parameters":[{"name":"skip","required":false,"in":"query","schema":{"type":"number"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/file/{assetId}":{"get":{"operationId":"serveFile","parameters":[{"name":"isThumb","required":false,"in":"query","schema":{"title":"Is serve thumbnail (resize) file","type":"boolean"}},{"name":"isWeb","required":false,"in":"query","schema":{"title":"Is request made from web","type":"boolean"}},{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/thumbnail/{assetId}":{"get":{"operationId":"getAssetThumbnail","parameters":[{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}},{"name":"format","required":false,"in":"query","schema":{"$ref":"#/components/schemas/ThumbnailFormat"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/curated-objects":{"get":{"operationId":"getCuratedObjects","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CuratedObjectsResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/curated-locations":{"get":{"operationId":"getCuratedLocations","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CuratedLocationsResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/search-terms":{"get":{"operationId":"getAssetSearchTerms","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"type":"string"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/search":{"post":{"operationId":"searchAsset","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SearchAssetDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AssetResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/count-by-time-bucket":{"post":{"operationId":"getAssetCountByTimeBucket","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GetAssetCountByTimeBucketDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetCountByTimeBucketResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/count-by-user-id":{"get":{"operationId":"getAssetCountByUserId","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetCountByUserIdResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset":{"get":{"operationId":"getAllAssets","summary":"","description":"Get all AssetEntity belong to the user","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AssetResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]},"delete":{"operationId":"deleteAsset","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeleteAssetDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/DeleteAssetResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/time-bucket":{"post":{"operationId":"getAssetByTimeBucket","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GetAssetByTimeBucketDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AssetResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/{deviceId}":{"get":{"operationId":"getUserAssetsByDeviceId","summary":"","description":"Get all asset of a device that are in the database, ID only.","parameters":[{"name":"deviceId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"type":"string"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/assetById/{assetId}":{"get":{"operationId":"getAssetById","summary":"","description":"Get a single asset's information","parameters":[{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]},"put":{"operationId":"updateAssetById","summary":"","description":"Update an asset","parameters":[{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateAssetDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/check":{"post":{"operationId":"checkDuplicateAsset","summary":"","description":"Check duplicated asset before uploading - for Web upload used","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckDuplicateAssetDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckDuplicateAssetResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/exist":{"post":{"operationId":"checkExistingAssets","summary":"","description":"Checks if multiple assets exist on the server and returns all existing - used by background backup","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckExistingAssetsDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckExistingAssetsResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/auth/login":{"post":{"operationId":"login","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginCredentialDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginResponseDto"}}}}},"tags":["Authentication"]}},"/auth/admin-sign-up":{"post":{"operationId":"adminSignUp","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignUpDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdminSignupResponseDto"}}}},"400":{"description":"The server already has an admin"}},"tags":["Authentication"]}},"/auth/validateToken":{"post":{"operationId":"validateAccessToken","parameters":[],"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateAccessTokenResponseDto"}}}}},"tags":["Authentication"],"security":[{"bearer":[]}]}},"/auth/logout":{"post":{"operationId":"logout","parameters":[],"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LogoutResponseDto"}}}}},"tags":["Authentication"]}},"/oauth/config":{"post":{"operationId":"generateConfig","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthConfigDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthConfigResponseDto"}}}}},"tags":["OAuth"]}},"/oauth/callback":{"post":{"operationId":"callback","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthCallbackDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginResponseDto"}}}}},"tags":["OAuth"]}},"/device-info":{"post":{"operationId":"createDeviceInfo","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateDeviceInfoDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeviceInfoResponseDto"}}}}},"tags":["Device Info"],"security":[{"bearer":[]}]},"patch":{"operationId":"updateDeviceInfo","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateDeviceInfoDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeviceInfoResponseDto"}}}}},"tags":["Device Info"],"security":[{"bearer":[]}]}},"/server-info":{"get":{"operationId":"getServerInfo","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerInfoResponseDto"}}}}},"tags":["Server Info"]}},"/server-info/ping":{"get":{"operationId":"pingServer","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerPingResponse"}}}}},"tags":["Server Info"]}},"/server-info/version":{"get":{"operationId":"getServerVersion","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerVersionReponseDto"}}}}},"tags":["Server Info"]}},"/server-info/stats":{"get":{"operationId":"getStats","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerStatsResponseDto"}}}}},"tags":["Server Info"]}},"/album/count-by-user-id":{"get":{"operationId":"getAlbumCountByUserId","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumCountResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album":{"post":{"operationId":"createAlbum","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateAlbumDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]},"get":{"operationId":"getAllAlbums","parameters":[{"name":"shared","required":false,"in":"query","schema":{"type":"boolean"}},{"name":"assetId","required":false,"in":"query","description":"Only returns albums that contain the asset\nIgnores the shared parameter\nundefined: get all albums","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}/users":{"put":{"operationId":"addUsersToAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddUsersDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}/assets":{"put":{"operationId":"addAssetsToAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddAssetsDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddAssetsResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]},"delete":{"operationId":"removeAssetFromAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RemoveAssetsDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}":{"get":{"operationId":"getAlbumInfo","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]},"delete":{"operationId":"deleteAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":""}},"tags":["Album"],"security":[{"bearer":[]}]},"patch":{"operationId":"updateAlbumInfo","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateAlbumDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}/user/{userId}":{"delete":{"operationId":"removeUserFromAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}},{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":""}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}/download":{"get":{"operationId":"downloadArchive","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}},{"name":"skip","required":false,"in":"query","schema":{"type":"number"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/jobs":{"get":{"operationId":"getAllJobsStatus","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AllJobStatusResponseDto"}}}}},"tags":["Job"],"security":[{"bearer":[]}]}},"/jobs/{jobId}":{"get":{"operationId":"getJobStatus","parameters":[{"name":"jobId","required":true,"in":"path","schema":{"$ref":"#/components/schemas/JobId"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/JobStatusResponseDto"}}}}},"tags":["Job"],"security":[{"bearer":[]}]},"put":{"operationId":"sendJobCommand","parameters":[{"name":"jobId","required":true,"in":"path","schema":{"$ref":"#/components/schemas/JobId"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/JobCommandDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"number"}}}}},"tags":["Job"],"security":[{"bearer":[]}]}},"/system-config":{"get":{"operationId":"getConfig","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SystemConfigResponseDto"}}}}},"tags":["System Config"],"security":[{"bearer":[]}]},"put":{"operationId":"updateConfig","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateSystemConfigDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SystemConfigResponseDto"}}}}},"tags":["System Config"],"security":[{"bearer":[]}]}}},"info":{"title":"Immich","description":"Immich API","version":"1.17.0","contact":{}},"tags":[],"servers":[{"url":"/api"}],"components":{"securitySchemes":{"bearer":{"scheme":"Bearer","bearerFormat":"JWT","type":"http","name":"JWT","description":"Enter JWT token","in":"header"}},"schemas":{"UserResponseDto":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"createdAt":{"type":"string"},"profileImagePath":{"type":"string"},"shouldChangePassword":{"type":"boolean"},"isAdmin":{"type":"boolean"},"deletedAt":{"format":"date-time","type":"string","nullable":true}},"required":["id","email","firstName","lastName","createdAt","profileImagePath","shouldChangePassword","isAdmin","deletedAt"]},"CreateUserDto":{"type":"object","properties":{"email":{"type":"string","example":"testuser@email.com"},"password":{"type":"string","example":"password"},"firstName":{"type":"string","example":"John"},"lastName":{"type":"string","example":"Doe"}},"required":["email","password","firstName","lastName"]},"UserCountResponseDto":{"type":"object","properties":{"userCount":{"type":"integer"}},"required":["userCount"]},"UpdateUserDto":{"type":"object","properties":{"id":{"type":"string"},"password":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"isAdmin":{"type":"boolean"},"shouldChangePassword":{"type":"boolean"},"profileImagePath":{"type":"string"}},"required":["id"]},"CreateProfileImageDto":{"type":"object","properties":{"file":{"type":"string","format":"binary"}},"required":["file"]},"CreateProfileImageResponseDto":{"type":"object","properties":{"userId":{"type":"string"},"profileImagePath":{"type":"string"}},"required":["userId","profileImagePath"]},"AssetFileUploadDto":{"type":"object","properties":{"assetData":{"type":"string","format":"binary"}},"required":["assetData"]},"AssetFileUploadResponseDto":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"ThumbnailFormat":{"type":"string","enum":["JPEG","WEBP"]},"CuratedObjectsResponseDto":{"type":"object","properties":{"id":{"type":"string"},"object":{"type":"string"},"resizePath":{"type":"string"},"deviceAssetId":{"type":"string"},"deviceId":{"type":"string"}},"required":["id","object","resizePath","deviceAssetId","deviceId"]},"CuratedLocationsResponseDto":{"type":"object","properties":{"id":{"type":"string"},"city":{"type":"string"},"resizePath":{"type":"string"},"deviceAssetId":{"type":"string"},"deviceId":{"type":"string"}},"required":["id","city","resizePath","deviceAssetId","deviceId"]},"SearchAssetDto":{"type":"object","properties":{"searchTerm":{"type":"string"}},"required":["searchTerm"]},"AssetTypeEnum":{"type":"string","enum":["IMAGE","VIDEO","AUDIO","OTHER"]},"ExifResponseDto":{"type":"object","properties":{"id":{"type":"integer","nullable":true,"default":null,"format":"int64"},"fileSizeInByte":{"type":"integer","nullable":true,"default":null,"format":"int64"},"make":{"type":"string","nullable":true,"default":null},"model":{"type":"string","nullable":true,"default":null},"imageName":{"type":"string","nullable":true,"default":null},"exifImageWidth":{"type":"number","nullable":true,"default":null},"exifImageHeight":{"type":"number","nullable":true,"default":null},"orientation":{"type":"string","nullable":true,"default":null},"dateTimeOriginal":{"format":"date-time","type":"string","nullable":true,"default":null},"modifyDate":{"format":"date-time","type":"string","nullable":true,"default":null},"lensModel":{"type":"string","nullable":true,"default":null},"fNumber":{"type":"number","nullable":true,"default":null},"focalLength":{"type":"number","nullable":true,"default":null},"iso":{"type":"number","nullable":true,"default":null},"exposureTime":{"type":"number","nullable":true,"default":null},"latitude":{"type":"number","nullable":true,"default":null},"longitude":{"type":"number","nullable":true,"default":null},"city":{"type":"string","nullable":true,"default":null},"state":{"type":"string","nullable":true,"default":null},"country":{"type":"string","nullable":true,"default":null}}},"SmartInfoResponseDto":{"type":"object","properties":{"id":{"type":"string"},"tags":{"nullable":true,"type":"array","items":{"type":"string"}},"objects":{"nullable":true,"type":"array","items":{"type":"string"}}}},"AssetResponseDto":{"type":"object","properties":{"type":{"$ref":"#/components/schemas/AssetTypeEnum"},"id":{"type":"string"},"deviceAssetId":{"type":"string"},"ownerId":{"type":"string"},"deviceId":{"type":"string"},"originalPath":{"type":"string"},"resizePath":{"type":"string","nullable":true},"createdAt":{"type":"string"},"modifiedAt":{"type":"string"},"isFavorite":{"type":"boolean"},"mimeType":{"type":"string","nullable":true},"duration":{"type":"string"},"webpPath":{"type":"string","nullable":true},"encodedVideoPath":{"type":"string","nullable":true},"exifInfo":{"$ref":"#/components/schemas/ExifResponseDto"},"smartInfo":{"$ref":"#/components/schemas/SmartInfoResponseDto"},"livePhotoVideoId":{"type":"string","nullable":true}},"required":["type","id","deviceAssetId","ownerId","deviceId","originalPath","resizePath","createdAt","modifiedAt","isFavorite","mimeType","duration","webpPath","encodedVideoPath","livePhotoVideoId"]},"TimeGroupEnum":{"type":"string","enum":["day","month"]},"GetAssetCountByTimeBucketDto":{"type":"object","properties":{"timeGroup":{"$ref":"#/components/schemas/TimeGroupEnum"}},"required":["timeGroup"]},"AssetCountByTimeBucket":{"type":"object","properties":{"timeBucket":{"type":"string"},"count":{"type":"integer"}},"required":["timeBucket","count"]},"AssetCountByTimeBucketResponseDto":{"type":"object","properties":{"totalCount":{"type":"integer"},"buckets":{"type":"array","items":{"$ref":"#/components/schemas/AssetCountByTimeBucket"}}},"required":["totalCount","buckets"]},"AssetCountByUserIdResponseDto":{"type":"object","properties":{"audio":{"type":"integer","default":0},"photos":{"type":"integer","default":0},"videos":{"type":"integer","default":0},"other":{"type":"integer","default":0},"total":{"type":"integer","default":0}},"required":["audio","photos","videos","other","total"]},"GetAssetByTimeBucketDto":{"type":"object","properties":{"timeBucket":{"title":"Array of date time buckets","example":["2015-06-01T00:00:00.000Z","2016-02-01T00:00:00.000Z","2016-03-01T00:00:00.000Z"],"type":"array","items":{"type":"string"}}},"required":["timeBucket"]},"UpdateAssetDto":{"type":"object","properties":{"isFavorite":{"type":"boolean"}},"required":["isFavorite"]},"DeleteAssetDto":{"type":"object","properties":{"ids":{"title":"Array of asset IDs to delete","example":["bf973405-3f2a-48d2-a687-2ed4167164be","dd41870b-5d00-46d2-924e-1d8489a0aa0f","fad77c3f-deef-4e7e-9608-14c1aa4e559a"],"type":"array","items":{"type":"string"}}},"required":["ids"]},"DeleteAssetStatus":{"type":"string","enum":["SUCCESS","FAILED"]},"DeleteAssetResponseDto":{"type":"object","properties":{"status":{"$ref":"#/components/schemas/DeleteAssetStatus"},"id":{"type":"string"}},"required":["status","id"]},"CheckDuplicateAssetDto":{"type":"object","properties":{"deviceAssetId":{"type":"string"},"deviceId":{"type":"string"}},"required":["deviceAssetId","deviceId"]},"CheckDuplicateAssetResponseDto":{"type":"object","properties":{"isExist":{"type":"boolean"},"id":{"type":"string"}},"required":["isExist"]},"CheckExistingAssetsDto":{"type":"object","properties":{"deviceAssetIds":{"type":"array","items":{"type":"string"}},"deviceId":{"type":"string"}},"required":["deviceAssetIds","deviceId"]},"CheckExistingAssetsResponseDto":{"type":"object","properties":{"existingIds":{"type":"array","items":{"type":"string"}}},"required":["existingIds"]},"LoginCredentialDto":{"type":"object","properties":{"email":{"type":"string","example":"testuser@email.com"},"password":{"type":"string","example":"password"}},"required":["email","password"]},"LoginResponseDto":{"type":"object","properties":{"accessToken":{"type":"string","readOnly":true},"userId":{"type":"string","readOnly":true},"userEmail":{"type":"string","readOnly":true},"firstName":{"type":"string","readOnly":true},"lastName":{"type":"string","readOnly":true},"profileImagePath":{"type":"string","readOnly":true},"isAdmin":{"type":"boolean","readOnly":true},"shouldChangePassword":{"type":"boolean","readOnly":true}},"required":["accessToken","userId","userEmail","firstName","lastName","profileImagePath","isAdmin","shouldChangePassword"]},"SignUpDto":{"type":"object","properties":{"email":{"type":"string","example":"testuser@email.com"},"password":{"type":"string","example":"password"},"firstName":{"type":"string","example":"Admin"},"lastName":{"type":"string","example":"Doe"}},"required":["email","password","firstName","lastName"]},"AdminSignupResponseDto":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"createdAt":{"type":"string"}},"required":["id","email","firstName","lastName","createdAt"]},"ValidateAccessTokenResponseDto":{"type":"object","properties":{"authStatus":{"type":"boolean"}},"required":["authStatus"]},"LogoutResponseDto":{"type":"object","properties":{"successful":{"type":"boolean","readOnly":true},"redirectUri":{"type":"string","readOnly":true}},"required":["successful","redirectUri"]},"OAuthConfigDto":{"type":"object","properties":{"redirectUri":{"type":"string"}},"required":["redirectUri"]},"OAuthConfigResponseDto":{"type":"object","properties":{"enabled":{"type":"boolean","readOnly":true},"url":{"type":"string","readOnly":true},"buttonText":{"type":"string","readOnly":true}},"required":["enabled"]},"OAuthCallbackDto":{"type":"object","properties":{"url":{"type":"string"}},"required":["url"]},"DeviceTypeEnum":{"type":"string","enum":["IOS","ANDROID","WEB"]},"CreateDeviceInfoDto":{"type":"object","properties":{"deviceType":{"$ref":"#/components/schemas/DeviceTypeEnum"},"deviceId":{"type":"string"},"isAutoBackup":{"type":"boolean"}},"required":["deviceType","deviceId"]},"DeviceInfoResponseDto":{"type":"object","properties":{"id":{"type":"integer"},"deviceType":{"$ref":"#/components/schemas/DeviceTypeEnum"},"userId":{"type":"string"},"deviceId":{"type":"string"},"createdAt":{"type":"string"},"isAutoBackup":{"type":"boolean"}},"required":["id","deviceType","userId","deviceId","createdAt","isAutoBackup"]},"UpdateDeviceInfoDto":{"type":"object","properties":{"deviceType":{"$ref":"#/components/schemas/DeviceTypeEnum"},"deviceId":{"type":"string"},"isAutoBackup":{"type":"boolean"}},"required":["deviceType","deviceId"]},"ServerInfoResponseDto":{"type":"object","properties":{"diskSizeRaw":{"type":"integer","format":"int64"},"diskUseRaw":{"type":"integer","format":"int64"},"diskAvailableRaw":{"type":"integer","format":"int64"},"diskUsagePercentage":{"type":"number","format":"float"},"diskSize":{"type":"string"},"diskUse":{"type":"string"},"diskAvailable":{"type":"string"}},"required":["diskSizeRaw","diskUseRaw","diskAvailableRaw","diskUsagePercentage","diskSize","diskUse","diskAvailable"]},"ServerPingResponse":{"type":"object","properties":{"res":{"type":"string","readOnly":true,"example":"pong"}},"required":["res"]},"ServerVersionReponseDto":{"type":"object","properties":{"major":{"type":"integer"},"minor":{"type":"integer"},"patch":{"type":"integer"},"build":{"type":"integer"}},"required":["major","minor","patch","build"]},"UsageByUserDto":{"type":"object","properties":{"userId":{"type":"string"},"objects":{"type":"integer"},"videos":{"type":"integer"},"photos":{"type":"integer"},"usageRaw":{"type":"integer","format":"int64"},"usage":{"type":"string"}},"required":["userId","objects","videos","photos","usageRaw","usage"]},"ServerStatsResponseDto":{"type":"object","properties":{"photos":{"type":"integer"},"videos":{"type":"integer"},"objects":{"type":"integer"},"usageRaw":{"type":"integer","format":"int64"},"usage":{"type":"string"},"usageByUser":{"title":"Array of usage for each user","example":[{"photos":1,"videos":1,"objects":1,"diskUsageRaw":1}],"type":"array","items":{"$ref":"#/components/schemas/UsageByUserDto"}}},"required":["photos","videos","objects","usageRaw","usage","usageByUser"]},"AlbumCountResponseDto":{"type":"object","properties":{"owned":{"type":"integer"},"shared":{"type":"integer"},"sharing":{"type":"integer"}},"required":["owned","shared","sharing"]},"CreateAlbumDto":{"type":"object","properties":{"albumName":{"type":"string"},"sharedWithUserIds":{"type":"array","items":{"type":"string"}},"assetIds":{"type":"array","items":{"type":"string"}}},"required":["albumName"]},"AlbumResponseDto":{"type":"object","properties":{"assetCount":{"type":"integer"},"id":{"type":"string"},"ownerId":{"type":"string"},"albumName":{"type":"string"},"createdAt":{"type":"string"},"albumThumbnailAssetId":{"type":"string","nullable":true},"shared":{"type":"boolean"},"sharedUsers":{"type":"array","items":{"$ref":"#/components/schemas/UserResponseDto"}},"assets":{"type":"array","items":{"$ref":"#/components/schemas/AssetResponseDto"}}},"required":["assetCount","id","ownerId","albumName","createdAt","albumThumbnailAssetId","shared","sharedUsers","assets"]},"AddUsersDto":{"type":"object","properties":{"sharedUserIds":{"type":"array","items":{"type":"string"}}},"required":["sharedUserIds"]},"AddAssetsDto":{"type":"object","properties":{"assetIds":{"type":"array","items":{"type":"string"}}},"required":["assetIds"]},"AddAssetsResponseDto":{"type":"object","properties":{"successfullyAdded":{"type":"integer"},"alreadyInAlbum":{"type":"array","items":{"type":"string"}},"album":{"$ref":"#/components/schemas/AlbumResponseDto"}},"required":["successfullyAdded","alreadyInAlbum"]},"RemoveAssetsDto":{"type":"object","properties":{"assetIds":{"type":"array","items":{"type":"string"}}},"required":["assetIds"]},"UpdateAlbumDto":{"type":"object","properties":{"albumName":{"type":"string"},"albumThumbnailAssetId":{"type":"string"}}},"JobCounts":{"type":"object","properties":{"active":{"type":"integer"},"completed":{"type":"integer"},"failed":{"type":"integer"},"delayed":{"type":"integer"},"waiting":{"type":"integer"}},"required":["active","completed","failed","delayed","waiting"]},"AllJobStatusResponseDto":{"type":"object","properties":{"thumbnailGenerationQueueCount":{"$ref":"#/components/schemas/JobCounts"},"metadataExtractionQueueCount":{"$ref":"#/components/schemas/JobCounts"},"videoConversionQueueCount":{"$ref":"#/components/schemas/JobCounts"},"machineLearningQueueCount":{"$ref":"#/components/schemas/JobCounts"},"isThumbnailGenerationActive":{"type":"boolean"},"isMetadataExtractionActive":{"type":"boolean"},"isVideoConversionActive":{"type":"boolean"},"isMachineLearningActive":{"type":"boolean"}},"required":["thumbnailGenerationQueueCount","metadataExtractionQueueCount","videoConversionQueueCount","machineLearningQueueCount","isThumbnailGenerationActive","isMetadataExtractionActive","isVideoConversionActive","isMachineLearningActive"]},"JobId":{"type":"string","enum":["thumbnail-generation","metadata-extraction","video-conversion","machine-learning"]},"JobStatusResponseDto":{"type":"object","properties":{"isActive":{"type":"boolean"},"queueCount":{"type":"object"}},"required":["isActive","queueCount"]},"JobCommand":{"type":"string","enum":["start","stop"]},"JobCommandDto":{"type":"object","properties":{"command":{"$ref":"#/components/schemas/JobCommand"}},"required":["command"]},"SystemConfigKey":{"type":"string","enum":["ffmpeg_crf","ffmpeg_preset","ffmpeg_target_video_codec","ffmpeg_target_audio_codec","ffmpeg_target_scaling"]},"SystemConfigResponseItem":{"type":"object","properties":{"name":{"type":"string"},"key":{"$ref":"#/components/schemas/SystemConfigKey"},"value":{"type":"string"},"defaultValue":{"type":"string"}},"required":["name","key","value","defaultValue"]},"SystemConfigResponseDto":{"type":"object","properties":{"config":{"type":"array","items":{"$ref":"#/components/schemas/SystemConfigResponseItem"}}},"required":["config"]},"UpdateSystemConfigDto":{"type":"object","properties":{}}}}} \ No newline at end of file +{"openapi":"3.0.0","paths":{"/user":{"get":{"operationId":"getAllUsers","parameters":[{"name":"isAll","required":true,"in":"query","schema":{"type":"boolean"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/UserResponseDto"}}}}}},"tags":["User"],"security":[{"bearer":[]}]},"post":{"operationId":"createUser","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateUserDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]},"put":{"operationId":"updateUser","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateUserDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/info/{userId}":{"get":{"operationId":"getUserById","parameters":[{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"]}},"/user/me":{"get":{"operationId":"getMyUserInfo","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/count":{"get":{"operationId":"getUserCount","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserCountResponseDto"}}}}},"tags":["User"]}},"/user/{userId}":{"delete":{"operationId":"deleteUser","parameters":[{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/{userId}/restore":{"post":{"operationId":"restoreUser","parameters":[{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/UserResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/profile-image":{"post":{"operationId":"createProfileImage","parameters":[],"requestBody":{"required":true,"description":"A new avatar for the user","content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/CreateProfileImageDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateProfileImageResponseDto"}}}}},"tags":["User"],"security":[{"bearer":[]}]}},"/user/profile-image/{userId}":{"get":{"operationId":"getProfileImage","parameters":[{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["User"]}},"/asset/upload":{"post":{"operationId":"uploadFile","parameters":[],"requestBody":{"required":true,"description":"Asset Upload Information","content":{"multipart/form-data":{"schema":{"$ref":"#/components/schemas/AssetFileUploadDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetFileUploadResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/download/{assetId}":{"get":{"operationId":"downloadFile","parameters":[{"name":"isThumb","required":false,"in":"query","schema":{"title":"Is serve thumbnail (resize) file","type":"boolean"}},{"name":"isWeb","required":false,"in":"query","schema":{"title":"Is request made from web","type":"boolean"}},{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/download-library":{"get":{"operationId":"downloadLibrary","parameters":[{"name":"skip","required":false,"in":"query","schema":{"type":"number"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/file/{assetId}":{"get":{"operationId":"serveFile","parameters":[{"name":"isThumb","required":false,"in":"query","schema":{"title":"Is serve thumbnail (resize) file","type":"boolean"}},{"name":"isWeb","required":false,"in":"query","schema":{"title":"Is request made from web","type":"boolean"}},{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/thumbnail/{assetId}":{"get":{"operationId":"getAssetThumbnail","parameters":[{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}},{"name":"format","required":false,"in":"query","schema":{"$ref":"#/components/schemas/ThumbnailFormat"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/curated-objects":{"get":{"operationId":"getCuratedObjects","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CuratedObjectsResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/curated-locations":{"get":{"operationId":"getCuratedLocations","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/CuratedLocationsResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/search-terms":{"get":{"operationId":"getAssetSearchTerms","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"type":"string"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/search":{"post":{"operationId":"searchAsset","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SearchAssetDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AssetResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/count-by-time-bucket":{"post":{"operationId":"getAssetCountByTimeBucket","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GetAssetCountByTimeBucketDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetCountByTimeBucketResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/count-by-user-id":{"get":{"operationId":"getAssetCountByUserId","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetCountByUserIdResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset":{"get":{"operationId":"getAllAssets","summary":"","description":"Get all AssetEntity belong to the user","parameters":[{"name":"if-none-match","in":"header","description":"ETag of data already cached on the client","required":false,"schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AssetResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]},"delete":{"operationId":"deleteAsset","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeleteAssetDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/DeleteAssetResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/time-bucket":{"post":{"operationId":"getAssetByTimeBucket","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GetAssetByTimeBucketDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AssetResponseDto"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/{deviceId}":{"get":{"operationId":"getUserAssetsByDeviceId","summary":"","description":"Get all asset of a device that are in the database, ID only.","parameters":[{"name":"deviceId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"type":"string"}}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/assetById/{assetId}":{"get":{"operationId":"getAssetById","summary":"","description":"Get a single asset's information","parameters":[{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]},"put":{"operationId":"updateAssetById","summary":"","description":"Update an asset","parameters":[{"name":"assetId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateAssetDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AssetResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/check":{"post":{"operationId":"checkDuplicateAsset","summary":"","description":"Check duplicated asset before uploading - for Web upload used","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckDuplicateAssetDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckDuplicateAssetResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/asset/exist":{"post":{"operationId":"checkExistingAssets","summary":"","description":"Checks if multiple assets exist on the server and returns all existing - used by background backup","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckExistingAssetsDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CheckExistingAssetsResponseDto"}}}}},"tags":["Asset"],"security":[{"bearer":[]}]}},"/auth/login":{"post":{"operationId":"login","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginCredentialDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginResponseDto"}}}}},"tags":["Authentication"]}},"/auth/admin-sign-up":{"post":{"operationId":"adminSignUp","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SignUpDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AdminSignupResponseDto"}}}},"400":{"description":"The server already has an admin"}},"tags":["Authentication"]}},"/auth/validateToken":{"post":{"operationId":"validateAccessToken","parameters":[],"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ValidateAccessTokenResponseDto"}}}}},"tags":["Authentication"],"security":[{"bearer":[]}]}},"/auth/logout":{"post":{"operationId":"logout","parameters":[],"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LogoutResponseDto"}}}}},"tags":["Authentication"]}},"/oauth/config":{"post":{"operationId":"generateConfig","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthConfigDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthConfigResponseDto"}}}}},"tags":["OAuth"]}},"/oauth/callback":{"post":{"operationId":"callback","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/OAuthCallbackDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/LoginResponseDto"}}}}},"tags":["OAuth"]}},"/device-info":{"post":{"operationId":"createDeviceInfo","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateDeviceInfoDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeviceInfoResponseDto"}}}}},"tags":["Device Info"],"security":[{"bearer":[]}]},"patch":{"operationId":"updateDeviceInfo","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateDeviceInfoDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeviceInfoResponseDto"}}}}},"tags":["Device Info"],"security":[{"bearer":[]}]}},"/server-info":{"get":{"operationId":"getServerInfo","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerInfoResponseDto"}}}}},"tags":["Server Info"]}},"/server-info/ping":{"get":{"operationId":"pingServer","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerPingResponse"}}}}},"tags":["Server Info"]}},"/server-info/version":{"get":{"operationId":"getServerVersion","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerVersionReponseDto"}}}}},"tags":["Server Info"]}},"/server-info/stats":{"get":{"operationId":"getStats","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ServerStatsResponseDto"}}}}},"tags":["Server Info"]}},"/album/count-by-user-id":{"get":{"operationId":"getAlbumCountByUserId","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumCountResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album":{"post":{"operationId":"createAlbum","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/CreateAlbumDto"}}}},"responses":{"201":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]},"get":{"operationId":"getAllAlbums","parameters":[{"name":"shared","required":false,"in":"query","schema":{"type":"boolean"}},{"name":"assetId","required":false,"in":"query","description":"Only returns albums that contain the asset\nIgnores the shared parameter\nundefined: get all albums","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"array","items":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}/users":{"put":{"operationId":"addUsersToAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddUsersDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}/assets":{"put":{"operationId":"addAssetsToAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddAssetsDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AddAssetsResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]},"delete":{"operationId":"removeAssetFromAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/RemoveAssetsDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}":{"get":{"operationId":"getAlbumInfo","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]},"delete":{"operationId":"deleteAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":""}},"tags":["Album"],"security":[{"bearer":[]}]},"patch":{"operationId":"updateAlbumInfo","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateAlbumDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AlbumResponseDto"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}/user/{userId}":{"delete":{"operationId":"removeUserFromAlbum","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}},{"name":"userId","required":true,"in":"path","schema":{"type":"string"}}],"responses":{"200":{"description":""}},"tags":["Album"],"security":[{"bearer":[]}]}},"/album/{albumId}/download":{"get":{"operationId":"downloadArchive","parameters":[{"name":"albumId","required":true,"in":"path","schema":{"type":"string"}},{"name":"skip","required":false,"in":"query","schema":{"type":"number"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"object"}}}}},"tags":["Album"],"security":[{"bearer":[]}]}},"/jobs":{"get":{"operationId":"getAllJobsStatus","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AllJobStatusResponseDto"}}}}},"tags":["Job"],"security":[{"bearer":[]}]}},"/jobs/{jobId}":{"get":{"operationId":"getJobStatus","parameters":[{"name":"jobId","required":true,"in":"path","schema":{"$ref":"#/components/schemas/JobId"}}],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/JobStatusResponseDto"}}}}},"tags":["Job"],"security":[{"bearer":[]}]},"put":{"operationId":"sendJobCommand","parameters":[{"name":"jobId","required":true,"in":"path","schema":{"$ref":"#/components/schemas/JobId"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/JobCommandDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"type":"number"}}}}},"tags":["Job"],"security":[{"bearer":[]}]}},"/system-config":{"get":{"operationId":"getConfig","parameters":[],"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SystemConfigResponseDto"}}}}},"tags":["System Config"],"security":[{"bearer":[]}]},"put":{"operationId":"updateConfig","parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/UpdateSystemConfigDto"}}}},"responses":{"200":{"description":"","content":{"application/json":{"schema":{"$ref":"#/components/schemas/SystemConfigResponseDto"}}}}},"tags":["System Config"],"security":[{"bearer":[]}]}}},"info":{"title":"Immich","description":"Immich API","version":"1.17.0","contact":{}},"tags":[],"servers":[{"url":"/api"}],"components":{"securitySchemes":{"bearer":{"scheme":"Bearer","bearerFormat":"JWT","type":"http","name":"JWT","description":"Enter JWT token","in":"header"}},"schemas":{"UserResponseDto":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"createdAt":{"type":"string"},"profileImagePath":{"type":"string"},"shouldChangePassword":{"type":"boolean"},"isAdmin":{"type":"boolean"},"deletedAt":{"format":"date-time","type":"string"}},"required":["id","email","firstName","lastName","createdAt","profileImagePath","shouldChangePassword","isAdmin"]},"CreateUserDto":{"type":"object","properties":{"email":{"type":"string","example":"testuser@email.com"},"password":{"type":"string","example":"password"},"firstName":{"type":"string","example":"John"},"lastName":{"type":"string","example":"Doe"}},"required":["email","password","firstName","lastName"]},"UserCountResponseDto":{"type":"object","properties":{"userCount":{"type":"integer"}},"required":["userCount"]},"UpdateUserDto":{"type":"object","properties":{"id":{"type":"string"},"password":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"isAdmin":{"type":"boolean"},"shouldChangePassword":{"type":"boolean"},"profileImagePath":{"type":"string"}},"required":["id"]},"CreateProfileImageDto":{"type":"object","properties":{"file":{"type":"string","format":"binary"}},"required":["file"]},"CreateProfileImageResponseDto":{"type":"object","properties":{"userId":{"type":"string"},"profileImagePath":{"type":"string"}},"required":["userId","profileImagePath"]},"AssetFileUploadDto":{"type":"object","properties":{"assetData":{"type":"string","format":"binary"}},"required":["assetData"]},"AssetFileUploadResponseDto":{"type":"object","properties":{"id":{"type":"string"}},"required":["id"]},"ThumbnailFormat":{"type":"string","enum":["JPEG","WEBP"]},"CuratedObjectsResponseDto":{"type":"object","properties":{"id":{"type":"string"},"object":{"type":"string"},"resizePath":{"type":"string"},"deviceAssetId":{"type":"string"},"deviceId":{"type":"string"}},"required":["id","object","resizePath","deviceAssetId","deviceId"]},"CuratedLocationsResponseDto":{"type":"object","properties":{"id":{"type":"string"},"city":{"type":"string"},"resizePath":{"type":"string"},"deviceAssetId":{"type":"string"},"deviceId":{"type":"string"}},"required":["id","city","resizePath","deviceAssetId","deviceId"]},"SearchAssetDto":{"type":"object","properties":{"searchTerm":{"type":"string"}},"required":["searchTerm"]},"AssetTypeEnum":{"type":"string","enum":["IMAGE","VIDEO","AUDIO","OTHER"]},"ExifResponseDto":{"type":"object","properties":{"id":{"type":"integer","nullable":true,"default":null,"format":"int64"},"fileSizeInByte":{"type":"integer","nullable":true,"default":null,"format":"int64"},"make":{"type":"string","nullable":true,"default":null},"model":{"type":"string","nullable":true,"default":null},"imageName":{"type":"string","nullable":true,"default":null},"exifImageWidth":{"type":"number","nullable":true,"default":null},"exifImageHeight":{"type":"number","nullable":true,"default":null},"orientation":{"type":"string","nullable":true,"default":null},"dateTimeOriginal":{"format":"date-time","type":"string","nullable":true,"default":null},"modifyDate":{"format":"date-time","type":"string","nullable":true,"default":null},"lensModel":{"type":"string","nullable":true,"default":null},"fNumber":{"type":"number","nullable":true,"default":null},"focalLength":{"type":"number","nullable":true,"default":null},"iso":{"type":"number","nullable":true,"default":null},"exposureTime":{"type":"number","nullable":true,"default":null},"latitude":{"type":"number","nullable":true,"default":null},"longitude":{"type":"number","nullable":true,"default":null},"city":{"type":"string","nullable":true,"default":null},"state":{"type":"string","nullable":true,"default":null},"country":{"type":"string","nullable":true,"default":null}}},"SmartInfoResponseDto":{"type":"object","properties":{"id":{"type":"string"},"tags":{"nullable":true,"type":"array","items":{"type":"string"}},"objects":{"nullable":true,"type":"array","items":{"type":"string"}}}},"AssetResponseDto":{"type":"object","properties":{"type":{"$ref":"#/components/schemas/AssetTypeEnum"},"id":{"type":"string"},"deviceAssetId":{"type":"string"},"ownerId":{"type":"string"},"deviceId":{"type":"string"},"originalPath":{"type":"string"},"resizePath":{"type":"string","nullable":true},"createdAt":{"type":"string"},"modifiedAt":{"type":"string"},"isFavorite":{"type":"boolean"},"mimeType":{"type":"string","nullable":true},"duration":{"type":"string"},"webpPath":{"type":"string","nullable":true},"encodedVideoPath":{"type":"string","nullable":true},"exifInfo":{"$ref":"#/components/schemas/ExifResponseDto"},"smartInfo":{"$ref":"#/components/schemas/SmartInfoResponseDto"},"livePhotoVideoId":{"type":"string","nullable":true}},"required":["type","id","deviceAssetId","ownerId","deviceId","originalPath","resizePath","createdAt","modifiedAt","isFavorite","mimeType","duration","webpPath"]},"TimeGroupEnum":{"type":"string","enum":["day","month"]},"GetAssetCountByTimeBucketDto":{"type":"object","properties":{"timeGroup":{"$ref":"#/components/schemas/TimeGroupEnum"}},"required":["timeGroup"]},"AssetCountByTimeBucket":{"type":"object","properties":{"timeBucket":{"type":"string"},"count":{"type":"integer"}},"required":["timeBucket","count"]},"AssetCountByTimeBucketResponseDto":{"type":"object","properties":{"totalCount":{"type":"integer"},"buckets":{"type":"array","items":{"$ref":"#/components/schemas/AssetCountByTimeBucket"}}},"required":["totalCount","buckets"]},"AssetCountByUserIdResponseDto":{"type":"object","properties":{"audio":{"type":"integer","default":0},"photos":{"type":"integer","default":0},"videos":{"type":"integer","default":0},"other":{"type":"integer","default":0},"total":{"type":"integer","default":0}},"required":["audio","photos","videos","other","total"]},"GetAssetByTimeBucketDto":{"type":"object","properties":{"timeBucket":{"title":"Array of date time buckets","example":["2015-06-01T00:00:00.000Z","2016-02-01T00:00:00.000Z","2016-03-01T00:00:00.000Z"],"type":"array","items":{"type":"string"}}},"required":["timeBucket"]},"UpdateAssetDto":{"type":"object","properties":{"isFavorite":{"type":"boolean"}},"required":["isFavorite"]},"DeleteAssetDto":{"type":"object","properties":{"ids":{"title":"Array of asset IDs to delete","example":["bf973405-3f2a-48d2-a687-2ed4167164be","dd41870b-5d00-46d2-924e-1d8489a0aa0f","fad77c3f-deef-4e7e-9608-14c1aa4e559a"],"type":"array","items":{"type":"string"}}},"required":["ids"]},"DeleteAssetStatus":{"type":"string","enum":["SUCCESS","FAILED"]},"DeleteAssetResponseDto":{"type":"object","properties":{"status":{"$ref":"#/components/schemas/DeleteAssetStatus"},"id":{"type":"string"}},"required":["status","id"]},"CheckDuplicateAssetDto":{"type":"object","properties":{"deviceAssetId":{"type":"string"},"deviceId":{"type":"string"}},"required":["deviceAssetId","deviceId"]},"CheckDuplicateAssetResponseDto":{"type":"object","properties":{"isExist":{"type":"boolean"},"id":{"type":"string"}},"required":["isExist"]},"CheckExistingAssetsDto":{"type":"object","properties":{"deviceAssetIds":{"type":"array","items":{"type":"string"}},"deviceId":{"type":"string"}},"required":["deviceAssetIds","deviceId"]},"CheckExistingAssetsResponseDto":{"type":"object","properties":{"existingIds":{"type":"array","items":{"type":"string"}}},"required":["existingIds"]},"LoginCredentialDto":{"type":"object","properties":{"email":{"type":"string","example":"testuser@email.com"},"password":{"type":"string","example":"password"}},"required":["email","password"]},"LoginResponseDto":{"type":"object","properties":{"accessToken":{"type":"string","readOnly":true},"userId":{"type":"string","readOnly":true},"userEmail":{"type":"string","readOnly":true},"firstName":{"type":"string","readOnly":true},"lastName":{"type":"string","readOnly":true},"profileImagePath":{"type":"string","readOnly":true},"isAdmin":{"type":"boolean","readOnly":true},"shouldChangePassword":{"type":"boolean","readOnly":true}},"required":["accessToken","userId","userEmail","firstName","lastName","profileImagePath","isAdmin","shouldChangePassword"]},"SignUpDto":{"type":"object","properties":{"email":{"type":"string","example":"testuser@email.com"},"password":{"type":"string","example":"password"},"firstName":{"type":"string","example":"Admin"},"lastName":{"type":"string","example":"Doe"}},"required":["email","password","firstName","lastName"]},"AdminSignupResponseDto":{"type":"object","properties":{"id":{"type":"string"},"email":{"type":"string"},"firstName":{"type":"string"},"lastName":{"type":"string"},"createdAt":{"type":"string"}},"required":["id","email","firstName","lastName","createdAt"]},"ValidateAccessTokenResponseDto":{"type":"object","properties":{"authStatus":{"type":"boolean"}},"required":["authStatus"]},"LogoutResponseDto":{"type":"object","properties":{"successful":{"type":"boolean","readOnly":true},"redirectUri":{"type":"string","readOnly":true}},"required":["successful","redirectUri"]},"OAuthConfigDto":{"type":"object","properties":{"redirectUri":{"type":"string"}},"required":["redirectUri"]},"OAuthConfigResponseDto":{"type":"object","properties":{"enabled":{"type":"boolean","readOnly":true},"url":{"type":"string","readOnly":true},"buttonText":{"type":"string","readOnly":true}},"required":["enabled"]},"OAuthCallbackDto":{"type":"object","properties":{"url":{"type":"string"}},"required":["url"]},"DeviceTypeEnum":{"type":"string","enum":["IOS","ANDROID","WEB"]},"CreateDeviceInfoDto":{"type":"object","properties":{"deviceType":{"$ref":"#/components/schemas/DeviceTypeEnum"},"deviceId":{"type":"string"},"isAutoBackup":{"type":"boolean"}},"required":["deviceType","deviceId"]},"DeviceInfoResponseDto":{"type":"object","properties":{"id":{"type":"integer"},"deviceType":{"$ref":"#/components/schemas/DeviceTypeEnum"},"userId":{"type":"string"},"deviceId":{"type":"string"},"createdAt":{"type":"string"},"isAutoBackup":{"type":"boolean"}},"required":["id","deviceType","userId","deviceId","createdAt","isAutoBackup"]},"UpdateDeviceInfoDto":{"type":"object","properties":{"deviceType":{"$ref":"#/components/schemas/DeviceTypeEnum"},"deviceId":{"type":"string"},"isAutoBackup":{"type":"boolean"}},"required":["deviceType","deviceId"]},"ServerInfoResponseDto":{"type":"object","properties":{"diskSizeRaw":{"type":"integer","format":"int64"},"diskUseRaw":{"type":"integer","format":"int64"},"diskAvailableRaw":{"type":"integer","format":"int64"},"diskUsagePercentage":{"type":"number","format":"float"},"diskSize":{"type":"string"},"diskUse":{"type":"string"},"diskAvailable":{"type":"string"}},"required":["diskSizeRaw","diskUseRaw","diskAvailableRaw","diskUsagePercentage","diskSize","diskUse","diskAvailable"]},"ServerPingResponse":{"type":"object","properties":{"res":{"type":"string","readOnly":true,"example":"pong"}},"required":["res"]},"ServerVersionReponseDto":{"type":"object","properties":{"major":{"type":"integer"},"minor":{"type":"integer"},"patch":{"type":"integer"},"build":{"type":"integer"}},"required":["major","minor","patch","build"]},"UsageByUserDto":{"type":"object","properties":{"userId":{"type":"string"},"videos":{"type":"integer"},"photos":{"type":"integer"},"usageRaw":{"type":"integer","format":"int64"},"usage":{"type":"string"}},"required":["userId","videos","photos","usageRaw","usage"]},"ServerStatsResponseDto":{"type":"object","properties":{"photos":{"type":"integer"},"videos":{"type":"integer"},"objects":{"type":"integer"},"usageRaw":{"type":"integer","format":"int64"},"usage":{"type":"string"},"usageByUser":{"title":"Array of usage for each user","example":[{"photos":1,"videos":1,"diskUsageRaw":1}],"type":"array","items":{"$ref":"#/components/schemas/UsageByUserDto"}}},"required":["photos","videos","objects","usageRaw","usage","usageByUser"]},"AlbumCountResponseDto":{"type":"object","properties":{"owned":{"type":"integer"},"shared":{"type":"integer"},"sharing":{"type":"integer"}},"required":["owned","shared","sharing"]},"CreateAlbumDto":{"type":"object","properties":{"albumName":{"type":"string"},"sharedWithUserIds":{"type":"array","items":{"type":"string"}},"assetIds":{"type":"array","items":{"type":"string"}}},"required":["albumName"]},"AlbumResponseDto":{"type":"object","properties":{"assetCount":{"type":"integer"},"id":{"type":"string"},"ownerId":{"type":"string"},"albumName":{"type":"string"},"createdAt":{"type":"string"},"albumThumbnailAssetId":{"type":"string","nullable":true},"shared":{"type":"boolean"},"sharedUsers":{"type":"array","items":{"$ref":"#/components/schemas/UserResponseDto"}},"assets":{"type":"array","items":{"$ref":"#/components/schemas/AssetResponseDto"}}},"required":["assetCount","id","ownerId","albumName","createdAt","albumThumbnailAssetId","shared","sharedUsers","assets"]},"AddUsersDto":{"type":"object","properties":{"sharedUserIds":{"type":"array","items":{"type":"string"}}},"required":["sharedUserIds"]},"AddAssetsDto":{"type":"object","properties":{"assetIds":{"type":"array","items":{"type":"string"}}},"required":["assetIds"]},"AddAssetsResponseDto":{"type":"object","properties":{"successfullyAdded":{"type":"integer"},"alreadyInAlbum":{"type":"array","items":{"type":"string"}},"album":{"$ref":"#/components/schemas/AlbumResponseDto"}},"required":["successfullyAdded","alreadyInAlbum"]},"RemoveAssetsDto":{"type":"object","properties":{"assetIds":{"type":"array","items":{"type":"string"}}},"required":["assetIds"]},"UpdateAlbumDto":{"type":"object","properties":{"albumName":{"type":"string"},"albumThumbnailAssetId":{"type":"string"}}},"JobCounts":{"type":"object","properties":{"active":{"type":"integer"},"completed":{"type":"integer"},"failed":{"type":"integer"},"delayed":{"type":"integer"},"waiting":{"type":"integer"}},"required":["active","completed","failed","delayed","waiting"]},"AllJobStatusResponseDto":{"type":"object","properties":{"thumbnailGenerationQueueCount":{"$ref":"#/components/schemas/JobCounts"},"metadataExtractionQueueCount":{"$ref":"#/components/schemas/JobCounts"},"videoConversionQueueCount":{"$ref":"#/components/schemas/JobCounts"},"machineLearningQueueCount":{"$ref":"#/components/schemas/JobCounts"},"isThumbnailGenerationActive":{"type":"boolean"},"isMetadataExtractionActive":{"type":"boolean"},"isVideoConversionActive":{"type":"boolean"},"isMachineLearningActive":{"type":"boolean"}},"required":["thumbnailGenerationQueueCount","metadataExtractionQueueCount","videoConversionQueueCount","machineLearningQueueCount","isThumbnailGenerationActive","isMetadataExtractionActive","isVideoConversionActive","isMachineLearningActive"]},"JobId":{"type":"string","enum":["thumbnail-generation","metadata-extraction","video-conversion","machine-learning"]},"JobStatusResponseDto":{"type":"object","properties":{"isActive":{"type":"boolean"},"queueCount":{"type":"object"}},"required":["isActive","queueCount"]},"JobCommand":{"type":"string","enum":["start","stop"]},"JobCommandDto":{"type":"object","properties":{"command":{"$ref":"#/components/schemas/JobCommand"}},"required":["command"]},"SystemConfigKey":{"type":"string","enum":["ffmpeg_crf","ffmpeg_preset","ffmpeg_target_video_codec","ffmpeg_target_audio_codec","ffmpeg_target_scaling"]},"SystemConfigResponseItem":{"type":"object","properties":{"name":{"type":"string"},"key":{"$ref":"#/components/schemas/SystemConfigKey"},"value":{"type":"string"},"defaultValue":{"type":"string"}},"required":["name","key","value","defaultValue"]},"SystemConfigResponseDto":{"type":"object","properties":{"config":{"type":"array","items":{"$ref":"#/components/schemas/SystemConfigResponseItem"}}},"required":["config"]},"UpdateSystemConfigDto":{"type":"object","properties":{}}}}} \ No newline at end of file diff --git a/web/src/api/open-api/api.ts b/web/src/api/open-api/api.ts index 98539841fa..233800bdfe 100644 --- a/web/src/api/open-api/api.ts +++ b/web/src/api/open-api/api.ts @@ -427,7 +427,7 @@ export interface AssetResponseDto { * @type {string} * @memberof AssetResponseDto */ - 'encodedVideoPath': string | null; + 'encodedVideoPath'?: string | null; /** * * @type {ExifResponseDto} @@ -445,7 +445,7 @@ export interface AssetResponseDto { * @type {string} * @memberof AssetResponseDto */ - 'livePhotoVideoId': string | null; + 'livePhotoVideoId'?: string | null; } /** * @@ -1632,12 +1632,6 @@ export interface UsageByUserDto { * @memberof UsageByUserDto */ 'userId': string; - /** - * - * @type {number} - * @memberof UsageByUserDto - */ - 'objects': number; /** * * @type {number} @@ -1735,7 +1729,7 @@ export interface UserResponseDto { * @type {string} * @memberof UserResponseDto */ - 'deletedAt': string | null; + 'deletedAt'?: string; } /** * @@ -2794,10 +2788,11 @@ export const AssetApiAxiosParamCreator = function (configuration?: Configuration /** * Get all AssetEntity belong to the user * @summary + * @param {string} [ifNoneMatch] ETag of data already cached on the client * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getAllAssets: async (options: AxiosRequestConfig = {}): Promise => { + getAllAssets: async (ifNoneMatch?: string, options: AxiosRequestConfig = {}): Promise => { const localVarPath = `/asset`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -2814,6 +2809,10 @@ export const AssetApiAxiosParamCreator = function (configuration?: Configuration // http bearer authentication required await setBearerAuthToObject(localVarHeaderParameter, configuration) + if (ifNoneMatch !== undefined && ifNoneMatch !== null) { + localVarHeaderParameter['if-none-match'] = String(ifNoneMatch); + } + setSearchParams(localVarUrlObj, localVarQueryParameter); @@ -3394,11 +3393,12 @@ export const AssetApiFp = function(configuration?: Configuration) { /** * Get all AssetEntity belong to the user * @summary + * @param {string} [ifNoneMatch] ETag of data already cached on the client * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getAllAssets(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { - const localVarAxiosArgs = await localVarAxiosParamCreator.getAllAssets(options); + async getAllAssets(ifNoneMatch?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + const localVarAxiosArgs = await localVarAxiosParamCreator.getAllAssets(ifNoneMatch, options); return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); }, /** @@ -3596,11 +3596,12 @@ export const AssetApiFactory = function (configuration?: Configuration, basePath /** * Get all AssetEntity belong to the user * @summary + * @param {string} [ifNoneMatch] ETag of data already cached on the client * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getAllAssets(options?: any): AxiosPromise> { - return localVarFp.getAllAssets(options).then((request) => request(axios, basePath)); + getAllAssets(ifNoneMatch?: string, options?: any): AxiosPromise> { + return localVarFp.getAllAssets(ifNoneMatch, options).then((request) => request(axios, basePath)); }, /** * Get a single asset\'s information @@ -3794,12 +3795,13 @@ export class AssetApi extends BaseAPI { /** * Get all AssetEntity belong to the user * @summary + * @param {string} [ifNoneMatch] ETag of data already cached on the client * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AssetApi */ - public getAllAssets(options?: AxiosRequestConfig) { - return AssetApiFp(this.configuration).getAllAssets(options).then((request) => request(this.axios, this.basePath)); + public getAllAssets(ifNoneMatch?: string, options?: AxiosRequestConfig) { + return AssetApiFp(this.configuration).getAllAssets(ifNoneMatch, options).then((request) => request(this.axios, this.basePath)); } /** diff --git a/web/src/lib/components/admin-page/server-stats/server-stats-panel.svelte b/web/src/lib/components/admin-page/server-stats/server-stats-panel.svelte index b5269b0bee..0ef9184312 100644 --- a/web/src/lib/components/admin-page/server-stats/server-stats-panel.svelte +++ b/web/src/lib/components/admin-page/server-stats/server-stats-panel.svelte @@ -2,7 +2,6 @@ import { ServerStatsResponseDto, UserResponseDto } from '@api'; import CameraIris from 'svelte-material-icons/CameraIris.svelte'; import PlayCircle from 'svelte-material-icons/PlayCircle.svelte'; - import FileImageOutline from 'svelte-material-icons/FileImageOutline.svelte'; import Memory from 'svelte-material-icons/Memory.svelte'; import StatsCard from './stats-card.svelte'; export let stats: ServerStatsResponseDto; @@ -16,8 +15,8 @@ return name; }; - $: spaceUnit = stats.usage.slice(stats.usage.length - 2, stats.usage.length); - $: spaceUsage = stats.usage.slice(0, stats.usage.length - 2); + $: spaceUnit = stats.usage.split(' ')[1]; + $: spaceUsage = stats.usage.split(' ')[0];
@@ -27,7 +26,6 @@
-
@@ -39,11 +37,10 @@ class="border rounded-md mb-4 bg-gray-50 dark:bg-immich-dark-gray dark:border-immich-dark-gray flex text-immich-primary dark:text-immich-dark-primary w-full h-12" > - User - Photos - Videos - Objects - Size + User + Photos + Videos + Size - {getFullName(user.userId)} - {user.photos} - {user.videos} - {user.objects} - {user.usage} + {getFullName(user.userId)} + {user.photos} + {user.videos} + {user.usage} {/each} diff --git a/web/src/lib/components/admin-page/server-stats/stats-card.svelte b/web/src/lib/components/admin-page/server-stats/stats-card.svelte index 5af64d38bc..e60ebbf9f8 100644 --- a/web/src/lib/components/admin-page/server-stats/stats-card.svelte +++ b/web/src/lib/components/admin-page/server-stats/stats-card.svelte @@ -7,7 +7,7 @@ $: zeros = () => { let result = ''; - const maxLength = 9; + const maxLength = 13; const valueLength = parseInt(value).toString().length; const zeroLength = maxLength - valueLength; for (let i = 0; i < zeroLength; i++) { @@ -18,7 +18,7 @@
diff --git a/web/src/lib/components/asset-viewer/asset-viewer-nav-bar.svelte b/web/src/lib/components/asset-viewer/asset-viewer-nav-bar.svelte index 93a929fbac..6240545ed7 100644 --- a/web/src/lib/components/asset-viewer/asset-viewer-nav-bar.svelte +++ b/web/src/lib/components/asset-viewer/asset-viewer-nav-bar.svelte @@ -46,7 +46,7 @@
dispatch('goBack')} /> diff --git a/web/src/lib/components/asset-viewer/detail-panel.svelte b/web/src/lib/components/asset-viewer/detail-panel.svelte index a254224b5e..c427443392 100644 --- a/web/src/lib/components/asset-viewer/detail-panel.svelte +++ b/web/src/lib/components/asset-viewer/detail-panel.svelte @@ -8,6 +8,7 @@ import { createEventDispatcher, onMount } from 'svelte'; import { browser } from '$app/environment'; import { AssetResponseDto, AlbumResponseDto } from '@api'; + import { getHumanReadableBytes } from '../../utils/byte-units'; type Leaflet = typeof import('leaflet'); type LeafletMap = import('leaflet').Map; @@ -59,32 +60,6 @@ } const dispatch = createEventDispatcher(); - const getHumanReadableString = (sizeInByte: number) => { - const pepibyte = 1.126 * Math.pow(10, 15); - const tebibyte = 1.1 * Math.pow(10, 12); - const gibibyte = 1.074 * Math.pow(10, 9); - const mebibyte = 1.049 * Math.pow(10, 6); - const kibibyte = 1024; - // Pebibyte - if (sizeInByte >= pepibyte) { - // Pe - return `${(sizeInByte / pepibyte).toFixed(1)}PB`; - } else if (tebibyte <= sizeInByte && sizeInByte < pepibyte) { - // Te - return `${(sizeInByte / tebibyte).toFixed(1)}TB`; - } else if (gibibyte <= sizeInByte && sizeInByte < tebibyte) { - // Gi - return `${(sizeInByte / gibibyte).toFixed(1)}GB`; - } else if (mebibyte <= sizeInByte && sizeInByte < gibibyte) { - // Mega - return `${(sizeInByte / mebibyte).toFixed(1)}MB`; - } else if (kibibyte <= sizeInByte && sizeInByte < mebibyte) { - // Kibi - return `${(sizeInByte / kibibyte).toFixed(1)}KB`; - } else { - return `${sizeInByte}B`; - } - }; const getMegapixel = (width: number, height: number): number | undefined => { const megapixel = Math.round((height * width) / 1_000_000); @@ -143,13 +118,13 @@ {#if asset.exifInfo.exifImageHeight && asset.exifInfo.exifImageWidth} {#if getMegapixel(asset.exifInfo.exifImageHeight, asset.exifInfo.exifImageWidth)}

- {getMegapixel(asset.exifInfo.exifImageHeight, asset.exifInfo.exifImageWidth)}MP + {getMegapixel(asset.exifInfo.exifImageHeight, asset.exifInfo.exifImageWidth)} MP

{/if}

{asset.exifInfo.exifImageHeight} x {asset.exifInfo.exifImageWidth}

{/if} -

{getHumanReadableString(asset.exifInfo.fileSizeInByte)}

+

{getHumanReadableBytes(asset.exifInfo.fileSizeInByte)}

@@ -162,7 +137,7 @@

{asset.exifInfo.make || ''} {asset.exifInfo.model || ''}

-

{`f/${asset.exifInfo.fNumber}` || ''}

+

{`ƒ/${asset.exifInfo.fNumber}` || ''}

{#if asset.exifInfo.exposureTime}

{`1/${Math.floor(1 / asset.exifInfo.exposureTime)}`}

diff --git a/web/src/lib/components/shared-components/scrollbar/scrollbar.svelte b/web/src/lib/components/shared-components/scrollbar/scrollbar.svelte index fdddf6fcd9..38270f531f 100644 --- a/web/src/lib/components/shared-components/scrollbar/scrollbar.svelte +++ b/web/src/lib/components/shared-components/scrollbar/scrollbar.svelte @@ -94,7 +94,7 @@
(isHover = true)} @@ -109,7 +109,7 @@ > {#if isHover}
{hoveredDate?.toLocaleString('default', { month: 'short' })} diff --git a/web/src/lib/components/shared-components/upload-panel.svelte b/web/src/lib/components/shared-components/upload-panel.svelte index f33df973d4..0901cc008c 100644 --- a/web/src/lib/components/shared-components/upload-panel.svelte +++ b/web/src/lib/components/shared-components/upload-panel.svelte @@ -6,6 +6,8 @@ import WindowMinimize from 'svelte-material-icons/WindowMinimize.svelte'; import type { UploadAsset } from '$lib/models/upload-asset'; import { notificationController, NotificationType } from './notification/notification'; + import { getHumanReadableBytes } from '../../utils/byte-units'; + let showDetail = true; let uploadLength = 0; @@ -30,33 +32,6 @@ } }; - function getSizeInHumanReadableFormat(sizeInByte: number) { - const pepibyte = 1.126 * Math.pow(10, 15); - const tebibyte = 1.1 * Math.pow(10, 12); - const gibibyte = 1.074 * Math.pow(10, 9); - const mebibyte = 1.049 * Math.pow(10, 6); - const kibibyte = 1024; - // Pebibyte - if (sizeInByte >= pepibyte) { - // Pe - return `${(sizeInByte / pepibyte).toFixed(1)}PB`; - } else if (tebibyte <= sizeInByte && sizeInByte < pepibyte) { - // Te - return `${(sizeInByte / tebibyte).toFixed(1)}TB`; - } else if (gibibyte <= sizeInByte && sizeInByte < tebibyte) { - // Gi - return `${(sizeInByte / gibibyte).toFixed(1)}GB`; - } else if (mebibyte <= sizeInByte && sizeInByte < gibibyte) { - // Mega - return `${(sizeInByte / mebibyte).toFixed(1)}MB`; - } else if (kibibyte <= sizeInByte && sizeInByte < mebibyte) { - // Kibi - return `${(sizeInByte / kibibyte).toFixed(1)}KB`; - } else { - return `${sizeInByte}B`; - } - } - // Reactive action to get thumbnail image of upload asset whenever there is a new one added to the list $: { if ($uploadAssetsStore.length != uploadLength) { @@ -140,7 +115,7 @@ diff --git a/web/src/lib/utils/byte-units.ts b/web/src/lib/utils/byte-units.ts new file mode 100644 index 0000000000..f8fa139fbe --- /dev/null +++ b/web/src/lib/utils/byte-units.ts @@ -0,0 +1,16 @@ +export function getHumanReadableBytes(bytes: number): string { + const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']; + + let magnitude = 0; + let remainder = bytes; + while (remainder >= 1024) { + if (magnitude + 1 < units.length) { + magnitude++; + remainder /= 1024; + } else { + break; + } + } + + return `${remainder.toFixed(magnitude == 0 ? 0 : 1)} ${units[magnitude]}`; +}