From 5d2cc4a775af0093ae9e515b9d4f49908a53440c Mon Sep 17 00:00:00 2001 From: Philippe Date: Wed, 18 Nov 2026 16:47:09 +0100 Subject: [PATCH 1/5] Harden credentials, app lock and PIN storage; trim request load Credentials stay on the server's origin: - AuthHeaders.forUrl gives the API key / session cookie only for URLs on the configured scheme, host and port (images, sprites, streams, previews, lock screen art, iOS PiP, cast ?apikey=). - OriginGuardClient follows redirects itself and drops ApiKey, Cookie and Authorization once a redirect leaves the origin (GraphQL, server files, and the image cache via stashImageCacheManager). - StashSessionClient adds the cookie only on the origin. - MediaOriginBanner warns when the server hands out media URLs on another origin (proxy without Host / X-Forwarded-Proto), naming both addresses. App lock and PIN: - PINs are stored as PBKDF2-HMAC-SHA256 (StoredPin). Legacy salted SHA-256 values are still accepted and upgraded after the next correct PIN, so existing users keep their PIN. - An enabled lock whose PIN can't be read (unreadable or emptied secure storage) stays locked: PinLostView offers biometrics followed by a new PIN, or resetting the app. Other fixes: - User info in a server URL (user:password@) is kept in the secret store (url_auth:) instead of the profile JSON; stored profiles migrate on start, and the UI shows the URL without it. - GraphQL uses noCache: networkOnly kept filling a normalized cache that was never read. - The preview check cancels the body after the status instead of downloading whole files when a server ignores Range. - The password login times out after 20 s and reads only the headers. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 10 +- lib/core/config/image_cache.dart | 19 ++- lib/core/config/secret_store.dart | 19 ++- lib/core/config/server_config.dart | 59 +++++++- lib/core/network/origin_guard.dart | 126 ++++++++++++++++ lib/data/media_origin_check.dart | 88 +++++++++++ lib/data/repositories/stash_repository.dart | 52 +++++-- lib/data/repositories/stash_session.dart | 54 +++++-- lib/features/auth/login_page.dart | 2 +- lib/features/auth/server_avatar.dart | 2 +- lib/features/auth/server_switcher.dart | 2 +- lib/features/cast/cast_media.dart | 20 ++- lib/features/library/stats_tab.dart | 2 +- lib/features/pip/pip.dart | 4 +- lib/features/player/lock_screen.dart | 2 +- lib/features/player/player_controls.dart | 2 +- lib/features/player/player_providers.dart | 4 +- lib/features/player/preview_seek_bar.dart | 8 +- lib/features/player/scene_description.dart | 2 +- lib/features/security/app_lock.dart | 115 +++++++++----- lib/features/security/app_lock_gate.dart | 129 ++++++++++++++++ lib/features/security/pin_hash.dart | 116 ++++++++++++++ .../settings/settings_categories.dart | 2 +- lib/features/shorts/shorts_page.dart | 2 +- lib/l10n/app_de.arb | 13 +- lib/l10n/app_en.arb | 14 +- lib/l10n/gen/app_localizations.dart | 66 ++++++++ lib/l10n/gen/app_localizations_de.dart | 39 +++++ lib/l10n/gen/app_localizations_en.dart | 39 +++++ lib/widgets/connection_banner.dart | 78 +++++++++- lib/widgets/preview_video.dart | 2 +- lib/widgets/stash_image.dart | 9 +- test/core/origin_guard_test.dart | 96 ++++++++++++ test/core/server_profiles_test.dart | 28 ++++ test/data/media_origin_check_test.dart | 110 ++++++++++++++ test/data/repository_graphql_test.dart | 13 +- test/data/scrub_thumbnails_test.dart | 33 +++- test/data/stash_session_test.dart | 31 +++- test/features/app_lock_test.dart | 142 +++++++++++++++--- test/features/cast_test.dart | 14 +- test/features/pip_return_test.dart | 3 +- test/features/pip_test.dart | 3 +- .../player/chapters_channel_test.dart | 3 +- test/features/player/gesture_tips_test.dart | 3 +- test/features/player/marker_ranges_test.dart | 9 +- test/features/player/player_details_test.dart | 7 +- test/features/player/queue_controls_test.dart | 3 +- test/features/player/seek_sequence_test.dart | 3 +- test/features/player/touch_lock_test.dart | 3 +- test/features/preview_seek_bar_test.dart | 3 +- test/features/shorts_markers_ui_test.dart | 7 +- test/features/video_controls_test.dart | 3 +- test/flutter_test_config.dart | 11 ++ 53 files changed, 1474 insertions(+), 155 deletions(-) create mode 100644 lib/core/network/origin_guard.dart create mode 100644 lib/data/media_origin_check.dart create mode 100644 lib/features/security/pin_hash.dart create mode 100644 test/core/origin_guard_test.dart create mode 100644 test/data/media_origin_check_test.dart create mode 100644 test/flutter_test_config.dart diff --git a/CLAUDE.md b/CLAUDE.md index 5714d2d..06e5eeb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,9 +53,9 @@ lib/ widgets/ shared UI (SceneCard, PagedSliver, SceneFeedView, StashImage, ...) ``` -**Server config and data flow.** `main()` overrides `sharedPreferencesProvider`. `serverProfilesProvider` holds the saved servers and the active one (stored as JSON; a single-server login from older versions is migrated once). API keys and passwords are not in that JSON but in the `SecretStore` (`secretStoreProvider`, `core/config/secret_store.dart`): `flutter_secure_storage`, loaded in `main()` before `runApp` and then read synchronously; tests get a `MemorySecretStore` unless they override it (share one instance to simulate a restart). `serverConfigProvider` (the active server's URL and API key, with value equality; the login tries `ServerConfig.candidateUrls`, i.e. without a port also Stash's default 9999, through `findServer`) and `activeServerIdProvider` derive from it, and `graphQLClientProvider`/`stashRepositoryProvider` derive from the config. `StashApp` keys `AppShell` by server id, so switching servers rebuilds the per-server UI state. The login asks before plain HTTP to a host outside the home network (`ServerConfig.isUnencryptedOverInternet`/`isLocalHost`). Per-server data must key on `activeServerIdProvider`: stored lists use `:`, which removing a server deletes (with its secrets and the image cache, `clearImageCacheProvider`), and in-memory caches `ref.watch` it so they reset. Tests that touch such state use `testServer` from `test/helpers.dart` (it also fixes the scene card settings; use `testServerOnly` to set your own). UI code never builds GraphQL queries itself; it watches providers from `data/providers.dart`. +**Server config and data flow.** `main()` overrides `sharedPreferencesProvider`. `serverProfilesProvider` holds the saved servers and the active one (stored as JSON; a single-server login from older versions is migrated once). API keys, passwords and user info in a server URL (`https://user:pw@host`, kept in memory in `baseUrl` but stored as `url_auth:`; show `ServerConfig.displayUrl`) are not in that JSON but in the `SecretStore` (`secretStoreProvider`, `core/config/secret_store.dart`): `flutter_secure_storage`, loaded in `main()` before `runApp` and then read synchronously; tests get a `MemorySecretStore` unless they override it (share one instance to simulate a restart). `serverConfigProvider` (the active server's URL and API key, with value equality; the login tries `ServerConfig.candidateUrls`, i.e. without a port also Stash's default 9999, through `findServer`) and `activeServerIdProvider` derive from it, and `graphQLClientProvider`/`stashRepositoryProvider` derive from the config. `StashApp` keys `AppShell` by server id, so switching servers rebuilds the per-server UI state. The login asks before plain HTTP to a host outside the home network (`ServerConfig.isUnencryptedOverInternet`/`isLocalHost`). Per-server data must key on `activeServerIdProvider`: stored lists use `:`, which removing a server deletes (with its secrets and the image cache, `clearImageCacheProvider`), and in-memory caches `ref.watch` it so they reset. Tests that touch such state use `testServer` from `test/helpers.dart` (it also fixes the scene card settings; use `testServerOnly` to set your own). UI code never builds GraphQL queries itself; it watches providers from `data/providers.dart`. -**GraphQL types (codegen).** The documents live in `lib/core/api/documents/*.graphql`; graphql_codegen (`build.yaml`) checks them against `stash_schema.graphql` and generates `Query$…`/`Mutation$…`/`Fragment$…` classes, `Options$…` and `Variables$…`, plus `Input$…`/`Enum$…` for the whole schema. The generated files are committed (like `lib/l10n/gen`), excluded from analysis and marked generated in `.gitattributes`. Models have factories from the generated fragments (`Scene.fromFields`, `Studio.fromRef`, …) instead of `fromJson`; shared selections are fragments in `refs.graphql`. Keep `addTypename: true`: the normalized cache resolves fragments by `__typename`, and without it lists come back as nulls. Filters and edit changes are still built as maps (`SceneQuery.toSceneFilter`, the forms' `_diff`); `StashRepository._input` turns them into the input types and asserts in debug/tests that every key is in the schema (`fitsInput`), and `convertSavedSceneFilter` drops saved criteria that don't fit `Input$SceneFilterType`. Tests build models and fake responses with `test/fixtures.dart` (complete results with `__typename`s); `test/data/repository_graphql_test.dart` runs the repository through a real client and cache. The schema is the newest Stash's, so compatibility with older servers is not checked at build time. +**GraphQL types (codegen).** The documents live in `lib/core/api/documents/*.graphql`; graphql_codegen (`build.yaml`) checks them against `stash_schema.graphql` and generates `Query$…`/`Mutation$…`/`Fragment$…` classes, `Options$…` and `Variables$…`, plus `Input$…`/`Enum$…` for the whole schema. The generated files are committed (like `lib/l10n/gen`), excluded from analysis and marked generated in `.gitattributes`. Models have factories from the generated fragments (`Scene.fromFields`, `Studio.fromRef`, …) instead of `fromJson`; shared selections are fragments in `refs.graphql`. Keep `addTypename: true`: the generated parsers resolve fragments by `__typename`. The client caches nothing (`stashGraphQLPolicies`, `FetchPolicy.noCache` for queries and mutations): `networkOnly` still wrote every response into the normalized cache, which grew with every page, filter and random seed and was never read; `repository_graphql_test.dart` checks the cache stays empty. Filters and edit changes are still built as maps (`SceneQuery.toSceneFilter`, the forms' `_diff`); `StashRepository._input` turns them into the input types and asserts in debug/tests that every key is in the schema (`fitsInput`), and `convertSavedSceneFilter` drops saved criteria that don't fit `Input$SceneFilterType`. Tests build models and fake responses with `test/fixtures.dart` (complete results with `__typename`s); `test/data/repository_graphql_test.dart` runs the repository through a real client and cache. The schema is the newest Stash's, so compatibility with older servers is not checked at build time. **Paginated lists.** `sceneListProvider`, `performerListProvider` and `studioListProvider` are auto-dispose family `PagedNotifier`s keyed by query objects (`SceneQuery`, `PerformerQuery`, `StudioQuery`). These query objects must keep value equality. UI code reads paged lists through `.current` (`PagedValue` extension), not `.value`. On a server switch the lists rebuild (`isReloading`), and `.value` would keep showing the previous server's items, or would hide a failed load behind them. A reload of the same list (pull-to-refresh, the connection banner's `reloadLists`) that fails with a network error keeps the loaded items as data with `PagedState.refreshError` (STATE-1; the banner explains it), but only when `PagedState.origin` (server and paging mode) still matches, so after a server switch the error shows instead; server-reported errors still replace the list by an `ErrorView`. The random sort uses a `random_` sort field so pages stay stable, and the seed is 0 for every other sort. To get an infinite, refreshable list with sort chips, use `SceneFeedView`, or compose `RefreshIndicator`, `LoadMoreListener`, `CustomScrollView` and `PagedSliver` yourself. After a failed page, scrolling doesn't retry; `PagedSliver`'s `onLoadMore` (its "try again" button) passes `loadMore(retry: true)`. `pagingModeProvider` (settings) switches all paged lists to numbered pages: `loadMore` then does nothing, `PagedSliver` shows a `PageBar` driving `PagedNotifier.goToPage` (pass `onGoToPage`), and changing the mode rebuilds the lists. The first page loads as skeletons (`widgets/skeleton.dart`, `PagedSliver(skeletonBuilder:)`), not a spinner. `SceneFeedView(pinChips: true)` pins the filter, sort and saved-filter chips under the home app bar (shelves go into `belowChipsSlivers`); `unfilteredEmptyView` replaces the empty message only without filters or search term (home: "scan your library" with a button to the server tasks). `EmptyView` takes an optional action. @@ -79,7 +79,7 @@ lib/ **Library.** The `library` tab (`features/library/`) has a sub-tab per `LibrarySection.media`; the other sections open from the "You" page or as tabs of their own. The markers section (`markers_tab.dart`, `markerListProvider`/`MarkerQuery`, `StashRepository.findMarkers`) lists the scene markers of all scenes; a tile plays its scene from the marker via `NowPlayingNotifier.play(scene, at:)`. All scenes uses `SceneFeedView` with `SceneFeedLayout.grid`. Images and galleries share `ImageGridView`, which takes an `ImageQuery` (optionally with a `galleryId`); tapping an image opens `ImageViewerPage` on the root navigator, so it covers the shell and the player. The stats section (`libraryStatsProvider` plus the optional `activityStatsProvider`, which returns null on Stash versions without those fields). The viewer's info button opens `showImageInfoSheet` (`image_info.dart`), loading `imageDetailsProvider` (`FindImageDetails`, cached 2 min) only then; tapping a studio, performer, tag or gallery there closes the sheet and the viewer and opens the page in the current tab. The viewer opens through `ImageViewerPage.route()` (a non-opaque fade route) so that swiping an unzoomed image down closes it with the page showing through. -**Login (session).** Instead of an API key a server can have a username and password (`ServerConfig.usesSession`: credentials and no API key). `StashSessionNotifier` (`data/repositories/stash_session.dart`) signs in through `POST /login` for Stash's `session` cookie, renews it shortly before it expires, and `StashSessionClient` (the `stashHttpClientProvider` used by GraphQL and the repository) sends it and signs in again on a 401, repeating the request. `authHeadersProvider` (images, streams) adds the cookie; the repository deliberately doesn't watch it, so a renewed cookie doesn't reload everything. Cast devices can't send cookies, so casting still needs an API key. The login is two steps: URL and optional name first (`findServer` without credentials, through `serverVerifierProvider` for tests); only when the server answers 401/403 does it ask for an API key or username and password (`SegmentedButton`). Editing a server shows one form. +**Login (session).** Instead of an API key a server can have a username and password (`ServerConfig.usesSession`: credentials and no API key). `StashSessionNotifier` (`data/repositories/stash_session.dart`) signs in through `POST /login` for Stash's `session` cookie, renews it shortly before it expires, and `StashSessionClient` (the `stashHttpClientProvider` used by GraphQL and the repository) sends it and signs in again on a 401, repeating the request. `authHeadersProvider` (images, streams) adds the cookie; the repository deliberately doesn't watch it, so a renewed cookie doesn't reload everything. `stashLogin` reads only the headers and gives up after `stashLoginTimeout` (20 s) as unreachable. Cast devices can't send cookies, so casting still needs an API key. The login is two steps: URL and optional name first (`findServer` without credentials, through `serverVerifierProvider` for tests); only when the server answers 401/403 does it ask for an API key or username and password (`SegmentedButton`). Editing a server shows one form. **Demo (App Store review).** `features/demo/`. The login's "Try the demo" button starts `DemoServer`, a Stash look-alike on `ServerConfig.demoUrl` (`http://127.0.0.1:47999`, loopback only), and saves it as the server "Demo"; `main()` starts it again when a saved server has that URL (`ServerProfilesNotifier.hasDemo`), and it rebinds on resume (iOS can take the socket away). The rest of the app talks to it like to any Stash. `DemoHandler` (no sockets, so tests call it directly) answers `POST /graphql` through `DemoGraphql`, a small executor that runs the app's own documents (fragments, aliases, variables) against `DemoLibrary`'s object graph of maps with `__typename`s, and serves `assets/demo/` with byte ranges plus generated sprite WebVTT. `DemoLibrary` keeps the sample data in memory (edits last until the app restarts) and implements the criteria, sorts (`random_`) and paging the app sends; a field it lacks resolves to null, so a new field in a document needs a value there too (`test/features/demo_test.dart` runs every repository call against it). The media are clips from Big Buck Bunny (CC BY 3.0, credited in `registerAppLicenses`) built by `tool/demo/make_demo_assets.sh`, which also writes `assets/demo/manifest.json` (durations, sizes); keep them small, they ship in every build. Casting doesn't work with the demo (the TV can't reach the phone's loopback). @@ -101,7 +101,7 @@ lib/ **Animations.** `ConfettiBurst` (`widgets/confetti.dart`) bursts when its `trigger` changes (the favorite buttons count up when a performer becomes a favorite) and paints outside its child without taking taps. `PlayPauseIcon` morphs `AnimatedIcons.play_pause` with a small pop; use it for every play/pause button. Animations check `MediaQuery.disableAnimationsOf` and skip themselves. -**Security.** `features/security/`. `AppLockGate` in `MaterialApp.builder` shows `LockScreen` while `appLockedProvider` is true, and a `PrivacyCover` while the app is inactive (with the lock on or "hide in app switcher"). Without a delay the lock engages as the app is hidden, not on return. `LockScreen` asks for biometrics only once the app is resumed (iOS cancels a prompt while still inactive), again after the app was in the background but not after its own prompt. `confirmPin`/`showCreatePin` push full-screen routes on the root navigator, so they cover the app above the settings sheet too. `AppLockSettings.hidesApp` (lock on or "hide in app switcher"; the switch is fixed on with the lock) drives `SecureWindow`: Android's FLAG_SECURE, and on iOS `PrivacyCoverController` (AppDelegate.swift), a native cover added on `UIScene.willDeactivateNotification`, because the app is in the background before Flutter draws another frame (locking the phone showed the old content on return). Whether to cover it reads from UserDefaults itself (`flutter.lock_enabled`, `flutter.lock_hide_in_switcher`): a channel message sent at startup can arrive before the handler exists. Dart removes it (`SecureWindow.uncover`) once a frame was drawn after resuming; a 2 s fallback removes it otherwise. The PIN is stored only as a salted SHA-256 hash, as `:` under `lock_pin` in the `SecretStore` (older versions' SharedPreferences values are moved there). `PinThrottle` blocks the PIN pad for a growing time after 5 wrong PINs (stored, so restarts don't reset it); `LockScreen` then shows `PinBlockedView`. While locked, `AppLockGate` excludes focus and semantics, and `lockBackGuard` (registered in `main()` before `runApp`) turns back into leaving the app. The main player keeps playing (background playback, PiP); the shorts stop. Native channels: `stash/privacy` (Android `FLAG_SECURE`) and `stash/appicon` (Android activity-aliases / iOS alternate icons). On Android the launcher entries are the `activity-alias`es in `src/main/AndroidManifest.xml`. MainActivity keeps a MAIN/LAUNCHER filter there only because `flutter run` looks for it; the debug/profile/release manifests remove that filter again (`tools:node="remove"`). Android uses `FlutterFragmentActivity` and an AppCompat launch theme for `local_auth`. +**Security.** `features/security/`. `AppLockGate` in `MaterialApp.builder` shows `LockScreen` while `appLockedProvider` is true, and a `PrivacyCover` while the app is inactive (with the lock on or "hide in app switcher"). Without a delay the lock engages as the app is hidden, not on return. `LockScreen` asks for biometrics only once the app is resumed (iOS cancels a prompt while still inactive), again after the app was in the background but not after its own prompt. `confirmPin`/`showCreatePin` push full-screen routes on the root navigator, so they cover the app above the settings sheet too. `AppLockSettings.hidesApp` (lock on or "hide in app switcher"; the switch is fixed on with the lock) drives `SecureWindow`: Android's FLAG_SECURE, and on iOS `PrivacyCoverController` (AppDelegate.swift), a native cover added on `UIScene.willDeactivateNotification`, because the app is in the background before Flutter draws another frame (locking the phone showed the old content on return). Whether to cover it reads from UserDefaults itself (`flutter.lock_enabled`, `flutter.lock_hide_in_switcher`): a channel message sent at startup can arrive before the handler exists. Dart removes it (`SecureWindow.uncover`) once a frame was drawn after resuming; a 2 s fallback removes it otherwise. The PIN is stored only as a PBKDF2-HMAC-SHA256 hash (`pin_hash.dart`, `StoredPin`: `pbkdf2-sha256$$$`, `StoredPin.defaultIterations` rounds in an isolate; every value keeps its own count, so it can be raised later) under `lock_pin` in the `SecretStore`. Older versions stored `:` (`legacyHashPin`; in SharedPreferences before that, moved to the secret store at start): it is still accepted, and `verify` (async) replaces it with the PBKDF2 format after the next correct PIN. Tests run with few rounds on their own isolate (`test/flutter_test_config.dart`). A lock that is on (`lock_enabled`) stays on without its PIN (`AppLockSettings.pinLost`: secure storage unreadable or emptied, e.g. after a restore): `LockScreen` shows `PinLostView` instead of the PIN pad, where biometrics (if they were on) lead to choosing a new PIN before unlocking, and "Reset app" (`AppLockSettingsNotifier.resetApp`, confirmed inline) clears all preferences, secrets and cached images and starts over at the login. `PinThrottle` blocks the PIN pad for a growing time after 5 wrong PINs (stored, so restarts don't reset it); `LockScreen` then shows `PinBlockedView`. While locked, `AppLockGate` excludes focus and semantics, and `lockBackGuard` (registered in `main()` before `runApp`) turns back into leaving the app. The main player keeps playing (background playback, PiP); the shorts stop. Native channels: `stash/privacy` (Android `FLAG_SECURE`) and `stash/appicon` (Android activity-aliases / iOS alternate icons). On Android the launcher entries are the `activity-alias`es in `src/main/AndroidManifest.xml`. MainActivity keeps a MAIN/LAUNCHER filter there only because `flutter run` looks for it; the debug/profile/release manifests remove that filter again (`tools:node="remove"`). Android uses `FlutterFragmentActivity` and an AppCompat launch theme for `local_auth`. **Animated previews.** Stash's looping previews, switched separately (`widgets/animated_previews.dart`, on by default; `previewsPlay` also checks reduced motion): `markerPreviewsProvider` for marker tiles (`Marker.previewUrl`), `feedPreviewsProvider` for the first fully shown video in `SceneFeedView`: `AutoPreviewScope` around the list picks it `feedPreviewDelayProvider` (0.5 s by default) after scrolling stopped, and the `AutoPreview` in `SceneThumbnail` plays `Scene.webpUrl` over the still. Scrolling stops it. Thumbnails outside a scope (the player's "Up next") never play. `previewSourceProvider` picks what the lists' previews play: by default Stash's MP4 preview (`Scene.previewUrl`), played by `PreviewVideo` in a media_kit player of its own (one at a time, hardware-decoded), or the WebP (`Scene.webpUrl`), which Flutter decodes frame by frame in software (raster jank with Stash's 640×1136 portrait previews, 3–5 MB); markers always play the WebP (small enough to run smoothly). "Only on Wi-Fi" (`previewsWifiOnlyProvider`, off by default) stops them off Wi-Fi/ethernet via `connectivity_plus` (`unmeteredConnectionProvider`). @@ -117,4 +117,4 @@ lib/ **About.** *Settings → About* (`features/settings/about.dart`, plus the app tour and "What's new") shows the version (set by the release pipeline's `--build-name`/`--build-number`) (`appInfoProvider`, package_info_plus; null in tests) and Flutter's license page, which collects every Dart package's license. `registerAppLicenses` (called in `main`) adds StashTube's own `LICENSE` and the `nativeLibraries` inside media_kit's libmpv builds (texts in `assets/licenses/`), which their packages don't ship; update that list when the media_kit libs change. The app is licensed under AGPL-3.0 (`LICENSE`). Repository docs: `README.md`, `SECURITY.md` (private vulnerability reporting), `CONTRIBUTING.md`. -**Images and auth.** Always load server images through `StashImage` or `ChannelAvatar`, which add the `ApiKey` header. Stash serves SVG placeholders for missing images, which fall back to an icon or the name's initial; performer, studio and tag models drop those URLs up front (`stashImageUrl`: Stash marks them `default=true`), so they aren't fetched and fail to decode. +**Images and auth.** Credentials stay on the server's origin (scheme, host and port; `core/network/origin_guard.dart`). `authHeadersProvider` is an `AuthHeaders`: take the headers with `forUrl(url)` for every image, sprite, stream or preview (an EDL clip counts by the URL inside), never as a plain map; a URL the server returns that points elsewhere gets none. `withApiKey` (cast, iOS PiP) likewise adds `?apikey=` only on the origin. HTTP goes through `OriginGuardClient`, which follows redirects itself and drops `ApiKey`/`Cookie`/`Authorization` once one leaves the origin (`dart:io` forwards custom headers such as `ApiKey`): `stashHttpClientProvider` (inside `StashSessionClient`, which adds the cookie only on the origin), the GraphQL client and `stashImageCacheManager` (`core/config/image_cache.dart`, the default cache's key and files with a guarded download client; pass it as `cacheManager` to every `CachedNetworkImage`/`CachedNetworkImageProvider`, never use `DefaultCacheManager` next to it). mpv (media_kit) follows redirects on its own, so for streams only the first request is guarded. Because of that binding, a server whose media URLs point to another origin (Stash behind a proxy without `Host`/`X-Forwarded-Proto`) loads images without credentials: `mediaOriginMismatchProvider` (`data/media_origin_check.dart`, only with credentials) compares one scene's screenshot URL with the server address, and `ConnectionBannerScope` then shows `MediaOriginBanner` with both addresses and the proxy fix, hidden per server until the mismatch changes (`media_origin_hint_hidden:`). The server-file checks (`fileExists`, preview check) ask for one byte and cancel the body. Always load server images through `StashImage` or `ChannelAvatar`, which add the auth headers. Stash serves SVG placeholders for missing images, which fall back to an icon or the name's initial; performer, studio and tag models drop those URLs up front (`stashImageUrl`: Stash marks them `default=true`), so they aren't fetched and fail to decode. diff --git a/lib/core/config/image_cache.dart b/lib/core/config/image_cache.dart index 88d27da..975fdd9 100644 --- a/lib/core/config/image_cache.dart +++ b/lib/core/config/image_cache.dart @@ -3,17 +3,30 @@ import 'dart:async'; import 'package:flutter/painting.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:http/http.dart' as http; + +import '../network/origin_guard.dart'; + +/// The cache behind every `CachedNetworkImage` of server images: the +/// default cache's files and limits, but its downloads go through an +/// [OriginGuardClient], so a redirect away from the server doesn't take +/// the API key or session cookie along. Pass it as `cacheManager` to every +/// cached image; `DefaultCacheManager` itself must not be used next to it +/// (same key, same files). +final stashImageCacheManager = CacheManager( + Config(DefaultCacheManager.key, fileService: HttpFileService(httpClient: OriginGuardClient(http.Client()))), +); /// Empties the image cache, e.g. when a server is removed: its thumbnails /// must not stay on the device. Overridden in `main()` with /// [clearDeviceImageCache]; does nothing elsewhere (tests have no cache). final clearImageCacheProvider = Provider((ref) => () {}); -/// Clears the images held in memory and the files `CachedNetworkImage` -/// keeps in the default cache manager. Best effort, and not awaited. +/// Clears the images held in memory and the files of +/// [stashImageCacheManager]. Best effort, and not awaited. void clearDeviceImageCache() { PaintingBinding.instance.imageCache ..clear() ..clearLiveImages(); - unawaited(DefaultCacheManager().emptyCache().catchError((Object _) {})); + unawaited(stashImageCacheManager.emptyCache().catchError((Object _) {})); } diff --git a/lib/core/config/secret_store.dart b/lib/core/config/secret_store.dart index 199fdae..62f13f2 100644 --- a/lib/core/config/secret_store.dart +++ b/lib/core/config/secret_store.dart @@ -16,6 +16,9 @@ abstract interface class SecretStore { /// Deletes every secret whose key passes [test], e.g. a removed server's. Future deleteWhere(bool Function(String key) test); + + /// Deletes every secret, also ones that couldn't be read. + Future clear(); } class SecureSecretStore implements SecretStore { @@ -28,7 +31,8 @@ class SecureSecretStore implements SecretStore { values = await storage.readAll(); } catch (e) { // Unreadable (e.g. a restored Android backup): start empty, the user - // enters the key again. + // enters the key again. A PIN lost with it keeps the app locked + // (AppLockSettings.pinLost). debugPrint('Secure storage unreadable: $e'); values = {}; } @@ -59,6 +63,16 @@ class SecureSecretStore implements SecretStore { await write(key, null); } } + + @override + Future clear() async { + _cache.clear(); + try { + await _storage.deleteAll(); + } catch (e) { + debugPrint('Secure storage not cleared: $e'); + } + } } /// In memory only: the default in tests, which don't override @@ -82,6 +96,9 @@ class MemorySecretStore implements SecretStore { @override Future deleteWhere(bool Function(String key) test) async => values.removeWhere((key, _) => test(key)); + + @override + Future clear() async => values.clear(); } /// Overridden in `main()` with the [SecureSecretStore] loaded before `runApp`. diff --git a/lib/core/config/server_config.dart b/lib/core/config/server_config.dart index 4208183..b329964 100644 --- a/lib/core/config/server_config.dart +++ b/lib/core/config/server_config.dart @@ -55,6 +55,26 @@ class ServerConfig { return key == null || key.isEmpty ? const {} : {'ApiKey': key}; } + /// [baseUrl] without the user info (`user:password@`) a URL may carry + /// for a proxy's basic auth: for showing, and for links that leave the + /// app. + String get displayUrl => withoutUserInfo(baseUrl); + + /// [url] without `user:password@`. + static String withoutUserInfo(String url) { + final uri = Uri.tryParse(url); + if (uri == null || uri.userInfo.isEmpty) return url; + return uri.replace(userInfo: '').toString(); + } + + /// [url] with [userInfo] (`user:password`) put back, as stored apart + /// from it. + static String withUserInfo(String url, String? userInfo) { + final uri = Uri.tryParse(url); + if (uri == null || userInfo == null || userInfo.isEmpty) return url; + return uri.replace(userInfo: userInfo).toString(); + } + /// True for plain HTTP to a server outside the home network: the API key /// and everything watched would cross the internet unencrypted. bool get isUnencryptedOverInternet { @@ -136,7 +156,9 @@ class ServerConfig { } /// A saved Stash server (2.6). Its API key and password live in the -/// [SecretStore] (2.5), not in the stored JSON. +/// [SecretStore] (2.5), not in the stored JSON; so does user info in its +/// URL (`https://user:password@host`, a proxy's basic auth): the JSON keeps +/// the URL without it ([urlAuthSecret]). @immutable class ServerProfile { const ServerProfile({ @@ -185,12 +207,33 @@ class ServerProfile { static String apiKeySecret(String id) => 'api_key:$id'; static String passwordSecret(String id) => 'password:$id'; + static String urlAuthSecret(String id) => 'url_auth:$id'; + + /// The user info of [baseUrl] (`user:password`), kept as a secret; null + /// without. + String? get urlAuth { + final info = Uri.tryParse(baseUrl)?.userInfo; + return info == null || info.isEmpty ? null : info; + } /// Without the secrets. - Map toJson() => {'id': id, 'name': name, 'url': baseUrl, if (username != null) 'username': username}; + Map toJson() => { + 'id': id, + 'name': name, + 'url': ServerConfig.withoutUserInfo(baseUrl), + if (username != null) 'username': username, + }; + + /// Whether a stored entry still has secrets in its JSON (API key of + /// versions before 2.5, user info in the URL, stored by older versions), + /// which saving it again moves to the secret store. + static bool hasSecretsInJson(Map json) { + final url = json['url']; + return json.containsKey('apiKey') || (url is String && (Uri.tryParse(url)?.userInfo.isNotEmpty ?? false)); + } - /// Null for an entry that can't be read. Versions before 2.5 stored the - /// API key in the JSON; it is moved to the secret store on load. + /// Null for an entry that can't be read. Secrets still in the JSON + /// ([hasSecretsInJson]) are used and moved to the secret store on load. static ServerProfile? tryFromJson(Map json, SecretStore secrets) { final id = json['id']; final url = json['url']; @@ -198,10 +241,11 @@ class ServerProfile { final legacyKey = json['apiKey']; final username = json['username']; if (id is! String || id.isEmpty || url is! String || url.isEmpty) return null; + final storedAuth = Uri.tryParse(url)?.userInfo ?? ''; return ServerProfile( id: id, name: name is String && name.isNotEmpty ? name : defaultName(url), - baseUrl: url, + baseUrl: storedAuth.isNotEmpty ? url : ServerConfig.withUserInfo(url, secrets.read(urlAuthSecret(id))), apiKey: secrets.read(apiKeySecret(id)) ?? (legacyKey is String ? legacyKey : null), username: username is String ? username : null, password: secrets.read(passwordSecret(id)), @@ -244,8 +288,8 @@ class ServerProfilesNotifier extends Notifier { profiles: [for (final p in json) ?ServerProfile.tryFromJson(p, _secrets)], activeId: prefs.getString(_activeKey), ); - // Move API keys of older versions out of the preferences. - if (json.any((p) => p.containsKey('apiKey'))) _persist(profiles); + // Move API keys and URL passwords of older versions out of the preferences. + if (json.any(ServerProfile.hasSecretsInJson)) _persist(profiles); _moveLegacyLists(prefs, profiles.profiles.firstOrNull?.id); return profiles; } @@ -311,6 +355,7 @@ class ServerProfilesNotifier extends Notifier { for (final p in value.profiles) { await _secrets.write(ServerProfile.apiKeySecret(p.id), p.apiKey); await _secrets.write(ServerProfile.passwordSecret(p.id), p.password); + await _secrets.write(ServerProfile.urlAuthSecret(p.id), p.urlAuth); } await prefs.setString(_profilesKey, jsonEncode([for (final p in value.profiles) p.toJson()])); if (value.activeId == null) { diff --git a/lib/core/network/origin_guard.dart b/lib/core/network/origin_guard.dart new file mode 100644 index 0000000..d4dbcae --- /dev/null +++ b/lib/core/network/origin_guard.dart @@ -0,0 +1,126 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; + +/// Headers that carry the server's credentials: never sent to another +/// origin (another scheme, host or port), e.g. a media URL the server +/// returned that points elsewhere, or a redirect away from the server. +const credentialHeaders = {'apikey', 'cookie', 'authorization', 'proxy-authorization'}; + +/// Whether [a] and [b] have the same scheme, host and port (the port +/// counts with its default, so `https://s` and `https://s:443` match). +bool sameOrigin(Uri a, Uri b) => + a.scheme.toLowerCase() == b.scheme.toLowerCase() && + a.host.toLowerCase() == b.host.toLowerCase() && + a.port == b.port; + +/// The URL mpv actually fetches for [url]: an EDL clip (`edl://%%,…`, +/// see `Short.playbackUrl`) wraps the stream's URL. +@visibleForTesting +Uri? fetchedUri(String url) { + final edl = RegExp(r'^edl://%(\d+)%').firstMatch(url); + if (edl == null) return Uri.tryParse(url); + final bytes = utf8.encode(url.substring(edl.end)); + final length = int.parse(edl.group(1)!); + if (length > bytes.length) return null; + return Uri.tryParse(utf8.decode(bytes.sublist(0, length), allowMalformed: true)); +} + +/// The active server's credential headers (API key or session cookie), +/// bound to the server's origin: [forUrl] gives them only for URLs on the +/// server itself, so a scene, image or stream URL pointing elsewhere never +/// gets them. +@immutable +class AuthHeaders { + const AuthHeaders(this.origin, this.headers); + + /// No server, or no credentials. + static const none = AuthHeaders(null, {}); + + final Uri? origin; + final Map headers; + + /// The headers to send with a request to [url]: all of them on the + /// server's origin, none elsewhere. + Map forUrl(String url) { + final origin = this.origin; + if (headers.isEmpty || origin == null) return const {}; + final uri = fetchedUri(url); + return uri != null && sameOrigin(uri, origin) ? headers : const {}; + } + + @override + bool operator ==(Object other) => other is AuthHeaders && other.origin == origin && mapEquals(other.headers, headers); + + @override + int get hashCode => Object.hash(origin, Object.hashAllUnordered(headers.entries.map((e) => (e.key, e.value)))); +} + +/// Keeps credentials on their origin: drops the [credentialHeaders] of a +/// request that doesn't go to [origin] (when given), and follows redirects +/// itself, dropping them as soon as a redirect leaves the origin the request +/// started on. `dart:io` would forward a custom header such as `ApiKey` to +/// whatever host a redirect names. +class OriginGuardClient extends http.BaseClient { + OriginGuardClient(this._inner, {this.origin}); + + final http.Client _inner; + + /// The only origin credentials may go to; null: the request's own. + final Uri? origin; + + static const _redirects = {301, 302, 303, 307, 308}; + + @override + Future send(http.BaseRequest request) async { + final allowed = origin ?? request.url; + if (!sameOrigin(request.url, allowed)) _strip(request.headers); + // Only plain requests can be sent again; others don't follow redirects. + if (request is! http.Request || !request.followRedirects) { + request.followRedirects = false; + return _inner.send(request); + } + + var current = request; + for (var hops = 0;; hops++) { + final next = _copy(current)..followRedirects = false; + final response = await _inner.send(next); + final location = response.headers['location']; + if (!_redirects.contains(response.statusCode) || location == null) return response; + if (hops >= request.maxRedirects) { + await response.stream.drain(); + throw http.ClientException('Redirect limit exceeded', request.url); + } + await response.stream.drain(); + final target = current.url.resolve(location); + // 303, and 301/302 after a POST, continue as GET without a body, like browsers. + final keepMethod = response.statusCode == 307 || + response.statusCode == 308 || + (current.method == 'GET' || current.method == 'HEAD'); + final redirected = http.Request(keepMethod ? current.method : 'GET', target) + ..headers.addAll(current.headers) + ..maxRedirects = request.maxRedirects + ..persistentConnection = request.persistentConnection; + if (keepMethod) { + redirected.bodyBytes = current.bodyBytes; + } else { + redirected.headers.removeWhere((k, _) => k.toLowerCase() == 'content-type'); + } + if (!sameOrigin(target, allowed)) _strip(redirected.headers); + current = redirected; + } + } + + static void _strip(Map headers) => + headers.removeWhere((key, _) => credentialHeaders.contains(key.toLowerCase())); + + static http.Request _copy(http.Request request) => http.Request(request.method, request.url) + ..headers.addAll(request.headers) + ..bodyBytes = request.bodyBytes + ..maxRedirects = request.maxRedirects + ..persistentConnection = request.persistentConnection; + + @override + void close() => _inner.close(); +} diff --git a/lib/data/media_origin_check.dart b/lib/data/media_origin_check.dart new file mode 100644 index 0000000..5845414 --- /dev/null +++ b/lib/data/media_origin_check.dart @@ -0,0 +1,88 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../core/config/server_config.dart'; +import '../core/network/origin_guard.dart'; +import 'models/list_queries.dart'; +import 'repositories/stash_repository.dart'; + +/// The server hands out media URLs (screenshots, streams) on another origin +/// than the one the app connects to, typically Stash behind a reverse proxy +/// that doesn't forward the `Host` header or `X-Forwarded-Proto` (Stash +/// builds its URLs from them). Credentials only go to the configured origin +/// (`AuthHeaders.forUrl`), so such images and videos load without them and +/// fail on a server that needs a login. +@immutable +class MediaOriginMismatch { + const MediaOriginMismatch({required this.server, required this.media}); + + /// Where the app connects to, e.g. `https://stash.example`. + final String server; + + /// Where the server's media URLs point, e.g. `http://stash.example`. + final String media; + + @override + bool operator ==(Object other) => other is MediaOriginMismatch && other.server == server && other.media == media; + + @override + int get hashCode => Object.hash(server, media); +} + +/// `scheme://host[:port]`, the port only when it isn't the scheme's default. +String originOf(Uri uri) => Uri(scheme: uri.scheme, host: uri.host, port: uri.hasPort ? uri.port : null).toString(); + +/// The mismatch between [baseUrl] and [mediaUrl], or null when they share +/// an origin (or either can't be read). +MediaOriginMismatch? mediaOriginMismatch(String baseUrl, String? mediaUrl) { + final server = Uri.tryParse(baseUrl); + final media = mediaUrl == null ? null : Uri.tryParse(mediaUrl); + if (server == null || media == null || !media.hasScheme || media.host.isEmpty) return null; + if (sameOrigin(server, media)) return null; + return MediaOriginMismatch(server: originOf(server), media: originOf(media)); +} + +/// Checks one scene's media URLs against the active server's address; null +/// when they match, without credentials (nothing to lose) or when the check +/// fails (the lists show those errors). Once per server and session. +final mediaOriginMismatchProvider = FutureProvider((ref) async { + final config = ref.watch(serverConfigProvider); + if (config == null || (config.authHeaders.isEmpty && !config.usesSession)) return null; + final repo = ref.watch(stashRepositoryProvider); + try { + final scene = (await repo.findScenes(SceneQuery(), perPage: 1)).items.firstOrNull; + if (scene == null) return null; + return mediaOriginMismatch(config.baseUrl, scene.screenshotUrl ?? scene.streamUrl); + } catch (_) { + return null; + } +}, retry: (_, _) => null); + +/// The mismatch the user hid for the active server (stored per server as +/// its media origin): the hint shows again only for another mismatch. +class MediaOriginHintNotifier extends Notifier { + static String _key(String serverId) => 'media_origin_hint_hidden:$serverId'; + + @override + String? build() { + final id = ref.watch(activeServerIdProvider); + return id == null ? null : ref.watch(sharedPreferencesProvider).getString(_key(id)); + } + + Future hide(MediaOriginMismatch mismatch) async { + final id = ref.read(activeServerIdProvider); + if (id == null) return; + state = mismatch.media; + await ref.read(sharedPreferencesProvider).setString(_key(id), mismatch.media); + } +} + +final mediaOriginHintHiddenProvider = + NotifierProvider(MediaOriginHintNotifier.new); + +/// The mismatch to warn about: found and not hidden by the user. +final mediaOriginWarningProvider = Provider((ref) { + final mismatch = ref.watch(mediaOriginMismatchProvider).value; + if (mismatch == null || ref.watch(mediaOriginHintHiddenProvider) == mismatch.media) return null; + return mismatch; +}); diff --git a/lib/data/repositories/stash_repository.dart b/lib/data/repositories/stash_repository.dart index 37fd8c9..93ba37d 100644 --- a/lib/data/repositories/stash_repository.dart +++ b/lib/data/repositories/stash_repository.dart @@ -1,4 +1,6 @@ -import 'package:flutter/foundation.dart' show TargetPlatform, defaultTargetPlatform; +import 'dart:async'; + +import 'package:flutter/foundation.dart' show TargetPlatform, defaultTargetPlatform, visibleForTesting; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:http/http.dart' as http; @@ -17,6 +19,7 @@ import '../../core/api/documents/tags.graphql.dart'; import '../../core/api/documents/tasks.graphql.dart'; import '../../core/api/stash_schema.graphql.dart'; import '../../core/config/server_config.dart'; +import '../../core/network/origin_guard.dart'; import '../../features/player/playback_tracker.dart'; import '../connection_status.dart'; import '../models/gallery.dart'; @@ -129,16 +132,27 @@ Duration? stashRetry(int retryCount, Object error) { return Duration(milliseconds: 500 * (1 << retryCount)); } +/// No caching at all: lists are paginated and refreshed by their providers, +/// which hold the results. `networkOnly` would still write every response +/// into the normalized cache, which then grows with every page, filter and +/// random seed and is never read. +final stashGraphQLPolicies = DefaultPolicies( + query: Policies(fetch: FetchPolicy.noCache), + mutate: Policies(fetch: FetchPolicy.noCache), + watchQuery: Policies(fetch: FetchPolicy.noCache), + watchMutation: Policies(fetch: FetchPolicy.noCache), +); + GraphQLClient createGraphQLClient(ServerConfig config, {http.Client? httpClient, StashSessionCookie? session}) => GraphQLClient( link: HttpLink( config.graphqlEndpoint, defaultHeaders: {...config.authHeaders, if (session != null) 'Cookie': session.header}, - httpClient: httpClient, + httpClient: httpClient ?? OriginGuardClient(http.Client(), origin: Uri.parse(config.baseUrl)), ), - // Lists are paginated and refreshed manually, so no normalized caching. + // Required by the client; stays empty with these policies. cache: GraphQLCache(), - defaultPolicies: DefaultPolicies(query: Policies(fetch: FetchPolicy.networkOnly)), + defaultPolicies: stashGraphQLPolicies, ); /// A scene's place in a group: the group and the scene's position in it. @@ -146,8 +160,8 @@ typedef SceneGroupEntry = ({String groupId, int? sceneIndex}); /// All access to the Stash GraphQL API goes through this class. class StashRepository implements PlaybackActivityApi { - StashRepository(this._client, {this._authHeaders = const {}, http.Client? httpClient, this._onReachability}) - : _http = httpClient ?? http.Client(); + StashRepository(this._client, {this._auth = AuthHeaders.none, http.Client? httpClient, this._onReachability}) + : _http = httpClient ?? OriginGuardClient(http.Client()); final GraphQLClient _client; @@ -155,7 +169,7 @@ class StashRepository implements PlaybackActivityApi { /// reached (false); feeds [connectionStatusProvider]. Server and auth /// errors aren't reported. final void Function(bool reachable)? _onReachability; - final Map _authHeaders; + final AuthHeaders _auth; /// For non-GraphQL server files such as the sprite VTT. final http.Client _http; @@ -615,7 +629,7 @@ class StashRepository implements PlaybackActivityApi { final vttUrl = details.vttUrl; if (vttUrl == null) return null; try { - final response = await _http.get(Uri.parse(vttUrl), headers: _authHeaders); + final response = await _http.get(Uri.parse(vttUrl), headers: _auth.forUrl(vttUrl)); if (response.statusCode != 200) return null; return ScrubThumbnails.parse(response.body, spriteUrl: details.spriteUrl, vttUrl: vttUrl); } catch (_) { @@ -915,7 +929,7 @@ class StashRepository implements PlaybackActivityApi { final scenes = (await findScenes(SceneQuery(sort: SceneSort.random), perPage: sample)).items; final markers = (await findMarkers(MarkerQuery(sort: MarkerSort.random), perPage: sample ~/ 2)).items; Future count(Iterable urls) async => - (await Future.wait(urls.map(_exists))).where((found) => found).length; + (await Future.wait(urls.map(fileExists))).where((found) => found).length; final (animated, videos, markerAnimated) = await ( count(scenes.map((s) => s.webpUrl)), count(scenes.map((s) => s.previewUrl)), @@ -930,17 +944,26 @@ class StashRepository implements PlaybackActivityApi { ); } - /// Whether the server has the file at [url]; asks for one byte only. - Future _exists(String? url) async { + /// Whether the server has the file at [url]; asks for one byte only and + /// reads no body: a server or proxy that ignores the range would + /// otherwise send the whole preview. + @visibleForTesting + Future fileExists(String? url) async { if (url == null) return false; try { - final response = await _http.get(Uri.parse(url), headers: {..._authHeaders, 'Range': 'bytes=0-0'}); + final request = http.Request('GET', Uri.parse(url)) + ..headers.addAll({..._auth.forUrl(url), 'Range': 'bytes=0-0'}); + final response = await _http.send(request).timeout(_existsTimeout); + // Cancelling the body closes the connection instead of downloading it. + unawaited(response.stream.listen(null).cancel()); return response.statusCode == 200 || response.statusCode == 206; } catch (_) { return false; } } + static const _existsTimeout = Duration(seconds: 15); + static Input$FindFilterType _findFilter({ String? search, required int page, @@ -1061,7 +1084,10 @@ final stashRepositoryProvider = Provider((ref) { final serverId = ref.watch(activeServerIdProvider); return StashRepository( ref.watch(graphQLClientProvider), - authHeaders: ref.watch(serverConfigProvider)?.authHeaders ?? const {}, + auth: switch (ref.watch(serverConfigProvider)) { + final config? => AuthHeaders(Uri.parse(config.baseUrl), config.authHeaders), + null => AuthHeaders.none, + }, httpClient: ref.watch(stashHttpClientProvider), // Read on each report, not watched: the status doesn't rebuild the // repository. Calls that end after a server switch report nothing. diff --git a/lib/data/repositories/stash_session.dart b/lib/data/repositories/stash_session.dart index a94b1bb..8a80353 100644 --- a/lib/data/repositories/stash_session.dart +++ b/lib/data/repositories/stash_session.dart @@ -5,6 +5,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; import '../../core/config/server_config.dart'; +import '../../core/network/origin_guard.dart'; import 'stash_repository.dart'; /// Stash's session cookie after signing in (2.7). @@ -19,17 +20,29 @@ class StashSessionCookie { String get header => 'session=$value'; } +/// How long signing in may take, answer included, before it counts as +/// unreachable: a server that keeps the connection open must not leave the +/// login spinning forever. +const stashLoginTimeout = Duration(seconds: 20); + /// Signs in with [config]'s username and password the way Stash's login /// page does (`POST /login`). Stash answers a valid login with a redirect -/// and a `session` cookie, a wrong one with the login page again. -Future stashLogin(http.Client client, ServerConfig config, {DateTime Function()? now}) async { +/// and a `session` cookie, a wrong one with the login page again. Only the +/// headers are read; the body is dropped unread. The caller closes +/// [client], which also ends a request that timed out. +Future stashLogin( + http.Client client, + ServerConfig config, { + DateTime Function()? now, + Duration timeout = stashLoginTimeout, +}) async { final request = http.Request('POST', Uri.parse('${config.baseUrl}/login')) ..followRedirects = false ..bodyFields = {'username': config.username ?? '', 'password': config.password ?? ''}; final http.StreamedResponse response; try { - response = await client.send(request); - await response.stream.drain(); + response = await client.send(request).timeout(timeout); + unawaited(response.stream.listen(null).cancel()); } catch (e) { throw unreachableException(e, host: request.url.host); } @@ -108,17 +121,20 @@ class StashSessionNotifier extends Notifier { final stashSessionProvider = NotifierProvider(StashSessionNotifier.new); -/// Sends the session cookie with every request and, when the server -/// answers 401, signs in again and repeats the request once. +/// Sends the session cookie with every request to the server's [origin] +/// and, when the server answers 401, signs in again and repeats the request +/// once. Requests to other origins go out without it. class StashSessionClient extends http.BaseClient { - StashSessionClient(this._inner, {required this.ensure, required this.renew}); + StashSessionClient(this._inner, {required this.origin, required this.ensure, required this.renew}); final http.Client _inner; + final Uri origin; final Future Function() ensure; final Future Function() renew; @override Future send(http.BaseRequest request) async { + if (!sameOrigin(request.url, origin)) return _inner.send(request); final cookie = await ensure(); if (cookie == null) return _inner.send(request); @@ -147,11 +163,15 @@ class StashSessionClient extends http.BaseClient { } /// The HTTP client for the active server's GraphQL API and files: adds the -/// session cookie where needed (the API key is a default header). +/// session cookie where needed (the API key is a default header), and +/// keeps both on the server's origin, redirects included +/// ([OriginGuardClient]). final stashHttpClientProvider = Provider((ref) { - ref.watch(serverConfigProvider); + final config = ref.watch(serverConfigProvider); + final origin = Uri.parse(config?.baseUrl ?? ServerConfig.demoUrl); final client = StashSessionClient( - http.Client(), + OriginGuardClient(http.Client(), origin: origin), + origin: origin, ensure: () => ref.read(stashSessionProvider.notifier).ensure(), renew: () => ref.read(stashSessionProvider.notifier).renew(), ); @@ -160,9 +180,15 @@ final stashHttpClientProvider = Provider((ref) { }); /// Auth headers for the current server, for image and video requests: -/// the API key, or the session cookie once signed in. -final authHeadersProvider = Provider>((ref) { - final headers = ref.watch(serverConfigProvider)?.authHeaders ?? const {}; +/// the API key, or the session cookie once signed in. Bound to the +/// server's origin: take them with [AuthHeaders.forUrl]. +final authHeadersProvider = Provider((ref) { + final config = ref.watch(serverConfigProvider); + if (config == null) return AuthHeaders.none; + final headers = config.authHeaders; final cookie = ref.watch(stashSessionProvider); - return cookie == null ? headers : {...headers, 'Cookie': cookie.header}; + return AuthHeaders( + Uri.parse(config.baseUrl), + cookie == null ? headers : {...headers, 'Cookie': cookie.header}, + ); }); diff --git a/lib/features/auth/login_page.dart b/lib/features/auth/login_page.dart index 7e6f4b5..2f873f1 100644 --- a/lib/features/auth/login_page.dart +++ b/lib/features/auth/login_page.dart @@ -345,7 +345,7 @@ class _LoginPageState extends ConsumerState { child: ListTile( leading: const Icon(Icons.dns_outlined), title: Text(server.name, maxLines: 1, overflow: TextOverflow.ellipsis), - subtitle: Text(server.baseUrl, maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: Text(ServerConfig.withoutUserInfo(server.baseUrl), maxLines: 1, overflow: TextOverflow.ellipsis), trailing: const Icon(Icons.chevron_right), onTap: () => ref.read(serverProfilesProvider.notifier).activate(server.id), ), diff --git a/lib/features/auth/server_avatar.dart b/lib/features/auth/server_avatar.dart index c804766..fbd29e9 100644 --- a/lib/features/auth/server_avatar.dart +++ b/lib/features/auth/server_avatar.dart @@ -67,7 +67,7 @@ class AccountSheet extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final l = context.l10n; final name = _serverName(ref); - final url = ref.watch(serverConfigProvider)?.baseUrl; + final url = ref.watch(serverConfigProvider)?.displayUrl; final count = ref.watch(serverProfilesProvider).profiles.length; return SafeArea( child: SingleChildScrollView( diff --git a/lib/features/auth/server_switcher.dart b/lib/features/auth/server_switcher.dart index b54ef9c..b5c30ca 100644 --- a/lib/features/auth/server_switcher.dart +++ b/lib/features/auth/server_switcher.dart @@ -65,7 +65,7 @@ class ServerSwitcher extends ConsumerWidget { color: server.id == state.activeId ? theme.colorScheme.primary : null, ), title: Text(server.name, maxLines: 1, overflow: TextOverflow.ellipsis), - subtitle: Text(server.baseUrl, maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: Text(ServerConfig.withoutUserInfo(server.baseUrl), maxLines: 1, overflow: TextOverflow.ellipsis), onTap: () { Navigator.pop(context); if (server.id != state.activeId) ref.read(serverProfilesProvider.notifier).activate(server.id); diff --git a/lib/features/cast/cast_media.dart b/lib/features/cast/cast_media.dart index 367b9cb..cc57ad8 100644 --- a/lib/features/cast/cast_media.dart +++ b/lib/features/cast/cast_media.dart @@ -1,3 +1,5 @@ +import '../../core/config/server_config.dart'; +import '../../core/network/origin_guard.dart'; import '../../data/models/scene.dart'; import '../../data/models/scene_details.dart'; import 'cast_service.dart' show CastKind; @@ -22,10 +24,14 @@ class CastMedia { } /// Cast devices fetch media themselves and can't send the `ApiKey` header, -/// so the key goes into the URL (Stash also accepts `?apikey=`). -String withApiKey(String url, String? apiKey) { - if (apiKey == null || apiKey.isEmpty) return url; - final uri = Uri.parse(url); +/// so [server]'s key goes into the URL (Stash also accepts `?apikey=`); +/// only for URLs on the server itself, never for one pointing elsewhere. +String withApiKey(String url, ServerConfig? server) { + final apiKey = server?.apiKey; + if (server == null || apiKey == null || apiKey.isEmpty) return url; + final uri = Uri.tryParse(url); + final origin = Uri.tryParse(server.baseUrl); + if (uri == null || origin == null || !sameOrigin(uri, origin)) return url; return uri.replace(queryParameters: {...uri.queryParameters, 'apikey': apiKey}).toString(); } @@ -71,18 +77,18 @@ String withApiKey(String url, String? apiKey) { CastMedia castMediaFor( Scene scene, SceneDetails? details, { - String? apiKey, + ServerConfig? server, Duration start = Duration.zero, CastKind kind = CastKind.googleCast, }) { final stream = kind == CastKind.airPlay ? pickAirPlayStream(scene, details) : pickCastStream(scene, details); final image = scene.screenshotUrl; return CastMedia( - url: withApiKey(stream.url, apiKey), + url: withApiKey(stream.url, server), contentType: stream.contentType, title: scene.title, subtitle: scene.studio?.name ?? scene.performers.firstOrNull?.name, - imageUrl: image == null ? null : withApiKey(image, apiKey), + imageUrl: image == null ? null : withApiKey(image, server), start: start, ); } diff --git a/lib/features/library/stats_tab.dart b/lib/features/library/stats_tab.dart index 9db9af5..b5e0b2d 100644 --- a/lib/features/library/stats_tab.dart +++ b/lib/features/library/stats_tab.dart @@ -130,7 +130,7 @@ class _ServerCard extends ConsumerWidget { leading: Icon(Icons.dns_outlined, color: statusColor), title: Text(server.name, maxLines: 1, overflow: TextOverflow.ellipsis), subtitle: Text( - '${server.baseUrl}\n$status • ${l.apiKey}: ${server.apiKey == null ? l.notSet : l.isSet}', + '${server.config.displayUrl}\n$status • ${l.apiKey}: ${server.apiKey == null ? l.notSet : l.isSet}', ), isThreeLine: true, trailing: const Icon(Icons.edit_outlined), diff --git a/lib/features/pip/pip.dart b/lib/features/pip/pip.dart index 7f2eeea..4fdf365 100644 --- a/lib/features/pip/pip.dart +++ b/lib/features/pip/pip.dart @@ -224,8 +224,8 @@ class PipNotifier extends Notifier { // Pause first, so both don't play while the native player starts. await player.pause(); final started = await service.startNative( - url: withApiKey(stream.url, ref.read(serverConfigProvider)?.apiKey), - headers: ref.read(authHeadersProvider), + url: withApiKey(stream.url, ref.read(serverConfigProvider)), + headers: ref.read(authHeadersProvider).forUrl(stream.url), start: start, from: from ?? Rect.zero, aspect: videoAspect(player.state, scene, sceneFirst: true), diff --git a/lib/features/player/lock_screen.dart b/lib/features/player/lock_screen.dart index 7a2956d..3fe3e79 100644 --- a/lib/features/player/lock_screen.dart +++ b/lib/features/player/lock_screen.dart @@ -172,7 +172,7 @@ final lockScreenControlsProvider = Provider((ref) { } final player = ref.read(playerProvider); - final item = lockScreenItem(scene, headers: ref.read(authHeadersProvider)); + final item = lockScreenItem(scene, headers: ref.read(authHeadersProvider).forUrl(scene.screenshotUrl ?? '')); final subscriptions = >[]; var disposed = false; ref.onDispose(() { diff --git a/lib/features/player/player_controls.dart b/lib/features/player/player_controls.dart index 982e8f1..a49cdf8 100644 --- a/lib/features/player/player_controls.dart +++ b/lib/features/player/player_controls.dart @@ -534,7 +534,7 @@ class _ChapterThumbnailTile extends ConsumerWidget { cue: cue, width: width, height: width * cue.height / cue.width, - headers: ref.watch(authHeadersProvider), + headers: ref.watch(authHeadersProvider).forUrl(sprite.spriteUrl), ), ), ) diff --git a/lib/features/player/player_providers.dart b/lib/features/player/player_providers.dart index 2c68727..0d420f2 100644 --- a/lib/features/player/player_providers.dart +++ b/lib/features/player/player_providers.dart @@ -536,7 +536,7 @@ class NowPlayingNotifier extends Notifier { final media = castMediaFor( scene, await details.read().catchError((Object _) => const SceneDetails()), - apiKey: ref.read(serverConfigProvider)?.apiKey, + server: ref.read(serverConfigProvider), start: start, kind: ref.read(castConnectionProvider).value?.kind ?? CastKind.googleCast, ); @@ -594,7 +594,7 @@ class NowPlayingNotifier extends Notifier { player.open( Media( url, - httpHeaders: ref.read(authHeadersProvider), + httpHeaders: ref.read(authHeadersProvider).forUrl(url), start: start > Duration.zero ? start : null, ), play: play && !buffering, diff --git a/lib/features/player/preview_seek_bar.dart b/lib/features/player/preview_seek_bar.dart index 0ad89a9..0f7a7ad 100644 --- a/lib/features/player/preview_seek_bar.dart +++ b/lib/features/player/preview_seek_bar.dart @@ -7,6 +7,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:media_kit/media_kit.dart'; import '../../core/config/haptics.dart'; +import '../../core/config/image_cache.dart'; import '../../core/config/theme.dart'; import '../../core/utils/format.dart'; import '../../data/models/scene_details.dart'; @@ -249,12 +250,13 @@ class _PreviewSeekBarState extends ConsumerState { final played = _drag ?? _fractionOf(remote?.position ?? _position); // The duration or the window may have changed since the last position. if (remote == null) _played.value = _fractionOf(_position); - final headers = ref.watch(authHeadersProvider); + final auth = ref.watch(authHeadersProvider); final thumbs = _loadThumbnails ? ref.watch(scrubThumbnailsProvider(widget.sceneId)).value : null; + final headers = thumbs == null ? const {} : auth.forUrl(thumbs.spriteUrl); if (thumbs != null && thumbs.spriteUrl != _precachedSprite) { _precachedSprite = thumbs.spriteUrl; // Errors are fine: the preview then shows only the time. - unawaited(precacheImage(CachedNetworkImageProvider(thumbs.spriteUrl, headers: headers), context, + unawaited(precacheImage(CachedNetworkImageProvider(thumbs.spriteUrl, headers: headers, cacheManager: stashImageCacheManager), context, onError: (_, _) {})); } // Like the thumbnails, only once the bar is shown or touched. @@ -463,7 +465,7 @@ class SpriteFrame extends StatelessWidget { // Natural size: one logical pixel per sprite pixel, so the // cue's pixel coordinates apply directly. child: Image( - image: CachedNetworkImageProvider(spriteUrl, headers: headers), + image: CachedNetworkImageProvider(spriteUrl, headers: headers, cacheManager: stashImageCacheManager), filterQuality: FilterQuality.medium, gaplessPlayback: true, ), diff --git a/lib/features/player/scene_description.dart b/lib/features/player/scene_description.dart index 8bce1fa..375c50f 100644 --- a/lib/features/player/scene_description.dart +++ b/lib/features/player/scene_description.dart @@ -134,7 +134,7 @@ class SceneDescriptionSheet extends ConsumerWidget { OutlinedButton.icon( icon: const Icon(Icons.open_in_new), label: Text(l.openInStash), - onPressed: () => openExternalUrl(context, stashSceneWebUrl(server.baseUrl, scene.id)), + onPressed: () => openExternalUrl(context, stashSceneWebUrl(server.displayUrl, scene.id)), ), ], ), diff --git a/lib/features/security/app_lock.dart b/lib/features/security/app_lock.dart index fb7dca0..5e772b9 100644 --- a/lib/features/security/app_lock.dart +++ b/lib/features/security/app_lock.dart @@ -1,14 +1,12 @@ -import 'dart:convert'; -import 'dart:math'; - -import 'package:crypto/crypto.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:local_auth/local_auth.dart'; +import '../../core/config/image_cache.dart'; import '../../core/config/secret_store.dart'; import '../../core/config/server_config.dart'; +import 'pin_hash.dart'; /// App lock (11.1) and app switcher privacy (11.2) settings. @immutable @@ -19,9 +17,16 @@ class AppLockSettings { this.lockAfter = Duration.zero, this.hideInSwitcher = false, this.pinLength = 4, + this.pinLost = false, }); final bool enabled; + + /// The lock is on, but its PIN is gone: the secure storage couldn't be + /// read (e.g. after a restore or a Keystore problem) or no longer has it. + /// The app stays locked; the lock screen offers biometrics (then a new + /// PIN) or resetting the app instead of the PIN pad. + final bool pinLost; final bool biometrics; /// How long the app may be in the background before it locks again. @@ -33,19 +38,24 @@ class AppLockSettings { /// inactive: always with the lock on, else by [hideInSwitcher]. bool get hidesApp => enabled || hideInSwitcher; - AppLockSettings copyWith({bool? enabled, bool? biometrics, Duration? lockAfter, bool? hideInSwitcher, int? pinLength}) => + AppLockSettings copyWith({ + bool? enabled, + bool? biometrics, + Duration? lockAfter, + bool? hideInSwitcher, + int? pinLength, + bool? pinLost, + }) => AppLockSettings( enabled: enabled ?? this.enabled, biometrics: biometrics ?? this.biometrics, lockAfter: lockAfter ?? this.lockAfter, hideInSwitcher: hideInSwitcher ?? this.hideInSwitcher, pinLength: pinLength ?? this.pinLength, + pinLost: pinLost ?? this.pinLost, ); } -/// Salted SHA-256 of a PIN; the PIN itself is never stored. -String hashPin(String pin, String salt) => sha256.convert(utf8.encode('$salt:$pin')).toString(); - class AppLockSettingsNotifier extends Notifier { static const _enabled = 'lock_enabled'; static const _biometrics = 'lock_biometrics'; @@ -53,24 +63,21 @@ class AppLockSettingsNotifier extends Notifier { static const _hide = 'lock_hide_in_switcher'; static const _pinLength = 'lock_pin_length'; - /// `:` in the [SecretStore]: one value, so changing the PIN - /// can't leave a new salt with the old hash. + /// The PIN's hash in the [SecretStore] ([StoredPin.encode]): one value, so + /// changing the PIN can't leave a new salt with the old hash. static const _pin = 'lock_pin'; // Where versions before the secret store kept them (SharedPreferences). static const _legacySalt = 'lock_pin_salt'; static const _legacyHash = 'lock_pin_hash'; - /// Salt and hash of the PIN, or null when none is set. - ({String salt, String hash})? _storedPin() { - final stored = ref.read(secretStoreProvider).read(_pin); - final separator = stored?.indexOf(':') ?? -1; - if (stored != null && separator > 0) { - return (salt: stored.substring(0, separator), hash: stored.substring(separator + 1)); - } + /// The stored PIN hash, or null when none is set. + StoredPin? _storedPin() { + final stored = StoredPin.parse(ref.read(secretStoreProvider).read(_pin)); + if (stored != null) return stored; final prefs = ref.read(sharedPreferencesProvider); final salt = prefs.getString(_legacySalt); final hash = prefs.getString(_legacyHash); - return salt == null || hash == null ? null : (salt: salt, hash: hash); + return salt == null || hash == null ? null : StoredPin.legacy(salt, hash); } @override @@ -80,14 +87,17 @@ class AppLockSettingsNotifier extends Notifier { final pin = _storedPin(); if (pin != null && secrets.read(_pin) == null) { // Move a PIN of an older version out of SharedPreferences. - secrets.write(_pin, '${pin.salt}:${pin.hash}').then((_) async { + secrets.write(_pin, pin.encode()).then((_) async { await prefs.remove(_legacySalt); await prefs.remove(_legacyHash); }); } + final enabled = prefs.getBool(_enabled) ?? false; return AppLockSettings( - // Only "enabled" when a PIN exists, so a half-set-up lock can't lock out. - enabled: (prefs.getBool(_enabled) ?? false) && pin != null, + // A lock that is on stays on without its PIN (pinLost): failing to + // read the secure storage must not open the app. + enabled: enabled, + pinLost: enabled && pin == null, biometrics: prefs.getBool(_biometrics) ?? false, lockAfter: Duration(seconds: prefs.getInt(_lockAfter) ?? 0), hideInSwitcher: prefs.getBool(_hide) ?? false, @@ -95,19 +105,20 @@ class AppLockSettingsNotifier extends Notifier { ); } - /// Turns the lock on with a new PIN (also used to change the PIN). + /// Turns the lock on with a new PIN (also used to change the PIN, and to + /// set one after it was lost). Future enable(String pin) async { final prefs = ref.read(sharedPreferencesProvider); - final random = Random.secure(); - final salt = base64Encode(List.generate(16, (_) => random.nextInt(256))); - await ref.read(secretStoreProvider).write(_pin, '$salt:${hashPin(pin, salt)}'); + final stored = await StoredPin.create(pin); + // The PIN first: "enabled" must never be stored without it. + await ref.read(secretStoreProvider).write(_pin, stored.encode()); await prefs.remove(_legacySalt); await prefs.remove(_legacyHash); await prefs.setInt(_pinLength, pin.length); await prefs.setBool(_enabled, true); if (!ref.mounted) return; ref.read(pinThrottleProvider.notifier).reset(); - state = state.copyWith(enabled: true, pinLength: pin.length); + state = state.copyWith(enabled: true, pinLength: pin.length, pinLost: false); } Future disable() async { @@ -118,22 +129,58 @@ class AppLockSettingsNotifier extends Notifier { await prefs.setBool(_enabled, false); await prefs.setBool(_biometrics, false); if (!ref.mounted) return; - state = state.copyWith(enabled: false, biometrics: false); + state = state.copyWith(enabled: false, biometrics: false, pinLost: false); } /// Checks [pin]. Wrong PINs count towards [PinThrottle]; while it blocks, - /// every PIN is rejected. - bool verify(String pin) { + /// every PIN is rejected. A PIN stored in the legacy format is replaced + /// by the current one once it was entered correctly. + Future verify(String pin) async { final throttle = ref.read(pinThrottleProvider.notifier); if (throttle.remaining() > Duration.zero) return false; final stored = _storedPin(); - final ok = stored != null && hashPin(pin, stored.salt) == stored.hash; - if (ok) { - throttle.reset(); - } else { + final ok = stored != null && await stored.matches(pin); + if (!ref.mounted) return ok; + if (!ok) { throttle.recordFailure(); + return false; + } + throttle.reset(); + if (stored.isLegacy) await _upgrade(pin, stored); + return true; + } + + /// Stores [pin] in the current format in place of [legacy], unless the + /// PIN changed meanwhile. Failing is fine: it is tried at the next unlock. + Future _upgrade(String pin, StoredPin legacy) async { + try { + final upgraded = await StoredPin.create(pin); + if (!ref.mounted || _storedPin()?.encode() != legacy.encode()) return; + await ref.read(secretStoreProvider).write(_pin, upgraded.encode()); + final prefs = ref.read(sharedPreferencesProvider); + await prefs.remove(_legacySalt); + await prefs.remove(_legacyHash); + } catch (e) { + debugPrint('PIN hash upgrade failed: $e'); } - return ok; + } + + /// The way out when the PIN is lost ([AppLockSettings.pinLost]) and + /// can't be confirmed otherwise: deletes everything the lock protected, + /// i.e. all settings, saved servers and their data, secrets and cached + /// images, and starts over at the login, with the lock off. + Future resetApp() async { + final prefs = ref.read(sharedPreferencesProvider); + final clearImages = ref.read(clearImageCacheProvider); + await ref.read(secretStoreProvider).clear(); + await prefs.clear(); + clearImages(); + if (!ref.mounted) return; + ref + ..invalidate(serverProfilesProvider) + ..invalidate(pinThrottleProvider) + ..invalidate(appLockedProvider) + ..invalidateSelf(); } Future setBiometrics(bool value) async { diff --git a/lib/features/security/app_lock_gate.dart b/lib/features/security/app_lock_gate.dart index 5c6d10c..3a0c3f0 100644 --- a/lib/features/security/app_lock_gate.dart +++ b/lib/features/security/app_lock_gate.dart @@ -152,6 +152,9 @@ class _LockScreenBodyState extends ConsumerState<_LockScreenBody> { bool _askBiometrics = true; bool _asking = false; + /// After biometrics while the PIN is lost: a new PIN is being chosen. + bool _choosingPin = false; + @override void initState() { super.initState(); @@ -183,15 +186,43 @@ class _LockScreenBodyState extends ConsumerState<_LockScreenBody> { final ok = await ref.read(biometricAuthProvider).authenticate(context.l10n.unlockReason); if (!ok || !mounted) return; ref.read(pinThrottleProvider.notifier).reset(); + // Without a PIN the lock would be useless after unlocking: a new one first. + if (ref.read(appLockSettingsProvider).pinLost) { + setState(() => _choosingPin = true); + return; + } ref.read(appLockedProvider.notifier).unlock(); } finally { _asking = false; } } + Future _setNewPin(String pin) async { + await ref.read(appLockSettingsProvider.notifier).enable(pin); + if (!mounted) return; + Haptics.medium(); + _choosingPin = false; + ref.read(appLockedProvider.notifier).unlock(); + } + @override Widget build(BuildContext context) { final settings = ref.watch(appLockSettingsProvider); + if (settings.pinLost) { + if (_choosingPin) { + return ScreenLock.create( + title: Text(context.l10n.chooseNewPin), + confirmTitle: Text(context.l10n.repeatPin), + useBlur: false, + onConfirmed: _setNewPin, + onCancelled: () => setState(() => _choosingPin = false), + ); + } + return PinLostView( + onBiometric: settings.biometrics ? _biometric : null, + onReset: () => ref.read(appLockSettingsProvider.notifier).resetApp(), + ); + } ref.watch(pinThrottleProvider); final throttle = ref.read(pinThrottleProvider.notifier); @@ -291,6 +322,104 @@ class _PinBlockedViewState extends State { } } +/// Shown instead of the PIN pad when the lock is on but its PIN can't be +/// read ([AppLockSettings.pinLost]): biometrics lead to a new PIN; without +/// them, the only way in is resetting the app, asked once more inline (the +/// lock screen sits above the navigator, so no dialog). +class PinLostView extends StatefulWidget { + const PinLostView({super.key, required this.onReset, this.onBiometric}); + + final VoidCallback? onBiometric; + final Future Function() onReset; + + @override + State createState() => _PinLostViewState(); +} + +class _PinLostViewState extends State { + bool _confirming = false; + bool _resetting = false; + + Future _reset() async { + setState(() => _resetting = true); + try { + await widget.onReset(); + } finally { + if (mounted) setState(() => _resetting = false); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final l = context.l10n; + final muted = theme.textTheme.bodyMedium?.copyWith(color: theme.colorScheme.onSurfaceVariant); + final biometric = widget.onBiometric; + return SafeArea( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: _confirming + ? [ + Icon(Icons.restart_alt, size: 56, color: theme.colorScheme.error), + const SizedBox(height: 16), + Text(l.resetAppTitle, textAlign: TextAlign.center, style: theme.textTheme.titleMedium), + const SizedBox(height: 8), + Text(l.resetAppBody, textAlign: TextAlign.center, style: muted), + const SizedBox(height: 24), + Wrap( + alignment: WrapAlignment.center, + spacing: 12, + runSpacing: 8, + children: [ + OutlinedButton( + onPressed: _resetting ? null : () => setState(() => _confirming = false), + child: Text(l.cancel), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: theme.colorScheme.error, + foregroundColor: theme.colorScheme.onError, + ), + onPressed: _resetting ? null : _reset, + child: Text(l.resetApp), + ), + ], + ), + ] + : [ + Icon(Icons.lock_reset, size: 56, color: theme.colorScheme.onSurfaceVariant), + const SizedBox(height: 16), + Text(l.pinLostTitle, textAlign: TextAlign.center, style: theme.textTheme.titleMedium), + const SizedBox(height: 8), + Text(l.pinLostBody, textAlign: TextAlign.center, style: muted), + if (biometric != null) ...[ + const SizedBox(height: 8), + Text(l.pinLostBiometricHint, textAlign: TextAlign.center, style: muted), + const SizedBox(height: 24), + FilledButton.icon( + icon: const Icon(Icons.fingerprint), + label: Text(l.unlockBiometric), + onPressed: biometric, + ), + ], + const SizedBox(height: 16), + Text(l.pinLostResetHint, textAlign: TextAlign.center, style: muted), + const SizedBox(height: 8), + TextButton( + onPressed: () => setState(() => _confirming = true), + child: Text(l.resetApp), + ), + ], + ), + ), + ), + ); + } +} + /// Asks for a new PIN twice; returns it, or null if cancelled. Covers the /// whole app like the lock screen, also above the settings sheet. Future showCreatePin(BuildContext context) { diff --git a/lib/features/security/pin_hash.dart b/lib/features/security/pin_hash.dart new file mode 100644 index 0000000..eb5c1a1 --- /dev/null +++ b/lib/features/security/pin_hash.dart @@ -0,0 +1,116 @@ +import 'dart:convert'; +import 'dart:isolate'; +import 'dart:math'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter/foundation.dart'; + +/// How a PIN is stored: never the PIN, only a slow, salted hash of it. +/// +/// Current format: `pbkdf2-sha256$$$` (salt and +/// hash base64). A 4–6 digit PIN has at most a million values, so a fast +/// hash could be tried out offline in seconds if the stored value leaked +/// (rooted or jailbroken device); PBKDF2 makes every guess cost +/// [defaultIterations] HMAC rounds. Versions before it stored +/// `:` ([legacyHashPin]); such a value is +/// still accepted and replaced by the current format at the next correct +/// PIN (see `AppLockSettingsNotifier.verify`). +@immutable +class StoredPin { + const StoredPin._(this.salt, this.hash, this.rounds); + + static const _prefix = 'pbkdf2-sha256'; + + /// Rounds for new hashes. Every stored value keeps its own count, so this + /// can be raised later without breaking existing PINs. + static const defaultIterations = 60000; + + /// Rounds used by [create]; tests lower it. + @visibleForTesting + static int iterations = defaultIterations; + + final String salt; + final String hash; + + /// PBKDF2 rounds; null for the legacy SHA-256 format. + final int? rounds; + + /// Whether this is the old fast hash, to be replaced after the next + /// correct PIN. + bool get isLegacy => rounds == null; + + /// Parses a stored value; null when it is neither format. + static StoredPin? parse(String? stored) { + if (stored == null) return null; + if (stored.startsWith('$_prefix\$')) { + final parts = stored.split('\$'); + final rounds = parts.length == 4 ? int.tryParse(parts[1]) : null; + if (rounds == null || rounds <= 0 || parts[2].isEmpty || parts[3].isEmpty) return null; + return StoredPin._(parts[2], parts[3], rounds); + } + final separator = stored.indexOf(':'); + if (separator <= 0 || separator == stored.length - 1) return null; + return StoredPin._(stored.substring(0, separator), stored.substring(separator + 1), null); + } + + /// The legacy format, e.g. from the preferences of older versions. + static StoredPin legacy(String salt, String hash) => StoredPin._(salt, hash, null); + + /// A new hash of [pin] with a random salt, in the current format. + static Future create(String pin) async { + final random = Random.secure(); + final salt = base64Encode(List.generate(16, (_) => random.nextInt(256))); + final rounds = iterations; + final hash = base64Encode(await _derive(pin, salt, rounds)); + return StoredPin._(salt, hash, rounds); + } + + /// Whether [pin] matches, compared in constant time. + Future matches(String pin) async { + final rounds = this.rounds; + if (rounds == null) return _equal(utf8.encode(legacyHashPin(pin, salt)), utf8.encode(hash)); + final List expected; + try { + expected = base64Decode(hash); + } on FormatException { + return false; + } + return _equal(await _derive(pin, salt, rounds), expected); + } + + /// The value to store. + String encode() => isLegacy ? '$salt:$hash' : '$_prefix\$$rounds\$$salt\$$hash'; + + /// Off the UI thread: [defaultIterations] rounds take a noticeable moment. + static Future _derive(String pin, String salt, int rounds) { + if (rounds < 20000) return Future.value(pbkdf2Sha256(utf8.encode(pin), utf8.encode(salt), rounds)); + return Isolate.run(() => pbkdf2Sha256(utf8.encode(pin), utf8.encode(salt), rounds)); + } + + static bool _equal(List a, List b) { + if (a.length != b.length) return false; + var diff = 0; + for (var i = 0; i < a.length; i++) { + diff |= a[i] ^ b[i]; + } + return diff == 0; + } +} + +/// The hash of versions before PBKDF2: salted SHA-256. Only for checking +/// PINs stored by them. +String legacyHashPin(String pin, String salt) => sha256.convert(utf8.encode('$salt:$pin')).toString(); + +/// PBKDF2 with HMAC-SHA256 (RFC 8018), one 32-byte block. +Uint8List pbkdf2Sha256(List password, List salt, int iterations) { + final hmac = Hmac(sha256, password); + var u = hmac.convert([...salt, 0, 0, 0, 1]).bytes; + final result = Uint8List.fromList(u); + for (var i = 1; i < iterations; i++) { + u = hmac.convert(u).bytes; + for (var j = 0; j < result.length; j++) { + result[j] ^= u[j]; + } + } + return result; +} diff --git a/lib/features/settings/settings_categories.dart b/lib/features/settings/settings_categories.dart index 43f14d1..7b55b5e 100644 --- a/lib/features/settings/settings_categories.dart +++ b/lib/features/settings/settings_categories.dart @@ -149,7 +149,7 @@ class ServerSettingsPage extends ConsumerWidget { leading: const Icon(Icons.dns_outlined), title: Text(server?.name ?? '-', maxLines: 1, overflow: TextOverflow.ellipsis), subtitle: Text( - '${config?.baseUrl ?? ''}\n${switch (version) { + '${config?.displayUrl ?? ''}\n${switch (version) { AsyncData(:final value) => l.stashVersion(value ?? l.unknownVersion), AsyncError() => l.notReachable, _ => l.checking, diff --git a/lib/features/shorts/shorts_page.dart b/lib/features/shorts/shorts_page.dart index 3636049..d35f7df 100644 --- a/lib/features/shorts/shorts_page.dart +++ b/lib/features/shorts/shorts_page.dart @@ -239,7 +239,7 @@ class _ShortsPageState extends ConsumerState { player .open( // A marker opens only its clip (Short.playbackUrl), from 0. - Media(short.playbackUrl!, httpHeaders: ref.read(authHeadersProvider)), + Media(short.playbackUrl!, httpHeaders: ref.read(authHeadersProvider).forUrl(short.playbackUrl!)), play: false, ) .then((_) { diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 3b00349..7abad49 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -762,5 +762,16 @@ "markerDeleteConfirm": "„{title}“ bei {time} wird aus der Szene entfernt.", "markerDeleteAction": "Löschen", "markerDeleted": "Marker gelöscht", - "markerSaved": "Marker gespeichert" + "markerSaved": "Marker gespeichert", + "pinLostTitle": "Die PIN ist nicht mehr auf diesem Gerät", + "pinLostBody": "Die App-Sperre ist an, aber ihre PIN ließ sich nicht aus dem sicheren Speicher des Geräts lesen, zum Beispiel nach dem Wiederherstellen eines Backups.", + "pinLostBiometricHint": "Entsperre mit Face ID oder Fingerabdruck, um eine neue PIN festzulegen.", + "pinLostResetHint": "Oder setze die App zurück: Alles, was StashTube auf diesem Gerät gespeichert hat, wird entfernt.", + "resetApp": "App zurücksetzen", + "resetAppTitle": "StashTube zurücksetzen?", + "resetAppBody": "Alle Server, Einstellungen, Listen und zwischengespeicherten Bilder werden von diesem Gerät entfernt und die App-Sperre wird ausgeschaltet. Auf deinen Stash-Servern ändert sich nichts.", + "chooseNewPin": "Neue PIN festlegen", + "mediaOriginTitle": "Bilder und Videos laden eventuell nicht", + "mediaOriginBody": "Stash gibt Medienadressen auf {media} heraus, StashTube verbindet sich aber mit {server}. Dein API-Key oder Login geht nur an {server}, diese Anfragen gehen deshalb ohne ihn raus. Hinter einem Reverse-Proxy: den Host-Header weitergeben und X-Forwarded-Proto setzen.", + "mediaOriginHide": "Ausblenden" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index d5bcf43..d6ae336 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1555,5 +1555,17 @@ "@markerDeleteConfirm": {"placeholders": {"title": {"type": "String"}, "time": {"type": "String"}}}, "markerDeleteAction": "Delete", "markerDeleted": "Marker deleted", - "markerSaved": "Marker saved" + "markerSaved": "Marker saved", + "pinLostTitle": "The PIN is no longer on this device", + "pinLostBody": "The app lock is on, but its PIN couldn't be read from the device's secure storage, for example after restoring a backup.", + "pinLostBiometricHint": "Unlock with Face ID or your fingerprint to choose a new PIN.", + "pinLostResetHint": "Or reset the app: everything StashTube stored on this device is removed.", + "resetApp": "Reset app", + "resetAppTitle": "Reset StashTube?", + "resetAppBody": "All servers, settings, lists and cached images are removed from this device and the app lock is turned off. Nothing changes on your Stash servers.", + "chooseNewPin": "Choose a new PIN", + "mediaOriginTitle": "Images and videos may not load", + "mediaOriginBody": "Stash gives out media addresses on {media}, but StashTube connects to {server}. Your API key or login only goes to {server}, so those requests are sent without it. Behind a reverse proxy, pass on the Host header and set X-Forwarded-Proto.", + "@mediaOriginBody": {"placeholders": {"media": {"type": "String"}, "server": {"type": "String"}}}, + "mediaOriginHide": "Hide" } diff --git a/lib/l10n/gen/app_localizations.dart b/lib/l10n/gen/app_localizations.dart index 4cb81d4..6b6b684d 100644 --- a/lib/l10n/gen/app_localizations.dart +++ b/lib/l10n/gen/app_localizations.dart @@ -4465,6 +4465,72 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Marker saved'** String get markerSaved; + + /// No description provided for @pinLostTitle. + /// + /// In en, this message translates to: + /// **'The PIN is no longer on this device'** + String get pinLostTitle; + + /// No description provided for @pinLostBody. + /// + /// In en, this message translates to: + /// **'The app lock is on, but its PIN couldn\'t be read from the device\'s secure storage, for example after restoring a backup.'** + String get pinLostBody; + + /// No description provided for @pinLostBiometricHint. + /// + /// In en, this message translates to: + /// **'Unlock with Face ID or your fingerprint to choose a new PIN.'** + String get pinLostBiometricHint; + + /// No description provided for @pinLostResetHint. + /// + /// In en, this message translates to: + /// **'Or reset the app: everything StashTube stored on this device is removed.'** + String get pinLostResetHint; + + /// No description provided for @resetApp. + /// + /// In en, this message translates to: + /// **'Reset app'** + String get resetApp; + + /// No description provided for @resetAppTitle. + /// + /// In en, this message translates to: + /// **'Reset StashTube?'** + String get resetAppTitle; + + /// No description provided for @resetAppBody. + /// + /// In en, this message translates to: + /// **'All servers, settings, lists and cached images are removed from this device and the app lock is turned off. Nothing changes on your Stash servers.'** + String get resetAppBody; + + /// No description provided for @chooseNewPin. + /// + /// In en, this message translates to: + /// **'Choose a new PIN'** + String get chooseNewPin; + + /// No description provided for @mediaOriginTitle. + /// + /// In en, this message translates to: + /// **'Images and videos may not load'** + String get mediaOriginTitle; + + /// No description provided for @mediaOriginBody. + /// + /// In en, this message translates to: + /// **'Stash gives out media addresses on {media}, but StashTube connects to {server}. Your API key or login only goes to {server}, so those requests are sent without it. Behind a reverse proxy, pass on the Host header and set X-Forwarded-Proto.'** + String mediaOriginBody(String media, String server); + + /// No description provided for @mediaOriginHide. + /// + /// In en, this message translates to: + /// **'Hide'** + String get mediaOriginHide; } class _AppLocalizationsDelegate diff --git a/lib/l10n/gen/app_localizations_de.dart b/lib/l10n/gen/app_localizations_de.dart index f99349a..1cbe699 100644 --- a/lib/l10n/gen/app_localizations_de.dart +++ b/lib/l10n/gen/app_localizations_de.dart @@ -2704,4 +2704,43 @@ class AppLocalizationsDe extends AppLocalizations { @override String get markerSaved => 'Marker gespeichert'; + + @override + String get pinLostTitle => 'Die PIN ist nicht mehr auf diesem Gerät'; + + @override + String get pinLostBody => + 'Die App-Sperre ist an, aber ihre PIN ließ sich nicht aus dem sicheren Speicher des Geräts lesen, zum Beispiel nach dem Wiederherstellen eines Backups.'; + + @override + String get pinLostBiometricHint => + 'Entsperre mit Face ID oder Fingerabdruck, um eine neue PIN festzulegen.'; + + @override + String get pinLostResetHint => + 'Oder setze die App zurück: Alles, was StashTube auf diesem Gerät gespeichert hat, wird entfernt.'; + + @override + String get resetApp => 'App zurücksetzen'; + + @override + String get resetAppTitle => 'StashTube zurücksetzen?'; + + @override + String get resetAppBody => + 'Alle Server, Einstellungen, Listen und zwischengespeicherten Bilder werden von diesem Gerät entfernt und die App-Sperre wird ausgeschaltet. Auf deinen Stash-Servern ändert sich nichts.'; + + @override + String get chooseNewPin => 'Neue PIN festlegen'; + + @override + String get mediaOriginTitle => 'Bilder und Videos laden eventuell nicht'; + + @override + String mediaOriginBody(String media, String server) { + return 'Stash gibt Medienadressen auf $media heraus, StashTube verbindet sich aber mit $server. Dein API-Key oder Login geht nur an $server, diese Anfragen gehen deshalb ohne ihn raus. Hinter einem Reverse-Proxy: den Host-Header weitergeben und X-Forwarded-Proto setzen.'; + } + + @override + String get mediaOriginHide => 'Ausblenden'; } diff --git a/lib/l10n/gen/app_localizations_en.dart b/lib/l10n/gen/app_localizations_en.dart index 36d5fa7..c9c6da3 100644 --- a/lib/l10n/gen/app_localizations_en.dart +++ b/lib/l10n/gen/app_localizations_en.dart @@ -2693,4 +2693,43 @@ class AppLocalizationsEn extends AppLocalizations { @override String get markerSaved => 'Marker saved'; + + @override + String get pinLostTitle => 'The PIN is no longer on this device'; + + @override + String get pinLostBody => + 'The app lock is on, but its PIN couldn\'t be read from the device\'s secure storage, for example after restoring a backup.'; + + @override + String get pinLostBiometricHint => + 'Unlock with Face ID or your fingerprint to choose a new PIN.'; + + @override + String get pinLostResetHint => + 'Or reset the app: everything StashTube stored on this device is removed.'; + + @override + String get resetApp => 'Reset app'; + + @override + String get resetAppTitle => 'Reset StashTube?'; + + @override + String get resetAppBody => + 'All servers, settings, lists and cached images are removed from this device and the app lock is turned off. Nothing changes on your Stash servers.'; + + @override + String get chooseNewPin => 'Choose a new PIN'; + + @override + String get mediaOriginTitle => 'Images and videos may not load'; + + @override + String mediaOriginBody(String media, String server) { + return 'Stash gives out media addresses on $media, but StashTube connects to $server. Your API key or login only goes to $server, so those requests are sent without it. Behind a reverse proxy, pass on the Host header and set X-Forwarded-Proto.'; + } + + @override + String get mediaOriginHide => 'Hide'; } diff --git a/lib/widgets/connection_banner.dart b/lib/widgets/connection_banner.dart index 9ab1509..e1aaf45 100644 --- a/lib/widgets/connection_banner.dart +++ b/lib/widgets/connection_banner.dart @@ -4,6 +4,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../core/config/haptics.dart'; import '../core/config/server_config.dart'; import '../data/connection_status.dart'; +import '../data/media_origin_check.dart'; import '../data/providers.dart'; import '../data/repositories/stash_repository.dart'; import '../features/auth/server_switcher.dart'; @@ -15,6 +16,9 @@ import '../l10n/l10n.dart'; /// list. The banner takes the status bar's space, so [child] loses its top /// padding meanwhile. It goes away by itself once any call succeeds; then /// the lists reload, so the ones that failed meanwhile recover. +/// +/// While the server is reachable it shows [MediaOriginBanner] instead when +/// the server's media URLs point to another origin than the app connects to. class ConnectionBannerScope extends ConsumerStatefulWidget { const ConnectionBannerScope({super.key, required this.child}); @@ -67,6 +71,7 @@ class _ConnectionBannerScopeState extends ConsumerState w @override Widget build(BuildContext context) { ref.listen(connectionStatusProvider, _onStatus); + final mismatch = _bannerShown ? null : ref.watch(mediaOriginWarningProvider); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -75,8 +80,13 @@ class _ConnectionBannerScopeState extends ConsumerState w alignment: Alignment.topCenter, child: _bannerShown ? const ConnectionBanner() : const SizedBox.shrink(), ), + ?mismatch == null ? null : MediaOriginBanner(mismatch: mismatch), Expanded( - child: MediaQuery.removePadding(context: context, removeTop: _bannerShown, child: widget.child), + child: MediaQuery.removePadding( + context: context, + removeTop: _bannerShown || mismatch != null, + child: widget.child, + ), ), ], ); @@ -203,3 +213,69 @@ class _ConnectionBannerState extends ConsumerState { ); } } + +/// Warns that the server's media URLs point to another origin than the app +/// connects to ([MediaOriginMismatch]), with both addresses and how to fix +/// the proxy; hidden per server until the mismatch changes. +class MediaOriginBanner extends ConsumerWidget { + const MediaOriginBanner({super.key, required this.mismatch}); + + final MediaOriginMismatch mismatch; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final l = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return Semantics( + container: true, + child: Material( + color: scheme.surfaceContainerHigh, + child: SafeArea( + bottom: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 12, 8, 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 2, right: 16), + child: Icon(Icons.warning_amber_rounded, color: scheme.error), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l.mediaOriginTitle, style: theme.textTheme.titleSmall), + Text( + l.mediaOriginBody(mismatch.media, mismatch.server), + style: theme.textTheme.bodyMedium?.copyWith(color: scheme.onSurfaceVariant), + ), + ], + ), + ), + ], + ), + OverflowBar( + alignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () { + Haptics.light(); + ref.read(mediaOriginHintHiddenProvider.notifier).hide(mismatch); + }, + child: Text(l.mediaOriginHide), + ), + ], + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/preview_video.dart b/lib/widgets/preview_video.dart index 1ca71a6..bad3e4d 100644 --- a/lib/widgets/preview_video.dart +++ b/lib/widgets/preview_video.dart @@ -31,7 +31,7 @@ class _PreviewVideoState extends ConsumerState { _player ..setVolume(0) ..setPlaylistMode(PlaylistMode.single) - ..open(Media(widget.url, httpHeaders: ref.read(authHeadersProvider))).ignore(); + ..open(Media(widget.url, httpHeaders: ref.read(authHeadersProvider).forUrl(widget.url))).ignore(); _controller.waitUntilFirstFrameRendered.then((_) { if (mounted) setState(() => _shown = true); }); diff --git a/lib/widgets/stash_image.dart b/lib/widgets/stash_image.dart index 49db508..c2f2bee 100644 --- a/lib/widgets/stash_image.dart +++ b/lib/widgets/stash_image.dart @@ -4,6 +4,7 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../core/config/image_cache.dart'; import '../data/repositories/stash_session.dart'; /// Network image from the Stash server, sent with the API key header. @@ -55,7 +56,7 @@ class StashImage extends ConsumerWidget { final colors = Theme.of(context).colorScheme; final url = this.url; if (url == null) return standIn ?? _fallback(colors); - final headers = ref.watch(authHeadersProvider); + final auth = ref.watch(authHeadersProvider); return LayoutBuilder( builder: (context, constraints) { @@ -66,7 +67,8 @@ class StashImage extends ConsumerWidget { final preview = previewUrl; return CachedNetworkImage( imageUrl: url, - httpHeaders: headers, + httpHeaders: auth.forUrl(url), + cacheManager: stashImageCacheManager, width: width, height: height, fit: fit, @@ -78,7 +80,7 @@ class StashImage extends ConsumerWidget { standIn ?? (preview == null ? ShimmerBox(width: width, height: height) - : BlurredPreview(url: preview, headers: headers, fit: fit)), + : BlurredPreview(url: preview, headers: auth.forUrl(preview), fit: fit)), // Stash serves SVG placeholders for missing studio/performer images, // which CachedNetworkImage can't decode; show an icon instead. errorWidget: (_, _, _) => standIn ?? _fallback(colors), @@ -111,6 +113,7 @@ class BlurredPreview extends StatelessWidget { child: CachedNetworkImage( imageUrl: url, httpHeaders: headers, + cacheManager: stashImageCacheManager, fit: fit, fadeInDuration: Duration.zero, placeholder: (_, _) => const ShimmerBox(), diff --git a/test/core/origin_guard_test.dart b/test/core/origin_guard_test.dart new file mode 100644 index 0000000..99c5ede --- /dev/null +++ b/test/core/origin_guard_test.dart @@ -0,0 +1,96 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; + +void main() { + group('sameOrigin', () { + test('compares scheme, host and port, with default ports', () { + final server = Uri.parse('https://Stash.example'); + expect(sameOrigin(Uri.parse('https://stash.example:443/x'), server), isTrue); + expect(sameOrigin(Uri.parse('http://stash.example/x'), server), isFalse); + expect(sameOrigin(Uri.parse('https://stash.example:8443/x'), server), isFalse); + expect(sameOrigin(Uri.parse('https://evil.example/x'), server), isFalse); + expect(sameOrigin(Uri.parse('https://stash.example.evil/x'), server), isFalse); + }); + }); + + group('AuthHeaders', () { + final auth = AuthHeaders(Uri.parse('http://s:9999'), const {'ApiKey': 'k'}); + + test('only for URLs on the server', () { + expect(auth.forUrl('http://s:9999/scene/1/screenshot'), {'ApiKey': 'k'}); + expect(auth.forUrl('http://cdn.example/image.jpg'), isEmpty); + expect(auth.forUrl('http://s/image.jpg'), isEmpty, reason: 'another port'); + expect(auth.forUrl('not a url ::'), isEmpty); + expect(AuthHeaders.none.forUrl('http://s:9999/x'), isEmpty); + }); + + test("an EDL clip counts by the stream's URL inside", () { + String edl(String url) => 'edl://%${url.length}%$url,start=1.000,length=2.000'; + expect(auth.forUrl(edl('http://s:9999/scene/1/stream')), {'ApiKey': 'k'}); + expect(auth.forUrl(edl('http://evil/stream')), isEmpty); + expect(fetchedUri('edl://%99%http://s'), isNull); + }); + }); + + group('OriginGuardClient', () { + test('drops credentials of a request to another origin', () async { + final sent = >{}; + final client = OriginGuardClient( + MockClient((r) async { + sent[r.url] = r.headers; + return http.Response('', 200); + }), + origin: Uri.parse('http://s'), + ); + await client.get(Uri.parse('http://s/a'), headers: {'ApiKey': 'k', 'Cookie': 'session=1', 'X': 'y'}); + await client.get(Uri.parse('http://other/a'), headers: {'ApiKey': 'k', 'Cookie': 'session=1', 'X': 'y'}); + expect(sent[Uri.parse('http://s/a')], containsPair('ApiKey', 'k')); + expect(sent[Uri.parse('http://other/a')], {'X': 'y'}); + }); + + test('follows redirects, without credentials once they leave the origin', () async { + final sent = >{}; + final client = OriginGuardClient(MockClient((r) async { + sent[r.url.toString()] = r.headers; + return switch (r.url.path) { + '/start' => http.Response('', 302, headers: {'location': '/moved'}), + '/moved' => http.Response('', 301, headers: {'location': 'https://evil.example/steal'}), + _ => http.Response('done', 200), + }; + })); + final response = await client.get(Uri.parse('http://s/start'), headers: {'ApiKey': 'k'}); + expect(response.body, 'done'); + expect(sent['http://s/moved'], containsPair('ApiKey', 'k'), reason: 'same origin'); + expect(sent['https://evil.example/steal'], isNot(contains('ApiKey'))); + }); + + test('a 303 after a POST continues as GET; 307 keeps method and body', () async { + final seen = []; + final client = OriginGuardClient(MockClient((r) async { + seen.add('${r.method} ${r.url.path} ${r.body}'); + return switch (r.url.path) { + '/see-other' => http.Response('', 303, headers: {'location': '/result'}), + '/temporary' => http.Response('', 307, headers: {'location': '/result'}), + _ => http.Response('', 200), + }; + })); + await client.post(Uri.parse('http://s/see-other'), body: 'q'); + await client.post(Uri.parse('http://s/temporary'), body: 'q'); + expect(seen, ['POST /see-other q', 'GET /result ', 'POST /temporary q', 'POST /result q']); + }); + + test('stops after maxRedirects', () async { + final client = OriginGuardClient(MockClient((r) async => http.Response('', 302, headers: {'location': '/again'}))); + final request = http.Request('GET', Uri.parse('http://s/loop'))..maxRedirects = 3; + await expectLater(client.send(request), throwsA(isA())); + }); + + test('returns the redirect itself when the request asks not to follow', () async { + final client = OriginGuardClient(MockClient((r) async => http.Response('', 302, headers: {'location': '/x'}))); + final request = http.Request('POST', Uri.parse('http://s/login'))..followRedirects = false; + expect((await client.send(request)).statusCode, 302); + }); + }); +} diff --git a/test/core/server_profiles_test.dart b/test/core/server_profiles_test.dart index 7bfed70..413cb7a 100644 --- a/test/core/server_profiles_test.dart +++ b/test/core/server_profiles_test.dart @@ -43,6 +43,34 @@ void main() { expect(prefs.getString('server_profiles'), isNotNull); }); + test('a password in the URL goes to the secret store, not the preferences', () async { + final c = await containerWith({}); + await c.read(serverProfilesProvider.notifier).add(const ServerConfig(baseUrl: 'https://alice:s3cret@proxy.example')); + await pumpEventQueue(); + expect(prefs.getString('server_profiles'), isNot(contains('s3cret'))); + expect(prefs.getString('server_profiles'), contains('"url":"https://proxy.example"')); + expect(secrets.values.values, contains('alice:s3cret')); + + final config = restart().read(serverConfigProvider)!; + expect(config.baseUrl, 'https://alice:s3cret@proxy.example', reason: 'still used for requests after a restart'); + expect(config.displayUrl, 'https://proxy.example'); + }); + + test('a password in a URL stored by an older version moves out of the preferences', () async { + final c = await containerWith({ + 'server_profiles': '[{"id":"1","name":"Proxy","url":"https://alice:s3cret@proxy.example"}]', + 'active_server': '1', + }); + expect(c.read(serverConfigProvider)?.baseUrl, 'https://alice:s3cret@proxy.example'); + await pumpEventQueue(); + expect(prefs.getString('server_profiles'), isNot(contains('s3cret'))); + expect(secrets.read('url_auth:1'), 'alice:s3cret'); + expect(restart().read(serverConfigProvider)?.baseUrl, 'https://alice:s3cret@proxy.example'); + + await restart().read(serverProfilesProvider.notifier).remove('1'); + expect(secrets.read('url_auth:1'), isNull, reason: 'removed with the server'); + }); + test('tells main() whether the demo is saved', () async { final c = await containerWith({}); expect(ServerProfilesNotifier.hasDemo(prefs), isFalse); diff --git a/test/data/media_origin_check_test.dart b/test/data/media_origin_check_test.dart new file mode 100644 index 0000000..be5512c --- /dev/null +++ b/test/data/media_origin_check_test.dart @@ -0,0 +1,110 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:stash_app_mobile/core/config/server_config.dart'; +import 'package:stash_app_mobile/data/media_origin_check.dart'; +import 'package:stash_app_mobile/data/models/list_queries.dart'; +import 'package:stash_app_mobile/data/models/page_result.dart'; +import 'package:stash_app_mobile/data/models/scene.dart'; +import 'package:stash_app_mobile/data/repositories/stash_repository.dart'; +import 'package:stash_app_mobile/widgets/connection_banner.dart'; + +class _OneScene implements StashRepository { + _OneScene(this.screenshotUrl); + + final String screenshotUrl; + int calls = 0; + + @override + Future> findScenes(SceneQuery query, {int page = 1, int perPage = 24}) async { + calls++; + return PageResult(items: [Scene(id: '1', title: 'A', screenshotUrl: screenshotUrl)], totalCount: 1); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} + +void main() { + test('compares the media URL with the server address by origin', () { + expect(mediaOriginMismatch('https://stash.example', 'https://stash.example/scene/1/screenshot'), isNull); + expect(mediaOriginMismatch('https://stash.example', 'https://stash.example:443/x'), isNull); + expect( + mediaOriginMismatch('https://stash.example', 'http://stash.example/scene/1/screenshot'), + const MediaOriginMismatch(server: 'https://stash.example', media: 'http://stash.example'), + reason: 'X-Forwarded-Proto missing', + ); + expect( + mediaOriginMismatch('https://stash.example', 'http://localhost:9999/scene/1/screenshot'), + const MediaOriginMismatch(server: 'https://stash.example', media: 'http://localhost:9999'), + reason: 'Host header not passed on', + ); + expect(mediaOriginMismatch('https://stash.example', '/relative'), isNull); + expect(mediaOriginMismatch('https://stash.example', null), isNull); + }); + + group('check', () { + late SharedPreferences prefs; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + prefs = await SharedPreferences.getInstance(); + }); + + ProviderContainer container(ServerConfig config, StashRepository repo) { + final c = ProviderContainer(overrides: [ + sharedPreferencesProvider.overrideWithValue(prefs), + activeServerIdProvider.overrideWithValue('a'), + serverConfigProvider.overrideWithValue(config), + stashRepositoryProvider.overrideWithValue(repo), + ]); + addTearDown(c.dispose); + return c; + } + + test('warns when a server with credentials hands out media elsewhere', () async { + final c = container( + const ServerConfig(baseUrl: 'https://stash.example', apiKey: 'k'), + _OneScene('http://stash.example/scene/1/screenshot'), + ); + expect(await c.read(mediaOriginMismatchProvider.future), isNotNull); + expect(c.read(mediaOriginWarningProvider)?.media, 'http://stash.example'); + + await c.read(mediaOriginHintHiddenProvider.notifier).hide(c.read(mediaOriginWarningProvider)!); + expect(c.read(mediaOriginWarningProvider), isNull); + expect(prefs.getString('media_origin_hint_hidden:a'), 'http://stash.example'); + }); + + test('no check without credentials: nothing to lose', () async { + final repo = _OneScene('http://elsewhere/scene/1/screenshot'); + final c = container(const ServerConfig(baseUrl: 'https://stash.example'), repo); + expect(await c.read(mediaOriginMismatchProvider.future), isNull); + expect(repo.calls, 0); + }); + }); + + testWidgets('the banner names both addresses and hides for good', (tester) async { + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + await tester.pumpWidget(ProviderScope( + overrides: [ + sharedPreferencesProvider.overrideWithValue(prefs), + activeServerIdProvider.overrideWithValue('a'), + mediaOriginMismatchProvider.overrideWith( + (ref) async => const MediaOriginMismatch(server: 'https://stash.example', media: 'http://stash.example'), + ), + ], + child: const MaterialApp(home: ConnectionBannerScope(child: Text('content'))), + )); + await tester.pumpAndSettle(); + expect(find.text('Images and videos may not load'), findsOneWidget); + expect(find.textContaining('http://stash.example, but StashTube connects to https://stash.example'), findsOneWidget); + + await tester.tap(find.text('Hide')); + await tester.pumpAndSettle(); + expect(find.text('Images and videos may not load'), findsNothing); + expect(find.text('content'), findsOneWidget); + expect(prefs.getString('media_origin_hint_hidden:a'), 'http://stash.example'); + }); +} diff --git a/test/data/repository_graphql_test.dart b/test/data/repository_graphql_test.dart index a610406..125bd3e 100644 --- a/test/data/repository_graphql_test.dart +++ b/test/data/repository_graphql_test.dart @@ -9,16 +9,18 @@ import 'package:stash_app_mobile/data/repositories/stash_repository.dart'; import '../fixtures.dart'; /// The repository through a real GraphQL client with the app's policies -/// (network only, normalized cache): responses go through the cache, which -/// resolves fragments by `__typename` (1.8). +/// ([stashGraphQLPolicies]: no cache), parsing the responses into the +/// generated types (1.8). void main() { late List sent; + late GraphQLCache cache; StashRepository repo(Map> dataByOperation) { sent = []; + cache = GraphQLCache(); return StashRepository(GraphQLClient( - cache: GraphQLCache(), - defaultPolicies: DefaultPolicies(query: Policies(fetch: FetchPolicy.networkOnly)), + cache: cache, + defaultPolicies: stashGraphQLPolicies, link: Link.function((request, [forward]) { sent.add(request); final data = dataByOperation[request.operation.operationName]; @@ -30,7 +32,7 @@ void main() { Map page(String field, String resultType, String listField, List> items) => {field: {'__typename': resultType, 'count': items.length, listField: items}}; - test('lists and details resolve their fragments through the cache', () async { + test('lists and details parse their fragments, and nothing is cached', () async { final r = repo({ 'FindScenes': page('findScenes', 'FindScenesResultType', 'scenes', [ sceneJson({ @@ -88,6 +90,7 @@ void main() { expect([details.streams.single.label, details.markers.single.title, details.files.single.height], ['Direct stream', 'Intro', 1080]); expect((await r.libraryStats()).sceneCount, 12); + expect(cache.store.toMap(), isEmpty, reason: 'responses must not pile up in the normalized cache'); }); test('markers come with their tag and scene', () async { diff --git a/test/data/scrub_thumbnails_test.dart b/test/data/scrub_thumbnails_test.dart index 4c63e09..4775cc3 100644 --- a/test/data/scrub_thumbnails_test.dart +++ b/test/data/scrub_thumbnails_test.dart @@ -2,6 +2,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/data/models/scene_details.dart'; import 'package:stash_app_mobile/data/models/scrub_thumbnails.dart'; import 'package:stash_app_mobile/data/repositories/stash_repository.dart'; @@ -64,7 +65,7 @@ void main() { group('StashRepository.scrubThumbnails', () { StashRepository repo(MockClient client) => StashRepository( GraphQLClient(cache: GraphQLCache(), link: HttpLink('http://s/graphql')), - authHeaders: const {'ApiKey': 'secret'}, + auth: AuthHeaders(Uri.parse('http://s'), const {'ApiKey': 'secret'}), httpClient: client, ); @@ -88,4 +89,34 @@ void main() { expect(await offline.scrubThumbnails(const SceneDetails(vttUrl: 'http://s/vtt')), isNull); }); }); + + group('StashRepository.fileExists', () { + test('asks for one byte and never downloads the body', () async { + var bodyListened = false; + Map? sent; + final repo = StashRepository( + GraphQLClient(cache: GraphQLCache(), link: HttpLink('http://s/graphql')), + auth: AuthHeaders(Uri.parse('http://s'), const {'ApiKey': 'secret'}), + httpClient: MockClient.streaming((request, _) async { + sent = request.headers; + // A server that ignores the range and sends an endless body. + final body = Stream>.periodic(const Duration(milliseconds: 1), (_) => List.filled(1024, 0)); + return http.StreamedResponse( + body.map((chunk) { + bodyListened = true; + return chunk; + }), + 200, + ); + }), + ); + expect(await repo.fileExists('http://s/scene/1/preview'), isTrue); + expect(sent?['Range'], 'bytes=0-0'); + expect(sent?['ApiKey'], 'secret'); + await Future.delayed(const Duration(milliseconds: 20)); + expect(bodyListened, isFalse, reason: 'cancelled before the first chunk'); + expect(await repo.fileExists('http://elsewhere/preview'), isTrue); + expect(sent?['ApiKey'], isNull, reason: 'no API key for another origin'); + }); + }); } diff --git a/test/data/stash_session_test.dart b/test/data/stash_session_test.dart index 3d61feb..9644e2a 100644 --- a/test/data/stash_session_test.dart +++ b/test/data/stash_session_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -60,6 +61,16 @@ void main() { ); }); + test('a login that never answers times out as unreachable', () async { + final hanging = MockClient((_) => Completer().future); + await expectLater( + stashLogin(hanging, _login, timeout: const Duration(milliseconds: 10)), + throwsA(isA() + .having((e) => e.isNetworkError, 'isNetworkError', isTrue) + .having((e) => e.kind, 'kind', StashErrorKind.unreachable)), + ); + }); + test('a login is only used without an API key', () { expect(_login.usesSession, isTrue); expect(const ServerConfig(baseUrl: 'http://s', apiKey: 'k', username: 'me', password: 'pw').usesSession, isFalse); @@ -83,6 +94,7 @@ void main() { StashSessionClient client() => StashSessionClient( stash.client, + origin: Uri.parse('http://s'), ensure: () => container.read(stashSessionProvider.notifier).ensure(), renew: () => container.read(stashSessionProvider.notifier).renew(), ); @@ -91,7 +103,24 @@ void main() { final response = await client().post(Uri.parse('http://s/graphql'), body: '{"query":"q"}'); expect(response.statusCode, 200); expect(stash.graphqlCookies, ['session=s1']); - expect(container.read(authHeadersProvider), {'Cookie': 'session=s1'}, reason: 'for images and streams'); + expect(container.read(authHeadersProvider).forUrl('http://s/image'), {'Cookie': 'session=s1'}, reason: 'for images and streams'); + expect(container.read(authHeadersProvider).forUrl('http://elsewhere/image'), isEmpty); + }); + + test('requests to another origin get no cookie and sign nobody in', () async { + final sent = >[]; + final foreign = StashSessionClient( + MockClient((r) async { + sent.add(r.headers); + return http.Response('', 200); + }), + origin: Uri.parse('http://s'), + ensure: () => container.read(stashSessionProvider.notifier).ensure(), + renew: () => container.read(stashSessionProvider.notifier).renew(), + ); + await foreign.get(Uri.parse('http://cdn.example/image.jpg')); + expect(sent.single, isNot(contains('Cookie'))); + expect(stash.logins, 0); }); test('signs in again when the server rejects the cookie, repeating the request', () async { diff --git a/test/features/app_lock_test.dart b/test/features/app_lock_test.dart index a07bee3..8bc72bf 100644 --- a/test/features/app_lock_test.dart +++ b/test/features/app_lock_test.dart @@ -7,6 +7,7 @@ import 'package:stash_app_mobile/core/config/secret_store.dart'; import 'package:stash_app_mobile/core/config/server_config.dart'; import 'package:stash_app_mobile/features/security/app_lock.dart'; import 'package:stash_app_mobile/features/security/app_lock_gate.dart'; +import 'package:stash_app_mobile/features/security/pin_hash.dart'; class FakeBiometrics implements BiometricAuth { FakeBiometrics({this.succeed = true}); @@ -47,10 +48,28 @@ void main() { return c; } - test('PIN hashes depend on the salt and never equal the PIN', () { - expect(hashPin('1234', 'a'), hashPin('1234', 'a')); - expect(hashPin('1234', 'a'), isNot(hashPin('1234', 'b'))); - expect(hashPin('1234', 'a'), isNot(contains('1234'))); + test('legacy PIN hashes depend on the salt and never equal the PIN', () { + expect(legacyHashPin('1234', 'a'), legacyHashPin('1234', 'a')); + expect(legacyHashPin('1234', 'a'), isNot(legacyHashPin('1234', 'b'))); + expect(legacyHashPin('1234', 'a'), isNot(contains('1234'))); + }); + + test('PBKDF2-HMAC-SHA256 matches the RFC 7914 test vector', () { + String hex(List b) => b.map((x) => x.toRadixString(16).padLeft(2, '0')).join(); + expect(hex(pbkdf2Sha256('passwd'.codeUnits, 'salt'.codeUnits, 1)), + '55ac046e56e3089fec1691c22544b605f94185216dde0465e68b9d57c20dacbc'); + }); + + test('a stored PIN round-trips and only matches its PIN', () async { + final stored = await StoredPin.create('2580'); + expect(stored.isLegacy, isFalse); + final parsed = StoredPin.parse(stored.encode())!; + expect(parsed.rounds, StoredPin.iterations); + expect(await parsed.matches('2580'), isTrue); + expect(await parsed.matches('2581'), isFalse); + expect(StoredPin.parse('pbkdf2-sha256\$x\$s\$h'), isNull); + expect(StoredPin.parse('garbage'), isNull); + expect(StoredPin.parse('salt:${legacyHashPin('1', 'salt')}')!.isLegacy, isTrue); }); test('enable stores only a salted hash; verify and disable', () async { @@ -59,36 +78,78 @@ void main() { await settings.enable('2580'); expect(c.read(appLockSettingsProvider).enabled, isTrue); expect(prefs.getKeys().map(prefs.get), isNot(contains('2580'))); - expect(settings.verify('2580'), isTrue); - expect(settings.verify('0000'), isFalse); + expect(await settings.verify('2580'), isTrue); + expect(await settings.verify('0000'), isFalse); await settings.disable(); expect(c.read(appLockSettingsProvider).enabled, isFalse); - expect(settings.verify('2580'), isFalse); + expect(await settings.verify('2580'), isFalse); }); - test('the PIN hash is kept in the secret store, as one value', () async { + test('the PIN hash is kept in the secret store, as one PBKDF2 value', () async { final c = container(); await c.read(appLockSettingsProvider.notifier).enable('2580'); - expect(secrets.read('lock_pin'), matches(RegExp(r'^[^:]+:[0-9a-f]{64}$'))); + expect(secrets.read('lock_pin'), matches(RegExp(r'^pbkdf2-sha256\$\d+\$[^$]+\$[^$]+$'))); expect(prefs.getKeys().where((k) => k.startsWith('lock_pin_') && k != 'lock_pin_length'), isEmpty); - expect(container().read(appLockSettingsProvider.notifier).verify('2580'), isTrue, reason: 'after a restart'); + expect(await container().read(appLockSettingsProvider.notifier).verify('2580'), isTrue, reason: 'after a restart'); }); - test('a PIN of an older version moves out of SharedPreferences', () async { + test('a PIN of an older version moves out of SharedPreferences and is upgraded', () async { SharedPreferences.setMockInitialValues({ 'lock_enabled': true, 'lock_pin_salt': 'salt', - 'lock_pin_hash': hashPin('1234', 'salt'), + 'lock_pin_hash': legacyHashPin('1234', 'salt'), }); prefs = await SharedPreferences.getInstance(); final c = container(); expect(c.read(appLockSettingsProvider).enabled, isTrue); - expect(c.read(appLockSettingsProvider.notifier).verify('1234'), isTrue); await pumpEventQueue(); expect(prefs.getString('lock_pin_hash'), isNull); - expect(secrets.read('lock_pin'), 'salt:${hashPin('1234', 'salt')}'); - expect(container().read(appLockSettingsProvider.notifier).verify('1234'), isTrue); + expect(secrets.read('lock_pin'), 'salt:${legacyHashPin('1234', 'salt')}', reason: 'moved as it was'); + expect(await c.read(appLockSettingsProvider.notifier).verify('1234'), isTrue); + expect(secrets.read('lock_pin'), startsWith('pbkdf2-sha256\$'), reason: 'upgraded after the right PIN'); + expect(await container().read(appLockSettingsProvider.notifier).verify('1234'), isTrue); + }); + + test('a legacy SHA-256 PIN stays until the right PIN, then becomes PBKDF2', () async { + secrets.values['lock_pin'] = 'salt:${legacyHashPin('1234', 'salt')}'; + await prefs.setBool('lock_enabled', true); + final settings = container().read(appLockSettingsProvider.notifier); + expect(await settings.verify('0000'), isFalse); + expect(secrets.read('lock_pin'), startsWith('salt:'), reason: 'a wrong PIN changes nothing'); + expect(await settings.verify('1234'), isTrue); + expect(StoredPin.parse(secrets.read('lock_pin'))!.isLegacy, isFalse); + expect(await container().read(appLockSettingsProvider.notifier).verify('1234'), isTrue); + expect(await container().read(appLockSettingsProvider.notifier).verify('0000'), isFalse); + }); + + test('a lock whose PIN is lost stays on and locked', () async { + await prefs.setBool('lock_enabled', true); + final c = container(); + final settings = c.read(appLockSettingsProvider); + expect(settings.enabled, isTrue, reason: 'an unreadable secure storage must not open the app'); + expect(settings.pinLost, isTrue); + expect(c.read(appLockedProvider), isTrue); + expect(await c.read(appLockSettingsProvider.notifier).verify('1234'), isFalse); + + await c.read(appLockSettingsProvider.notifier).enable('4321'); + expect(c.read(appLockSettingsProvider).pinLost, isFalse); + expect(await c.read(appLockSettingsProvider.notifier).verify('4321'), isTrue); + }); + + test('resetting the app removes everything and turns the lock off', () async { + await prefs.setBool('lock_enabled', true); + await prefs.setString('server_profiles', '[{"id":"1","name":"s","url":"http://s"}]'); + await prefs.setString('active_server', '1'); + secrets.values['api_key:1'] = 'k'; + final c = container(); + expect(c.read(serverProfilesProvider).profiles, hasLength(1)); + await c.read(appLockSettingsProvider.notifier).resetApp(); + expect(prefs.getKeys(), isEmpty); + expect(secrets.values, isEmpty); + expect(c.read(appLockSettingsProvider).enabled, isFalse); + expect(c.read(appLockedProvider), isFalse); + expect(c.read(serverProfilesProvider).profiles, isEmpty); }); test('wrong PINs block the PIN for a growing time, across restarts', () async { @@ -99,12 +160,12 @@ void main() { final settings = c.read(appLockSettingsProvider.notifier); for (var i = 0; i < PinThrottle.freeAttempts - 1; i++) { - expect(settings.verify('0000'), isFalse); + expect(await settings.verify('0000'), isFalse); } expect(throttle.remaining(), Duration.zero, reason: 'a few mistakes are free'); - expect(settings.verify('0000'), isFalse); + expect(await settings.verify('0000'), isFalse); expect(throttle.remaining(), const Duration(seconds: 30)); - expect(settings.verify('1234'), isFalse, reason: 'even the right PIN has to wait'); + expect(await settings.verify('1234'), isFalse, reason: 'even the right PIN has to wait'); // Restarting the app doesn't help. c = container(); @@ -113,7 +174,7 @@ void main() { now = now.add(const Duration(seconds: 31)); expect(throttle.remaining(), Duration.zero); - expect(c.read(appLockSettingsProvider.notifier).verify('0000'), isFalse); + expect(await c.read(appLockSettingsProvider.notifier).verify('0000'), isFalse); expect(throttle.remaining(), const Duration(minutes: 1), reason: 'the next mistake waits longer'); // Setting the clock back doesn't stretch the wait beyond the delay. @@ -121,7 +182,7 @@ void main() { expect(throttle.remaining(), const Duration(minutes: 1)); now = now.add(const Duration(days: 2)); - expect(c.read(appLockSettingsProvider.notifier).verify('1234'), isTrue); + expect(await c.read(appLockSettingsProvider.notifier).verify('1234'), isTrue); expect(c.read(pinThrottleProvider).failures, 0, reason: 'a successful unlock starts over'); expect(prefs.getInt('lock_failed_attempts'), isNull); }); @@ -256,6 +317,47 @@ void main() { expect(c.read(appLockedProvider), isFalse); }); + testWidgets('a lost PIN keeps the app locked; resetting it starts over', (tester) async { + await prefs.setBool('lock_enabled', true); + await prefs.setString('server_profiles', '[{"id":"1","name":"s","url":"http://s"}]'); + final c = await pumpGate(tester); + expect(c.read(appLockedProvider), isTrue); + expect(find.text('The PIN is no longer on this device'), findsOneWidget); + expect(find.descendant(of: find.byType(LockScreen), matching: find.text('1')), findsNothing, + reason: 'no PIN pad: there is no PIN to check'); + + await tester.tap(find.text('Reset app')); + await tester.pumpAndSettle(); + expect(find.text('Reset StashTube?'), findsOneWidget); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(find.text('The PIN is no longer on this device'), findsOneWidget); + + await tester.tap(find.text('Reset app')); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(FilledButton, 'Reset app')); + await tester.pumpAndSettle(); + expect(c.read(appLockedProvider), isFalse); + expect(find.byType(LockScreen), findsNothing); + expect(prefs.getKeys(), isEmpty); + expect(c.read(serverProfilesProvider).profiles, isEmpty); + }); + + testWidgets('a lost PIN with biometrics: unlocking asks for a new PIN first', (tester) async { + await prefs.setBool('lock_enabled', true); + await prefs.setBool('lock_biometrics', true); + final c = await pumpGate(tester); + expect(biometrics.calls, 1); + expect(c.read(appLockedProvider), isTrue, reason: 'not open without a PIN for next time'); + expect(find.text('Choose a new PIN'), findsOneWidget); + + await enterPin(tester, '2468'); + await enterPin(tester, '2468'); + expect(c.read(appLockedProvider), isFalse); + expect(c.read(appLockSettingsProvider).pinLost, isFalse); + expect(await tester.runAsync(() => c.read(appLockSettingsProvider.notifier).verify('2468')), isTrue); + }); + testWidgets('app switcher cover appears while inactive when enabled', (tester) async { await tester.runAsync(() => container().read(appLockSettingsProvider.notifier).setHideInSwitcher(true)); await pumpGate(tester); diff --git a/test/features/cast_test.dart b/test/features/cast_test.dart index eaedbc3..9f11210 100644 --- a/test/features/cast_test.dart +++ b/test/features/cast_test.dart @@ -88,10 +88,20 @@ const _details = SceneDetails(streams: [ void main() { group('cast media', () { test('adds the API key as URL parameter, keeping existing ones', () { - expect(withApiKey('http://s/stream.mp4?resolution=HD', 'k'), 'http://s/stream.mp4?resolution=HD&apikey=k'); + const server = ServerConfig(baseUrl: 'http://s', apiKey: 'k'); + expect(withApiKey('http://s/stream.mp4?resolution=HD', server), 'http://s/stream.mp4?resolution=HD&apikey=k'); + expect(withApiKey('http://s/stream', const ServerConfig(baseUrl: 'http://s')), 'http://s/stream'); expect(withApiKey('http://s/stream', null), 'http://s/stream'); }); + test('never puts the API key into a URL on another origin', () { + const server = ServerConfig(baseUrl: 'https://s', apiKey: 'k'); + expect(withApiKey('https://elsewhere/stream', server), 'https://elsewhere/stream'); + expect(withApiKey('http://s/stream', server), 'http://s/stream', reason: 'another scheme'); + expect(withApiKey('https://s:8443/stream', server), 'https://s:8443/stream', reason: 'another port'); + expect(withApiKey('https://s:443/stream', server), endsWith('/stream?apikey=k'), reason: 'the default port'); + }); + test('prefers a castable original file, then HLS, then MP4', () { const scene = Scene(id: '1', title: 'A', streamUrl: 'http://s/scene/1/stream'); expect(pickCastStream(scene, _details).contentType, 'application/x-mpegURL', reason: 'mkv is not castable'); @@ -124,7 +134,7 @@ void main() { final media = castMediaFor( const Scene(id: '1', title: 'Sunset', screenshotUrl: 'http://s/shot', streamUrl: 'http://s/stream'), _details, - apiKey: 'k', + server: const ServerConfig(baseUrl: 'http://s', apiKey: 'k'), start: const Duration(seconds: 42), ); expect(media.title, 'Sunset'); diff --git a/test/features/pip_return_test.dart b/test/features/pip_return_test.dart index f506107..5682047 100644 --- a/test/features/pip_return_test.dart +++ b/test/features/pip_return_test.dart @@ -7,6 +7,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:media_kit/media_kit.dart'; import 'package:media_kit_video/media_kit_video.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/core/config/secret_store.dart'; import 'package:stash_app_mobile/core/config/server_config.dart' show sharedPreferencesProvider; import 'package:stash_app_mobile/data/models/scene.dart'; @@ -78,7 +79,7 @@ void main() { ...testServer, sharedPreferencesProvider.overrideWithValue(prefs), secretStoreProvider.overrideWithValue(MemorySecretStore()), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), pipServiceProvider.overrideWithValue(pip), heldOrientationProvider.overrideWithValue(turns), playerProvider.overrideWithValue(player), diff --git a/test/features/pip_test.dart b/test/features/pip_test.dart index 7626e05..fe72bcf 100644 --- a/test/features/pip_test.dart +++ b/test/features/pip_test.dart @@ -6,6 +6,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:media_kit/media_kit.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/core/config/server_config.dart'; import 'package:stash_app_mobile/data/models/scene.dart'; import 'package:stash_app_mobile/data/models/scene_details.dart'; @@ -149,7 +150,7 @@ void main() { final c = ProviderContainer(overrides: [ sharedPreferencesProvider.overrideWithValue(prefs), serverConfigProvider.overrideWithValue(const ServerConfig(baseUrl: 'http://s', apiKey: 'k')), - authHeadersProvider.overrideWithValue(const {'ApiKey': 'k'}), + authHeadersProvider.overrideWithValue(AuthHeaders(Uri.parse('http://s'), const {'ApiKey': 'k'})), pipServiceProvider.overrideWithValue(pip), playerProvider.overrideWithValue(player), playerPlayingProvider.overrideWith((ref) => Stream.value(playing)), diff --git a/test/features/player/chapters_channel_test.dart b/test/features/player/chapters_channel_test.dart index fe27d07..2827520 100644 --- a/test/features/player/chapters_channel_test.dart +++ b/test/features/player/chapters_channel_test.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/core/config/server_config.dart'; import 'package:stash_app_mobile/data/models/list_queries.dart'; import 'package:stash_app_mobile/data/models/page_result.dart'; @@ -96,7 +97,7 @@ void main() { ...testServer, sharedPreferencesProvider.overrideWithValue(prefs), playerProvider.overrideWithValue(player), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), sceneDetailsProvider('s1').overrideWith((ref) async => details), scrubThumbnailsProvider('s1').overrideWith((ref) async => thumbs), stashRepositoryProvider.overrideWithValue(repository), diff --git a/test/features/player/gesture_tips_test.dart b/test/features/player/gesture_tips_test.dart index 86a09cb..591192f 100644 --- a/test/features/player/gesture_tips_test.dart +++ b/test/features/player/gesture_tips_test.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/core/config/server_config.dart'; import 'package:stash_app_mobile/data/models/scene.dart'; import 'package:stash_app_mobile/data/providers.dart'; @@ -36,7 +37,7 @@ void main() { sharedPreferencesProvider.overrideWithValue(prefs), playerProvider.overrideWithValue(FakePlayer(position: const Duration(seconds: 30))), scrubThumbnailsProvider('1').overrideWith((ref) async => null), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), playbackErrorProvider.overrideWith(() => _Errors(error)), ], child: const MaterialApp( diff --git a/test/features/player/marker_ranges_test.dart b/test/features/player/marker_ranges_test.dart index 60d130c..1852b8e 100644 --- a/test/features/player/marker_ranges_test.dart +++ b/test/features/player/marker_ranges_test.dart @@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/core/config/server_config.dart'; import 'package:stash_app_mobile/data/models/list_queries.dart'; import 'package:stash_app_mobile/data/models/marker.dart'; @@ -191,7 +192,7 @@ void main() { overrides: [ playerProvider.overrideWithValue(FakePlayer()), scrubThumbnailsProvider('1').overrideWith((ref) async => null), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), sceneDetailsProvider('1').overrideWith((ref) async => details), ], child: const MaterialApp( @@ -237,7 +238,7 @@ void main() { await tester.pumpWidget(ProviderScope( overrides: [ playerProvider.overrideWithValue(player), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), ...testServer, ], child: const MaterialApp(home: Scaffold(body: ChapterList(sceneId: '1', details: details))), @@ -345,7 +346,7 @@ void main() { overrides: [ ...testServer, sharedPreferencesProvider.overrideWithValue(prefs), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), stashRepositoryProvider.overrideWithValue(repo), sceneDetailsProvider('s1').overrideWith((ref) async => const SceneDetails(markerRanges: true)), playerProvider.overrideWithValue(FakePlayer(position: const Duration(seconds: 30))), @@ -417,7 +418,7 @@ void main() { testWidgets('a ranged marker tile shows its range and length', (tester) async { await tester.pumpWidget(ProviderScope( - overrides: [...testServer, authHeadersProvider.overrideWithValue(const {})], + overrides: [...testServer, authHeadersProvider.overrideWithValue(AuthHeaders.none)], child: const MaterialApp( home: Scaffold( body: SizedBox( diff --git a/test/features/player/player_details_test.dart b/test/features/player/player_details_test.dart index b4b95aa..cb41662 100644 --- a/test/features/player/player_details_test.dart +++ b/test/features/player/player_details_test.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/core/config/server_config.dart'; import 'package:stash_app_mobile/data/models/list_queries.dart'; import 'package:stash_app_mobile/data/models/page_result.dart'; @@ -80,7 +81,7 @@ void main() { ...testServer, sharedPreferencesProvider.overrideWithValue(prefs), playerProvider.overrideWithValue(FakePlayer()), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), sceneDetailsProvider('s1').overrideWith((ref) async => _details), stashRepositoryProvider.overrideWithValue(_LoadingRepository()), ]); @@ -138,7 +139,7 @@ void main() { ...testServer, sharedPreferencesProvider.overrideWithValue(prefs), playerProvider.overrideWithValue(FakePlayer()), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), sceneDetailsProvider('s1').overrideWith((ref) async => _details), stashRepositoryProvider.overrideWithValue(_LoadingRepository()), ]); @@ -327,7 +328,7 @@ void main() { ...testServer, sharedPreferencesProvider.overrideWithValue(prefs), playerProvider.overrideWithValue(FakePlayer()), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), sceneDetailsProvider('s1').overrideWith((ref) async => _details), stashRepositoryProvider.overrideWithValue(_LoadingRepository()), ]); diff --git a/test/features/player/queue_controls_test.dart b/test/features/player/queue_controls_test.dart index c58b04c..3d08b44 100644 --- a/test/features/player/queue_controls_test.dart +++ b/test/features/player/queue_controls_test.dart @@ -2,6 +2,7 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/data/models/scene.dart'; import 'package:stash_app_mobile/data/providers.dart'; import 'package:stash_app_mobile/data/repositories/stash_session.dart'; @@ -50,7 +51,7 @@ void main() { ...testServer, playerProvider.overrideWithValue(FakePlayer(position: const Duration(seconds: 30))), scrubThumbnailsProvider('1').overrideWith((ref) async => null), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), nowPlayingProvider.overrideWith(() => nowPlaying), ], child: MaterialApp( diff --git a/test/features/player/seek_sequence_test.dart b/test/features/player/seek_sequence_test.dart index 00c251e..d8c3229 100644 --- a/test/features/player/seek_sequence_test.dart +++ b/test/features/player/seek_sequence_test.dart @@ -2,6 +2,7 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/data/models/scene.dart'; import 'package:stash_app_mobile/data/models/scene_details.dart'; import 'package:stash_app_mobile/data/providers.dart'; @@ -75,7 +76,7 @@ void main() { ...testServer, playerProvider.overrideWithValue(player), scrubThumbnailsProvider('1').overrideWith((ref) async => null), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), sceneDetailsProvider('1').overrideWith((ref) async => const SceneDetails(streams: [])), castServiceProvider.overrideWithValue(cast), seekSettingsProvider.overrideWith(() => _Seek(seek)), diff --git a/test/features/player/touch_lock_test.dart b/test/features/player/touch_lock_test.dart index 929f6c4..3ec2656 100644 --- a/test/features/player/touch_lock_test.dart +++ b/test/features/player/touch_lock_test.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/semantics.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/data/models/scene.dart'; import 'package:stash_app_mobile/data/providers.dart'; import 'package:stash_app_mobile/data/repositories/stash_session.dart'; @@ -26,7 +27,7 @@ void main() { ...testServer, playerProvider.overrideWithValue(player), scrubThumbnailsProvider('1').overrideWith((ref) async => null), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), ], child: MaterialApp( home: Scaffold( diff --git a/test/features/preview_seek_bar_test.dart b/test/features/preview_seek_bar_test.dart index 1780fb3..c0105af 100644 --- a/test/features/preview_seek_bar_test.dart +++ b/test/features/preview_seek_bar_test.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/data/models/scene_details.dart'; import 'package:stash_app_mobile/data/providers.dart'; import 'package:stash_app_mobile/data/repositories/stash_session.dart'; @@ -23,7 +24,7 @@ void main() { thumbnailLoads++; return null; }), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), sceneDetailsProvider('1').overrideWith( (ref) async => const SceneDetails(markers: [SceneMarker(id: 'm', title: 'Intro', seconds: 30)]), ), diff --git a/test/features/shorts_markers_ui_test.dart b/test/features/shorts_markers_ui_test.dart index 1348299..6f421f4 100644 --- a/test/features/shorts_markers_ui_test.dart +++ b/test/features/shorts_markers_ui_test.dart @@ -3,6 +3,7 @@ import 'package:flutter/semantics.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/core/config/server_config.dart'; import 'package:stash_app_mobile/data/models/list_queries.dart'; import 'package:stash_app_mobile/data/models/marker.dart'; @@ -78,7 +79,7 @@ void main() { overrides: [ playerProvider.overrideWithValue(player), scrubThumbnailsProvider('1').overrideWith((ref) async => null), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), sceneDetailsProvider('1').overrideWith((ref) async => details), ], child: MaterialApp( @@ -166,7 +167,7 @@ void main() { overrides: [ playerProvider.overrideWithValue(player), scrubThumbnailsProvider('1').overrideWith((ref) async => null), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), sceneDetailsProvider('1').overrideWith((ref) async => details), ], child: const MaterialApp( @@ -197,7 +198,7 @@ void main() { group('short tile', () { Future pumpTile(WidgetTester tester, Short short) => tester.pumpWidget(ProviderScope( - overrides: [...testServer, authHeadersProvider.overrideWithValue(const {})], + overrides: [...testServer, authHeadersProvider.overrideWithValue(AuthHeaders.none)], child: MaterialApp( home: Scaffold( body: Center(child: SizedBox(width: 135, height: 240, child: ShortTile(short: short, onTap: () {}))), diff --git a/test/features/video_controls_test.dart b/test/features/video_controls_test.dart index 77fdc03..505b66b 100644 --- a/test/features/video_controls_test.dart +++ b/test/features/video_controls_test.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/core/network/origin_guard.dart'; import 'package:stash_app_mobile/data/models/scene.dart'; import 'package:stash_app_mobile/data/models/scene_details.dart'; import 'package:stash_app_mobile/data/providers.dart'; @@ -59,7 +60,7 @@ void main() { ...testServer, playerProvider.overrideWithValue(player), scrubThumbnailsProvider('1').overrideWith((ref) async => null), - authHeadersProvider.overrideWithValue(const {}), + authHeadersProvider.overrideWithValue(AuthHeaders.none), playbackErrorProvider.overrideWith(() => errors), sceneDetailsProvider('1').overrideWith((ref) async => SceneDetails(streams: streams)), ], diff --git a/test/flutter_test_config.dart b/test/flutter_test_config.dart new file mode 100644 index 0000000..e9389ee --- /dev/null +++ b/test/flutter_test_config.dart @@ -0,0 +1,11 @@ +import 'dart:async'; + +import 'package:stash_app_mobile/features/security/pin_hash.dart'; + +/// Runs before every test file: PIN hashes with few rounds, computed on the +/// test's own isolate, so tests that enter PINs stay fast and work in fake +/// async zones. +Future testExecutable(FutureOr Function() testMain) async { + StoredPin.iterations = 1000; + await testMain(); +} From fb8a0b7f15ea99cc05c30ccfed27de9722324777 Mon Sep 17 00:00:00 2001 From: Philippe Date: Wed, 18 Nov 2026 17:37:04 +0100 Subject: [PATCH 2/5] Keep list position through fullscreen, favorites selector, zoom snap feedback - LayoutFreeze keeps the shell's layout while the player's fullscreen turns the window, so lists no longer lose their place (pixel offset clamped by the landscape column layout). - Favorites tab: avatars select "All" or one performer (long press opens the channel), with a header and "View channel". - ZoomSnapFeedback: "Original"/"Fill" pill with a pop and guide lines where the pan snaps; still with reduced motion. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 6 +- docs/BACKLOG.md | 2 +- docs/UX_REVIEW.md | 2 +- lib/features/player/fullscreen_route.dart | 6 + lib/features/player/player_controls.dart | 9 +- lib/features/player/video_controls.dart | 19 +- lib/features/player/video_zoom.dart | 150 +++++++++++ lib/features/shell/app_shell.dart | 20 +- .../subscriptions/subscriptions_page.dart | 249 ++++++++++++++++-- lib/l10n/app_de.arb | 8 + lib/l10n/app_en.arb | 15 ++ lib/l10n/gen/app_localizations.dart | 48 ++++ lib/l10n/gen/app_localizations_de.dart | 27 ++ lib/l10n/gen/app_localizations_en.dart | 27 ++ lib/widgets/layout_freeze.dart | 137 ++++++++++ test/features/player/seek_sequence_test.dart | 11 +- .../player/zoom_snap_feedback_test.dart | 105 ++++++++ test/features/subscriptions_test.dart | 31 +++ test/features/text_scale_test.dart | 12 + test/features/video_controls_test.dart | 10 +- test/widgets/layout_freeze_test.dart | 105 ++++++++ 21 files changed, 953 insertions(+), 46 deletions(-) create mode 100644 lib/widgets/layout_freeze.dart create mode 100644 test/features/player/zoom_snap_feedback_test.dart create mode 100644 test/widgets/layout_freeze_test.dart diff --git a/CLAUDE.md b/CLAUDE.md index 5714d2d..1da4593 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,9 +59,9 @@ lib/ **Paginated lists.** `sceneListProvider`, `performerListProvider` and `studioListProvider` are auto-dispose family `PagedNotifier`s keyed by query objects (`SceneQuery`, `PerformerQuery`, `StudioQuery`). These query objects must keep value equality. UI code reads paged lists through `.current` (`PagedValue` extension), not `.value`. On a server switch the lists rebuild (`isReloading`), and `.value` would keep showing the previous server's items, or would hide a failed load behind them. A reload of the same list (pull-to-refresh, the connection banner's `reloadLists`) that fails with a network error keeps the loaded items as data with `PagedState.refreshError` (STATE-1; the banner explains it), but only when `PagedState.origin` (server and paging mode) still matches, so after a server switch the error shows instead; server-reported errors still replace the list by an `ErrorView`. The random sort uses a `random_` sort field so pages stay stable, and the seed is 0 for every other sort. To get an infinite, refreshable list with sort chips, use `SceneFeedView`, or compose `RefreshIndicator`, `LoadMoreListener`, `CustomScrollView` and `PagedSliver` yourself. After a failed page, scrolling doesn't retry; `PagedSliver`'s `onLoadMore` (its "try again" button) passes `loadMore(retry: true)`. `pagingModeProvider` (settings) switches all paged lists to numbered pages: `loadMore` then does nothing, `PagedSliver` shows a `PageBar` driving `PagedNotifier.goToPage` (pass `onGoToPage`), and changing the mode rebuilds the lists. The first page loads as skeletons (`widgets/skeleton.dart`, `PagedSliver(skeletonBuilder:)`), not a spinner. `SceneFeedView(pinChips: true)` pins the filter, sort and saved-filter chips under the home app bar (shelves go into `belowChipsSlivers`); `unfilteredEmptyView` replaces the empty message only without filters or search term (home: "scan your library" with a button to the server tasks). `EmptyView` takes an optional action. -**Shell and navigation.** `AppShell` holds an `IndexedStack` with one nested `Navigator` per `AppTab`, with the player's `SlidingPanel` on top. The bottom `NavigationBar` collapses as the player expands, driven by `miniplayerHeightProvider`. `IndexedStack` keeps hidden tabs ticking, so `_TabTickers` turns `TickerMode` off for every tab but the shown one, and for that one too while the player is fully open (animated images and shimmers pause). `ShellLayout` (`features/shell/shell_layout.dart`, NAV-4) picks the navigation by width (`ShellNavigation.forWidth`): the bar below `kWideLayoutBreakpoint`, from there a `NavigationRail` on the left (also on phones in landscape; labels clamped to 1.3× text), extended with labels beside the icons from `kExtendedRailBreakpoint` (1240). The content sits right of the rail (which takes the side's safe area), the collapsed miniplayer at the bottom of the content above the home indicator; while expanding, the panel's left edge slides over the rail (its `MediaQuery` width is the space it has), so the expanded player covers the rail and the content never resizes. The shorts' fullscreen hides the rail like the bar. The bar shows only the tabs in `navBarConfigProvider` (`features/shell/nav_bar_config.dart`, configured in the settings, stored for all servers); `currentTabProvider` starts on the first one and falls back to it when its tab is hidden. Each `LibrarySection` (`features/library/library_page.dart`) is an `AppTab` of its own (`AppTab.section`, shown by `LibrarySectionPage`); only `LibrarySection.media` (scenes, images, galleries) are the library's text-only sub-tabs, the others are on the "You" page. A new `AppTab` needs a root page in `AppShell.rootPage` and should be hidden in `NavBarConfig.standard` (home, shorts, search, library, you). `AppTab.you` (`YouPage`, `features/you/`: shelves for history, watch later, groups and markers with "See all", then stats, performers, studios, tags, the views not in the bar, server tasks and settings; picked views open inside that tab) is `NavBarConfig.alwaysShown` and last by default; it replaced the former `all` tab, and a stored `all` becomes `you` at its place. The bar has at most `NavBarConfig.maxVisible` (5) tabs and stored bars with more are `fitted()`. The tab pages' app bars end with `ServerAvatarButton` (`features/auth/server_avatar.dart`, the active server's initial), which opens the account sheet: switch server, server tasks and settings. The settings are not a tab but a `showCupertinoSheet` over the whole app (`openSettings` in `settings_button.dart`, from the account sheet and the "You" page): closed with its X or by swiping down, with its own nested navigator, so its sub-pages push with `Navigator.of(context)`, not `openPage`. `settingsOpenProvider` tells the shorts to pause while it is open. Re-selecting the current tab (`reselectTab`) pops back to its root, or there scrolls to the top: each tab root gets its own `PrimaryScrollController` (`tabScrollControllersProvider`), so its lists must not bring a controller of their own if they should follow. To navigate, use `openPage`, `openPerformer`, `openStudio` or `openSearch` from `features/shell/navigation.dart`. They push onto the current tab's navigator and collapse the player, and they also work from inside the player, which sits outside the tab navigators. Settings open on a page of categories (`settings_page.dart`) whose sub-pages live in `settings_categories.dart`; "Remove this server" is only on the server page. `openSettings(context, ref, initialPage:)` opens the sheet with a sub-page already pushed (home's empty state opens the server tasks that way). Settings picked from a menu use `SettingsDropdownTile`, which moves the menu under the title when it would take more than half the row (large text). `test/features/text_scale_test.dart` pumps the main pages and the shell's bar/rail at 1.0×, 1.5× and 2.0× text on a 360×780 phone (plus 320×640 and a 1024×768 tablet) and fails on layout errors (A11Y-3); its `_knownOverflows` lists the ones not fixed yet. Optional tab `AppTab.subscriptions`, labelled "Favorites" (`features/subscriptions/`): favorite performers' avatars (dot = new since the last visit) and their newest scenes. `LastVisitNotifier` (`last_visit:`) is the baseline for home's "N new videos since your last visit" banner (`SceneQuery.createdAfter`); `JobFinishedListener` reports server jobs the user started once they end. Home's dice plays a random scene. Scenes are added to groups through `showAddToGroupSheet` (scene menu, player's More sheet). External links go through `openExternalUrl` (`core/utils/external_links.dart`, url_launcher; never with the API key); the description sheet has "Open in Stash" (not for the demo). +**Shell and navigation.** `AppShell` holds an `IndexedStack` with one nested `Navigator` per `AppTab`, with the player's `SlidingPanel` on top. The bottom `NavigationBar` collapses as the player expands, driven by `miniplayerHeightProvider`. `IndexedStack` keeps hidden tabs ticking, so `_TabTickers` turns `TickerMode` off for every tab but the shown one, and for that one too while the player is fully open (animated images and shimmers pause). `ShellLayout` (`features/shell/shell_layout.dart`, NAV-4) picks the navigation by width (`ShellNavigation.forWidth`): the bar below `kWideLayoutBreakpoint`, from there a `NavigationRail` on the left (also on phones in landscape; labels clamped to 1.3× text), extended with labels beside the icons from `kExtendedRailBreakpoint` (1240). The content sits right of the rail (which takes the side's safe area), the collapsed miniplayer at the bottom of the content above the home indicator; while expanding, the panel's left edge slides over the rail (its `MediaQuery` width is the space it has), so the expanded player covers the rail and the content never resizes. The shorts' fullscreen hides the rail like the bar. The bar shows only the tabs in `navBarConfigProvider` (`features/shell/nav_bar_config.dart`, configured in the settings, stored for all servers); `currentTabProvider` starts on the first one and falls back to it when its tab is hidden. Each `LibrarySection` (`features/library/library_page.dart`) is an `AppTab` of its own (`AppTab.section`, shown by `LibrarySectionPage`); only `LibrarySection.media` (scenes, images, galleries) are the library's text-only sub-tabs, the others are on the "You" page. A new `AppTab` needs a root page in `AppShell.rootPage` and should be hidden in `NavBarConfig.standard` (home, shorts, search, library, you). `AppTab.you` (`YouPage`, `features/you/`: shelves for history, watch later, groups and markers with "See all", then stats, performers, studios, tags, the views not in the bar, server tasks and settings; picked views open inside that tab) is `NavBarConfig.alwaysShown` and last by default; it replaced the former `all` tab, and a stored `all` becomes `you` at its place. The bar has at most `NavBarConfig.maxVisible` (5) tabs and stored bars with more are `fitted()`. The tab pages' app bars end with `ServerAvatarButton` (`features/auth/server_avatar.dart`, the active server's initial), which opens the account sheet: switch server, server tasks and settings. The settings are not a tab but a `showCupertinoSheet` over the whole app (`openSettings` in `settings_button.dart`, from the account sheet and the "You" page): closed with its X or by swiping down, with its own nested navigator, so its sub-pages push with `Navigator.of(context)`, not `openPage`. `settingsOpenProvider` tells the shorts to pause while it is open. Re-selecting the current tab (`reselectTab`) pops back to its root, or there scrolls to the top: each tab root gets its own `PrimaryScrollController` (`tabScrollControllersProvider`), so its lists must not bring a controller of their own if they should follow. To navigate, use `openPage`, `openPerformer`, `openStudio` or `openSearch` from `features/shell/navigation.dart`. They push onto the current tab's navigator and collapse the player, and they also work from inside the player, which sits outside the tab navigators. Settings open on a page of categories (`settings_page.dart`) whose sub-pages live in `settings_categories.dart`; "Remove this server" is only on the server page. `openSettings(context, ref, initialPage:)` opens the sheet with a sub-page already pushed (home's empty state opens the server tasks that way). Settings picked from a menu use `SettingsDropdownTile`, which moves the menu under the title when it would take more than half the row (large text). `test/features/text_scale_test.dart` pumps the main pages and the shell's bar/rail at 1.0×, 1.5× and 2.0× text on a 360×780 phone (plus 320×640 and a 1024×768 tablet) and fails on layout errors (A11Y-3); its `_knownOverflows` lists the ones not fixed yet. Optional tab `AppTab.subscriptions`, labelled "Favorites" (`features/subscriptions/`): only performers with Stash's `favorite` flag (ratings play no part). Their avatars (dot = new since the last visit) are a selector, "All" first: a tap shows only that performer's scenes (newest first, with "View channel"; tapping it again goes back to all), a long press opens the channel; "All" is `SceneQuery.newFromFavorites` (shared with home's shelf). The feed is keyed by the selection, so it starts at the top. `LastVisitNotifier` (`last_visit:`) is the baseline for home's "N new videos since your last visit" banner (`SceneQuery.createdAfter`); `JobFinishedListener` reports server jobs the user started once they end. Home's dice plays a random scene. Scenes are added to groups through `showAddToGroupSheet` (scene menu, player's More sheet). External links go through `openExternalUrl` (`core/utils/external_links.dart`, url_launcher; never with the API key); the description sheet has "Open in Stash" (not for the demo). -**Player.** There is a single media_kit `Player` in `playerProvider`. `nowPlayingProvider.play(scene)` opens the stream with the auth headers, starting at the resume position, and expands the panel. `PlayerPanel` is a single layout that `PlayerTransition` interpolates between the mini bar and the expanded page (video, details, "Up next") based on the panel height. The one `PlayerVideo` instance stays in place, so it is never rebuilt mid-transition. The details are built while the panel rests (collapsed or open, never mid-animation) and then kept (hidden with `Visibility(maintainState:)` while collapsed), laid out at their expanded height and reused as one widget while only the height changes, so expanding and collapsing doesn't rebuild, relayout or reload "Up next" every frame. The video area follows the video's aspect ratio (`PlayerTransition.videoAspect`; portrait videos up to `maxVideoShare` of the panel). From `PlayerTransition.splitBreakpoint` (840 dp) the expanded video takes `splitShare` (half) of the width (`columnWidth`, `expandedWidth`), with `PlayerDetails(part: info)` below it and `part: list` ("Up next" or the queue) on the right; the right `Positioned` is always in the stack so the video never moves in the tree. Phones stay portrait everywhere, the player too (4.28): `AppOrientation` (`widgets/app_orientation.dart`; `AppOrientationScope` in `MaterialApp.builder` tells it whether the window is a phone's) allows only portrait on phones, all on tablets, and the fullscreen sets its orientations through `AppOrientation.turnTo`, which waits until the window has turned (never call `SystemChrome.setPreferredOrientations` elsewhere). On a phone `PlayerVideo` listens to `heldOrientationProvider` (`held_orientation.dart`, the `stash/device_orientation` event channel: Android's `OrientationEventListener` in `MainActivity`, iOS' UIDevice orientation in `DeviceOrientationStream`; `portrait`/`turnedLeft`/`turnedRight`, physical, both respect the system's rotation lock) for as long as it lives, not only while expanded: the panel isn't expanded for a moment while the screen turns, and listening anew reported the sideways hold at once, so leaving fullscreen by its button jumped right back in. A report counts once it held for 250 ms (held at an angle, the reports flip back and forth), and not while the app is locked or away (coming back reported turns that each opened another fullscreen; `enterPlayerFullscreen` also opens only one route, `playerFullscreenOpen`). Sideways in the open player with a wide video enters fullscreen (`fullscreenByRotation`), upright leaves it, and after leaving it while sideways a new turn counts only once the phone was upright. Tablets don't enter fullscreen by turning. Fullscreen goes through `enterPlayerFullscreen`/`exitPlayerFullscreen`/`togglePlayerFullscreen` (`fullscreen_route.dart`, a copy of media_kit's route without its own transition) and `FullscreenMorph` (`fullscreen_morph.dart`, in `MaterialApp.builder`): a second `Video` of the controller moves from the player's place (`inlineVideoRect`) to the fullscreen pose, turned by `HeldOrientation.uprightAngle` in a portrait window, while the app goes black; the screen then turns underneath (both landscape sides allowed, so the system picks the held one), where the pose already matches, and the morph goes. By default (`FullscreenMorph.curtainOnly`, both platforms) the app only fades to black (`cover`/`uncover`), turns underneath and fades back in, both ways: on iOS the morph's turn still showed, and the plain fade read best. The morph (kept, tested with `curtainOnlyOverride = false`) needs a turn without the system's rotation animation, which would turn the already turned picture once more: iOS' `RunnerViewController` disables it, Android's `MainActivity` sets `ROTATION_ANIMATION_JUMPCUT` on phones (no system animation on top of the app's fade; the old frame it stretches for a moment is black). Leaving, `_onExitFullscreen` shows the pose at once (also after the system's back), turns back and moves the video home. They need a context below the `Video`, so `PlayerVideo` keeps the controls' contexts (inline and fullscreen). A portrait video's extra height covers a spacer at the top of the details and shrinks as they scroll (`PlayerTransition.extraVideoHeight`). Pinch zoom (`video_zoom.dart`, 4.22/4.31) is a Flutter transform: `ZoomedVideo` (around the inline and the fullscreen `Video`) draws the video scaled 1–4× and panned, clipped to its box, and `ZoomCounter` (around the controls inside the `Video`) applies the inverse so the controls keep their size. mpv's `video-zoom` was dropped: it stays inside the video's rectangle, so the box's black bars never went. The scale grows continuously and sticks (±7 %) to 1× (the video's width or height fills the box) and to the scale where the video covers the box (`VideoZoom.coverScale`, `fill`: recomputed for every box, so it holds in fullscreen and when turning); the pan sticks to the center and the edges (`VideoZoom.panSnap`, both axes); each new snap gives a light tick (`VideoZoom.snaps`); `NowPlayingNotifier.play` resets the pinch zoom for a new scene but keeps a fill. Both widgets always build the same tree (an identity transform at no zoom), so the `Video` is never remounted. Subtitles (4.32, `captions.dart`): `SceneDetails.captions` (`captions` and `paths.caption` of `FindSceneDetails`, url `…?lang=&type=`), the top bar's subtitle button opens `showCaptionSheet`, `selectCaption` adds the file with mpv's `sub-add` (`SubtitleTrack.uri`) and `preferredCaptionProvider` (stored language) switches them on for later scenes as soon as the file's duration is known; the demo serves generated WebVTT under `/demo/caption/` (en, de). The double-tap seek feedback is a half disc (`_SeekFeedback`, `_HalfDiscClipper`) over the outer 30 % of the tapped side, its text toward the edge; it fades in with the first tap and out after the sequence (`_feedbackFading` keeps it mounted meanwhile). On iOS, `RunnerViewController` (Main.storyboard) turns without UIKit's rotation animation, which stretched the video. Keep the panel's widget tree structurally stable and toggle behavior with flags. Don't pass media_kit's `NoVideoControls` to `Video`: since media_kit_video 2 it is `null`, which `Video` ignores on update, so the old controls would stay; `PlayerVideo` uses an empty builder instead. With `showControls`, `PlayerVideo` (`player_controls.dart`) wraps media_kit's `MaterialVideoControls` on both platforms, with double-tap seeking, the collapse button and the quality sheet. `sceneDetailsProvider` loads `sceneStreams`, scene markers and the file infos (`SceneFile`, shown by `FileInfoCard`) lazily per scene. Chapters appear as gaps in the controls' `PreviewSeekBar` and in `ChapterList`; there is deliberately no progress line under the expanded video. `preferredStreamProvider` stores the chosen stream label (from the HD button, or ` p` from the settings), `pickPreferredStream` matches it by format and height (the `resolution` URL parameter), and `play` only waits for the stream list when a preference is set. Playback errors: `playbackErrorProvider` counts mpv's `stream.error` only when playback hasn't moved on for 2 s (mpv also reports errors it recovers from); `_PlaybackErrorOverlay` and the mini bar offer `retry()` (`NowPlayingNotifier.reopen`) and the quality sheet. Failed casts go through `castFailureProvider` to a snack bar. Under the video, `PlayerDetails` shows title and meta (a tap opens the description sheet, `scene_description.dart`: description, tags, file info, edit scene), the channel row, one action bar (`SceneActions`: rating pill with `showRatingSheet`, O-counter pill with `showOCounterSheet` (−/+, no undo snack bar), watch later, marker, More with `showSceneMoreSheet`), performers, one line of tags (`SceneTagsRow`: as many as fit, then "+N" opening the description sheet), chapters, then Up next; sheet actions pop first and then act through the root navigator. Markers can be ranges on newer Stash (`end_seconds`): the end times come from the optional `SceneMarkerEnds`/`MarkerEnds` queries merged into the markers (a server error means unsupported and stops asking); ranges show as a tinted segment in the seek bar, "0:40–1:10" in the marker list and grid, and the add-marker sheet offers an end only when supported (`SceneDetails.markerRanges`). The list under the video is titled "Markers" (Stash has no chapters). A long press on a chapter or a markers-grid tile opens `showMarkerMenu` (`scene_actions.dart`; the grid adds play and play as loop): edit reuses `AddMarkerSheet(marker:)` and sends only changes (`StashRepository.updateMarker`, a map like the other forms; `end_seconds: null` removes the end), delete asks first (`confirmDeleteMarker`, `deleteMarker`); both reload the scene details and the marker lists. `SceneMarker`/`Marker` carry `ownTitle` and the primary `tag` for that. +**Player.** There is a single media_kit `Player` in `playerProvider`. `nowPlayingProvider.play(scene)` opens the stream with the auth headers, starting at the resume position, and expands the panel. `PlayerPanel` is a single layout that `PlayerTransition` interpolates between the mini bar and the expanded page (video, details, "Up next") based on the panel height. The one `PlayerVideo` instance stays in place, so it is never rebuilt mid-transition. The details are built while the panel rests (collapsed or open, never mid-animation) and then kept (hidden with `Visibility(maintainState:)` while collapsed), laid out at their expanded height and reused as one widget while only the height changes, so expanding and collapsing doesn't rebuild, relayout or reload "Up next" every frame. The video area follows the video's aspect ratio (`PlayerTransition.videoAspect`; portrait videos up to `maxVideoShare` of the panel). From `PlayerTransition.splitBreakpoint` (840 dp) the expanded video takes `splitShare` (half) of the width (`columnWidth`, `expandedWidth`), with `PlayerDetails(part: info)` below it and `part: list` ("Up next" or the queue) on the right; the right `Positioned` is always in the stack so the video never moves in the tree. Phones stay portrait everywhere, the player too (4.28): `AppOrientation` (`widgets/app_orientation.dart`; `AppOrientationScope` in `MaterialApp.builder` tells it whether the window is a phone's) allows only portrait on phones, all on tablets, and the fullscreen sets its orientations through `AppOrientation.turnTo`, which waits until the window has turned (never call `SystemChrome.setPreferredOrientations` elsewhere). On a phone `PlayerVideo` listens to `heldOrientationProvider` (`held_orientation.dart`, the `stash/device_orientation` event channel: Android's `OrientationEventListener` in `MainActivity`, iOS' UIDevice orientation in `DeviceOrientationStream`; `portrait`/`turnedLeft`/`turnedRight`, physical, both respect the system's rotation lock) for as long as it lives, not only while expanded: the panel isn't expanded for a moment while the screen turns, and listening anew reported the sideways hold at once, so leaving fullscreen by its button jumped right back in. A report counts once it held for 250 ms (held at an angle, the reports flip back and forth), and not while the app is locked or away (coming back reported turns that each opened another fullscreen; `enterPlayerFullscreen` also opens only one route, `playerFullscreenOpen`). Sideways in the open player with a wide video enters fullscreen (`fullscreenByRotation`), upright leaves it, and after leaving it while sideways a new turn counts only once the phone was upright. Tablets don't enter fullscreen by turning. Fullscreen goes through `enterPlayerFullscreen`/`exitPlayerFullscreen`/`togglePlayerFullscreen` (`fullscreen_route.dart`, a copy of media_kit's route without its own transition) and `FullscreenMorph` (`fullscreen_morph.dart`, in `MaterialApp.builder`): a second `Video` of the controller moves from the player's place (`inlineVideoRect`) to the fullscreen pose, turned by `HeldOrientation.uprightAngle` in a portrait window, while the app goes black; the screen then turns underneath (both landscape sides allowed, so the system picks the held one), where the pose already matches, and the morph goes. By default (`FullscreenMorph.curtainOnly`, both platforms) the app only fades to black (`cover`/`uncover`), turns underneath and fades back in, both ways: on iOS the morph's turn still showed, and the plain fade read best. The morph (kept, tested with `curtainOnlyOverride = false`) needs a turn without the system's rotation animation, which would turn the already turned picture once more: iOS' `RunnerViewController` disables it, Android's `MainActivity` sets `ROTATION_ANIMATION_JUMPCUT` on phones (no system animation on top of the app's fade; the old frame it stretches for a moment is black). Leaving, `_onExitFullscreen` shows the pose at once (also after the system's back), turns back and moves the video home. They need a context below the `Video`, so `PlayerVideo` keeps the controls' contexts (inline and fullscreen). A portrait video's extra height covers a spacer at the top of the details and shrinks as they scroll (`PlayerTransition.extraVideoHeight`). Pinch zoom (`video_zoom.dart`, 4.22/4.31) is a Flutter transform: `ZoomedVideo` (around the inline and the fullscreen `Video`) draws the video scaled 1–4× and panned, clipped to its box, and `ZoomCounter` (around the controls inside the `Video`) applies the inverse so the controls keep their size. mpv's `video-zoom` was dropped: it stays inside the video's rectangle, so the box's black bars never went. The scale grows continuously and sticks (±7 %) to 1× (the video's width or height fills the box) and to the scale where the video covers the box (`VideoZoom.coverScale`, `fill`: recomputed for every box, so it holds in fullscreen and when turning); the pan sticks to the center and the edges (`VideoZoom.panSnap`, both axes); each new snap gives a light tick (`VideoZoom.snaps`), and `ZoomSnapFeedback` (in the controls' stack, always there) shows it while pinching: the scale pill reads "Original"/"Fill" in the accent with a small pop when the scale sticks, thin guide lines (`VideoZoom.guideX`/`guideY`) where the pan sticks; no pop or fade with reduced motion; `NowPlayingNotifier.play` resets the pinch zoom for a new scene but keeps a fill. Both widgets always build the same tree (an identity transform at no zoom), so the `Video` is never remounted. Subtitles (4.32, `captions.dart`): `SceneDetails.captions` (`captions` and `paths.caption` of `FindSceneDetails`, url `…?lang=&type=`), the top bar's subtitle button opens `showCaptionSheet`, `selectCaption` adds the file with mpv's `sub-add` (`SubtitleTrack.uri`) and `preferredCaptionProvider` (stored language) switches them on for later scenes as soon as the file's duration is known; the demo serves generated WebVTT under `/demo/caption/` (en, de). The double-tap seek feedback is a half disc (`_SeekFeedback`, `_HalfDiscClipper`) over the outer 30 % of the tapped side, its text toward the edge; it fades in with the first tap and out after the sequence (`_feedbackFading` keeps it mounted meanwhile). On iOS, `RunnerViewController` (Main.storyboard) turns without UIKit's rotation animation, which stretched the video. Keep the panel's widget tree structurally stable and toggle behavior with flags. Don't pass media_kit's `NoVideoControls` to `Video`: since media_kit_video 2 it is `null`, which `Video` ignores on update, so the old controls would stay; `PlayerVideo` uses an empty builder instead. With `showControls`, `PlayerVideo` (`player_controls.dart`) wraps media_kit's `MaterialVideoControls` on both platforms, with double-tap seeking, the collapse button and the quality sheet. `sceneDetailsProvider` loads `sceneStreams`, scene markers and the file infos (`SceneFile`, shown by `FileInfoCard`) lazily per scene. Chapters appear as gaps in the controls' `PreviewSeekBar` and in `ChapterList`; there is deliberately no progress line under the expanded video. `preferredStreamProvider` stores the chosen stream label (from the HD button, or ` p` from the settings), `pickPreferredStream` matches it by format and height (the `resolution` URL parameter), and `play` only waits for the stream list when a preference is set. Playback errors: `playbackErrorProvider` counts mpv's `stream.error` only when playback hasn't moved on for 2 s (mpv also reports errors it recovers from); `_PlaybackErrorOverlay` and the mini bar offer `retry()` (`NowPlayingNotifier.reopen`) and the quality sheet. Failed casts go through `castFailureProvider` to a snack bar. Under the video, `PlayerDetails` shows title and meta (a tap opens the description sheet, `scene_description.dart`: description, tags, file info, edit scene), the channel row, one action bar (`SceneActions`: rating pill with `showRatingSheet`, O-counter pill with `showOCounterSheet` (−/+, no undo snack bar), watch later, marker, More with `showSceneMoreSheet`), performers, one line of tags (`SceneTagsRow`: as many as fit, then "+N" opening the description sheet), chapters, then Up next; sheet actions pop first and then act through the root navigator. Markers can be ranges on newer Stash (`end_seconds`): the end times come from the optional `SceneMarkerEnds`/`MarkerEnds` queries merged into the markers (a server error means unsupported and stops asking); ranges show as a tinted segment in the seek bar, "0:40–1:10" in the marker list and grid, and the add-marker sheet offers an end only when supported (`SceneDetails.markerRanges`). The list under the video is titled "Markers" (Stash has no chapters). A long press on a chapter or a markers-grid tile opens `showMarkerMenu` (`scene_actions.dart`; the grid adds play and play as loop): edit reuses `AddMarkerSheet(marker:)` and sends only changes (`StashRepository.updateMarker`, a map like the other forms; `end_seconds: null` removes the end), delete asks first (`confirmDeleteMarker`, `deleteMarker`); both reload the scene details and the marker lists. `SceneMarker`/`Marker` carry `ownTitle` and the primary `tag` for that. **Player gestures.** The panel is our own `SlidingPanel` (`sliding_panel.dart`, replaced the unmaintained `miniplayer` package): collapsed, a tap expands it and a vertical drag follows the finger, snapping on release (`SlidingPanel.snapAfterDrag`) or dismissing below the bar; expanded, it takes no gestures, so taps belong to the video controls without a guard. media_kit's controls and the details list both claim vertical drags, so `DragToMinimize` reads raw pointer events and drives the panel through `SlidingPanelController.jumpTo`/`expand`/`collapse` (`miniplayerControllerProvider`; calls while no panel is mounted do nothing). Back while the player is open collapses it (`AppShell`'s `PopScope`). An expanded panel stays expanded when the window's height changes. That's also why the player's details have no pull-to-refresh. The player uses its own `StashVideoControls` instead of media_kit's, because media_kit's hide timer removed our seek bar mid-scrub. The controls take the fullscreen state and a toggle callback from media_kit's `VideoState`; buttons sit above the tap/double-tap gesture layer so they react without waiting for a double tap. Holding the video (`HoldDetector`, 250 ms) plays at 2× until released, and the speed button opens `showSpeedSheet` (mpv keeps the speed across files). mpv reports the position every frame, so `PreviewSeekBar` repaints its `SeekBarPainter` through a `ValueNotifier` (`progress`) and rebuilds only once a second (the spoken value). Their `PreviewSeekBar` shows sprite thumbnails (`scrubThumbnailsProvider`, parsed from Stash's WebVTT) while scrubbing. They load lazily: the controls stay mounted while hidden, so the bar reads the provider only once it is `visible` or touched, then precaches the sprite. `sceneDetailsProvider` and `scrubThumbnailsProvider` stay cached for 5 minutes without listeners (`Ref.cacheFor`), so collapsing and expanding the player doesn't refetch. On first use the controls show one-time gesture tips (`gesture_hints.dart`, `gesture_tips_seen`, resettable in Settings → Playback). In fullscreen a lock button (`TouchLockLayer`, `touch_lock.dart`) ignores all touches until its pill is held for 1 s; leaving fullscreen or a playback error unlocks. Chapters show the marker's screenshot (sprite frame as stand-in). The channel row has a favorite heart (performers; studios from Stash 0.25 through the optional `StudioFavorite` query). Channel pages put `ChannelFavoriteButton` (`FavoriteButton`, `StudioFavoriteButton`) and `ChannelRatingButton` (`features/channel/channel_rating.dart`) under the name: stars are saved through `channelRatingsProvider` (optimistic, `:`), a studio's come from the optional `StudioRating` query, and the picker is `showStarsSheet`, shared with the scenes' `showRatingSheet`. Double-tap seeking is a sequence like YouTube's: a double tap on the left/right third starts it and every further tap on that side within 700 ms extends it (5, 10, 20, 30, 40 s; `seekSequenceTotal`), counted from raw pointers so extending taps react at once; it also works while casting (tap areas over `CastingControls`) and not while locked. A tap on the other side starts a new sequence from one step; for 2 s after a seek (`_seekSettling`) a new sequence counts from the last target, since mpv (and a TV) still report the old position. Double-tap seeking is configurable per device (`seekSettingsProvider`, `seek_settings.dart`; Settings → Playback): on/off (off = single taps react without the double-tap delay), step 5/10/15/30 s, and cumulative (`SeekSettings.total`: step, then 2×step×(n−1), i.e. 5, 10, 20, 30, 40 s) or linear (one step per tap). @@ -97,7 +97,7 @@ lib/ **Picture-in-picture and background playback.** `features/pip/`. `PipService` (`stash/pip` channel; `UnsupportedPipService` in tests and on desktop) has two shapes: Android (`canAutoEnter`) shrinks the app's own window (`MainActivity`, `supportsPictureInPicture`), and `PipScope` (in `MaterialApp.builder`, inside `AppLockGate`) then shows only a second `Video` of the player; `AppLockGate` skips the privacy cover while `pipProvider` is true. iOS can't put mpv's video into picture-in-picture, so `PipNotifier.enter` pauses mpv and hands the stream (`pickAirPlayStream`, API key in the URL plus the auth headers) to `PictureInPictureController` in `AppDelegate.swift`, an AVPlayer whose layer sits where the video is; `pipStopped` reports the position, and Dart seeks there. That needs `UIBackgroundModes` audio. `backgroundPlaybackProvider` decides on hide: with `PlaybackModes.background` mpv keeps playing with `vid=no` (restored on show), otherwise it pauses; not while casting or in picture-in-picture. So `PlayerVideo` passes `pauseUponEnteringBackgroundMode: false`. Watch the main player's `playing` only through providers that check `nowPlayingProvider` first, or the native player is created at startup (and fails in tests). Lock screen and notification controls (`player/lock_screen.dart`, audio_service) follow `PlaybackModes.lockScreen`, off by default for discretion: `lockScreenControlsProvider` (watched by `PipScope`) creates the `StashAudioHandler` only once it is switched on and a scene plays locally (AudioService.init runs once per process), publishes `lockScreenItem`/`lockScreenState` (position only on jumps; the platform extrapolates) and clears both when switched off, while casting or when the player closes. On Android `MainActivity` extends `AudioServiceFragmentActivity`, which shares the engine with the media service. With a queue the lock screen also offers previous/next (`hasPrevious`/`hasNext`); on iOS, whose skip buttons replace the track buttons, rewind and fast-forward are dropped meanwhile (`skipsHideTracks`). Playback errors show in `StashVideoControls`, so also in fullscreen. The PiP shape follows the video: `pipAspect` (Stash's file size first, then the decoded size, clamped to Android's 1:2.39–2.39:1) is re-sent for auto-enter whenever it changes, and iOS starts PiP only once the AVPlayerItem has a presentation size, with the layer fitted to it. System notifications (`features/notifications/`, flutter_local_notifications behind `NotificationService`) are off by default and discreet by default ("StashTube", no names, secret on the Android lock screen); they report a started server task that ends while the app is in the background, and a tap opens the server tasks. iOS sets the `UNUserNotificationCenter` delegate in `AppDelegate`. Android's PiP window reads as landscape: `PlayerVideo` doesn't treat it as turning the phone (no rotation fullscreen while `pipProvider`), `PipScope` stops the tickers of the app below the PiP video, and the player's controls read fullscreen from their own context (`isFullscreen(controlsContext)`), never from media_kit's remembered context, which may belong to a just-closed fullscreen route ("deactivated widget's ancestor"). -**Wide layouts.** From `kWideLayoutBreakpoint` (600 dp, `widgets/sliver_columns.dart`) lists get columns: `PagedSliver(columnWidth:)` or `SliverColumns` lay items out in rows (each as tall as its tallest item, unlike a grid), used by `SceneFeedView`'s cards and rows, the studio lists and watch later. Grids (`gridDelegate`) already adapt by their max extent. +**Wide layouts.** From `kWideLayoutBreakpoint` (600 dp, `widgets/sliver_columns.dart`) lists get columns: `PagedSliver(columnWidth:)` or `SliverColumns` lay items out in rows (each as tall as its tallest item, unlike a grid), used by `SceneFeedView`'s cards and rows, the studio lists and watch later. Grids (`gridDelegate`) already adapt by their max extent. Since columns depend on the width, a scroll offset (pixels) means another item after a width change, and a shorter list clamps it: so `AppShell` sits in a `LayoutFreeze` (`widgets/layout_freeze.dart`) that keeps the constraints and `MediaQuery` from before the player's fullscreen while `shellLayoutHold` is set (by `enterPlayerFullscreen`, released by `PlayerVideo` once the screen has turned back, else 3 s after the route went), and then until the window is back to that size, at most 800 ms (a tablet left sideways relayouts). The lists behind the fullscreen never see the landscape window and come back at the same item. **Animations.** `ConfettiBurst` (`widgets/confetti.dart`) bursts when its `trigger` changes (the favorite buttons count up when a performer becomes a favorite) and paints outside its child without taking taps. `PlayPauseIcon` morphs `AnimatedIcons.play_pause` with a small pop; use it for every play/pause button. Animations check `MediaQuery.disableAnimationsOf` and skip themselves. diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index c16a0ce..171791c 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -83,5 +83,5 @@ Eine wartbare Basis, damit Features unabhängig voneinander wachsen können. | 4.28 | Als Nutzer möchte ich, dass sich auf dem Handy nur das Vollbild des Players ins Querformat dreht. | Handys (kürzeste Seite unter 600 dp) bleiben überall hochkant, auch der aufgeklappte Player. Kippen des Handys meldet das System samt Richtung (Android `OrientationEventListener`, iOS UIDevice; bei aktiver Drehsperre nicht): mit einem breiten Video im aufgeklappten Player öffnet es das Vollbild, aufrecht halten beendet es. Eine Haltung zählt erst nach 0,25 s (schräg gehalten flippte das Video sonst kurz), nicht bei gesperrter oder verlassener App, und es gibt immer nur ein Vollbild (beim Entsperren öffneten sich sonst mehrere). Nach Verlassen per Knopf im Querformat öffnet erst wieder Kippen nach einmal aufrecht halten (vorher sprang es sofort zurück ins Vollbild). Tablets drehen sich überall. | Next | 🟡 Ungetestet auf Gerät | | 4.29 | Als Nutzer möchte ich einen ruhigen Übergang ins Vollbild und Shorts, deren Knöpfe das Video wenig verdecken. | Vollbild wie bei YouTube: das Video löst sich von seinem Platz, wächst und dreht sich mit dem Handy, während die App dahinter schwarz wird; erst dann dreht sich der Bildschirm unsichtbar darunter (ohne die Dreh-Animation des Systems, die das schon gedrehte Bild noch einmal drehte; Android: harter Schnitt auf Handys, die Dreh-Animation des Systems ist aus; das kurz gestreckte alte Bild liegt unter der Schwarzblende). Verlassen (Knopf, Zurück, aufrecht halten) läuft rückwärts. Auf iOS war die Drehung trotzdem zu sehen; jetzt blendet die App auf beiden Plattformen stattdessen nach Schwarz, dreht sich darunter und blendet wieder ein (0,12 s abdunkeln, warten bis das Fenster gedreht ist und zwei Bilder gemalt sind, 0,2 s aufhellen) (der bewegte Übergang bleibt im Code abschaltbar erhalten). Per Knopf im Hochformat wächst das Video ungedreht, der Bildschirm dreht sich sichtbar. Ohne Animationen (Bedienungshilfen) springt es. Shorts: während ein Short läuft, bleiben rechts nur Performer, Bewertung und O-Zähler, oben Vollbild und Ton; Später ansehen, Ganzes Video, ⋮, Mischen und Shorts-Einstellungen gleiten beim Pausieren herein. Text unten links (Studio, Performer, Titel, Tags, Wiedergaben) und der Umschalter „Shorts \| Loops“ blenden 2 s nach jedem Wischen und nach der Rückkehr in den Tab aus und erscheinen beim Pausieren wieder. Ohne Shorts und mit Screenreader ist alles sichtbar. | Next | 🟡 Ungetestet auf Gerät | | 4.30 | Als Nutzer möchte ich Marker bearbeiten und löschen. | Langes Drücken auf einen Marker im Player (Kapitel) oder im Marker-Raster (dort auch ⋮) öffnet ein Menü: im Raster Abspielen und Als Loop abspielen, dann „Marker bearbeiten“ (dasselbe Sheet wie beim Setzen, vorausgefüllt mit Titel, Haupt-Tag und Ende; gesendet wird nur, was sich geändert hat, das Ende nur bei Servern mit Endzeiten) und „Marker löschen“ (mit Rückfrage). Kapitel, Marker-Raster und -Zähler laden danach neu. Auch in der Demo. | Next | 🟡 Ungetestet auf Gerät | -| 4.31 | Als Nutzer möchte ich, dass das Video den ganzen Bildschirm füllt, ohne schwarze Balken (GitHub #58). | Der Zwei-Finger-Zoom (4.22) wächst stufenlos mit den Fingern (1–4×) und rastet kurz bei 1× (Breite bzw. Höhe füllt den Bereich) und dort ein, wo das Video den ganzen Bereich bedeckt (±7 %, mit Haptik): keine schwarzen Balken mehr, was übersteht, wird abgeschnitten. Die Position rastet in der Mitte und an den Rändern ein (14 px, senkrecht und waagerecht). Gezeichnet als Transform des Video-Bereichs (`ZoomedVideo`), die Steuerung darin wird gegengerechnet (`ZoomCounter`) und bleibt normal groß; mpvs `video-zoom` bleibt im Rechteck des Videos und ging deshalb nicht. Das Einrasten gilt für jeden Bereich neu (Vollbild, gedrehter Bildschirm) und bleibt über andere Szenen; ein Zoom darüber wird mit der Szene zurückgesetzt. Das Doppeltipp-Feedback beim Spulen (4.11) ist eine Halbscheibe mit Kreisbogen über den äußeren 30 % der angetippten Seite, der Text zum Rand hin. | Next | 🟡 Ungetestet auf Gerät | +| 4.31 | Als Nutzer möchte ich, dass das Video den ganzen Bildschirm füllt, ohne schwarze Balken (GitHub #58). | Der Zwei-Finger-Zoom (4.22) wächst stufenlos mit den Fingern (1–4×) und rastet kurz bei 1× (Breite bzw. Höhe füllt den Bereich) und dort ein, wo das Video den ganzen Bereich bedeckt (±7 %, mit Haptik): keine schwarzen Balken mehr, was übersteht, wird abgeschnitten. Die Position rastet in der Mitte und an den Rändern ein (14 px, senkrecht und waagerecht). Zum Haptik-Tick zeigt das Zoom-Label beim Einrasten „Original“ bzw. „Füllen“ in der Akzentfarbe (kurzes Aufploppen), beim Pan-Snap erscheinen dünne Hilfslinien; bei reduzierten Animationen ohne Ploppen und Blenden. Gezeichnet als Transform des Video-Bereichs (`ZoomedVideo`), die Steuerung darin wird gegengerechnet (`ZoomCounter`) und bleibt normal groß; mpvs `video-zoom` bleibt im Rechteck des Videos und ging deshalb nicht. Das Einrasten gilt für jeden Bereich neu (Vollbild, gedrehter Bildschirm) und bleibt über andere Szenen; ein Zoom darüber wird mit der Szene zurückgesetzt. Das Doppeltipp-Feedback beim Spulen (4.11) ist eine Halbscheibe mit Kreisbogen über den äußeren 30 % der angetippten Seite, der Text zum Rand hin. | Next | 🟡 Ungetestet auf Gerät | | 4.32 | Als Nutzer möchte ich Untertitel sehen, die Stash zur Szene hat (GitHub #57). | Hat die Szene Untertitel (`captions`, geladen über `paths.caption?lang=&type=`), erscheint oben im Player ein Untertitel-Knopf mit Auswahl (Aus oder je eine Sprache, bei mehreren Formaten mit Format). Die Wahl gilt als Sprache auch für die nächsten Szenen und wird dort eingeschaltet, sobald die Datei geladen ist, sofern es die Sprache gibt. Dargestellt von media_kit; mpv fügt die Datei per `sub-add` hinzu. Nicht für Cast. Die Demo hat Untertitel (en, de) für jede Szene. | Next | 🟡 Ungetestet auf Gerät | diff --git a/docs/UX_REVIEW.md b/docs/UX_REVIEW.md index 5ba64dd..d1cc6ba 100644 --- a/docs/UX_REVIEW.md +++ b/docs/UX_REVIEW.md @@ -196,7 +196,7 @@ Alle Quick Wins sind auf `feature/ux-review` umgesetzt (Phase 2, Schritt 1). | CTRL-2 | Einmalige Gesten-Tipps, in den Einstellungen erneut zeigbar | ✅ | | CTRL-3 | Touch-Sperre im Vollbild | ✅ | | PL-1 | Zu Gruppe hinzufügen, neue Gruppe | ✅ | -| SUB-1 | Abos: Favoriten-Avatare und ihr Feed (optionaler Tab, „Du“, Home) | ✅ | +| SUB-1 | Abos: Favoriten-Avatare als Auswahl („Alle“ oder ein Darsteller) und ihr Feed (optionaler Tab, „Du“, Home) | ✅ | | NOTIF-1 | „N neu seit deinem letzten Besuch“, Meldung bei fertigen Server-Aufgaben (nur in der App) | ✅ | | – | Kapitel mit Vorschaubildern, Favorit in der Kanalzeile, „In Stash öffnen“, Würfel, Seh-Diagramm, Wischen zwischen Kanal-Tabs, Bild nach unten wischen zum Schließen, Pfeiltasten in der Suche, Links öffnen | ✅ | | – | Sleep-Timer, Offline-Downloads, System-Benachrichtigungen | offen | diff --git a/lib/features/player/fullscreen_route.dart b/lib/features/player/fullscreen_route.dart index 29895d0..58d6bdc 100644 --- a/lib/features/player/fullscreen_route.dart +++ b/lib/features/player/fullscreen_route.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:media_kit_video/media_kit_video.dart'; +import '../../widgets/layout_freeze.dart'; import 'fullscreen_morph.dart'; import 'held_orientation.dart'; import 'video_zoom.dart'; @@ -105,8 +106,13 @@ Future enterPlayerFullscreen(BuildContext context, {HeldOrientation? held, ), ); _openRoute = route; + // The app behind keeps its layout while the window is turned + // (LayoutFreeze); PlayerVideo releases it once the screen has turned + // back, this only if that never comes. + shellLayoutHold.hold(); route.popped.whenComplete(() { if (_openRoute == route) _openRoute = null; + shellLayoutHold.releaseLater(const Duration(seconds: 3)); }); Navigator.of(context, rootNavigator: true).push(route); try { diff --git a/lib/features/player/player_controls.dart b/lib/features/player/player_controls.dart index 982e8f1..27df655 100644 --- a/lib/features/player/player_controls.dart +++ b/lib/features/player/player_controls.dart @@ -20,6 +20,7 @@ import '../pip/pip.dart'; import '../security/app_lock.dart'; import '../../widgets/sliver_columns.dart'; import '../../widgets/app_orientation.dart'; +import '../../widgets/layout_freeze.dart'; import 'fullscreen_morph.dart'; import 'fullscreen_route.dart'; import 'held_orientation.dart'; @@ -185,6 +186,8 @@ class _PlayerVideoState extends ConsumerState { try { await _exitFullscreen(); } finally { + // The screen has turned back: the lists behind lay out as before. + shellLayoutHold.release(); await morph?.uncover(); } return; @@ -195,7 +198,11 @@ class _PlayerVideoState extends ConsumerState { at: 1, ); try { - await _exitFullscreen(); + try { + await _exitFullscreen(); + } finally { + shellLayoutHold.release(); + } await morph?.animateTo(0); } finally { morph?.hide(); diff --git a/lib/features/player/video_controls.dart b/lib/features/player/video_controls.dart index 774af2e..a2c6456 100644 --- a/lib/features/player/video_controls.dart +++ b/lib/features/player/video_controls.dart @@ -748,22 +748,9 @@ class _StashVideoControlsState extends ConsumerState { GestureTipsOverlay(seekSeconds: seek.enabled ? seek.step.inSeconds : null, onDismiss: _dismissTips), // Always there (empty while unlocked), above the gestures and buttons. TouchLockLayer(locked: _locked && fullscreen, onUnlock: _unlock), - if (_pinching) - IgnorePointer( - child: Align( - alignment: const Alignment(0, -0.75), - child: DecoratedBox( - decoration: BoxDecoration(color: AppColors.of(context).videoScrimSoft, borderRadius: AppRadius.pillBorder), - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: AppSpacing.m, vertical: AppSpacing.xs), - child: Text( - context.l10n.speedValue(double.parse(ref.watch(videoZoomProvider).scale.toStringAsFixed(1))), - style: const TextStyle(color: Colors.white), - ), - ), - ), - ), - ), + // Always there (empty unless pinching): the scale and what it + // sticks to, beside the haptic tick. + ZoomSnapFeedback(pinching: _pinching), ], ), ); diff --git a/lib/features/player/video_zoom.dart b/lib/features/player/video_zoom.dart index 9fca3b9..aece5ea 100644 --- a/lib/features/player/video_zoom.dart +++ b/lib/features/player/video_zoom.dart @@ -3,7 +3,9 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../core/config/theme.dart'; import '../../data/models/scene.dart'; +import '../../l10n/l10n.dart'; import 'player_controls.dart' show videoAspect; import 'player_providers.dart'; @@ -49,6 +51,21 @@ class VideoZoom { bool get isZoomed => scale > 1 || fill; + /// Where the pan sticks horizontally, as a share of the box's width: 0.5 + /// the center, 0 or 1 the video's edge on the box's left or right edge; + /// null while it doesn't stick. For [ZoomSnapFeedback]'s guide lines. + double? get guideX => _guide(snapPanX, panX); + + /// The same vertically ([guideX]). + double? get guideY => _guide(snapPanY, panY); + + double? _guide(int bit, double pan) { + if ((snaps & bit) == 0) return null; + if (pan == 0) return 0.5; + // Moved right (down): the video's left (top) edge sits on the box's. + return pan > 0 ? 0 : 1; + } + /// The scale at which a video of [aspect] (width / height) covers [box]. static double coverScale(Size box, double? aspect) { if (aspect == null || aspect <= 0 || box.isEmpty) return 1; @@ -226,3 +243,136 @@ class ZoomCounter extends ConsumerWidget { ); } } + +/// What a pinch sticks to, shown over the video next to the haptic tick +/// ([VideoZoom.snaps]): while pinching, a pill with the scale that reads +/// "Original" (1×, the whole video) or "Fill" (no black bars) and turns to +/// the accent with a small pop when it sticks there; thin guide lines where +/// the pan sticks (the center, or the video's edge on the box's). Lives in +/// the controls (inside [ZoomCounter], so in the box's coordinates), always +/// in the tree and never taking touches; the video isn't touched. Without +/// animations (reduced motion) it appears and goes without fading or popping. +class ZoomSnapFeedback extends ConsumerStatefulWidget { + const ZoomSnapFeedback({super.key, required this.pinching}); + + /// Two fingers are on the video. + final bool pinching; + + static const labelKey = ValueKey('zoomLabel'); + static const guidesKey = ValueKey('zoomGuides'); + + /// How long the pill pops when the scale sticks. + static const popDuration = Duration(milliseconds: 180); + static const fadeDuration = Duration(milliseconds: 150); + + @override + ConsumerState createState() => _ZoomSnapFeedbackState(); +} + +class _ZoomSnapFeedbackState extends ConsumerState { + /// Counts the scale's new snaps: a new value restarts the pop. + int _scalePops = 0; + + @override + void initState() { + super.initState(); + ref.listenManual(videoZoomProvider, (previous, next) { + final newly = next.snaps & ~(previous?.snaps ?? 0); + if (mounted && widget.pinching && (newly & VideoZoom.snapScale) != 0) setState(() => _scalePops++); + }); + } + + @override + Widget build(BuildContext context) { + final zoom = ref.watch(videoZoomProvider); + final l = context.l10n; + final scheme = Theme.of(context).colorScheme; + final still = MediaQuery.disableAnimationsOf(context); + final pinching = widget.pinching; + final atFit = !zoom.fill && zoom.scale == 1; + final stuck = zoom.fill || atFit; + final text = zoom.fill + ? l.zoomFill + : atFit + ? l.zoomOriginal + : l.speedValue(double.parse(zoom.scale.toStringAsFixed(1))); + final guideX = pinching ? zoom.guideX : null; + final guideY = pinching ? zoom.guideY : null; + final fade = still ? Duration.zero : ZoomSnapFeedback.fadeDuration; + return IgnorePointer( + child: ExcludeSemantics( + child: Stack( + fit: StackFit.expand, + children: [ + AnimatedOpacity( + opacity: guideX != null || guideY != null ? 1 : 0, + duration: fade, + child: CustomPaint( + key: ZoomSnapFeedback.guidesKey, + painter: SnapGuidesPainter(x: guideX, y: guideY), + ), + ), + Align( + alignment: const Alignment(0, -0.75), + child: AnimatedOpacity( + opacity: pinching ? 1 : 0, + duration: fade, + child: TweenAnimationBuilder( + // A new key restarts the pop; only the pill is rebuilt. + key: ValueKey(_scalePops), + tween: Tween(begin: still || _scalePops == 0 ? 1 : 1.15, end: 1), + duration: still ? Duration.zero : ZoomSnapFeedback.popDuration, + curve: Curves.easeOutBack, + builder: (context, scale, child) => Transform.scale(scale: scale, child: child), + child: AnimatedContainer( + key: ZoomSnapFeedback.labelKey, + duration: fade, + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.m, vertical: AppSpacing.xs), + decoration: BoxDecoration( + color: stuck ? scheme.primary : AppColors.of(context).videoScrimSoft, + borderRadius: AppRadius.pillBorder, + ), + child: Text(text, style: TextStyle(color: stuck ? scheme.onPrimary : Colors.white)), + ), + ), + ), + ), + ], + ), + ), + ); + } +} + +/// Thin white lines across the box where the pan sticks ([VideoZoom.guideX], +/// [VideoZoom.guideY]), with a soft shadow so they show on bright video. +@visibleForTesting +class SnapGuidesPainter extends CustomPainter { + const SnapGuidesPainter({required this.x, required this.y}); + + final double? x; + final double? y; + + static const _width = 1.5; + + @override + void paint(Canvas canvas, Size size) { + final line = Paint() + ..color = Colors.white.withValues(alpha: 0.85) + ..strokeWidth = _width; + final shadow = Paint() + ..color = Colors.black.withValues(alpha: 0.35) + ..strokeWidth = _width * 3; + // At an edge the line sits just inside the box. + double at(double share, double extent) => (share * extent).clamp(_width, math.max(_width, extent - _width)); + final x = this.x; + final y = this.y; + for (final paint in [shadow, line]) { + if (x != null) canvas.drawLine(Offset(at(x, size.width), 0), Offset(at(x, size.width), size.height), paint); + if (y != null) canvas.drawLine(Offset(0, at(y, size.height)), Offset(size.width, at(y, size.height)), paint); + } + } + + @override + bool shouldRepaint(SnapGuidesPainter old) => old.x != x || old.y != y; +} diff --git a/lib/features/shell/app_shell.dart b/lib/features/shell/app_shell.dart index 714ffa9..dfb21b0 100644 --- a/lib/features/shell/app_shell.dart +++ b/lib/features/shell/app_shell.dart @@ -6,6 +6,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../core/config/haptics.dart'; import '../../l10n/l10n.dart'; import '../../widgets/connection_banner.dart'; +import '../../widgets/layout_freeze.dart'; import '../home/home_page.dart'; import '../library/library_page.dart'; import '../performers/performers_page.dart'; @@ -29,7 +30,7 @@ import 'shell_layout.dart'; /// Root layout after login: per-tab navigators, the miniplayer on top of /// them and a bottom navigation bar that slides away as the player expands, /// or a navigation rail on wide windows ([ShellLayout], NAV-4). -class AppShell extends ConsumerWidget { +class AppShell extends StatelessWidget { const AppShell({super.key, @visibleForTesting this.pageBuilder, @visibleForTesting this.panelBuilder}); /// Replaces [rootPage] in tests. @@ -53,6 +54,21 @@ class AppShell extends ConsumerWidget { _ => throw StateError('No page for $tab'), }; + // Behind the player's fullscreen the tabs keep their portrait layout, so + // their lists stay where they were ([LayoutFreeze]). + @override + Widget build(BuildContext context) => LayoutFreeze( + hold: shellLayoutHold, + child: _AppShellBody(pageBuilder: pageBuilder, panelBuilder: panelBuilder), + ); +} + +class _AppShellBody extends ConsumerWidget { + const _AppShellBody({required this.pageBuilder, required this.panelBuilder}); + + final Widget Function(AppTab tab)? pageBuilder; + final Widget Function(double height)? panelBuilder; + @override Widget build(BuildContext context, WidgetRef ref) { final currentTab = ref.watch(currentTabProvider); @@ -141,7 +157,7 @@ class AppShell extends ConsumerWidget { onGenerateRoute: (_) => MaterialPageRoute( builder: (_) => PrimaryScrollController( controller: scrollControllers[tab]!, - child: (pageBuilder ?? rootPage)(tab), + child: (pageBuilder ?? AppShell.rootPage)(tab), ), ), ), diff --git a/lib/features/subscriptions/subscriptions_page.dart b/lib/features/subscriptions/subscriptions_page.dart index 1c7632c..7009e88 100644 --- a/lib/features/subscriptions/subscriptions_page.dart +++ b/lib/features/subscriptions/subscriptions_page.dart @@ -16,10 +16,17 @@ import '../performers/performers_page.dart'; import '../shell/navigation.dart'; import 'last_visit.dart'; -/// Subscriptions (SUB-1): the favorite performers as a row of avatars (a -/// dot on those with scenes added since the last visit), then the newest -/// scenes of all of them. An optional tab, a tile on the "You" page and -/// home's "New from favorites" "See all". +/// Subscriptions (SUB-1), the "Favorites" tab: only performers marked as +/// favorite (Stash's `favorite` flag; star ratings play no part here). +/// +/// The avatars at the top pick whose videos show below, like a channel +/// filter: "All" (the default) lists the newest scenes of all favorites +/// ([SceneQuery.newFromFavorites], shared with home's shelf), one avatar +/// only that performer's scenes, newest first, with "View channel". The +/// avatars open the channel only on a long press, so a tap never leaves the +/// page. A dot marks performers with scenes added since the last visit. An +/// optional tab, a tile on the "You" page and home's "New from favorites" +/// "See all". class SubscriptionsPage extends ConsumerStatefulWidget { const SubscriptionsPage({super.key}); @@ -32,18 +39,38 @@ class SubscriptionsPage extends ConsumerStatefulWidget { class _SubscriptionsPageState extends ConsumerState { // The same query as home's shelf, so both share one list. - final _feed = SceneQuery.newFromFavorites(); + final _allFeed = SceneQuery.newFromFavorites(); + + /// The performer whose videos show; null: all favorites. + Performer? _selected; + + /// Kept across the feed's rebuild for another selection. + final _avatarScroll = ScrollController(); + + @override + void dispose() { + _avatarScroll.dispose(); + super.dispose(); + } void _refresh() { ref.invalidate(performerListProvider(SubscriptionsPage.favorites)); ref.invalidate(performersWithNewScenesProvider); } + /// Selects [performer] (null: all); selecting the selected one again + /// goes back to all. + void _select(Performer? performer) { + Haptics.selection(); + setState(() => _selected = performer?.id == _selected?.id ? null : performer); + } + @override Widget build(BuildContext context) { final l = context.l10n; final favorites = ref.watch(performerListProvider(SubscriptionsPage.favorites)); final none = favorites.current?.items.isEmpty ?? false; + final selected = _selected; return Scaffold( appBar: AppBar( title: Text(l.tabSubscriptions), @@ -75,20 +102,80 @@ class _SubscriptionsPageState extends ConsumerState { ), ), ) + // A feed of its own per selection: it starts at the top. : SceneFeedView( - initialQuery: _feed, + key: ValueKey(selected?.id), + initialQuery: selected == null + ? _allFeed + : SceneQuery(sort: SceneSort.recentlyAdded, performerId: selected.id), filterable: true, onRefresh: _refresh, - headerSlivers: const [SliverToBoxAdapter(child: FavoritePerformersRow())], + emptyMessage: selected == null ? null : l.subscriptionsPerformerEmpty(selected.name), + headerSlivers: [ + SliverToBoxAdapter( + child: FavoritePerformersRow( + selectedId: selected?.id, + onSelected: _select, + controller: _avatarScroll, + ), + ), + SliverToBoxAdapter(child: _SelectionHeader(performer: selected)), + ], + ), + ); + } +} + +/// What the feed below shows: all favorites, or one performer with a way +/// to their channel. +class _SelectionHeader extends ConsumerWidget { + const _SelectionHeader({required this.performer}); + + final Performer? performer; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final l = context.l10n; + final theme = Theme.of(context); + final performer = this.performer; + return Padding( + padding: const EdgeInsetsDirectional.fromSTEB(AppSpacing.l, AppSpacing.s, AppSpacing.s, 0), + child: Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: AppSpacing.s, + children: [ + Text( + performer?.name ?? l.subscriptionsLatest, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleMedium, + ), + if (performer != null) + TextButton.icon( + icon: const Icon(Icons.account_circle_outlined), + label: Text(l.subscriptionsViewChannel), + onPressed: () { + Haptics.selection(); + openPerformer(ref, performer.id); + }, ), + ], + ), ); } } -/// The favorite performers' avatars in a horizontal row; tapping one opens -/// their channel. Loads further pages as it scrolls. +/// The favorite performers' avatars in a horizontal row. With [onSelected] +/// it starts with "All", and a tap selects ([onSelected] with null for +/// "All") while a long press opens the channel; without, a tap opens the +/// channel. Loads further pages as it scrolls. class FavoritePerformersRow extends ConsumerWidget { - const FavoritePerformersRow({super.key}); + const FavoritePerformersRow({super.key, this.selectedId, this.onSelected, this.controller}); + + final String? selectedId; + final ValueChanged? onSelected; + final ScrollController? controller; static const _avatarRadius = 30.0; static const _itemWidth = 76.0; @@ -106,16 +193,28 @@ class FavoritePerformersRow extends ConsumerWidget { return ShelfSkeleton(height: height, itemWidth: _itemWidth); } final items = state.items; + final onSelected = this.onSelected; + final lead = onSelected == null ? 0 : 1; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox( height: height, child: ListView.builder( + controller: controller, scrollDirection: Axis.horizontal, padding: const EdgeInsets.symmetric(horizontal: AppSpacing.s, vertical: AppSpacing.s), - itemCount: items.length, - itemBuilder: (context, i) { + itemCount: items.length + lead, + itemBuilder: (context, index) { + if (onSelected != null && index == 0) { + return _AllAvatar( + selected: selectedId == null, + width: _itemWidth, + radius: _avatarRadius, + onTap: () => onSelected(null), + ); + } + final i = index - lead; if (i >= items.length - 4 && state.hasMore && !state.isLoadingMore && state.loadMoreError == null) { WidgetsBinding.instance.addPostFrameCallback((_) => ref.read(provider.notifier).loadMore()); } @@ -123,8 +222,10 @@ class FavoritePerformersRow extends ConsumerWidget { return _Avatar( performer: performer, hasNew: withNew.contains(performer.id), + selected: performer.id == selectedId, width: _itemWidth, radius: _avatarRadius, + onTap: onSelected == null ? null : () => onSelected(performer), ); }, ), @@ -135,29 +236,129 @@ class FavoritePerformersRow extends ConsumerWidget { } } +/// The ring (in the accent) around a selected avatar; its room is kept +/// unselected too, so selecting doesn't move anything. +class _SelectionRing extends StatelessWidget { + const _SelectionRing({required this.selected, required this.child}); + + static const width = 2.5; + static const gap = 2.0; + + final bool selected; + final Widget child; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Container( + padding: const EdgeInsets.all(gap), + decoration: BoxDecoration( + shape: BoxShape.circle, + border: Border.all(color: selected ? scheme.primary : Colors.transparent, width: width), + ), + child: child, + ); + } +} + +/// The avatar's radius inside the [_SelectionRing], so the row keeps its size. +double _innerRadius(double radius) => radius - _SelectionRing.width - _SelectionRing.gap; + +class _AllAvatar extends StatelessWidget { + const _AllAvatar({required this.selected, required this.width, required this.radius, required this.onTap}); + + final bool selected; + final double width; + final double radius; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final l = context.l10n; + final theme = Theme.of(context); + final scheme = theme.colorScheme; + return Semantics( + button: true, + selected: selected, + label: l.subscriptionsAllLabel, + excludeSemantics: true, + child: InkWell( + key: const ValueKey('favorites-all'), + borderRadius: AppRadius.cardBorder, + onTap: onTap, + child: SizedBox( + width: width, + child: Column( + children: [ + _SelectionRing( + selected: selected, + child: CircleAvatar( + radius: _innerRadius(radius), + backgroundColor: selected ? scheme.primaryContainer : scheme.surfaceContainerHighest, + foregroundColor: selected ? scheme.onPrimaryContainer : scheme.onSurfaceVariant, + child: const Icon(Icons.favorite), + ), + ), + const SizedBox(height: AppSpacing.xs), + Text( + l.subscriptionsAll, + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: theme.textTheme.labelSmall?.copyWith( + fontWeight: selected ? FontWeight.w700 : null, + color: selected ? scheme.primary : null, + ), + ), + ], + ), + ), + ), + ); + } +} + class _Avatar extends ConsumerWidget { - const _Avatar({required this.performer, required this.hasNew, required this.width, required this.radius}); + const _Avatar({ + required this.performer, + required this.hasNew, + required this.selected, + required this.width, + required this.radius, + this.onTap, + }); final Performer performer; final bool hasNew; + final bool selected; final double width; final double radius; + /// Selects the performer; null: a tap opens the channel. + final VoidCallback? onTap; + @override Widget build(BuildContext context, WidgetRef ref) { final l = context.l10n; final theme = Theme.of(context); final scheme = theme.colorScheme; + void openChannel() { + Haptics.selection(); + openPerformer(ref, performer.id); + } + + final select = onTap; return Semantics( button: true, + selected: select == null ? null : selected, label: hasNew ? l.performerHasNewScenes(performer.name) : performer.name, + hint: select == null ? null : l.subscriptionsSelectHint, excludeSemantics: true, + onLongPress: select == null ? null : openChannel, child: InkWell( - borderRadius: BorderRadius.circular(12), - onTap: () { - Haptics.selection(); - openPerformer(ref, performer.id); - }, + borderRadius: AppRadius.cardBorder, + onTap: select ?? openChannel, + onLongPress: select == null ? null : openChannel, child: SizedBox( width: width, child: Column( @@ -165,7 +366,14 @@ class _Avatar extends ConsumerWidget { Stack( clipBehavior: Clip.none, children: [ - ChannelAvatar(name: performer.name, imageUrl: performer.imageUrl, radius: radius), + _SelectionRing( + selected: selected, + child: ChannelAvatar( + name: performer.name, + imageUrl: performer.imageUrl, + radius: _innerRadius(radius), + ), + ), if (hasNew) PositionedDirectional( end: 0, @@ -190,7 +398,8 @@ class _Avatar extends ConsumerWidget { overflow: TextOverflow.ellipsis, textAlign: TextAlign.center, style: theme.textTheme.labelSmall?.copyWith( - fontWeight: hasNew ? FontWeight.w700 : null, + fontWeight: hasNew || selected ? FontWeight.w700 : null, + color: selected ? scheme.primary : null, ), ), ], diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 3b00349..2d69507 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -197,6 +197,12 @@ "subscriptionsEmpty": "Noch keine Favoriten", "subscriptionsEmptyHint": "Markiere Darsteller als Favoriten, um hier ihre neuesten Szenen zu sehen.", "performerHasNewScenes": "{name}, neue Szenen", + "subscriptionsAll": "Alle", + "subscriptionsAllLabel": "Alle Favoriten", + "subscriptionsLatest": "Neueste Videos deiner Favoriten", + "subscriptionsViewChannel": "Kanal ansehen", + "subscriptionsPerformerEmpty": "Noch keine Videos mit {name}", + "subscriptionsSelectHint": "Tippen zeigt nur ihre Videos, Halten öffnet den Kanal", "newSinceLastVisit": "{count, plural, =1{1 neues Video seit deinem letzten Besuch} other{{count} neue Videos seit deinem letzten Besuch}}", "newSinceLastVisitTitle": "Neu seit deinem letzten Besuch", "newSinceLastVisitEmpty": "Nichts Neues seit deinem letzten Besuch", @@ -564,6 +570,8 @@ "playbackSpeed": "Wiedergabetempo", "speedNormal": "Normal", "speedValue": "{rate}×", + "zoomOriginal": "Original", + "zoomFill": "Füllen", "editServer": "Server bearbeiten", "statsAndServer": "Statistik & Server", "airPlay": "AirPlay", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index d5bcf43..cd2fc69 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -508,6 +508,19 @@ } } }, + "subscriptionsAll": "All", + "subscriptionsAllLabel": "All favorites", + "subscriptionsLatest": "Newest from your favorites", + "subscriptionsViewChannel": "View channel", + "subscriptionsPerformerEmpty": "No videos with {name} yet", + "@subscriptionsPerformerEmpty": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "subscriptionsSelectHint": "Tap to show only their videos, hold to open the channel", "newSinceLastVisit": "{count, plural, =1{1 new video since your last visit} other{{count} new videos since your last visit}}", "@newSinceLastVisit": { "placeholders": { @@ -1212,6 +1225,8 @@ "unknownPerformer": "Unknown performer", "playbackSpeed": "Playback speed", "speedNormal": "Normal", + "zoomOriginal": "Original", + "zoomFill": "Fill", "speedValue": "{rate}×", "@speedValue": { "placeholders": { diff --git a/lib/l10n/gen/app_localizations.dart b/lib/l10n/gen/app_localizations.dart index 4cb81d4..feef745 100644 --- a/lib/l10n/gen/app_localizations.dart +++ b/lib/l10n/gen/app_localizations.dart @@ -1220,6 +1220,42 @@ abstract class AppLocalizations { /// **'{name}, new scenes'** String performerHasNewScenes(String name); + /// No description provided for @subscriptionsAll. + /// + /// In en, this message translates to: + /// **'All'** + String get subscriptionsAll; + + /// No description provided for @subscriptionsAllLabel. + /// + /// In en, this message translates to: + /// **'All favorites'** + String get subscriptionsAllLabel; + + /// No description provided for @subscriptionsLatest. + /// + /// In en, this message translates to: + /// **'Newest from your favorites'** + String get subscriptionsLatest; + + /// No description provided for @subscriptionsViewChannel. + /// + /// In en, this message translates to: + /// **'View channel'** + String get subscriptionsViewChannel; + + /// No description provided for @subscriptionsPerformerEmpty. + /// + /// In en, this message translates to: + /// **'No videos with {name} yet'** + String subscriptionsPerformerEmpty(String name); + + /// No description provided for @subscriptionsSelectHint. + /// + /// In en, this message translates to: + /// **'Tap to show only their videos, hold to open the channel'** + String get subscriptionsSelectHint; + /// No description provided for @newSinceLastVisit. /// /// In en, this message translates to: @@ -3296,6 +3332,18 @@ abstract class AppLocalizations { /// **'Normal'** String get speedNormal; + /// No description provided for @zoomOriginal. + /// + /// In en, this message translates to: + /// **'Original'** + String get zoomOriginal; + + /// No description provided for @zoomFill. + /// + /// In en, this message translates to: + /// **'Fill'** + String get zoomFill; + /// No description provided for @speedValue. /// /// In en, this message translates to: diff --git a/lib/l10n/gen/app_localizations_de.dart b/lib/l10n/gen/app_localizations_de.dart index f99349a..2ea0cb8 100644 --- a/lib/l10n/gen/app_localizations_de.dart +++ b/lib/l10n/gen/app_localizations_de.dart @@ -807,6 +807,27 @@ class AppLocalizationsDe extends AppLocalizations { return '$name, neue Szenen'; } + @override + String get subscriptionsAll => 'Alle'; + + @override + String get subscriptionsAllLabel => 'Alle Favoriten'; + + @override + String get subscriptionsLatest => 'Neueste Videos deiner Favoriten'; + + @override + String get subscriptionsViewChannel => 'Kanal ansehen'; + + @override + String subscriptionsPerformerEmpty(String name) { + return 'Noch keine Videos mit $name'; + } + + @override + String get subscriptionsSelectHint => + 'Tippen zeigt nur ihre Videos, Halten öffnet den Kanal'; + @override String newSinceLastVisit(int count) { String _temp0 = intl.Intl.pluralLogic( @@ -2014,6 +2035,12 @@ class AppLocalizationsDe extends AppLocalizations { @override String get speedNormal => 'Normal'; + @override + String get zoomOriginal => 'Original'; + + @override + String get zoomFill => 'Füllen'; + @override String speedValue(double rate) { final intl.NumberFormat rateNumberFormat = intl.NumberFormat.decimalPattern( diff --git a/lib/l10n/gen/app_localizations_en.dart b/lib/l10n/gen/app_localizations_en.dart index 36d5fa7..20675d2 100644 --- a/lib/l10n/gen/app_localizations_en.dart +++ b/lib/l10n/gen/app_localizations_en.dart @@ -805,6 +805,27 @@ class AppLocalizationsEn extends AppLocalizations { return '$name, new scenes'; } + @override + String get subscriptionsAll => 'All'; + + @override + String get subscriptionsAllLabel => 'All favorites'; + + @override + String get subscriptionsLatest => 'Newest from your favorites'; + + @override + String get subscriptionsViewChannel => 'View channel'; + + @override + String subscriptionsPerformerEmpty(String name) { + return 'No videos with $name yet'; + } + + @override + String get subscriptionsSelectHint => + 'Tap to show only their videos, hold to open the channel'; + @override String newSinceLastVisit(int count) { String _temp0 = intl.Intl.pluralLogic( @@ -2007,6 +2028,12 @@ class AppLocalizationsEn extends AppLocalizations { @override String get speedNormal => 'Normal'; + @override + String get zoomOriginal => 'Original'; + + @override + String get zoomFill => 'Fill'; + @override String speedValue(double rate) { final intl.NumberFormat rateNumberFormat = intl.NumberFormat.decimalPattern( diff --git a/lib/widgets/layout_freeze.dart b/lib/widgets/layout_freeze.dart new file mode 100644 index 0000000..38e3e98 --- /dev/null +++ b/lib/widgets/layout_freeze.dart @@ -0,0 +1,137 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; + +/// True while the player's fullscreen is open or the screen is still turning +/// back from it: the app behind it keeps its layout ([LayoutFreeze]). +final shellLayoutHold = LayoutHold(); + +/// A hold for [LayoutFreeze], with a fallback release that a real one +/// cancels. +class LayoutHold extends ValueNotifier { + LayoutHold() : super(false); + + Timer? _fallback; + + void hold() { + _fallback?.cancel(); + value = true; + } + + void release() { + _fallback?.cancel(); + _fallback = null; + value = false; + } + + /// Releases after [after] unless [hold] or [release] come first. + void releaseLater(Duration after) { + if (!value) return; + _fallback?.cancel(); + _fallback = Timer(after, release); + } +} + +/// Keeps [child]'s layout (its constraints and the [MediaQuery]) as it was +/// while [hold] is true, so a turn of the window it doesn't show doesn't +/// lay it out anew. +/// +/// The player's fullscreen turns a phone's window to landscape. The lists +/// behind it then got the rail and more columns (`kWideLayoutBreakpoint`), +/// became much shorter, and their scroll offset (in pixels) was clamped to +/// the new end; back in portrait the list showed items far above the one +/// that was opened. Frozen, the lists never see the landscape window. +/// +/// After [hold] goes false the layout stays frozen until the constraints are +/// back to the frozen ones (the screen has turned back), at most [settle]: +/// a tablet may stay sideways, and then gets its new layout. +/// +/// The tree is the same frozen or not, so nothing below is remounted. +class LayoutFreeze extends StatefulWidget { + const LayoutFreeze({ + super.key, + required this.hold, + required this.child, + this.settle = const Duration(milliseconds: 800), + }); + + final ValueListenable hold; + final Duration settle; + final Widget child; + + @override + State createState() => _LayoutFreezeState(); +} + +class _LayoutFreezeState extends State { + BoxConstraints? _constraints; + MediaQueryData? _data; + bool _frozen = false; + Timer? _release; + + @override + void initState() { + super.initState(); + widget.hold.addListener(_onHold); + } + + @override + void didUpdateWidget(LayoutFreeze oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.hold != widget.hold) { + oldWidget.hold.removeListener(_onHold); + widget.hold.addListener(_onHold); + _onHold(); + } + } + + @override + void dispose() { + widget.hold.removeListener(_onHold); + _release?.cancel(); + super.dispose(); + } + + void _onHold() { + if (widget.hold.value) { + _release?.cancel(); + // Nothing to keep before the first layout. + if (_constraints != null && !_frozen) setState(() => _frozen = true); + } else if (_frozen) { + _release?.cancel(); + _release = Timer(widget.settle, () { + if (mounted && !widget.hold.value) setState(() => _frozen = false); + }); + // The builder unfreezes at once when the constraints already match. + setState(() {}); + } + } + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final data = MediaQuery.of(context); + if (_frozen && !widget.hold.value && constraints == _constraints) { + _frozen = false; + _release?.cancel(); + } + if (!_frozen) { + _constraints = constraints; + _data = data; + } + final kept = _frozen ? _constraints! : constraints; + return ClipRect( + clipBehavior: _frozen ? Clip.hardEdge : Clip.none, + child: OverflowBox( + alignment: Alignment.topLeft, + minWidth: kept.minWidth, + maxWidth: kept.maxWidth, + minHeight: kept.minHeight, + maxHeight: kept.maxHeight, + child: MediaQuery(data: _frozen ? _data! : data, child: widget.child), + ), + ); + }, + ); +} diff --git a/test/features/player/seek_sequence_test.dart b/test/features/player/seek_sequence_test.dart index 00c251e..bbe5708 100644 --- a/test/features/player/seek_sequence_test.dart +++ b/test/features/player/seek_sequence_test.dart @@ -12,6 +12,7 @@ import 'package:stash_app_mobile/features/cast/cast_service.dart'; import 'package:stash_app_mobile/features/player/player_providers.dart'; import 'package:stash_app_mobile/features/player/seek_settings.dart'; import 'package:stash_app_mobile/features/player/video_controls.dart'; +import 'package:stash_app_mobile/features/player/video_zoom.dart'; import '../../helpers.dart'; import '../fake_player.dart'; @@ -107,8 +108,16 @@ void main() { if (casting) await tester.pump(); // the stream overrides deliver } + // The controls' own fade, not the zoom feedback's. bool controlsVisible(WidgetTester tester) => - tester.widget(find.byType(AnimatedOpacity).last).opacity == 1; + (find + .byType(AnimatedOpacity) + .evaluate() + .where((e) => e.findAncestorWidgetOfExactType() == null) + .last + .widget as AnimatedOpacity) + .opacity == + 1; // The half disc over the tapped side. Finder halfDisc() => find.byWidgetPredicate((w) => w is ClipPath && w.clipper.runtimeType.toString() == '_HalfDiscClipper'); diff --git a/test/features/player/zoom_snap_feedback_test.dart b/test/features/player/zoom_snap_feedback_test.dart new file mode 100644 index 0000000..709d37a --- /dev/null +++ b/test/features/player/zoom_snap_feedback_test.dart @@ -0,0 +1,105 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/features/player/video_zoom.dart'; +import 'package:stash_app_mobile/l10n/gen/app_localizations.dart'; + +void main() { + group('guide lines', () { + test('at the center, at an edge, or none', () { + expect(const VideoZoom(scale: 2, snaps: VideoZoom.snapPanX).guideX, 0.5); + expect(const VideoZoom(scale: 2, panX: 0.1, snaps: VideoZoom.snapPanX).guideX, 0, reason: 'moved right'); + expect(const VideoZoom(scale: 2, panX: -0.1, snaps: VideoZoom.snapPanX).guideX, 1); + expect(const VideoZoom(scale: 2, panY: 0.1, snaps: VideoZoom.snapPanY).guideY, 0); + expect(const VideoZoom(scale: 2, panX: 0.1).guideX, isNull, reason: 'not sticking'); + expect(const VideoZoom(scale: 2, snaps: VideoZoom.snapScale).guideY, isNull); + }); + }); + + late ProviderContainer container; + setUp(() => container = ProviderContainer()); + tearDown(() => container.dispose()); + + Future pump(WidgetTester tester, {required bool pinching, bool reducedMotion = false}) => + tester.pumpWidget(UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: MediaQuery( + data: MediaQueryData(size: const Size(400, 225), disableAnimations: reducedMotion), + child: SizedBox(width: 400, height: 225, child: ZoomSnapFeedback(pinching: pinching)), + ), + ), + )); + + double opacityAbove(WidgetTester tester, Finder finder) => + tester.widget(find.ancestor(of: finder, matching: find.byType(AnimatedOpacity)).first).opacity; + + Color pillColor(WidgetTester tester) => + (tester.widget(find.byKey(ZoomSnapFeedback.labelKey)).decoration! as BoxDecoration).color!; + + SnapGuidesPainter guides(WidgetTester tester) => + tester.widget(find.byKey(ZoomSnapFeedback.guidesKey)).painter! as SnapGuidesPainter; + + double popScale(WidgetTester tester) => tester + .widget(find.ancestor(of: find.byKey(ZoomSnapFeedback.labelKey), matching: find.byType(Transform)).first) + .transform + .getMaxScaleOnAxis(); + + testWidgets('hidden without a pinch, always in the tree', (tester) async { + await pump(tester, pinching: false); + expect(find.byKey(ZoomSnapFeedback.labelKey), findsOneWidget); + expect(opacityAbove(tester, find.byKey(ZoomSnapFeedback.labelKey)), 0); + expect(opacityAbove(tester, find.byKey(ZoomSnapFeedback.guidesKey)), 0); + }); + + testWidgets('the pill names the sizes it sticks to, in the accent', (tester) async { + await pump(tester, pinching: true); + final primary = Theme.of(tester.element(find.byType(ZoomSnapFeedback))).colorScheme.primary; + expect(find.text('Original'), findsOneWidget); + expect(pillColor(tester), primary); + + container.read(videoZoomProvider.notifier).set(const VideoZoom(scale: 1.5)); + await tester.pumpAndSettle(); + expect(find.text('1.5×'), findsOneWidget); + expect(pillColor(tester), isNot(primary)); + + container.read(videoZoomProvider.notifier).set(const VideoZoom(scale: 1.33, fill: true, snaps: VideoZoom.snapScale)); + await tester.pump(); + expect(find.text('Fill'), findsOneWidget); + expect(popScale(tester), greaterThan(1), reason: 'pops as it sticks'); + await tester.pumpAndSettle(); + expect(popScale(tester), 1); + expect(pillColor(tester), primary); + }); + + testWidgets('guide lines show while the pan sticks', (tester) async { + await pump(tester, pinching: true); + container.read(videoZoomProvider.notifier).set(const VideoZoom(scale: 2, panY: 0.1, snaps: VideoZoom.snapPanX)); + await tester.pumpAndSettle(); + expect(guides(tester).x, 0.5); + expect(guides(tester).y, isNull); + expect(opacityAbove(tester, find.byKey(ZoomSnapFeedback.guidesKey)), 1); + + container.read(videoZoomProvider.notifier).set(const VideoZoom(scale: 2, panX: 0.2, panY: 0.1)); + await tester.pumpAndSettle(); + expect(opacityAbove(tester, find.byKey(ZoomSnapFeedback.guidesKey)), 0); + }); + + testWidgets('with reduced motion nothing pops or fades', (tester) async { + await pump(tester, pinching: true, reducedMotion: true); + container.read(videoZoomProvider.notifier).set(const VideoZoom(scale: 1.5)); + await tester.pump(); + container.read(videoZoomProvider.notifier).set(const VideoZoom(scale: 1.33, fill: true, snaps: VideoZoom.snapScale)); + await tester.pump(); + expect(popScale(tester), 1); + expect(tester.widget(find.byKey(ZoomSnapFeedback.labelKey)).duration, Duration.zero); + expect( + tester.widget( + find.ancestor(of: find.byKey(ZoomSnapFeedback.guidesKey), matching: find.byType(AnimatedOpacity)).first, + ).duration, + Duration.zero, + ); + }); +} diff --git a/test/features/subscriptions_test.dart b/test/features/subscriptions_test.dart index d471434..00db174 100644 --- a/test/features/subscriptions_test.dart +++ b/test/features/subscriptions_test.dart @@ -95,6 +95,37 @@ void main() { expect(find.bySemanticsLabel('Anna, new scenes'), findsOneWidget); }); + testWidgets('an avatar shows only that performer, "All" and a second tap go back', (tester) async { + final repo = _Repo(); + await pumpPage(tester, repo); + expect(find.text('Newest from your favorites'), findsOneWidget); + expect(find.bySemanticsLabel('All favorites'), findsOneWidget); + + Future tapAndPump(Finder finder) async { + await tester.tap(finder); + for (var i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + } + + await tapAndPump(find.text('Bea').first); + expect(repo.sceneQueries.last.performerId, 'p2'); + expect(repo.sceneQueries.last.favoritePerformersOnly, isFalse); + expect(find.text('View channel'), findsOneWidget); + expect(find.text('Newest from your favorites'), findsNothing); + // A tap selects; it doesn't open the channel. + expect(find.byType(SubscriptionsPage), findsOneWidget); + + await tapAndPump(find.byKey(const ValueKey('favorites-all'))); + expect(find.text('Newest from your favorites'), findsOneWidget); + expect(find.text('View channel'), findsNothing); + + await tapAndPump(find.text('Anna').first); + expect(repo.sceneQueries.last.performerId, 'p1'); + await tapAndPump(find.text('Anna').first); + expect(find.text('Newest from your favorites'), findsOneWidget); + }); + testWidgets('no dots on the first visit', (tester) async { await pumpPage(tester, _Repo()); expect(find.text('New with Anna'), findsOneWidget); diff --git a/test/features/text_scale_test.dart b/test/features/text_scale_test.dart index ac8bd2f..058fed8 100644 --- a/test/features/text_scale_test.dart +++ b/test/features/text_scale_test.dart @@ -32,6 +32,7 @@ import 'package:stash_app_mobile/features/player/player_providers.dart'; import 'package:stash_app_mobile/features/shell/app_shell.dart'; import 'package:stash_app_mobile/features/shell/navigation.dart'; import 'package:stash_app_mobile/features/shorts/shorts_settings_sheet.dart'; +import 'package:stash_app_mobile/features/subscriptions/subscriptions_page.dart'; import 'package:stash_app_mobile/features/you/you_page.dart'; import 'package:stash_app_mobile/l10n/gen/app_localizations.dart'; import 'package:stash_app_mobile/widgets/sliver_columns.dart'; @@ -320,6 +321,17 @@ void main() { expectNoOverflow(at, 'you, scrolled'); }); + testScaled('favorites: all and one performer', (tester) async { + await pumpPage(tester, const SubscriptionsPage(), at: at); + expect(find.text(l.subscriptionsLatest), findsOneWidget); + expect(find.textContaining('A scene title'), findsWidgets); + expectNoOverflow(at, 'favorites'); + await tester.tap(find.text('Performer with a long name').first); + await settle(tester); + expect(find.text(l.subscriptionsViewChannel), findsOneWidget); + expectNoOverflow(at, 'favorites, one performer'); + }); + testScaled('performer channel', (tester) async { await pumpPage(tester, const PerformerPage(performerId: 'p1'), at: at); expect(find.text('Performer with a long name'), findsWidgets); diff --git a/test/features/video_controls_test.dart b/test/features/video_controls_test.dart index 77fdc03..8a33d57 100644 --- a/test/features/video_controls_test.dart +++ b/test/features/video_controls_test.dart @@ -82,8 +82,16 @@ void main() { )); } + // The controls' own fade, not the zoom feedback's. bool controlsVisible(WidgetTester tester) => - tester.widget(find.byType(AnimatedOpacity).last).opacity == 1; + (find + .byType(AnimatedOpacity) + .evaluate() + .where((e) => e.findAncestorWidgetOfExactType() == null) + .last + .widget as AnimatedOpacity) + .opacity == + 1; Future tapVideo(WidgetTester tester) async { // Empty space: middle row, between the left edge and the play button. diff --git a/test/widgets/layout_freeze_test.dart b/test/widgets/layout_freeze_test.dart new file mode 100644 index 0000000..eb38928 --- /dev/null +++ b/test/widgets/layout_freeze_test.dart @@ -0,0 +1,105 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/widgets/layout_freeze.dart'; +import 'package:stash_app_mobile/widgets/sliver_columns.dart'; + +/// A list like the scene feeds: one column on a phone in portrait, several +/// in landscape (SliverColumns), items of 200 px. +Widget _list(ScrollController controller, ValueListenable hold) => MaterialApp( + home: LayoutFreeze( + hold: hold, + child: Scaffold( + body: CustomScrollView( + controller: controller, + slivers: [ + SliverColumns( + itemCount: 40, + columnWidth: 300, + itemBuilder: (_, i) => SizedBox(height: 200, child: Text('item $i')), + ), + ], + ), + ), + ), + ); + +const _portrait = Size(390, 844); +const _landscape = Size(844, 390); + +void main() { + late ScrollController controller; + late ValueNotifier hold; + + setUp(() { + controller = ScrollController(); + hold = ValueNotifier(false); + }); + + tearDown(() { + controller.dispose(); + hold.dispose(); + }); + + Future setWindow(WidgetTester tester, Size size) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + await tester.pumpAndSettle(); + } + + testWidgets('without the hold, a turn to landscape loses the place in the list', (tester) async { + addTearDown(tester.view.reset); + await setWindow(tester, _portrait); + await tester.pumpWidget(_list(controller, hold)); + controller.jumpTo(30 * 200); + await tester.pumpAndSettle(); + expect(find.text('item 30'), findsOneWidget); + + // 2 columns: 20 rows, so the offset is clamped to the shorter list. + await setWindow(tester, _landscape); + await setWindow(tester, _portrait); + expect(controller.offset, lessThan(30 * 200)); + expect(find.text('item 30'), findsNothing); + }); + + testWidgets('held, the list keeps its layout and offset through the turn and back', (tester) async { + addTearDown(tester.view.reset); + await setWindow(tester, _portrait); + await tester.pumpWidget(_list(controller, hold)); + controller.jumpTo(30 * 200); + await tester.pumpAndSettle(); + + // Fullscreen opens: hold, then the window turns. + hold.value = true; + await tester.pump(); + await setWindow(tester, _landscape); + expect(controller.position.viewportDimension, _portrait.height); + expect(tester.takeException(), isNull); + + // Fullscreen closes while still sideways: stays frozen until it turned. + hold.value = false; + await tester.pump(); + expect(controller.position.viewportDimension, _portrait.height); + await setWindow(tester, _portrait); + + expect(controller.offset, 30 * 200); + expect(find.text('item 30'), findsOneWidget); + }); + + testWidgets('a window that stays turned gets its new layout after the settle time', (tester) async { + addTearDown(tester.view.reset); + await setWindow(tester, _portrait); + await tester.pumpWidget(_list(controller, hold)); + + hold.value = true; + await tester.pump(); + await setWindow(tester, _landscape); + hold.value = false; + await tester.pump(); + expect(controller.position.viewportDimension, _portrait.height); + + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + expect(controller.position.viewportDimension, _landscape.height); + }); +} From 6150597e5a99d84765d566d5e59aa26f77c464df Mon Sep 17 00:00:00 2001 From: Philippe Date: Wed, 18 Nov 2026 18:03:50 +0100 Subject: [PATCH 3/5] Let biometrics confirm PIN changes and turning the lock off With biometric unlock on, confirmPin also accepts Face ID or the fingerprint: a button on the PIN pad, or asked right away while wrong PINs block the pad. Success resets the PIN throttle. Before, a forgotten PIN could only be replaced by clearing the app's data, even though the app could still be unlocked with biometrics. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- lib/features/security/app_lock_gate.dart | 23 ++++++++- test/features/app_lock_test.dart | 64 ++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 06e5eeb..36bde6e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -101,7 +101,7 @@ lib/ **Animations.** `ConfettiBurst` (`widgets/confetti.dart`) bursts when its `trigger` changes (the favorite buttons count up when a performer becomes a favorite) and paints outside its child without taking taps. `PlayPauseIcon` morphs `AnimatedIcons.play_pause` with a small pop; use it for every play/pause button. Animations check `MediaQuery.disableAnimationsOf` and skip themselves. -**Security.** `features/security/`. `AppLockGate` in `MaterialApp.builder` shows `LockScreen` while `appLockedProvider` is true, and a `PrivacyCover` while the app is inactive (with the lock on or "hide in app switcher"). Without a delay the lock engages as the app is hidden, not on return. `LockScreen` asks for biometrics only once the app is resumed (iOS cancels a prompt while still inactive), again after the app was in the background but not after its own prompt. `confirmPin`/`showCreatePin` push full-screen routes on the root navigator, so they cover the app above the settings sheet too. `AppLockSettings.hidesApp` (lock on or "hide in app switcher"; the switch is fixed on with the lock) drives `SecureWindow`: Android's FLAG_SECURE, and on iOS `PrivacyCoverController` (AppDelegate.swift), a native cover added on `UIScene.willDeactivateNotification`, because the app is in the background before Flutter draws another frame (locking the phone showed the old content on return). Whether to cover it reads from UserDefaults itself (`flutter.lock_enabled`, `flutter.lock_hide_in_switcher`): a channel message sent at startup can arrive before the handler exists. Dart removes it (`SecureWindow.uncover`) once a frame was drawn after resuming; a 2 s fallback removes it otherwise. The PIN is stored only as a PBKDF2-HMAC-SHA256 hash (`pin_hash.dart`, `StoredPin`: `pbkdf2-sha256$$$`, `StoredPin.defaultIterations` rounds in an isolate; every value keeps its own count, so it can be raised later) under `lock_pin` in the `SecretStore`. Older versions stored `:` (`legacyHashPin`; in SharedPreferences before that, moved to the secret store at start): it is still accepted, and `verify` (async) replaces it with the PBKDF2 format after the next correct PIN. Tests run with few rounds on their own isolate (`test/flutter_test_config.dart`). A lock that is on (`lock_enabled`) stays on without its PIN (`AppLockSettings.pinLost`: secure storage unreadable or emptied, e.g. after a restore): `LockScreen` shows `PinLostView` instead of the PIN pad, where biometrics (if they were on) lead to choosing a new PIN before unlocking, and "Reset app" (`AppLockSettingsNotifier.resetApp`, confirmed inline) clears all preferences, secrets and cached images and starts over at the login. `PinThrottle` blocks the PIN pad for a growing time after 5 wrong PINs (stored, so restarts don't reset it); `LockScreen` then shows `PinBlockedView`. While locked, `AppLockGate` excludes focus and semantics, and `lockBackGuard` (registered in `main()` before `runApp`) turns back into leaving the app. The main player keeps playing (background playback, PiP); the shorts stop. Native channels: `stash/privacy` (Android `FLAG_SECURE`) and `stash/appicon` (Android activity-aliases / iOS alternate icons). On Android the launcher entries are the `activity-alias`es in `src/main/AndroidManifest.xml`. MainActivity keeps a MAIN/LAUNCHER filter there only because `flutter run` looks for it; the debug/profile/release manifests remove that filter again (`tools:node="remove"`). Android uses `FlutterFragmentActivity` and an AppCompat launch theme for `local_auth`. +**Security.** `features/security/`. `AppLockGate` in `MaterialApp.builder` shows `LockScreen` while `appLockedProvider` is true, and a `PrivacyCover` while the app is inactive (with the lock on or "hide in app switcher"). Without a delay the lock engages as the app is hidden, not on return. `LockScreen` asks for biometrics only once the app is resumed (iOS cancels a prompt while still inactive), again after the app was in the background but not after its own prompt. `confirmPin`/`showCreatePin` push full-screen routes on the root navigator, so they cover the app above the settings sheet too. With biometric unlock on, `confirmPin` (changing the PIN, turning the lock off) also accepts Face ID/fingerprint: a button on the PIN pad, or asked right away while wrong PINs block it; success resets `PinThrottle`, so a forgotten PIN can be changed by whoever can unlock. `AppLockSettings.hidesApp` (lock on or "hide in app switcher"; the switch is fixed on with the lock) drives `SecureWindow`: Android's FLAG_SECURE, and on iOS `PrivacyCoverController` (AppDelegate.swift), a native cover added on `UIScene.willDeactivateNotification`, because the app is in the background before Flutter draws another frame (locking the phone showed the old content on return). Whether to cover it reads from UserDefaults itself (`flutter.lock_enabled`, `flutter.lock_hide_in_switcher`): a channel message sent at startup can arrive before the handler exists. Dart removes it (`SecureWindow.uncover`) once a frame was drawn after resuming; a 2 s fallback removes it otherwise. The PIN is stored only as a PBKDF2-HMAC-SHA256 hash (`pin_hash.dart`, `StoredPin`: `pbkdf2-sha256$$$`, `StoredPin.defaultIterations` rounds in an isolate; every value keeps its own count, so it can be raised later) under `lock_pin` in the `SecretStore`. Older versions stored `:` (`legacyHashPin`; in SharedPreferences before that, moved to the secret store at start): it is still accepted, and `verify` (async) replaces it with the PBKDF2 format after the next correct PIN. Tests run with few rounds on their own isolate (`test/flutter_test_config.dart`). A lock that is on (`lock_enabled`) stays on without its PIN (`AppLockSettings.pinLost`: secure storage unreadable or emptied, e.g. after a restore): `LockScreen` shows `PinLostView` instead of the PIN pad, where biometrics (if they were on) lead to choosing a new PIN before unlocking, and "Reset app" (`AppLockSettingsNotifier.resetApp`, confirmed inline) clears all preferences, secrets and cached images and starts over at the login. `PinThrottle` blocks the PIN pad for a growing time after 5 wrong PINs (stored, so restarts don't reset it); `LockScreen` then shows `PinBlockedView`. While locked, `AppLockGate` excludes focus and semantics, and `lockBackGuard` (registered in `main()` before `runApp`) turns back into leaving the app. The main player keeps playing (background playback, PiP); the shorts stop. Native channels: `stash/privacy` (Android `FLAG_SECURE`) and `stash/appicon` (Android activity-aliases / iOS alternate icons). On Android the launcher entries are the `activity-alias`es in `src/main/AndroidManifest.xml`. MainActivity keeps a MAIN/LAUNCHER filter there only because `flutter run` looks for it; the debug/profile/release manifests remove that filter again (`tools:node="remove"`). Android uses `FlutterFragmentActivity` and an AppCompat launch theme for `local_auth`. **Animated previews.** Stash's looping previews, switched separately (`widgets/animated_previews.dart`, on by default; `previewsPlay` also checks reduced motion): `markerPreviewsProvider` for marker tiles (`Marker.previewUrl`), `feedPreviewsProvider` for the first fully shown video in `SceneFeedView`: `AutoPreviewScope` around the list picks it `feedPreviewDelayProvider` (0.5 s by default) after scrolling stopped, and the `AutoPreview` in `SceneThumbnail` plays `Scene.webpUrl` over the still. Scrolling stops it. Thumbnails outside a scope (the player's "Up next") never play. `previewSourceProvider` picks what the lists' previews play: by default Stash's MP4 preview (`Scene.previewUrl`), played by `PreviewVideo` in a media_kit player of its own (one at a time, hardware-decoded), or the WebP (`Scene.webpUrl`), which Flutter decodes frame by frame in software (raster jank with Stash's 640×1136 portrait previews, 3–5 MB); markers always play the WebP (small enough to run smoothly). "Only on Wi-Fi" (`previewsWifiOnlyProvider`, off by default) stops them off Wi-Fi/ethernet via `connectivity_plus` (`unmeteredConnectionProvider`). diff --git a/lib/features/security/app_lock_gate.dart b/lib/features/security/app_lock_gate.dart index 3a0c3f0..d66820e 100644 --- a/lib/features/security/app_lock_gate.dart +++ b/lib/features/security/app_lock_gate.dart @@ -440,12 +440,25 @@ Future showCreatePin(BuildContext context) { /// the whole app like the lock screen. /// /// Wrong entries count like on the lock screen; while the PIN is blocked, -/// this only says how long to wait. +/// this only says how long to wait. With biometric unlock on, Face ID or +/// the fingerprint confirm as well (the PIN pad's fingerprint button, or +/// right away while the PIN is blocked), so a forgotten PIN can still be +/// changed by whoever can unlock the app. Future confirmPin(BuildContext context, WidgetRef ref) async { final l = context.l10n; final throttle = ref.read(pinThrottleProvider.notifier); final settings = ref.read(appLockSettingsProvider.notifier); final messenger = ScaffoldMessenger.of(context); + final biometrics = ref.read(appLockSettingsProvider).biometrics; + final auth = ref.read(biometricAuthProvider); + + Future biometric() async { + if (!await auth.authenticate(l.unlockReason)) return false; + throttle.reset(); + return true; + } + + if (biometrics && throttle.remaining() > Duration.zero && await biometric()) return true; bool showBlocked() { final remaining = throttle.remaining(); @@ -456,7 +469,7 @@ Future confirmPin(BuildContext context, WidgetRef ref) async { return true; } - if (showBlocked()) return false; + if (showBlocked() || !context.mounted) return false; final ok = await Navigator.of(context, rootNavigator: true).push(_PinRoute( builder: (context) => ScreenLock( title: Text(l.enterYourPin), @@ -469,6 +482,12 @@ Future confirmPin(BuildContext context, WidgetRef ref) async { }, onUnlocked: () => Navigator.of(context).pop(true), onCancelled: () => Navigator.of(context).pop(false), + customizedButtonChild: biometrics ? Icon(Icons.fingerprint, semanticLabel: l.unlockBiometric) : null, + customizedButtonTap: biometrics + ? () async { + if (await biometric() && context.mounted) Navigator.of(context).pop(true); + } + : null, ), )); return ok ?? false; diff --git a/test/features/app_lock_test.dart b/test/features/app_lock_test.dart index 8bc72bf..c525659 100644 --- a/test/features/app_lock_test.dart +++ b/test/features/app_lock_test.dart @@ -484,6 +484,70 @@ void main() { expect(created, '2580'); }); + testWidgets('with biometrics on, Face ID or the fingerprint confirm instead of the PIN', (tester) async { + await tester.runAsync(() async { + final c = container(); + await c.read(appLockSettingsProvider.notifier).enable('1234'); + await c.read(appLockSettingsProvider.notifier).setBiometrics(true); + }); + final c = container(); + c.read(appLockedProvider.notifier).unlock(); + bool? confirmed; + await tester.pumpWidget(UncontrolledProviderScope( + container: c, + child: MaterialApp( + home: Scaffold( + body: Consumer( + builder: (context, ref, _) => TextButton( + onPressed: () async => confirmed = await confirmPin(context, ref), + child: const Text('confirm'), + ), + ), + ), + ), + )); + + await tester.tap(find.text('confirm')); + await tester.pumpAndSettle(); + expect(biometrics.calls, 0, reason: 'not asked unprompted: the PIN pad comes first'); + await tester.tap(find.byIcon(Icons.fingerprint)); + await tester.pumpAndSettle(); + expect(biometrics.calls, 1); + expect(confirmed, isTrue, reason: 'a forgotten PIN can still be changed'); + + // While wrong PINs block the pad, biometrics are asked right away. + for (var i = 0; i < PinThrottle.freeAttempts; i++) { + c.read(pinThrottleProvider.notifier).recordFailure(); + } + confirmed = null; + await tester.tap(find.text('confirm')); + await tester.pumpAndSettle(); + expect(biometrics.calls, 2); + expect(confirmed, isTrue); + expect(c.read(pinThrottleProvider).failures, 0); + }); + + testWidgets('without biometrics, the PIN pad has no fingerprint button', (tester) async { + await tester.runAsync(() => container().read(appLockSettingsProvider.notifier).enable('1234')); + final c = container(); + await tester.pumpWidget(UncontrolledProviderScope( + container: c, + child: MaterialApp( + home: Scaffold( + body: Consumer( + builder: (context, ref, _) => TextButton( + onPressed: () => confirmPin(context, ref), + child: const Text('confirm'), + ), + ), + ), + ), + )); + await tester.tap(find.text('confirm')); + await tester.pumpAndSettle(); + expect(find.byIcon(Icons.fingerprint), findsNothing); + }); + test('the app is always hidden in the switcher while the lock is on', () { expect(const AppLockSettings().hidesApp, isFalse); expect(const AppLockSettings(hideInSwitcher: true).hidesApp, isTrue); From fa1261ac4630b320bb5e5f785052c41b2b99c148 Mon Sep 17 00:00:00 2001 From: Philippe Date: Wed, 18 Nov 2026 18:08:21 +0100 Subject: [PATCH 4/5] What's new: list position, favorites, zoom feedback, safer app lock Entry 3 (entry 2 shipped with v1.0.0-beta.8) announces the changes from PR #61 and this branch: lists keep their place through fullscreen, the favorites selector, zoom snap feedback, biometrics for the PIN and the proxy warning; the PIN hash, lost-PIN recovery, URL passwords in the secure storage and fewer requests are behind "Show more". The release notes draft now describes the next beta. Co-Authored-By: Claude Opus 5.5 --- docs/RELEASE_NOTES_next.md | 30 +++++++++++++++----------- lib/features/whats_new/whats_new.dart | 17 +++++++++++++++ lib/l10n/app_de.arb | 3 +++ lib/l10n/app_en.arb | 3 +++ lib/l10n/gen/app_localizations.dart | 18 ++++++++++++++++ lib/l10n/gen/app_localizations_de.dart | 12 +++++++++++ lib/l10n/gen/app_localizations_en.dart | 12 +++++++++++ test/features/whats_new_test.dart | 15 ++++++++----- 8 files changed, 92 insertions(+), 18 deletions(-) diff --git a/docs/RELEASE_NOTES_next.md b/docs/RELEASE_NOTES_next.md index cb503d1..c5be84d 100644 --- a/docs/RELEASE_NOTES_next.md +++ b/docs/RELEASE_NOTES_next.md @@ -1,24 +1,28 @@ -# StashTube 1.0.0-beta.8 +# StashTube 1.0.0-beta.9 -Pre-release. The pipeline picks the version (next beta after `v1.0.0-beta.7`). +Pre-release. The pipeline picks the version (next beta after `v1.0.0-beta.8`). ## What's new -- **Subtitles** – pick the captions your Stash has for a video from the new button in the player's top bar. The language is remembered for the next videos. The built-in demo has English and German subtitles to try it. -- **Zoom without black bars** – spread two fingers to fill the whole screen. The zoom grows continuously (up to 4×) and snaps at the fitted size and at full width/height, the position snaps to the center and the edges, each with a light haptic tick. Works inline, in fullscreen and after turning the phone. -- **Double tap to skip** – a half disc over the tapped side (like YouTube) with the total jump, fading in and out. -- **Playback** – videos can buffer fully before playing, position and picture are kept when you return to the app, the position is saved at once, a countdown runs before the next video of a queue, and the current frame can be saved. -- **Feedback and bugs** – Settings → About opens the GitHub issue forms. +- **Back where you were** – lists keep their place when you turn the phone for fullscreen and come back to them. +- **Favorites** – the avatars at the top pick "All" or one performer (a long press opens the channel), with a header and "View channel". +- **Zoom snap feedback** – "Original" and "Fill" show when the pinch zoom snaps, and guide lines where the picture snaps to the center or an edge. +- **PIN with biometrics** – changing the PIN or turning the app lock off also accepts Face ID or the fingerprint, so a forgotten PIN can be replaced. +- **Proxy warning** – a banner names both addresses when the server hands out media URLs on another address than the one StashTube connects to (a reverse proxy without `Host` / `X-Forwarded-Proto`), and how to fix it. -## Fixes and internals +## Security -- CI: generated l10n files regenerated with the CI's Flutter version (the generated-files check failed on `develop`). -- The pinch zoom is drawn by Flutter instead of mpv (`video-zoom` stays inside the video's rectangle); the controls keep their size. +- The API key and the session cookie only go to the server's own address (scheme, host and port): never to media URLs pointing elsewhere, and not along a redirect that leaves the server. +- The PIN is stored as PBKDF2-HMAC-SHA256. PINs of earlier versions keep working and are converted after the next correct entry. +- If the PIN can't be read (e.g. after restoring a backup), the app stays locked instead of opening: biometrics lead to a new PIN, otherwise the app can be reset. +- A password in a server address (`https://user:pass@host`) is kept in the secure storage instead of the settings; existing servers move on the first start. -## Issues +## Fixes and internals -Closes #57 (subtitles) and #58 (zoom/crop). +- GraphQL responses are no longer written into a cache that was never read. +- The preview check stops after the status instead of downloading whole files from servers that ignore `Range`. +- The password login gives up after 20 s instead of waiting forever. ## Not tested on a device yet -Pinch snapping and haptics (inline, fullscreen, turning), the skip half disc, subtitles on a real server, buffering and the queue countdown. +Proxy warning on a misconfigured server, the lost-PIN screen, and upgrading a PIN set by beta.8 or earlier. diff --git a/lib/features/whats_new/whats_new.dart b/lib/features/whats_new/whats_new.dart index 076dc49..5c2f356 100644 --- a/lib/features/whats_new/whats_new.dart +++ b/lib/features/whats_new/whats_new.dart @@ -18,6 +18,23 @@ typedef ChangelogItem = ({IconData icon, String text}); /// its texts in both ARB files, one change per line, the most relevant /// first, and an icon per line. List changelog(AppLocalizations l) => [ + ( + id: 3, + title: l.whatsNew3Title, + items: _items(l.whatsNew3, const [ + Icons.format_list_bulleted, // list position + Icons.favorite_border, // favorites + Icons.zoom_out_map, // zoom snap feedback + Icons.fingerprint, // biometrics for the PIN + Icons.shield_outlined, // credentials, proxy warning + ]), + more: _items(l.whatsNew3More, const [ + Icons.lock_outline, // PIN hash + Icons.lock_reset, // lost PIN + Icons.key_outlined, // URL password + Icons.speed, // fewer requests + ]), + ), ( id: 2, title: l.whatsNew2Title, diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index fc287a0..f485f85 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -756,6 +756,9 @@ "whatsNewTitle": "Neu in StashTube", "whatsNewDone": "Verstanden", "whatsNewSubtitle": "Was die letzten Updates gebracht haben", + "whatsNew3Title": "Zurück an derselben Stelle, Favoriten und eine sicherere App-Sperre", + "whatsNew3": "Listen behalten ihre Position, wenn du das Handy für den Vollbildmodus drehst und zurückkommst.\nFavoriten: Oben „Alle“ oder einen Darsteller wählen; langes Drücken öffnet seinen Kanal.\nBeim Zoomen erscheinen „Original“ und „Füllen“, wenn es einrastet, und Hilfslinien, wo das Bild einrastet.\nPIN ändern oder die App-Sperre ausschalten geht mit Face ID oder Fingerabdruck, auch wenn du die PIN vergessen hast.\nDein API-Key und Login gehen nur an deinen Server, und eine Warnung erscheint, wenn ein Proxy falsche Medienadressen herausgibt.", + "whatsNew3More": "Die PIN wird mit einem viel langsameren Hash gespeichert; deine PIN bleibt dieselbe.\nLässt sich die PIN nach einer Wiederherstellung nicht lesen, bleibt die App gesperrt und bietet per Biometrie eine neue PIN oder das Zurücksetzen an.\nEin Passwort in einer Server-Adresse liegt im sicheren Speicher des Geräts.\nWeniger Anfragen: Listen sammeln sich nicht mehr in einem Cache, und die Vorschauprüfung lädt keine ganzen Dateien mehr.", "whatsNew2Title": "Untertitel, Zoom ohne schwarze Balken und mehr", "whatsNew2": "Untertitel: Wähle die Untertitel, die dein Stash zu einem Video hat; die Sprache gilt auch für die nächsten.\nMit zwei Fingern auf den ganzen Bildschirm ziehen, ohne schwarze Balken; es rastet bei voller Breite und in der Mitte ein, mit leichtem Tick.\nDoppeltippen zum Spulen zeigt eine Halbscheibe über der angetippten Seite, die ein- und ausblendet.\nVideos können vor dem Abspielen ganz puffern und behalten Position und Bild, wenn du in die App zurückkommst.\nEin Countdown, bevor das nächste Video der Warteschlange startet.\nDas aktuelle Bild als Foto speichern.", "whatsNew1Title": "Loops, eine neue Player-Seite und mehr", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 3867580..779ce47 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1553,6 +1553,9 @@ "whatsNewTitle": "What's new", "whatsNewDone": "Got it", "whatsNewSubtitle": "What the latest updates brought", + "whatsNew3Title": "Back where you were, favorites and a safer app lock", + "whatsNew3": "Lists keep their place when you turn the phone for fullscreen and come back.\nFavorites: pick All or one performer at the top; a long press opens their channel.\nZooming shows Original and Fill when it snaps, and guide lines where the picture snaps.\nChange the PIN or turn the app lock off with Face ID or your fingerprint, also when you forgot the PIN.\nYour API key and login only go to your server, and a warning shows when a proxy hands out wrong media addresses.", + "whatsNew3More": "The PIN is stored with a much slower hash; your PIN stays the same.\nIf the PIN can't be read after a restore, the app stays locked and offers a new PIN with biometrics, or a reset.\nA password in a server address is kept in the device's secure storage.\nFewer requests: lists no longer pile up in a cache, and the preview check no longer downloads whole files.", "whatsNew2Title": "Subtitles, zoom without black bars and more", "whatsNew2": "Subtitles: pick the captions your Stash has for a video; the language is remembered for the next ones.\nPinch to fill the whole screen without black bars; it snaps at full width and in the center, with a light tick.\nDouble tap to skip shows a half disc over the tapped side that fades in and out.\nVideos can buffer fully before they play, and keep position and picture when you come back to the app.\nA countdown before the next video of a queue starts.\nSave the current frame as an image.", "whatsNew1Title": "Loops, a new watch page and more", diff --git a/lib/l10n/gen/app_localizations.dart b/lib/l10n/gen/app_localizations.dart index 1acdd9a..f24814c 100644 --- a/lib/l10n/gen/app_localizations.dart +++ b/lib/l10n/gen/app_localizations.dart @@ -4424,6 +4424,24 @@ abstract class AppLocalizations { /// **'What the latest updates brought'** String get whatsNewSubtitle; + /// No description provided for @whatsNew3Title. + /// + /// In en, this message translates to: + /// **'Back where you were, favorites and a safer app lock'** + String get whatsNew3Title; + + /// No description provided for @whatsNew3. + /// + /// In en, this message translates to: + /// **'Lists keep their place when you turn the phone for fullscreen and come back.\nFavorites: pick All or one performer at the top; a long press opens their channel.\nZooming shows Original and Fill when it snaps, and guide lines where the picture snaps.\nChange the PIN or turn the app lock off with Face ID or your fingerprint, also when you forgot the PIN.\nYour API key and login only go to your server, and a warning shows when a proxy hands out wrong media addresses.'** + String get whatsNew3; + + /// No description provided for @whatsNew3More. + /// + /// In en, this message translates to: + /// **'The PIN is stored with a much slower hash; your PIN stays the same.\nIf the PIN can\'t be read after a restore, the app stays locked and offers a new PIN with biometrics, or a reset.\nA password in a server address is kept in the device\'s secure storage.\nFewer requests: lists no longer pile up in a cache, and the preview check no longer downloads whole files.'** + String get whatsNew3More; + /// No description provided for @whatsNew2Title. /// /// In en, this message translates to: diff --git a/lib/l10n/gen/app_localizations_de.dart b/lib/l10n/gen/app_localizations_de.dart index f317273..c141f9b 100644 --- a/lib/l10n/gen/app_localizations_de.dart +++ b/lib/l10n/gen/app_localizations_de.dart @@ -2678,6 +2678,18 @@ class AppLocalizationsDe extends AppLocalizations { @override String get whatsNewSubtitle => 'Was die letzten Updates gebracht haben'; + @override + String get whatsNew3Title => + 'Zurück an derselben Stelle, Favoriten und eine sicherere App-Sperre'; + + @override + String get whatsNew3 => + 'Listen behalten ihre Position, wenn du das Handy für den Vollbildmodus drehst und zurückkommst.\nFavoriten: Oben „Alle“ oder einen Darsteller wählen; langes Drücken öffnet seinen Kanal.\nBeim Zoomen erscheinen „Original“ und „Füllen“, wenn es einrastet, und Hilfslinien, wo das Bild einrastet.\nPIN ändern oder die App-Sperre ausschalten geht mit Face ID oder Fingerabdruck, auch wenn du die PIN vergessen hast.\nDein API-Key und Login gehen nur an deinen Server, und eine Warnung erscheint, wenn ein Proxy falsche Medienadressen herausgibt.'; + + @override + String get whatsNew3More => + 'Die PIN wird mit einem viel langsameren Hash gespeichert; deine PIN bleibt dieselbe.\nLässt sich die PIN nach einer Wiederherstellung nicht lesen, bleibt die App gesperrt und bietet per Biometrie eine neue PIN oder das Zurücksetzen an.\nEin Passwort in einer Server-Adresse liegt im sicheren Speicher des Geräts.\nWeniger Anfragen: Listen sammeln sich nicht mehr in einem Cache, und die Vorschauprüfung lädt keine ganzen Dateien mehr.'; + @override String get whatsNew2Title => 'Untertitel, Zoom ohne schwarze Balken und mehr'; diff --git a/lib/l10n/gen/app_localizations_en.dart b/lib/l10n/gen/app_localizations_en.dart index bf1cc23..9476fb4 100644 --- a/lib/l10n/gen/app_localizations_en.dart +++ b/lib/l10n/gen/app_localizations_en.dart @@ -2667,6 +2667,18 @@ class AppLocalizationsEn extends AppLocalizations { @override String get whatsNewSubtitle => 'What the latest updates brought'; + @override + String get whatsNew3Title => + 'Back where you were, favorites and a safer app lock'; + + @override + String get whatsNew3 => + 'Lists keep their place when you turn the phone for fullscreen and come back.\nFavorites: pick All or one performer at the top; a long press opens their channel.\nZooming shows Original and Fill when it snaps, and guide lines where the picture snaps.\nChange the PIN or turn the app lock off with Face ID or your fingerprint, also when you forgot the PIN.\nYour API key and login only go to your server, and a warning shows when a proxy hands out wrong media addresses.'; + + @override + String get whatsNew3More => + 'The PIN is stored with a much slower hash; your PIN stays the same.\nIf the PIN can\'t be read after a restore, the app stays locked and offers a new PIN with biometrics, or a reset.\nA password in a server address is kept in the device\'s secure storage.\nFewer requests: lists no longer pile up in a cache, and the preview check no longer downloads whole files.'; + @override String get whatsNew2Title => 'Subtitles, zoom without black bars and more'; diff --git a/test/features/whats_new_test.dart b/test/features/whats_new_test.dart index 2771c5f..8a52e80 100644 --- a/test/features/whats_new_test.dart +++ b/test/features/whats_new_test.dart @@ -61,13 +61,18 @@ void main() { testWidgets('after an update: shown once', (tester) async { final c = await pump(tester); expect(find.text(l.whatsNewTitle), findsOneWidget); - expect(find.text(l.whatsNew2Title), findsOneWidget); - expect(find.text(l.whatsNew1Title), findsNothing, reason: 'seen with an earlier release'); + expect(find.text(l.whatsNew3Title), findsOneWidget, reason: 'the newest first'); expect(find.byIcon(Icons.auto_awesome), findsNothing); - expect(find.byIcon(Icons.closed_caption_outlined), findsOneWidget, reason: 'the subtitles item has its icon'); + expect(find.byIcon(Icons.fingerprint), findsOneWidget, reason: 'the biometrics item has its icon'); final entry = changelog(l).first; - expect(entry.more, isEmpty); - expect(find.text(l.whatsNewShowMore(1)), findsNothing, reason: 'nothing behind "show more"'); + expect(entry.more, hasLength(4)); + final more = entry.more.first.text; + expect(find.text(more, skipOffstage: false), findsNothing, reason: 'the rest waits behind "show more"'); + await tester.ensureVisible(find.text(l.whatsNewShowMore(4))); + await tester.pumpAndSettle(); + await tester.tap(find.text(l.whatsNewShowMore(4))); + await tester.pumpAndSettle(); + expect(find.text(more, skipOffstage: false), findsOneWidget); expect(c.read(whatsNewSeenProvider), latestChangelogId(l)); expect(prefs.getInt('whats_new_seen'), latestChangelogId(l), reason: 'stored'); From 5fb01d06f992e8250bc9cd618460c009e7db9238 Mon Sep 17 00:00:00 2001 From: Philippe Date: Wed, 18 Nov 2026 18:22:08 +0100 Subject: [PATCH 5/5] Share the banners' layout; one helper for the PIN confirm tests StatusBanner holds the layout ConnectionBanner and MediaOriginBanner both copied, and the two confirmPin widget tests pump the same page through pumpConfirm (Codacy's duplication report on PR #62). Co-Authored-By: Claude Opus 5.5 --- lib/widgets/connection_banner.dart | 139 +++++++++++++---------------- test/features/app_lock_test.dart | 44 ++++----- 2 files changed, 82 insertions(+), 101 deletions(-) diff --git a/lib/widgets/connection_banner.dart b/lib/widgets/connection_banner.dart index e1aaf45..7983549 100644 --- a/lib/widgets/connection_banner.dart +++ b/lib/widgets/connection_banner.dart @@ -150,66 +150,27 @@ class _ConnectionBannerState extends ConsumerState { @override Widget build(BuildContext context) { final l = context.l10n; - final scheme = Theme.of(context).colorScheme; final name = ref.watch(serverProfilesProvider.select((s) => s.active?.name)); - return Semantics( + return StatusBanner( + icon: Icons.cloud_off_outlined, + title: l.connectionLostTitle, + body: name == null ? null : l.connectionLostBody(name), liveRegion: true, - container: true, - child: Material( - color: scheme.surfaceContainerHigh, - child: SafeArea( - bottom: false, - child: Padding( - padding: const EdgeInsets.fromLTRB(16, 12, 8, 4), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Padding( - padding: const EdgeInsets.only(top: 2, right: 16), - child: Icon(Icons.cloud_off_outlined, color: scheme.error), - ), - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(l.connectionLostTitle, style: Theme.of(context).textTheme.titleSmall), - if (name != null) - Text( - l.connectionLostBody(name), - style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: scheme.onSurfaceVariant), - ), - ], - ), - ), - ], - ), - OverflowBar( - alignment: MainAxisAlignment.end, - spacing: 8, - children: [ - TextButton( - onPressed: () => showServerSwitcher(context), - child: Text(l.switchServer), - ), - TextButton( - onPressed: _checking ? null : _retry, - child: _checking - ? SizedBox.square( - dimension: 18, - child: CircularProgressIndicator(strokeWidth: 2, semanticsLabel: l.retry), - ) - : Text(l.retry), - ), - ], - ), - ], - ), - ), + actions: [ + TextButton( + onPressed: () => showServerSwitcher(context), + child: Text(l.switchServer), ), - ), + TextButton( + onPressed: _checking ? null : _retry, + child: _checking + ? SizedBox.square( + dimension: 18, + child: CircularProgressIndicator(strokeWidth: 2, semanticsLabel: l.retry), + ) + : Text(l.retry), + ), + ], ); } } @@ -225,9 +186,50 @@ class MediaOriginBanner extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final l = context.l10n; + return StatusBanner( + icon: Icons.warning_amber_rounded, + title: l.mediaOriginTitle, + body: l.mediaOriginBody(mismatch.media, mismatch.server), + actions: [ + TextButton( + onPressed: () { + Haptics.light(); + ref.read(mediaOriginHintHiddenProvider.notifier).hide(mismatch); + }, + child: Text(l.mediaOriginHide), + ), + ], + ); + } +} + +/// The banners' shared layout (Material 3): an icon in the error color, +/// title and body, the actions at the end; takes the status bar's space. +class StatusBanner extends StatelessWidget { + const StatusBanner({ + super.key, + required this.icon, + required this.title, + this.body, + this.actions = const [], + this.liveRegion = false, + }); + + final IconData icon; + final String title; + final String? body; + final List actions; + + /// Announced to screen readers when it appears. + final bool liveRegion; + + @override + Widget build(BuildContext context) { final theme = Theme.of(context); final scheme = theme.colorScheme; + final body = this.body; return Semantics( + liveRegion: liveRegion, container: true, child: Material( color: scheme.surfaceContainerHigh, @@ -243,34 +245,21 @@ class MediaOriginBanner extends ConsumerWidget { children: [ Padding( padding: const EdgeInsets.only(top: 2, right: 16), - child: Icon(Icons.warning_amber_rounded, color: scheme.error), + child: Icon(icon, color: scheme.error), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(l.mediaOriginTitle, style: theme.textTheme.titleSmall), - Text( - l.mediaOriginBody(mismatch.media, mismatch.server), - style: theme.textTheme.bodyMedium?.copyWith(color: scheme.onSurfaceVariant), - ), + Text(title, style: theme.textTheme.titleSmall), + if (body != null) + Text(body, style: theme.textTheme.bodyMedium?.copyWith(color: scheme.onSurfaceVariant)), ], ), ), ], ), - OverflowBar( - alignment: MainAxisAlignment.end, - children: [ - TextButton( - onPressed: () { - Haptics.light(); - ref.read(mediaOriginHintHiddenProvider.notifier).hide(mismatch); - }, - child: Text(l.mediaOriginHide), - ), - ], - ), + OverflowBar(alignment: MainAxisAlignment.end, spacing: 8, children: actions), ], ), ), diff --git a/test/features/app_lock_test.dart b/test/features/app_lock_test.dart index c525659..ecc2a8f 100644 --- a/test/features/app_lock_test.dart +++ b/test/features/app_lock_test.dart @@ -484,6 +484,22 @@ void main() { expect(created, '2580'); }); + /// A button that asks [confirmPin] and hands its answer to [onResult]. + Future pumpConfirm(WidgetTester tester, ProviderContainer c, void Function(bool) onResult) => + tester.pumpWidget(UncontrolledProviderScope( + container: c, + child: MaterialApp( + home: Scaffold( + body: Consumer( + builder: (context, ref, _) => TextButton( + onPressed: () async => onResult(await confirmPin(context, ref)), + child: const Text('confirm'), + ), + ), + ), + ), + )); + testWidgets('with biometrics on, Face ID or the fingerprint confirm instead of the PIN', (tester) async { await tester.runAsync(() async { final c = container(); @@ -493,19 +509,7 @@ void main() { final c = container(); c.read(appLockedProvider.notifier).unlock(); bool? confirmed; - await tester.pumpWidget(UncontrolledProviderScope( - container: c, - child: MaterialApp( - home: Scaffold( - body: Consumer( - builder: (context, ref, _) => TextButton( - onPressed: () async => confirmed = await confirmPin(context, ref), - child: const Text('confirm'), - ), - ), - ), - ), - )); + await pumpConfirm(tester, c, (ok) => confirmed = ok); await tester.tap(find.text('confirm')); await tester.pumpAndSettle(); @@ -530,19 +534,7 @@ void main() { testWidgets('without biometrics, the PIN pad has no fingerprint button', (tester) async { await tester.runAsync(() => container().read(appLockSettingsProvider.notifier).enable('1234')); final c = container(); - await tester.pumpWidget(UncontrolledProviderScope( - container: c, - child: MaterialApp( - home: Scaffold( - body: Consumer( - builder: (context, ref, _) => TextButton( - onPressed: () => confirmPin(context, ref), - child: const Text('confirm'), - ), - ), - ), - ), - )); + await pumpConfirm(tester, c, (_) {}); await tester.tap(find.text('confirm')); await tester.pumpAndSettle(); expect(find.byIcon(Icons.fingerprint), findsNothing);