Compare commits

..
148 Commits
Author SHA1 Message Date
edde746 260681aa24 chore: bump version 2025-11-08 10:10:58 +01:00
edde746 6228eb2690 refactor: rewrite os media controls
# Conflicts:
#	lib/screens/video_player_screen.dart
#	lib/services/media_service_manager.dart
#	pubspec.yaml
2025-11-08 10:04:51 +01:00
edde746 0d4f7a9e9f refactor: remove duplicate audio sessions 2025-11-08 08:35:52 +01:00
edde746 fac7aed1e7 feat: shuffle settings 2025-11-07 20:50:09 +01:00
edde746 b6234120dd fix: android crash 2025-11-07 17:53:44 +01:00
edde746 2eb33eb234 fix: android icons 2025-11-07 17:44:50 +01:00
edde746 d744e783ac feat: pgs & truehd support 2025-11-07 17:24:30 +01:00
edde746 3e068b2bea chore: update lockfile 2025-11-07 02:21:23 +01:00
edde746andGitHub 36a843b43f Merge pull request #65 from ComicalHysteria/QR-code-sign-in
Add QR code generation for sign in
2025-11-07 02:19:08 +01:00
edde746 3f40007f03 feat: throttle seeking commands 2025-11-07 02:16:07 +01:00
ComicalHysteriaandGitHub 66941b06d4 Add QR code generation for sign in 2025-11-06 14:40:38 -06:00
edde746 47f5454f61 feat: os media controls 2025-11-06 15:14:40 +01:00
edde746 2a6098c3ba feat: load library in parts 2025-11-06 11:54:31 +01:00
edde746 60a84380a6 feat: external subtitle support 2025-11-06 10:36:26 +01:00
edde746 e047c820ae chore: bump version 2025-11-06 07:06:52 +01:00
edde746 e4e7911573 fix: try http connections 2025-11-06 03:58:50 +01:00
edde746 7fcf79045b Revert "ci: cache cleanup"
This reverts commit 40b3142d23.
2025-11-05 20:34:32 +01:00
edde746 40b3142d23 ci: cache cleanup 2025-11-05 20:30:54 +01:00
edde746 8f18a7c941 chore: bump dependencies 2025-11-05 20:24:20 +01:00
edde746 07b4ba371e chore: bump version 2025-11-05 20:17:03 +01:00
edde746 2571a6c38b refactor: adjust video controls button sizes 2025-11-05 20:16:12 +01:00
edde746 57b691782c feat: subtitle styling 2025-11-05 20:06:18 +01:00
edde746 eb8968c428 feat(android): dark mode icon 2025-11-05 19:33:44 +01:00
edde746 8b6052d97b feat: rotation lock 2025-11-05 16:46:31 +01:00
edde746 155ac2042e feat: audio device selector 2025-11-05 15:00:17 +01:00
edde746 1c7fccdd6b feat: persist volume 2025-11-05 14:50:13 +01:00
edde746 c15bc6d4c2 feat: subtitle delay config 2025-11-05 14:43:05 +01:00
edde746 4888d125e4 refactor: merge video controls into one sheet 2025-11-05 14:22:24 +01:00
edde746 1c8d36f0e9 feat: configurable audio delay 2025-11-05 14:15:14 +01:00
edde746 6e58f26ee4 refactor: move fullscreen button into controls 2025-11-05 14:03:30 +01:00
edde746 b30c9c6420 refactor: split up video controls 2025-11-05 13:52:21 +01:00
edde746 cef1e38f6d Merge branch 'sleep-timer-47' 2025-11-05 13:29:45 +01:00
edde746 00c02730d7 refactor(sleep timer): remove default styling 2025-11-05 13:29:32 +01:00
edde746 bb97e5a418 feat: list mode 2025-11-05 13:26:02 +01:00
edde746andGitHub d51c3ff607 Merge pull request #53 from TheLidlMan/screen-refresh-fix
fix: home refresh everytime you go back a to home page
2025-11-05 12:44:04 +01:00
Sam Matthews e500fe452d fix: when navigating back to home screen it does full screen refresh, making it feel slow now it just refreshes the continue watching tab and keeps everything else the same. 2025-11-05 11:39:29 +00:00
edde746 fd9ba46b7b fix: allow malformed utf-8 2025-11-05 12:36:09 +01:00
Sam Matthews 00da8a23e3 feat: sleep timer
- default timer values in settings
- extend timer function
- pauses playback when done and shows popup
2025-11-05 11:28:51 +00:00
edde746 0817153f4b feat: shuffle play button on media detail screen 2025-11-05 12:20:52 +01:00
edde746 c559fbf89c fix: reload libraries on refresh 2025-11-05 11:06:52 +01:00
edde746 844965e051 refactor: fix warnings 2025-11-05 11:03:35 +01:00
edde746 60ba1b1570 feat: video fill modes 2025-11-05 11:00:22 +01:00
edde746 36c6adb50c chore: bump version 2025-11-05 08:26:28 +01:00
edde746 4180ab6248 feat: log viewer 2025-11-05 08:25:28 +01:00
edde746 597640ece5 ci: remove appimage 2025-11-05 08:10:41 +01:00
edde746 4031b6043c ci: appimage fixes 2025-11-05 08:05:07 +01:00
edde746 57676178e2 ci(linux): fix missing icon 2025-11-05 07:47:26 +01:00
edde746 4430581806 ci: optimize appimage build 2025-11-05 07:42:13 +01:00
edde746 7236702818 ci: replace flatpak with appimage 2025-11-05 07:36:55 +01:00
edde746 0774263d83 feat: hero section toggle 2025-11-05 07:35:04 +01:00
edde746 6243195b21 feat: shuffle play 2025-11-05 07:28:23 +01:00
edde746 8d8423d136 refactor: move library actions to context menu 2025-11-05 07:09:58 +01:00
Sam Matthews 2f7c1084cb Add library management features: scan, refresh metadata, empty trash, and analyze #38 2025-11-04 20:10:59 +00:00
edde746 03495b1ea3 refactor: deduplicate sort widget 2025-11-04 20:49:25 +01:00
edde746andGitHub a48032c706 Merge pull request #36 from TheLidlMan/plex-recommendation-on-discover-screen-28
Plex recommendation on Home screen
2025-11-04 20:39:12 +01:00
edde746 357a4a5590 ci(flatpak): correct container 2025-11-04 20:09:05 +01:00
Sam Matthews 81adf86769 formatting issues 2025-11-04 19:00:44 +00:00
Sam Matthews 50264d52f3 Merge branch 'main' into plex-recommendation-on-discover-screen-28 2025-11-04 18:59:31 +00:00
Sam Matthews 2603a3992c - Add PlexHub model to represent recommendation sections (trending, top in genre, etc.)
- Add getLibraryHubs() and getPlaylist() API methods to PlexClient
- Display library hubs below Recently Added on Discover screen
- Filter out duplicate hubs (Continue Watching, Recently Added) that are already shown
- Add dynamic context-aware icons based on hub titles (trending, genres, ratings, etc.)
- Support 20+ hub types with matching icons: trending, popular, seasonal, genres, top rated, playlists, and more
- Support for custom collections from Kometa/Pulsarr

Implements feature request #28
2025-11-04 18:57:46 +00:00
edde746 3f95b4d822 ci(flatpak): hardcode flutter version
ts garbage
2025-11-04 19:56:14 +01:00
edde746 3b8c944512 ci(flatpak): fix 2025-11-04 19:41:21 +01:00
edde746 d646adca89 docs: update google group 2025-11-04 19:21:56 +01:00
edde746 3e7a9231b7 ci(flatpak): fix 2025-11-04 19:18:26 +01:00
edde746 dd76e59bf1 fix: properly get sorts 2025-11-04 19:09:54 +01:00
Sam Matthews bc54a2230b feat: Add support for Plex recommendation hubs on Discover screen
- Add PlexHub model to represent recommendation sections (trending, top in genre, etc.)
- Add getLibraryHubs() and getPlaylist() API methods to PlexClient
- Display library hubs below Recently Added on Discover screen
- Filter out duplicate hubs (Continue Watching, Recently Added) that are already shown
- Add dynamic context-aware icons based on hub titles (trending, genres, ratings, etc.)
- Support 20+ hub types with matching icons: trending, popular, seasonal, genres, top rated, playlists, and more
- Support for custom collections from Kometa/Pulsarr

Implements feature request #28
2025-11-04 18:04:43 +00:00
Sam Matthews 4b972b0992 feat: Add 'Latest Episode Air Date' sort option for TV show libraries
- Add conditional sort option for TV show libraries that sorts by the most recent episode's original air date
- Uses 'episode.originallyAvailableAt' field to track when the latest episode aired
- Only appears for TV show libraries, not movies or other media types
- Defaults to descending order to show recently aired episodes first
- Perfect for tracking seasonal anime/shows with new episodes

Fixes #31
2025-11-04 17:15:21 +00:00
Sam Matthews 1cab790570 fix 2025-11-04 17:09:32 +00:00
edde746 feb9254aea ci(flatpak): fix
but actually this time
2025-11-04 17:38:44 +01:00
edde746andGitHub 9a2e5e5358 Merge pull request #32 from TheLidlMan/issue-20-hide-music-libraries
Hide music libraries from app (Issue #20)
2025-11-04 17:17:00 +01:00
edde746 e260f801d6 ci(flatpak): fix 2025-11-04 17:16:13 +01:00
Sam Matthews 2ac3555567 Merge main into issue-20: Combine music filtering with library ordering 2025-11-04 16:04:31 +00:00
edde746 dafdea282e fix: library management sheet scrolling 2025-11-04 16:55:52 +01:00
edde746 aa1efdff64 ci: flatpak build 2025-11-04 16:51:14 +01:00
edde746 3d5c7f7e3b feat: update checks 2025-11-04 16:50:46 +01:00
Sam Matthews 1ec9fbcc02 Hide music libraries from app (Issue #20)
- Filter out artist-type libraries in libraries_screen.dart
- Add safety check in media_card.dart to prevent music playback attempts
- Filter music content from getOnDeck() and getRecentlyAdded() in plex_client.dart

Music libraries are now hidden throughout the app since music playback
is not yet supported. This focuses the app on video content (movies and TV shows).
2025-11-04 15:49:00 +00:00
edde746 8e00ad0551 chore: bump version 2025-11-04 14:57:34 +01:00
edde746 deadbd1be7 fix: improve subtitle selection 2025-11-04 14:51:58 +01:00
edde746 3d3358e4f9 fix: library chip alignment 2025-11-04 14:43:31 +01:00
edde746 51cb83cef9 fix: request utf-8 encoding 2025-11-04 14:29:49 +01:00
edde746 0e2fe8a9f3 fix: sort not applying after restart 2025-11-04 13:35:33 +01:00
edde746 63fa08798c ci: notarization 2025-11-04 12:15:39 +01:00
edde746 94e6c4109a ci: macOS signing 2025-11-04 11:49:41 +01:00
edde746 4dd2d7b011 chore: bump version 2025-11-04 11:01:51 +01:00
edde746 4696b5c7b0 fix: hardware decoding toggle functionality 2025-11-04 11:01:43 +01:00
edde746 852cee8967 ci: sign android build 2025-11-04 11:00:22 +01:00
edde746 2e7babaae5 ci: macOS 26 runners 2025-11-04 10:53:02 +01:00
edde746 65057750f7 feat: file version picker 2025-11-04 10:28:37 +01:00
edde746 e50bd46386 fix: limit hero dots count 2025-11-04 09:40:02 +01:00
edde746 1c67fa3998 feat: mobile double tap rewind/skip 2025-11-04 09:26:03 +01:00
edde746 d586c8c067 fix: allow connections to local only servers 2025-11-04 09:07:04 +01:00
edde746 f1a5493aeb feat: higher playback speed options
add 2.5x and 3x speed options
2025-11-04 08:52:47 +01:00
edde746 7efa96be74 fix: missing subtitles on android 2025-11-04 08:48:04 +01:00
edde746 770cb6b744 feat: customizable seek durations 2025-11-04 08:26:05 +01:00
edde746 5126b67c9c refactor: remove redundant library management in settings 2025-11-04 08:21:52 +01:00
edde746 f0035d1335 fix: seek time overflow 2025-11-04 08:02:00 +01:00
edde746 ca576110b8 Merge branch 'feature/library-reordering-6'
# Conflicts:
#	lib/screens/libraries_screen.dart
#	lib/services/storage_service.dart
2025-11-04 07:50:12 +01:00
edde746 1f59374f62 feat: library hiding 2025-11-04 07:45:24 +01:00
edde746 679e5d5c39 feat: sorting 2025-11-04 07:45:24 +01:00
edde746 73568ee3ae refactor: unify library management 2025-11-04 07:44:36 +01:00
edde746 aa9dd045de Merge branch 'main' into feature/library-reordering-6
# Conflicts:
#	lib/screens/libraries_screen.dart
#	lib/services/storage_service.dart
2025-11-04 06:56:21 +01:00
edde746andGitHub 69e7e796b4 Merge pull request #14 from TheLidlMan/fix/issue-13-poster-sizing
Fix poster sizing on home screen to match libraries view
2025-11-04 06:47:18 +01:00
edde746 95263b7625 feat: library hiding 2025-11-04 06:45:16 +01:00
Sam Matthews 236e3e7cfc Fix poster sizing on home screen to match libraries view
- Increase minimum poster width from 130px to 160px
- Adjust poster sizing to account for MediaCard padding (16px)
- Calculate poster dimensions based on actual display area
- Ensure consistent poster sizing across Home and Libraries screens

Fixes #13
2025-11-04 05:06:55 +00:00
Sam Matthews f06deba0cc feat: add library reordering functionality (#6)
- Add reorder mode toggle button in Libraries screen app bar
- Implement drag & drop reordering for library chips
- Persist library order to local storage using SharedPreferences
- Restore saved library order on app launch
- Update selected library index when libraries are reordered
- Add visual feedback with drag handle icon in reorder mode

Fixes #6
2025-11-04 04:29:26 +00:00
edde746 dcb4f3ee8a feat: sorting 2025-11-04 05:25:29 +01:00
edde746andGitHub 4246d7689d Merge pull request #11 from TheLidlMan/fix/content-rating-display
Fix content rating display to remove country prefixes
2025-11-04 04:45:10 +01:00
edde746 781aa4640e fix: support pin protected profiles 2025-11-04 04:44:22 +01:00
Sam Matthews ed668ba0e4 Fix content rating display to remove country prefixes
- Add formatContentRating utility function to strip country codes (gb/, us/, de/, etc.)
- Apply formatter in discover_screen.dart hero section
- Apply formatter in media_detail_screen.dart (badge and info row)
- Ratings now display as '12', 'PG', 'PG-13' instead of 'gb/12', 'us/PG-13'
- Fixes #10
2025-11-04 03:32:28 +00:00
edde746andGitHub fffe342dd1 Merge pull request #9 from TheLidlMan/fix/rating-display-issue-7
Fix rating display showing 0.7 instead of 7.0
2025-11-04 04:22:36 +01:00
edde746 b5349d7b3d feat: library density settings
also add season/show poster toggle for episodes
2025-11-04 04:17:39 +01:00
Sam Matthews f7d98fbe44 Fix rating display showing 0.7 instead of 7.0
Fixes #7

- Changed rating field type from int to double in PlexMetadata model
- Removed incorrect division by 10 in discover screen rating display
- Regenerated JSON serialization to properly parse rating as double
- Rating now displays correctly (e.g., 7.0 instead of 0.7)
2025-11-04 03:12:42 +00:00
edde746 3a5b812a22 refactor: slow down hero scroll 2025-11-04 02:55:44 +01:00
edde746 b01f9ce3f9 fix: crashing when scrolling large libraries 2025-11-04 02:50:39 +01:00
edde746 25ff8f1d1f feat: horizontal scroll arrows on desktop 2025-11-04 02:14:50 +01:00
edde746 ce8d384e7c feat: file info 2025-11-03 15:08:48 +01:00
edde746 bae7b70feb docs: mobile store links 2025-11-02 07:21:41 +01:00
edde746 26e7dba0d0 fix: plex track preference 2025-11-01 12:12:16 +01:00
edde746 00fe8039cc chore: bump version 2025-11-01 09:54:49 +01:00
edde746 7526e80a40 fix: make profile fields optional 2025-11-01 09:51:00 +01:00
edde746 6e1a2e0568 fix: orientation issues when exiting player 2025-11-01 09:35:58 +01:00
edde746 127500329b refactor: remove player navigation animation 2025-11-01 09:28:47 +01:00
edde746 a81cf3b18f fix: not showing selected tracks properly 2025-11-01 08:04:54 +01:00
edde746 66f00d192f fix: buffer size not working 2025-11-01 08:04:33 +01:00
edde746 ad9502d3c7 feat: fastlane & screenshot scripts 2025-11-01 08:03:47 +01:00
edde746 380a15442a ci: fix linux builds 2025-10-31 05:31:14 +01:00
edde746 5c418395b1 chore: bump version
also update screenshots
2025-10-31 05:17:30 +01:00
edde746 90ec76b661 fix: clear all data on logout 2025-10-31 05:12:52 +01:00
edde746 5f1251d82b refactor: fix warnings 2025-10-31 04:27:32 +01:00
edde746 19ab6a21b9 feat: settings page 2025-10-31 03:55:01 +01:00
edde746 e0fc990b0e refactor: back button unification 2025-10-31 00:51:45 +01:00
edde746 36b897f963 feat: profiles 2025-10-30 19:50:50 +01:00
edde746 17dba97dbb fix: no redundant search queries 2025-10-30 13:08:31 +01:00
edde746 564746d6a7 refactor: mobile hero section improvements 2025-10-30 10:29:03 +01:00
edde746 a5063a662e refactor: remove dead code 2025-10-29 14:04:39 +01:00
edde746 8d086d282c chore: update screenshots 2025-10-29 11:01:20 +01:00
edde746 bf509ee57c chore: bump version 2025-10-29 10:51:22 +01:00
edde746 823ba0beab fix: context menu overflowing 2025-10-29 10:50:08 +01:00
edde746 b310d1f169 fix: macos app bar padding issue 2025-10-29 10:49:52 +01:00
edde746 bdd39c252e feat: design improvements 2025-10-29 10:33:16 +01:00
edde746 1d29281143 fix: update watch state properly 2025-10-29 02:35:00 +01:00
edde746 12ee134191 refactor: deduplicate 2025-10-28 10:06:29 +01:00
edde746 9248fb4ddb refactor: episode navigation 2025-10-28 08:10:32 +01:00
edde746 b3696035b5 feat: playback speed controls 2025-10-28 07:59:17 +01:00
edde746 b8a5afc08f feat: keyboard video controls 2025-10-28 07:59:17 +01:00
edde746 0796f9c30d feat: screenshots 2025-10-28 07:59:17 +01:00
edde746 cebe90d39b refactor: deduplicate track controls
also fixes double click to fullscreen issues
2025-10-28 07:59:17 +01:00
edde746 abd5900290 perf(auth): better connection choice 2025-10-28 07:59:16 +01:00
edde746 67934c1f1a chore: bump version 2025-10-25 16:32:30 +02:00
139 changed files with 21324 additions and 4200 deletions
+108 -14
View File
@@ -2,9 +2,6 @@ name: Build Flutter App
on:
workflow_dispatch:
push:
tags:
- "v*"
jobs:
build-android:
@@ -50,8 +47,22 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Configure Android signing
run: |
echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" | base64 --decode > android/app/upload-keystore.jks
cat > android/key.properties << EOF
storePassword=${{ secrets.ANDROID_STORE_PASSWORD }}
keyPassword=${{ secrets.ANDROID_KEY_PASSWORD }}
keyAlias=${{ secrets.ANDROID_KEY_ALIAS }}
storeFile=upload-keystore.jks
EOF
- name: Build APK
run: flutter build apk --release
run: flutter build apk --release --dart-define=ENABLE_UPDATE_CHECK=true
- name: Clean up keystore
if: always()
run: rm -f android/app/upload-keystore.jks android/key.properties
- name: Rename APK
run: |
@@ -69,7 +80,7 @@ jobs:
path: plezy-android.apk
build-ios:
runs-on: macos-latest
runs-on: macos-26
permissions:
id-token: write
attestations: write
@@ -107,7 +118,7 @@ jobs:
run: flutter pub get
- name: Build iOS (no codesign)
run: flutter build ios --release --no-codesign
run: flutter build ios --release --no-codesign --dart-define=ENABLE_UPDATE_CHECK=true
- name: Create IPA
run: |
@@ -127,7 +138,7 @@ jobs:
path: plezy-ios.ipa
build-macos:
runs-on: macos-latest
runs-on: macos-26
permissions:
id-token: write
attestations: write
@@ -165,12 +176,88 @@ jobs:
run: flutter pub get
- name: Build macOS
run: flutter build macos --release
run: flutter build macos --release --dart-define=ENABLE_UPDATE_CHECK=true
- name: Import Code Signing Certificate
env:
MACOS_CERTIFICATE_BASE64: ${{ secrets.MACOS_CERTIFICATE_BASE64 }}
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: |
# Create temporary keychain
KEYCHAIN_PATH=$RUNNER_TEMP/build.keychain
security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
# Import certificate to keychain
CERTIFICATE_PATH=$RUNNER_TEMP/certificate.p12
echo "$MACOS_CERTIFICATE_BASE64" | base64 --decode -o $CERTIFICATE_PATH
security import $CERTIFICATE_PATH -k $KEYCHAIN_PATH -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
# Add keychain to search list
security list-keychains -d user -s $KEYCHAIN_PATH login.keychain
- name: Sign Application
env:
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
# Find the identity
IDENTITY=$(security find-identity -v -p codesigning | grep "Developer ID Application" | head -1 | grep -o '".*"' | tr -d '"')
echo "Signing with identity: $IDENTITY"
APP_PATH="build/macos/Build/Products/Release/plezy.app"
# Sign all frameworks and dylibs first (inside-out signing)
find "$APP_PATH/Contents/Frameworks" -name "*.framework" -o -name "*.dylib" | while read framework; do
echo "Signing: $framework"
codesign --force --sign "$IDENTITY" --timestamp --options runtime "$framework"
done
# Sign the app bundle itself
echo "Signing app bundle: $APP_PATH"
codesign --force --sign "$IDENTITY" --timestamp --options runtime --entitlements macos/Runner/Release.entitlements "$APP_PATH"
- name: Verify Signature
run: |
APP_PATH="build/macos/Build/Products/Release/plezy.app"
echo "Verifying signature..."
codesign -dvvv "$APP_PATH"
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
- name: Notarize Application
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: |
APP_PATH="build/macos/Build/Products/Release/plezy.app"
# Create a temporary ZIP for notarization submission
echo "Creating ZIP for notarization..."
ditto -c -k --keepParent "$APP_PATH" notarization.zip
# Submit for notarization
echo "Submitting to Apple's notary service..."
xcrun notarytool submit notarization.zip \
--apple-id "$APPLE_ID" \
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
--team-id "$APPLE_TEAM_ID" \
--wait
# Staple the notarization ticket to the app
echo "Stapling notarization ticket..."
xcrun stapler staple "$APP_PATH"
# Verify stapling
echo "Verifying notarization..."
xcrun stapler validate "$APP_PATH"
- name: Create ZIP
run: |
cd build/macos/Build/Products/Release
zip -r $GITHUB_WORKSPACE/plezy-macos.zip plezy.app
ditto -c -k --sequesterRsrc --keepParent plezy.app $GITHUB_WORKSPACE/plezy-macos.zip
- name: Attest macOS ZIP
uses: actions/attest-build-provenance@v2
@@ -211,7 +298,7 @@ jobs:
run: flutter pub get
- name: Build Windows
run: flutter build windows --release
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true
- name: Build Windows Installer
run: .\windows\build-installer.ps1
@@ -262,19 +349,19 @@ jobs:
- name: Cache APT packages
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv
packages: clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0
version: 1.0
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv
sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0
- name: Install dependencies
run: flutter pub get
- name: Build Linux
run: flutter build linux --release
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true
- name: Create Archive
run: |
@@ -293,7 +380,14 @@ jobs:
path: plezy-linux.tar.gz
create-release:
needs: [build-android, build-ios, build-macos, build-windows, build-linux]
needs:
[
build-android,
build-ios,
build-macos,
build-windows,
build-linux,
]
runs-on: ubuntu-latest
permissions:
contents: write
+11
View File
@@ -43,3 +43,14 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release
# Code duplication reports
duplication-report/
.env.*
.env
!.env.example
**/fastlane/**/
**/fastlane/report.xml
maestro/**/*.png
+21
View File
@@ -0,0 +1,21 @@
{
"threshold": 5,
"reporters": ["html", "console"],
"ignore": [
"**/*.g.dart",
"**/*.freezed.dart",
"**/*.mocks.dart",
"**/generated/**",
"**/*.config.dart"
],
"absolute": true,
"gitignore": true,
"format": ["dart"],
"minLines": 5,
"minTokens": 50,
"output": "./duplication-report",
"mode": "strict",
"formatsExts": {
"dart": ["dart"]
}
}
+14 -19
View File
@@ -1,11 +1,23 @@
# Plezy
<h1>
<img src="assets/plezy.png" alt="Plezy Logo" height="24" style="vertical-align: middle;" />
Plezy
</h1>
Plezy is a modern Plex media client that provides a seamless streaming experience across desktop and mobile platforms. Built with Flutter, it offers native performance and a clean, intuitive interface for browsing and playing your Plex media library.
<p align="center">
<img src="assets/screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
</p>
*See more screenshots in the [screenshots folder](assets/screenshots/#readme)*
## Download
### Mobile
Coming soon
<a href='https://apps.apple.com/us/app/id6754315964'><img height='60' alt='Download on the App Store' src='./assets/app-store-badge.png'/></a>
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
> Google Play version is in closed testing ([required by Google](https://support.google.com/googleplay/android-developer/answer/14151465#overview)). Join the [Google Group](https://groups.google.com/g/plezy-testers-2) to get access.
### Desktop
- [Windows (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
@@ -34,14 +46,6 @@ Coming soon
- Playback progress sync and resume functionality
- Auto-play next episode
## Platform Support
- ✅ macOS
- ✅ Windows
- ✅ Linux
- ✅ Android
- ✅ iOS
## Prerequisites
- Flutter SDK 3.8.1 or higher
@@ -71,15 +75,6 @@ dart run build_runner build
flutter run
```
## Configuration
On first launch, Plezy will guide you through:
1. Authenticating with your Plex account
2. Selecting your Plex Media Server
3. Testing connections to find the optimal one
Your credentials and preferences are securely stored locally for automatic sign-in on subsequent launches.
## Development
### Code Generation
+22
View File
@@ -3,6 +3,11 @@
<!-- Internet access permissions -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Audio service permissions -->
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<!-- Explicitly remove media permissions that media_kit may add -->
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" tools:node="remove" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" tools:node="remove" />
@@ -40,6 +45,23 @@
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<!-- Audio service -->
<service android:name="com.ryanheise.audioservice.AudioService"
android:foregroundServiceType="mediaPlayback"
android:exported="true" tools:ignore="Instantiatable">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
<!-- Media button receiver -->
<receiver android:name="com.ryanheise.audioservice.MediaButtonReceiver"
android:exported="true" tools:ignore="Instantiatable">
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
@@ -1,5 +1,5 @@
package com.edde746.plezy
import io.flutter.embedding.android.FlutterActivity
import com.ryanheise.audioservice.AudioServiceActivity
class MainActivity : FlutterActivity()
class MainActivity : AudioServiceActivity()
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 820 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

@@ -1,5 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
<foreground>
<inset
android:drawable="@drawable/ic_launcher_foreground"
android:inset="16%" />
</foreground>
<monochrome>
<inset
android:drawable="@mipmap/ic_launcher_monochrome"
android:inset="16%" />
</monochrome>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#1a1a1a</color>
</resources>
+63
View File
@@ -0,0 +1,63 @@
require 'dotenv/load'
Dotenv.load("../../.env")
default_platform(:android)
platform :android do
desc "Deploy a new version to the Google Play"
lane :deploy do
gradle(task: "clean bundleRelease")
# Get version code from pubspec.yaml
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
pubspec_content = File.read(pubspec_path)
version_match = pubspec_content.match(/version:\s*(.+)\+(\d+)/)
if version_match
version_code = version_match[2].to_i
UI.message("Using version code: #{version_code}")
else
UI.user_error!("Could not extract version code from pubspec.yaml")
end
upload_to_play_store(
version_code: version_code,
skip_upload_changelogs: true,
skip_upload_metadata: true,
skip_upload_images: true,
skip_upload_screenshots: true
)
end
desc "Build release AAB"
lane :build do
# Navigate to Flutter project root and build
sh("cd #{ENV['PWD']}/.. && flutter build appbundle")
end
desc "Build and deploy to Google Play Store"
lane :release do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build appbundle")
# Get version code from pubspec.yaml
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
pubspec_content = File.read(pubspec_path)
version_match = pubspec_content.match(/version:\s*(.+)\+(\d+)/)
if version_match
version_code = version_match[2].to_i
UI.message("Using version code: #{version_code}")
else
UI.user_error!("Could not extract version code from pubspec.yaml")
end
# Upload to Play Store
upload_to_play_store(
track: "internal",
release_status: "draft",
version_code: version_code,
aab: "../build/app/outputs/bundle/release/app-release.aab"
)
end
end
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+15
View File
@@ -0,0 +1,15 @@
## iOS
| Home | Library | Media Card | Season |
|------|---------|------------|--------|
| ![iOS Home - Content discovery and recommendations](ios-home.png) | ![iOS Library - Media collection view](ios-library.png) | ![iOS Media Card](ios-media-card.png) | ![iOS Season View](ios-season.png) |
## macOS
![macOS Home - Content discovery and recommendations](macos-home.png)
![macOS Library - Media collection view](macos-library.png)
![macOS Media Card](macos-media-card.png)
![macOS Season View](macos-season.png)
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+15 -2
View File
@@ -1,4 +1,9 @@
PODS:
- audio_service (0.0.1):
- Flutter
- FlutterMacOS
- audio_session (0.0.1):
- Flutter
- Flutter (1.0.0)
- media_kit_libs_ios_video (1.0.4):
- Flutter
@@ -23,6 +28,8 @@ PODS:
- Flutter
DEPENDENCIES:
- audio_service (from `.symlinks/plugins/audio_service/darwin`)
- audio_session (from `.symlinks/plugins/audio_session/ios`)
- Flutter (from `Flutter`)
- media_kit_libs_ios_video (from `.symlinks/plugins/media_kit_libs_ios_video/ios`)
- media_kit_video (from `.symlinks/plugins/media_kit_video/ios`)
@@ -35,6 +42,10 @@ DEPENDENCIES:
- wakelock_plus (from `.symlinks/plugins/wakelock_plus/ios`)
EXTERNAL SOURCES:
audio_service:
:path: ".symlinks/plugins/audio_service/darwin"
audio_session:
:path: ".symlinks/plugins/audio_session/ios"
Flutter:
:path: Flutter
media_kit_libs_ios_video:
@@ -57,12 +68,14 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/wakelock_plus/ios"
SPEC CHECKSUMS:
audio_service: aa99a6ba2ae7565996015322b0bb024e1d25c6fd
audio_session: 9bb7f6c970f21241b19f5a3658097ae459681ba0
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
media_kit_libs_ios_video: 5a18affdb97d1f5d466dc79988b13eff6c5e2854
media_kit_video: 1746e198cb697d1ffb734b1d05ec429d1fcd1474
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564
shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
volume_controller: 3657a1f65bedb98fa41ff7dc5793537919f31b12
+4
View File
@@ -39,6 +39,10 @@
<string>This app needs to connect to your Plex Media Server on your local network.</string>
<key>UIApplicationSupportsIndirectInputEvents</key>
<true/>
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
+49
View File
@@ -0,0 +1,49 @@
require 'dotenv/load'
Dotenv.load("../../.env")
default_platform(:ios)
platform :ios do
desc "Push a new beta build to TestFlight"
lane :beta do
build_app(workspace: "Runner.xcworkspace", scheme: "Runner")
upload_to_testflight
end
desc "Push a new release build to the App Store"
lane :release do
build_app(workspace: "Runner.xcworkspace", scheme: "Runner")
upload_to_app_store
end
desc "Build release IPA"
lane :build do
# Navigate to Flutter project root and build
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
end
desc "Build and deploy to TestFlight"
lane :deploy_testflight do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
# Upload to TestFlight
upload_to_testflight(
skip_waiting_for_build_processing: true
)
end
desc "Build and deploy to App Store"
lane :deploy_appstore do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
# Upload to App Store
upload_to_app_store(
ipa: "../build/ios/ipa/Plezy.ipa",
force: true,
submit_for_review: false,
skip_screenshots: true, # https://github.com/fastlane/fastlane/issues/29735
)
end
end
-111
View File
@@ -1,111 +0,0 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
class PlexAuth {
static const String authUrl = 'https://plex.tv/api/v2';
static const String clientsUrl = 'https://clients.plex.tv/api/v2';
final String clientIdentifier;
final String product;
PlexAuth({
required this.clientIdentifier,
this.product = 'Plex Flutter Client',
});
Map<String, String> get _headers => {
'Accept': 'application/json',
'X-Plex-Client-Identifier': clientIdentifier,
'X-Plex-Product': product,
};
/// Generate a PIN for authentication
Future<Map<String, dynamic>> generatePin({bool strong = true}) async {
final response = await http.post(
Uri.parse('$authUrl/pins?strong=$strong'),
headers: _headers,
);
if (response.statusCode == 201) {
return json.decode(response.body);
} else {
throw Exception('Failed to generate PIN: ${response.body}');
}
}
/// Check PIN status
Future<Map<String, dynamic>> checkPin(int pinId) async {
final response = await http.get(
Uri.parse('$authUrl/pins/$pinId'),
headers: _headers,
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to check PIN: ${response.body}');
}
}
/// Get auth app URL for user to authenticate
String getAuthAppUrl(String code, {String? forwardUrl}) {
final params = {
'clientID': clientIdentifier,
'code': code,
'context[device][product]': product,
if (forwardUrl != null) 'forwardUrl': forwardUrl,
};
final queryString = params.entries
.map(
(e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}',
)
.join('&');
return 'https://app.plex.tv/auth#?$queryString';
}
/// Verify token validity
Future<bool> verifyToken(String token) async {
try {
final response = await http.get(
Uri.parse('$authUrl/user'),
headers: {..._headers, 'X-Plex-Token': token},
);
return response.statusCode == 200;
} catch (e) {
return false;
}
}
/// Get user info
Future<Map<String, dynamic>> getUserInfo(String token) async {
final response = await http.get(
Uri.parse('$authUrl/user'),
headers: {..._headers, 'X-Plex-Token': token},
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to get user info: ${response.body}');
}
}
/// Get available resources (servers)
Future<List<dynamic>> getResources(String token) async {
final response = await http.get(
Uri.parse(
'$clientsUrl/resources?includeHttps=1&includeRelay=1&includeIPv6=1',
),
headers: {..._headers, 'X-Plex-Token': token},
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to get resources: ${response.body}');
}
}
}
File diff suppressed because it is too large Load Diff
+1
View File
@@ -51,6 +51,7 @@ class PlexConfig {
'X-Plex-Platform': platform,
if (device != null) 'X-Plex-Device': device!,
if (acceptJson) 'Accept': 'application/json',
'Accept-Charset': 'utf-8',
};
if (token != null) {
+183 -102
View File
@@ -1,23 +1,36 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:io' show Platform;
import 'package:media_kit/media_kit.dart';
import 'package:window_manager/window_manager.dart';
import 'client/plex_client.dart';
import 'config/plex_config.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'screens/main_screen.dart';
import 'screens/auth_screen.dart';
import 'services/storage_service.dart';
import 'services/plex_auth_service.dart';
import 'services/server_connection_service.dart';
import 'services/macos_titlebar_service.dart';
import 'services/fullscreen_state_manager.dart';
import 'models/plex_user_profile.dart';
import 'services/update_service.dart';
import 'services/settings_service.dart';
import 'providers/user_profile_provider.dart';
import 'providers/plex_client_provider.dart';
import 'providers/theme_provider.dart';
import 'providers/settings_provider.dart';
import 'providers/hidden_libraries_provider.dart';
import 'providers/playback_state_provider.dart';
import 'utils/language_codes.dart';
import 'utils/app_logger.dart';
import 'utils/provider_extensions.dart';
import 'utils/orientation_helper.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Configure image cache for large libraries
PaintingBinding.instance.imageCache.maximumSizeBytes = 500 << 20; // 500MB
PaintingBinding.instance.imageCache.maximumSize = 500; // 500 images
// Initialize window_manager for desktop platforms
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
await windowManager.ensureInitialized();
@@ -29,17 +42,18 @@ void main() async {
// Initialize MediaKit
MediaKit.ensureInitialized();
// Lock orientation to portrait for all screens except video player
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
// Note: Orientation will be set dynamically based on device type in MainApp
await StorageService.getInstance();
// Initialize language codes for track selection
await LanguageCodes.initialize();
// Initialize logger level based on debug setting
final settings = await SettingsService.getInstance();
final debugEnabled = settings.getEnableDebugLogging();
setLoggerLevel(debugEnabled);
// Start global fullscreen state monitoring
FullscreenStateManager().startMonitoring();
@@ -56,20 +70,58 @@ class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Plezy',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
useMaterial3: true,
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => PlexClientProvider()),
ChangeNotifierProvider(
create: (context) => UserProfileProvider()..initialize(),
),
ChangeNotifierProvider(create: (context) => ThemeProvider()),
ChangeNotifierProvider(create: (context) => SettingsProvider()),
ChangeNotifierProvider(create: (context) => HiddenLibrariesProvider()),
ChangeNotifierProvider(create: (context) => PlaybackStateProvider()),
],
child: Consumer<ThemeProvider>(
builder: (context, themeProvider, child) {
return MaterialApp(
title: 'Plezy',
debugShowCheckedModeBanner: false,
theme: themeProvider.lightTheme,
darkTheme: themeProvider.darkTheme,
themeMode: themeProvider.materialThemeMode,
navigatorObservers: [routeObserver],
home: const OrientationAwareSetup(),
);
},
),
darkTheme: ThemeData.dark(useMaterial3: true),
navigatorObservers: [routeObserver],
home: const SetupScreen(),
);
}
}
class OrientationAwareSetup extends StatefulWidget {
const OrientationAwareSetup({super.key});
@override
State<OrientationAwareSetup> createState() => _OrientationAwareSetupState();
}
class _OrientationAwareSetupState extends State<OrientationAwareSetup> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
_setOrientationPreferences();
}
void _setOrientationPreferences() {
OrientationHelper.restoreDefaultOrientations(context);
}
@override
Widget build(BuildContext context) {
return const SetupScreen();
}
}
class SetupScreen extends StatefulWidget {
const SetupScreen({super.key});
@@ -84,6 +136,78 @@ class _SetupScreenState extends State<SetupScreen> {
_loadSavedCredentials();
}
void _checkForUpdatesOnStartup() async {
// Delay slightly to allow UI to settle
await Future.delayed(const Duration(milliseconds: 500));
if (!mounted) return;
try {
final updateInfo = await UpdateService.checkForUpdatesOnStartup();
if (updateInfo != null && updateInfo['hasUpdate'] == true && mounted) {
_showUpdateDialog(updateInfo);
}
} catch (e) {
appLogger.e('Error checking for updates', error: e);
}
}
void _showUpdateDialog(Map<String, dynamic> updateInfo) {
showDialog(
context: context,
builder: (BuildContext dialogContext) {
return AlertDialog(
title: const Text('Update Available'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Version ${updateInfo['latestVersion']} is available',
style: Theme.of(dialogContext).textTheme.titleMedium,
),
const SizedBox(height: 8),
Text(
'Current: ${updateInfo['currentVersion']}',
style: Theme.of(dialogContext).textTheme.bodySmall,
),
],
),
actions: [
TextButton(
onPressed: () {
Navigator.pop(dialogContext);
},
child: const Text('Later'),
),
TextButton(
onPressed: () async {
await UpdateService.skipVersion(updateInfo['latestVersion']);
if (dialogContext.mounted) {
Navigator.pop(dialogContext);
}
},
child: const Text('Skip This Version'),
),
FilledButton(
onPressed: () async {
final url = Uri.parse(updateInfo['releaseUrl']);
if (await canLaunchUrl(url)) {
await launchUrl(url, mode: LaunchMode.externalApplication);
}
if (dialogContext.mounted) {
Navigator.pop(dialogContext);
}
},
child: const Text('View Release'),
),
],
);
},
);
}
Future<void> _loadSavedCredentials() async {
final storage = await StorageService.getInstance();
@@ -92,57 +216,70 @@ class _SetupScreenState extends State<SetupScreen> {
final clientId = storage.getClientIdentifier();
final plexToken = storage.getPlexToken();
// Get current user's server token (prioritize over original server token)
final currentUserToken = storage.getToken();
if (serverData != null && clientId != null) {
try {
// Recreate PlexServer from stored data
final server = PlexServer.fromJson(serverData);
// Test connections to find best working one
final connection = await server.findBestWorkingConnection();
// Use current user's token if available, fallback to server's original token
final tokenToUse = currentUserToken ?? server.accessToken;
if (connection != null) {
// Update stored server URL with working connection
await storage.saveServerUrl(connection.uri);
appLogger.d(
'App startup token selection: currentUserToken=${currentUserToken != null ? 'present' : 'null'}, using=${currentUserToken != null ? 'current user' : 'original server'} token',
);
// Create client with working connection
final config = await PlexConfig.create(
baseUrl: connection.uri,
token: server.accessToken,
clientIdentifier: clientId,
);
final client = PlexClient(config);
// Create updated server with correct token for current user
final serverWithCurrentToken = PlexServer(
name: server.name,
clientIdentifier: server.clientIdentifier,
accessToken: tokenToUse,
connections: server.connections,
owned: server.owned,
product: server.product,
platform: server.platform,
lastSeenAt: server.lastSeenAt,
presence: server.presence,
);
// Verify server is accessible
try {
await client.getServerIdentity();
// Connect using the optimized service with current user's token
final result = await ServerConnectionService.connectToServer(
serverWithCurrentToken,
clientIdentifier: clientId,
verifyServer: true,
fetchUserProfile: plexToken != null,
plexToken: plexToken,
);
// Fetch and cache user profile if we have a plex token
PlexUserProfile? userProfile;
if (plexToken != null) {
userProfile = await _fetchAndCacheUserProfile(plexToken);
}
// Handle result
if (result.isSuccess) {
// Success! Set client in provider
if (mounted) {
context.plexClient.setClient(result.client!);
// Success! Navigate to main screen
// Check for updates BEFORE navigation to keep context valid
_checkForUpdatesOnStartup();
// Navigate to main screen after update check is initiated
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) =>
MainScreen(client: client, userProfile: userProfile),
builder: (context) => MainScreen(client: result.client!),
),
);
return;
}
} catch (e) {
// Server identity check failed
await storage.clearCredentials();
}
return;
} else {
// No working connections found
// Connection failed, clear credentials
await storage.clearCredentials();
}
} catch (e) {
// Error loading or testing server
appLogger.e('Error during auto-login', error: e);
await storage.clearCredentials();
}
}
@@ -156,62 +293,6 @@ class _SetupScreenState extends State<SetupScreen> {
}
}
Future<PlexUserProfile?> _fetchAndCacheUserProfile(String plexToken) async {
appLogger.d('Fetching user profile from Plex API');
try {
final authService = await PlexAuthService.create();
final profile = await authService.getUserProfile(plexToken);
appLogger.i(
'Successfully fetched user profile',
error: {
'autoSelectAudio': profile.autoSelectAudio,
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
'autoSelectSubtitle': profile.autoSelectSubtitle,
'defaultSubtitleLanguage':
profile.defaultSubtitleLanguage ?? 'not set',
'defaultSubtitleForced': profile.defaultSubtitleForced,
},
);
// Cache the profile
final storage = await StorageService.getInstance();
await storage.saveUserProfile(profile.toJson());
appLogger.d('User profile cached locally');
return profile;
} catch (e) {
appLogger.w(
'Failed to fetch user profile from API, attempting to load from cache',
error: e,
);
// Failed to fetch profile, try to load from cache
final storage = await StorageService.getInstance();
final cachedProfile = storage.getUserProfile();
if (cachedProfile != null) {
final profile = PlexUserProfile.fromJson(cachedProfile);
appLogger.i(
'Loaded user profile from cache',
error: {
'autoSelectAudio': profile.autoSelectAudio,
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
'autoSelectSubtitle': profile.autoSelectSubtitle,
'defaultSubtitleLanguage':
profile.defaultSubtitleLanguage ?? 'not set',
'defaultSubtitleForced': profile.defaultSubtitleForced,
},
);
return profile;
}
appLogger.w(
'No cached user profile available, track selection will use defaults',
);
return null;
}
}
@override
Widget build(BuildContext context) {
return const Scaffold(
+51
View File
@@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
/// Mixin for screens that need to update individual items after watch state changes
///
/// This provides a standard implementation for fetching updated metadata
/// and replacing items in lists, while allowing each screen to customize
/// which lists should be updated.
mixin ItemUpdatable<T extends StatefulWidget> on State<T> {
/// The Plex client to use for fetching updated metadata
/// Each screen must provide access to their client
PlexClient get client;
/// Updates a single item in the screen's list(s) after watch state changes
///
/// Fetches the latest metadata with images (including clearLogo) and
/// calls [updateItemInLists] to update the appropriate list(s).
///
/// If the fetch fails, the error is silently caught and the item will
/// be updated on the next full refresh.
Future<void> updateItem(String ratingKey) async {
try {
final updatedMetadata = await client.getMetadataWithImages(ratingKey);
if (updatedMetadata != null) {
setState(() {
updateItemInLists(ratingKey, updatedMetadata);
});
}
} catch (e) {
// Silently fail - the item will update on next full refresh
}
}
/// Override this method to specify which list(s) should be updated
///
/// This method is called within [setState], so you should directly
/// modify your list(s) without calling setState again.
///
/// Example:
/// ```dart
/// @override
/// void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
/// final index = _items.indexWhere((item) => item.ratingKey == ratingKey);
/// if (index != -1) {
/// _items[index] = updatedMetadata;
/// }
/// }
/// ```
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata);
}
+151
View File
@@ -0,0 +1,151 @@
class PlexFileInfo {
// Media level properties
final String? container;
final String? videoCodec;
final String? videoResolution;
final String? videoFrameRate;
final String? videoProfile;
final int? width;
final int? height;
final double? aspectRatio;
final int? bitrate;
final int? duration;
final String? audioCodec;
final String? audioProfile;
final int? audioChannels;
final bool? optimizedForStreaming;
final bool? has64bitOffsets;
// Part level properties (file)
final String? filePath;
final int? fileSize;
// Stream level properties (video stream details)
final String? colorSpace;
final String? colorRange;
final String? colorPrimaries;
final String? colorTrc;
final String? chromaSubsampling;
final double? frameRate;
final int? bitDepth;
final String? audioChannelLayout;
PlexFileInfo({
this.container,
this.videoCodec,
this.videoResolution,
this.videoFrameRate,
this.videoProfile,
this.width,
this.height,
this.aspectRatio,
this.bitrate,
this.duration,
this.audioCodec,
this.audioProfile,
this.audioChannels,
this.optimizedForStreaming,
this.has64bitOffsets,
this.filePath,
this.fileSize,
this.colorSpace,
this.colorRange,
this.colorPrimaries,
this.colorTrc,
this.chromaSubsampling,
this.frameRate,
this.bitDepth,
this.audioChannelLayout,
});
/// Format file size in human-readable format (GB, MB, KB, bytes)
String get fileSizeFormatted {
if (fileSize == null) return 'Unknown';
const kb = 1024;
const mb = kb * 1024;
const gb = mb * 1024;
if (fileSize! >= gb) {
return '${(fileSize! / gb).toStringAsFixed(2)} GB';
} else if (fileSize! >= mb) {
return '${(fileSize! / mb).toStringAsFixed(2)} MB';
} else if (fileSize! >= kb) {
return '${(fileSize! / kb).toStringAsFixed(2)} KB';
} else {
return '$fileSize bytes';
}
}
/// Format duration in HH:MM:SS or MM:SS format
String get durationFormatted {
if (duration == null) return 'Unknown';
final seconds = duration! ~/ 1000;
final hours = seconds ~/ 3600;
final minutes = (seconds % 3600) ~/ 60;
final secs = seconds % 60;
if (hours > 0) {
return '${hours}h ${minutes}m ${secs}s';
} else {
return '${minutes}m ${secs}s';
}
}
/// Format bitrate in Mbps or Kbps
String get bitrateFormatted {
if (bitrate == null) return 'Unknown';
const kbps = 1000;
const mbps = kbps * 1000;
if (bitrate! >= mbps) {
return '${(bitrate! / mbps).toStringAsFixed(2)} Mbps';
} else if (bitrate! >= kbps) {
return '${(bitrate! / kbps).toStringAsFixed(2)} Kbps';
} else {
return '$bitrate bps';
}
}
/// Format resolution as widthxheight
String get resolutionFormatted {
if (width != null && height != null) {
return '${width}x$height';
} else if (videoResolution != null) {
return videoResolution!;
}
return 'Unknown';
}
/// Format aspect ratio
String get aspectRatioFormatted {
if (aspectRatio != null) {
return aspectRatio!.toStringAsFixed(2);
}
return 'Unknown';
}
/// Format frame rate
String get frameRateFormatted {
if (frameRate != null) {
return '${frameRate!.toStringAsFixed(3)} fps';
} else if (videoFrameRate != null) {
return videoFrameRate!;
}
return 'Unknown';
}
/// Format audio channels (e.g., "2 channels (stereo)")
String get audioChannelsFormatted {
if (audioChannels != null) {
String channelText = '$audioChannels channel${audioChannels! > 1 ? 's' : ''}';
if (audioChannelLayout != null) {
channelText += ' ($audioChannelLayout)';
}
return channelText;
}
return 'Unknown';
}
}
+70
View File
@@ -0,0 +1,70 @@
import 'plex_home_user.dart';
class PlexHome {
final int id;
final String name;
final int? guestUserID;
final String guestUserUUID;
final bool guestEnabled;
final bool subscription;
final List<PlexHomeUser> users;
PlexHome({
required this.id,
required this.name,
required this.guestUserID,
required this.guestUserUUID,
required this.guestEnabled,
required this.subscription,
required this.users,
});
factory PlexHome.fromJson(Map<String, dynamic> json) {
final List<dynamic> usersJson = json['users'] as List<dynamic>;
final users = usersJson
.map(
(userJson) => PlexHomeUser.fromJson(userJson as Map<String, dynamic>),
)
.toList();
return PlexHome(
id: (json['id'] as num?)?.toInt() ?? 0,
name: json['name'] as String,
guestUserID: (json['guestUserID'] as num?)?.toInt(),
guestUserUUID: json['guestUserUUID'] as String,
guestEnabled: json['guestEnabled'] as bool,
subscription: json['subscription'] as bool,
users: users,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'guestUserID': guestUserID,
'guestUserUUID': guestUserUUID,
'guestEnabled': guestEnabled,
'subscription': subscription,
'users': users.map((user) => user.toJson()).toList(),
};
}
PlexHomeUser? get adminUser => users.where((user) => user.admin).firstOrNull;
List<PlexHomeUser> get managedUsers =>
users.where((user) => !user.admin).toList();
List<PlexHomeUser> get restrictedUsers =>
users.where((user) => user.restricted).toList();
PlexHomeUser? getUserByUUID(String uuid) {
try {
return users.firstWhere((user) => user.uuid == uuid);
} catch (e) {
return null;
}
}
bool get hasMultipleUsers => users.length > 1;
}
+74
View File
@@ -0,0 +1,74 @@
class PlexHomeUser {
final int id;
final String uuid;
final String title;
final String? username;
final String? email;
final String? friendlyName;
final String thumb;
final bool hasPassword;
final bool restricted;
final int? updatedAt;
final bool admin;
final bool guest;
final bool protected;
PlexHomeUser({
required this.id,
required this.uuid,
required this.title,
this.username,
this.email,
this.friendlyName,
required this.thumb,
required this.hasPassword,
required this.restricted,
required this.updatedAt,
required this.admin,
required this.guest,
required this.protected,
});
factory PlexHomeUser.fromJson(Map<String, dynamic> json) {
return PlexHomeUser(
id: (json['id'] as num?)?.toInt() ?? 0,
uuid: json['uuid'] as String? ?? '',
title: json['title'] as String? ?? 'Unknown',
username: json['username'] as String?,
email: json['email'] as String?,
friendlyName: json['friendlyName'] as String?,
thumb: json['thumb'] as String? ?? '',
hasPassword: json['hasPassword'] as bool? ?? false,
restricted: json['restricted'] as bool? ?? false,
updatedAt: (json['updatedAt'] as num?)?.toInt(),
admin: json['admin'] as bool? ?? false,
guest: json['guest'] as bool? ?? false,
protected: json['protected'] as bool? ?? false,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'uuid': uuid,
'title': title,
'username': username,
'email': email,
'friendlyName': friendlyName,
'thumb': thumb,
'hasPassword': hasPassword,
'restricted': restricted,
'updatedAt': updatedAt,
'admin': admin,
'guest': guest,
'protected': protected,
};
}
String get displayName => friendlyName ?? title;
bool get isAdminUser => admin;
bool get isRestrictedUser => restricted;
bool get isGuestUser => guest;
bool get requiresPassword => protected;
}
+57
View File
@@ -0,0 +1,57 @@
import 'plex_metadata.dart';
/// Represents a Plex hub/recommendation section (e.g., Trending Movies, Top Thrillers)
class PlexHub {
final String hubKey;
final String title;
final String type;
final String? hubIdentifier;
final int size;
final bool more;
final List<PlexMetadata> items;
PlexHub({
required this.hubKey,
required this.title,
required this.type,
this.hubIdentifier,
required this.size,
required this.more,
required this.items,
});
factory PlexHub.fromJson(Map<String, dynamic> json) {
final metadataList = <PlexMetadata>[];
// Hubs can contain either Metadata or Directory entries
if (json['Metadata'] != null) {
for (final item in json['Metadata'] as List) {
try {
metadataList.add(PlexMetadata.fromJson(item));
} catch (e) {
// Skip items that fail to parse
}
}
}
if (json['Directory'] != null) {
for (final item in json['Directory'] as List) {
try {
metadataList.add(PlexMetadata.fromJson(item));
} catch (e) {
// Skip items that fail to parse
}
}
}
return PlexHub(
hubKey: json['key'] as String? ?? '',
title: json['title'] as String? ?? 'Unknown',
type: json['type'] as String? ?? 'hub',
hubIdentifier: json['hubIdentifier'] as String?,
size: (json['size'] as num?)?.toInt() ?? metadataList.length,
more: json['more'] == true || json['more'] == 1,
items: metadataList,
);
}
}
+44
View File
@@ -77,6 +77,50 @@ class PlexSubtitleTrack {
if (forced) parts.add('Forced');
return parts.isEmpty ? 'Track ${index ?? id}' : parts.join(' · ');
}
/// Returns true if this subtitle track is an external file (sidecar subtitle)
/// External subtitles have a key property that points to /library/streams/{id}
bool get isExternal => key != null && key!.isNotEmpty;
/// Constructs the full URL for fetching external subtitle files
/// Returns null if this is not an external subtitle
String? getSubtitleUrl(String baseUrl, String token) {
if (!isExternal) return null;
// Determine file extension based on codec
final ext = _getExtensionFromCodec(codec);
// Construct URL with authentication token
return '$baseUrl$key.$ext?X-Plex-Token=$token';
}
/// Maps Plex subtitle codec names to file extensions
String _getExtensionFromCodec(String? codec) {
if (codec == null) return 'srt';
switch (codec.toLowerCase()) {
case 'subrip':
case 'srt':
return 'srt';
case 'ass':
return 'ass';
case 'ssa':
return 'ssa';
case 'webvtt':
case 'vtt':
return 'vtt';
case 'mov_text':
return 'srt';
case 'pgs':
case 'hdmv_pgs_subtitle':
return 'sup';
case 'dvd_subtitle':
case 'dvdsub':
return 'sub';
default:
return 'srt'; // Default to SRT for unknown codecs
}
}
}
class PlexChapter {
+77
View File
@@ -0,0 +1,77 @@
class PlexMediaVersion {
final int id;
final String? videoResolution;
final String? videoCodec;
final int? bitrate;
final int? width;
final int? height;
final String? container;
final String partKey;
PlexMediaVersion({
required this.id,
this.videoResolution,
this.videoCodec,
this.bitrate,
this.width,
this.height,
this.container,
required this.partKey,
});
/// Creates a PlexMediaVersion from Plex API Media object
factory PlexMediaVersion.fromJson(Map<String, dynamic> json) {
// Get the first Part key for playback
final parts = json['Part'] as List<dynamic>?;
final partKey = parts != null && parts.isNotEmpty
? parts[0]['key'] as String? ?? ''
: '';
return PlexMediaVersion(
id: json['id'] as int? ?? 0,
videoResolution: json['videoResolution'] as String?,
videoCodec: json['videoCodec'] as String?,
bitrate: json['bitrate'] as int?,
width: json['width'] as int?,
height: json['height'] as int?,
container: json['container'] as String?,
partKey: partKey,
);
}
/// Display label with detailed information: "1080p H.264 MKV (8.5 Mbps)"
String get displayLabel {
final parts = <String>[];
// Add resolution
if (videoResolution != null && videoResolution!.isNotEmpty) {
parts.add('${videoResolution}p');
} else if (height != null) {
parts.add('${height}p');
}
// Add codec
if (videoCodec != null && videoCodec!.isNotEmpty) {
parts.add(videoCodec!.toUpperCase());
}
// Add container
if (container != null && container!.isNotEmpty) {
parts.add(container!.toUpperCase());
}
// Build main label
String label = parts.isNotEmpty ? parts.join(' ') : 'Unknown';
// Add bitrate in parentheses
if (bitrate != null && bitrate! > 0) {
final bitrateInMbps = (bitrate! / 1000).toStringAsFixed(1);
label += ' ($bitrateInMbps Mbps)';
}
return label;
}
@override
String toString() => displayLabel;
}
+84 -5
View File
@@ -12,7 +12,7 @@ class PlexMetadata {
final String title;
final String? contentRating;
final String? summary;
final int? rating;
final double? rating;
final int? year;
final String? thumb;
final String? art;
@@ -24,6 +24,7 @@ class PlexMetadata {
final String? grandparentArt; // Show art for episodes
final String? grandparentRatingKey; // Show rating key for episodes
final String? parentTitle; // Season title for episodes
final String? parentThumb; // Season poster for episodes
final String? parentRatingKey; // Season rating key for episodes
final int? parentIndex; // Season number
final int? index; // Episode number
@@ -58,6 +59,7 @@ class PlexMetadata {
this.grandparentArt,
this.grandparentRatingKey,
this.parentTitle,
this.parentThumb,
this.parentRatingKey,
this.parentIndex,
this.index,
@@ -68,6 +70,74 @@ class PlexMetadata {
this.viewedLeafCount,
});
/// Create a copy of this metadata with optional field overrides
PlexMetadata copyWith({
String? ratingKey,
String? key,
String? guid,
String? studio,
String? type,
String? title,
String? contentRating,
String? summary,
double? rating,
int? year,
String? thumb,
String? art,
int? duration,
int? addedAt,
int? updatedAt,
String? grandparentTitle,
String? grandparentThumb,
String? grandparentArt,
String? grandparentRatingKey,
String? parentTitle,
String? parentThumb,
String? parentRatingKey,
int? parentIndex,
int? index,
String? grandparentTheme,
int? viewOffset,
int? viewCount,
int? leafCount,
int? viewedLeafCount,
}) {
final copy = PlexMetadata(
ratingKey: ratingKey ?? this.ratingKey,
key: key ?? this.key,
guid: guid ?? this.guid,
studio: studio ?? this.studio,
type: type ?? this.type,
title: title ?? this.title,
contentRating: contentRating ?? this.contentRating,
summary: summary ?? this.summary,
rating: rating ?? this.rating,
year: year ?? this.year,
thumb: thumb ?? this.thumb,
art: art ?? this.art,
duration: duration ?? this.duration,
addedAt: addedAt ?? this.addedAt,
updatedAt: updatedAt ?? this.updatedAt,
grandparentTitle: grandparentTitle ?? this.grandparentTitle,
grandparentThumb: grandparentThumb ?? this.grandparentThumb,
grandparentArt: grandparentArt ?? this.grandparentArt,
grandparentRatingKey: grandparentRatingKey ?? this.grandparentRatingKey,
parentTitle: parentTitle ?? this.parentTitle,
parentThumb: parentThumb ?? this.parentThumb,
parentRatingKey: parentRatingKey ?? this.parentRatingKey,
parentIndex: parentIndex ?? this.parentIndex,
index: index ?? this.index,
grandparentTheme: grandparentTheme ?? this.grandparentTheme,
viewOffset: viewOffset ?? this.viewOffset,
viewCount: viewCount ?? this.viewCount,
leafCount: leafCount ?? this.leafCount,
viewedLeafCount: viewedLeafCount ?? this.viewedLeafCount,
);
// Preserve clearLogo
copy._clearLogo = _clearLogo;
return copy;
}
// Extract clearLogo from Image array in raw JSON
void _extractClearLogo(Map<String, dynamic> json) {
if (!json.containsKey('Image')) return;
@@ -121,12 +191,21 @@ class PlexMetadata {
}
// Helper to get the poster (show poster for episodes/seasons, thumb otherwise)
String? get posterThumb {
// If useSeasonPoster is true, episodes will use season poster instead of series poster
String? posterThumb({bool useSeasonPoster = false}) {
final itemType = type.toLowerCase();
// For episodes and seasons, prefer grandparent thumb (show poster)
if ((itemType == 'episode' || itemType == 'season') &&
grandparentThumb != null) {
if (itemType == 'episode') {
// If season poster is enabled and available, use it
if (useSeasonPoster && parentThumb != null) {
return parentThumb!;
}
// Otherwise fall back to series poster, then item thumb
if (grandparentThumb != null) {
return grandparentThumb!;
}
} else if (itemType == 'season' && grandparentThumb != null) {
// For seasons, always use series poster
return grandparentThumb!;
}
return thumb;
+3 -1
View File
@@ -15,7 +15,7 @@ PlexMetadata _$PlexMetadataFromJson(Map<String, dynamic> json) => PlexMetadata(
title: json['title'] as String,
contentRating: json['contentRating'] as String?,
summary: json['summary'] as String?,
rating: (json['rating'] as num?)?.toInt(),
rating: (json['rating'] as num?)?.toDouble(),
year: (json['year'] as num?)?.toInt(),
thumb: json['thumb'] as String?,
art: json['art'] as String?,
@@ -27,6 +27,7 @@ PlexMetadata _$PlexMetadataFromJson(Map<String, dynamic> json) => PlexMetadata(
grandparentArt: json['grandparentArt'] as String?,
grandparentRatingKey: json['grandparentRatingKey'] as String?,
parentTitle: json['parentTitle'] as String?,
parentThumb: json['parentThumb'] as String?,
parentRatingKey: json['parentRatingKey'] as String?,
parentIndex: (json['parentIndex'] as num?)?.toInt(),
index: (json['index'] as num?)?.toInt(),
@@ -59,6 +60,7 @@ Map<String, dynamic> _$PlexMetadataToJson(PlexMetadata instance) =>
'grandparentArt': instance.grandparentArt,
'grandparentRatingKey': instance.grandparentRatingKey,
'parentTitle': instance.parentTitle,
'parentThumb': instance.parentThumb,
'parentRatingKey': instance.parentRatingKey,
'parentIndex': instance.parentIndex,
'index': instance.index,
+53
View File
@@ -0,0 +1,53 @@
class PlexSort {
final String key;
final String? descKey;
final String title;
final String? defaultDirection;
PlexSort({
required this.key,
this.descKey,
required this.title,
this.defaultDirection,
});
factory PlexSort.fromJson(Map<String, dynamic> json) {
return PlexSort(
key: json['key'] as String,
descKey: json['descKey'] as String?,
title: json['title'] as String,
defaultDirection: json['defaultDirection'] as String?,
);
}
/// Gets the full sort key with direction
/// If [descending] is true, returns the descKey or key:desc
/// Otherwise returns the key for ascending sort
String getSortKey({bool descending = false}) {
if (!descending) {
return key;
}
// Use descKey if available, otherwise append :desc to key
return descKey ?? '$key:desc';
}
/// Returns true if this sort's default direction is descending
bool get isDefaultDescending {
return defaultDirection?.toLowerCase() == 'desc';
}
@override
String toString() {
return 'PlexSort(key: $key, title: $title, defaultDirection: $defaultDirection)';
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is PlexSort && other.key == key;
}
@override
int get hashCode => key.hashCode;
}
+137
View File
@@ -0,0 +1,137 @@
import 'plex_user_profile.dart';
class UserSwitchResponse {
final int id;
final String uuid;
final String username;
final String title;
final String email;
final String? friendlyName;
final String? locale;
final bool confirmed;
final int joinedAt;
final bool emailOnlyAuth;
final bool hasPassword;
final bool protected;
final String thumb;
final String authToken;
final bool? mailingListActive;
final String scrobbleTypes;
final String country;
final bool restricted;
final bool? anonymous;
final bool home;
final bool guest;
final int homeSize;
final bool homeAdmin;
final int maxHomeSize;
final PlexUserProfile profile;
final bool twoFactorEnabled;
final bool backupCodesCreated;
final String? attributionPartner;
UserSwitchResponse({
required this.id,
required this.uuid,
required this.username,
required this.title,
required this.email,
this.friendlyName,
this.locale,
required this.confirmed,
required this.joinedAt,
required this.emailOnlyAuth,
required this.hasPassword,
required this.protected,
required this.thumb,
required this.authToken,
this.mailingListActive,
required this.scrobbleTypes,
required this.country,
required this.restricted,
this.anonymous,
required this.home,
required this.guest,
required this.homeSize,
required this.homeAdmin,
required this.maxHomeSize,
required this.profile,
required this.twoFactorEnabled,
required this.backupCodesCreated,
this.attributionPartner,
});
factory UserSwitchResponse.fromJson(Map<String, dynamic> json) {
return UserSwitchResponse(
id: json['id'] as int,
uuid: json['uuid'] as String,
username: json['username'] as String? ?? '',
title: json['title'] as String,
email: json['email'] as String? ?? '',
friendlyName: json['friendlyName'] as String?,
locale: json['locale'] as String?,
confirmed: json['confirmed'] as bool,
joinedAt: json['joinedAt'] as int,
emailOnlyAuth: json['emailOnlyAuth'] as bool,
hasPassword: json['hasPassword'] as bool,
protected: json['protected'] as bool,
thumb: json['thumb'] as String,
authToken: json['authToken'] as String,
mailingListActive: json['mailingListActive'] as bool?,
scrobbleTypes: json['scrobbleTypes'] as String? ?? '',
country: json['country'] as String? ?? '',
restricted: json['restricted'] as bool,
anonymous: json['anonymous'] as bool?,
home: json['home'] as bool,
guest: json['guest'] as bool,
homeSize: json['homeSize'] as int,
homeAdmin: json['homeAdmin'] as bool,
maxHomeSize: json['maxHomeSize'] as int,
profile: PlexUserProfile.fromJson(json),
twoFactorEnabled: json['twoFactorEnabled'] as bool,
backupCodesCreated: json['backupCodesCreated'] as bool,
attributionPartner: json['attributionPartner'] as String?,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'uuid': uuid,
'username': username,
'title': title,
'email': email,
'friendlyName': friendlyName,
'locale': locale,
'confirmed': confirmed,
'joinedAt': joinedAt,
'emailOnlyAuth': emailOnlyAuth,
'hasPassword': hasPassword,
'protected': protected,
'thumb': thumb,
'authToken': authToken,
'mailingListActive': mailingListActive,
'scrobbleTypes': scrobbleTypes,
'country': country,
'restricted': restricted,
'anonymous': anonymous,
'home': home,
'guest': guest,
'homeSize': homeSize,
'homeAdmin': homeAdmin,
'maxHomeSize': maxHomeSize,
'profile': profile.toJson()['profile'],
'twoFactorEnabled': twoFactorEnabled,
'backupCodesCreated': backupCodesCreated,
'attributionPartner': attributionPartner,
};
}
String get displayName => friendlyName ?? title;
bool get isAdminUser => homeAdmin;
bool get isRestrictedUser => restricted;
bool get isGuestUser => guest;
bool get requiresPassword => hasPassword;
bool get isSecureUser => twoFactorEnabled || backupCodesCreated;
}
@@ -0,0 +1,61 @@
import 'package:flutter/foundation.dart';
import '../services/storage_service.dart';
/// Provider for managing hidden library state across the app.
/// This ensures that when a library is hidden/unhidden in one screen,
/// all other screens are automatically updated.
class HiddenLibrariesProvider extends ChangeNotifier {
late StorageService _storageService;
Set<String> _hiddenLibraryKeys = {};
bool _isInitialized = false;
/// Get an unmodifiable copy of hidden library keys
Set<String> get hiddenLibraryKeys => Set.unmodifiable(_hiddenLibraryKeys);
/// Check if the provider has completed initialization
bool get isInitialized => _isInitialized;
HiddenLibrariesProvider() {
_initialize();
}
/// Initialize the provider by loading hidden libraries from storage
Future<void> _initialize() async {
_storageService = await StorageService.getInstance();
_hiddenLibraryKeys = _storageService.getHiddenLibraries();
_isInitialized = true;
notifyListeners();
}
/// Hide a library by its key
/// Updates both in-memory state and persistent storage
Future<void> hideLibrary(String libraryKey) async {
if (!_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..add(libraryKey);
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
notifyListeners();
}
}
/// Unhide a library by its key
/// Updates both in-memory state and persistent storage
Future<void> unhideLibrary(String libraryKey) async {
if (_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..remove(libraryKey);
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
notifyListeners();
}
}
/// Check if a specific library is hidden
bool isLibraryHidden(String libraryKey) {
return _hiddenLibraryKeys.contains(libraryKey);
}
/// Refresh hidden libraries from storage
/// Useful if storage was modified outside the provider
Future<void> refresh() async {
_hiddenLibraryKeys = _storageService.getHiddenLibraries();
notifyListeners();
}
}
@@ -0,0 +1,96 @@
import 'package:flutter/foundation.dart';
import '../models/plex_metadata.dart';
/// Manages shuffle playback state for TV shows and seasons.
/// This provider is session-only and does not persist across app restarts.
class PlaybackStateProvider with ChangeNotifier {
List<PlexMetadata> _shuffleQueue = [];
String?
_shuffleContextKey; // The show/season ratingKey for this shuffle session
int _currentIndex = 0;
/// Whether shuffle mode is currently active
bool get isShuffleActive => _shuffleQueue.isNotEmpty;
/// The context key (show or season ratingKey) for the current shuffle session
String? get shuffleContextKey => _shuffleContextKey;
/// Sets a new shuffle queue and starts shuffle mode
void setShuffleQueue(List<PlexMetadata> episodes, String contextKey) {
_shuffleQueue = List.from(episodes);
_shuffleContextKey = contextKey;
_currentIndex = 0;
notifyListeners();
}
/// Gets the next episode in the shuffle queue.
/// Returns null if queue is exhausted or current episode is not in queue.
/// [loopQueue] - If true, restart from beginning when queue is exhausted
PlexMetadata? getNextEpisode(String currentEpisodeKey, {bool loopQueue = false}) {
if (_shuffleQueue.isEmpty) return null;
// Find current episode in queue
final currentIndex = _shuffleQueue.indexWhere(
(ep) => ep.ratingKey == currentEpisodeKey,
);
if (currentIndex == -1) {
// Current episode not in queue, clear shuffle
clearShuffle();
return null;
}
// Check if there's a next episode
if (currentIndex + 1 >= _shuffleQueue.length) {
// Queue exhausted
if (loopQueue && _shuffleQueue.isNotEmpty) {
// Loop back to beginning
_currentIndex = 0;
return _shuffleQueue[_currentIndex];
}
return null;
}
_currentIndex = currentIndex + 1;
return _shuffleQueue[_currentIndex];
}
/// Gets the previous episode in the shuffle queue.
/// Returns null if at the beginning of the queue or current episode is not in queue.
PlexMetadata? getPreviousEpisode(String currentEpisodeKey) {
if (_shuffleQueue.isEmpty) return null;
// Find current episode in queue
final currentIndex = _shuffleQueue.indexWhere(
(ep) => ep.ratingKey == currentEpisodeKey,
);
if (currentIndex == -1) {
// Current episode not in queue
return null;
}
// Check if there's a previous episode
if (currentIndex <= 0) {
// At the beginning of queue
return null;
}
_currentIndex = currentIndex - 1;
return _shuffleQueue[_currentIndex];
}
/// Clears the shuffle queue and exits shuffle mode
void clearShuffle() {
_shuffleQueue = [];
_shuffleContextKey = null;
_currentIndex = 0;
notifyListeners();
}
/// Gets the total number of episodes in the current shuffle queue
int get queueLength => _shuffleQueue.length;
/// Gets the current position in the queue (1-indexed)
int get currentPosition => _currentIndex + 1;
}
+31
View File
@@ -0,0 +1,31 @@
import 'package:flutter/foundation.dart';
import '../client/plex_client.dart';
import '../utils/app_logger.dart';
class PlexClientProvider extends ChangeNotifier {
PlexClient? _client;
PlexClient? get client => _client;
void setClient(PlexClient client) {
_client = client;
appLogger.d('PlexClientProvider: Client set');
notifyListeners();
}
void updateToken(String newToken) {
if (_client != null) {
_client!.updateToken(newToken);
appLogger.d('PlexClientProvider: Token updated');
notifyListeners();
} else {
appLogger.w('PlexClientProvider: Cannot update token - no client set');
}
}
void clearClient() {
_client = null;
appLogger.d('PlexClientProvider: Client cleared');
notifyListeners();
}
}
+104
View File
@@ -0,0 +1,104 @@
import 'package:flutter/material.dart';
import '../services/settings_service.dart';
class SettingsProvider extends ChangeNotifier {
late SettingsService _settingsService;
LibraryDensity _libraryDensity = LibraryDensity.normal;
ViewMode _viewMode = ViewMode.grid;
bool _useSeasonPoster = false;
bool _showHeroSection = true;
bool _shuffleUnwatchedOnly = true;
bool _shuffleOrderNavigation = true;
bool _shuffleLoopQueue = false;
SettingsProvider() {
_initializeSettings();
}
Future<void> _initializeSettings() async {
_settingsService = await SettingsService.getInstance();
_libraryDensity = _settingsService.getLibraryDensity();
_viewMode = _settingsService.getViewMode();
_useSeasonPoster = _settingsService.getUseSeasonPoster();
_showHeroSection = _settingsService.getShowHeroSection();
_shuffleUnwatchedOnly = _settingsService.getShuffleUnwatchedOnly();
_shuffleOrderNavigation = _settingsService.getShuffleOrderNavigation();
_shuffleLoopQueue = _settingsService.getShuffleLoopQueue();
notifyListeners();
}
LibraryDensity get libraryDensity => _libraryDensity;
ViewMode get viewMode => _viewMode;
bool get useSeasonPoster => _useSeasonPoster;
bool get showHeroSection => _showHeroSection;
bool get shuffleUnwatchedOnly => _shuffleUnwatchedOnly;
bool get shuffleOrderNavigation => _shuffleOrderNavigation;
bool get shuffleLoopQueue => _shuffleLoopQueue;
Future<void> setLibraryDensity(LibraryDensity density) async {
if (_libraryDensity != density) {
_libraryDensity = density;
await _settingsService.setLibraryDensity(density);
notifyListeners();
}
}
Future<void> setViewMode(ViewMode mode) async {
if (_viewMode != mode) {
_viewMode = mode;
await _settingsService.setViewMode(mode);
notifyListeners();
}
}
Future<void> setUseSeasonPoster(bool value) async {
if (_useSeasonPoster != value) {
_useSeasonPoster = value;
await _settingsService.setUseSeasonPoster(value);
notifyListeners();
}
}
Future<void> setShowHeroSection(bool value) async {
if (_showHeroSection != value) {
_showHeroSection = value;
await _settingsService.setShowHeroSection(value);
notifyListeners();
}
}
Future<void> setShuffleUnwatchedOnly(bool value) async {
if (_shuffleUnwatchedOnly != value) {
_shuffleUnwatchedOnly = value;
await _settingsService.setShuffleUnwatchedOnly(value);
notifyListeners();
}
}
Future<void> setShuffleOrderNavigation(bool value) async {
if (_shuffleOrderNavigation != value) {
_shuffleOrderNavigation = value;
await _settingsService.setShuffleOrderNavigation(value);
notifyListeners();
}
}
Future<void> setShuffleLoopQueue(bool value) async {
if (_shuffleLoopQueue != value) {
_shuffleLoopQueue = value;
await _settingsService.setShuffleLoopQueue(value);
notifyListeners();
}
}
String get libraryDensityDisplayName {
switch (_libraryDensity) {
case LibraryDensity.compact:
return 'Compact';
case LibraryDensity.normal:
return 'Normal';
case LibraryDensity.comfortable:
return 'Comfortable';
}
}
}
+102
View File
@@ -0,0 +1,102 @@
import 'package:flutter/material.dart';
import '../services/settings_service.dart' as settings;
import '../theme/mono_theme.dart';
class ThemeProvider extends ChangeNotifier {
late settings.SettingsService _settingsService;
settings.ThemeMode _themeMode = settings.ThemeMode.system;
late Brightness _systemBrightness;
ThemeProvider() {
_systemBrightness =
WidgetsBinding.instance.platformDispatcher.platformBrightness;
_initializeSettings();
// Listen to system theme changes
WidgetsBinding.instance.platformDispatcher.onPlatformBrightnessChanged =
() {
_systemBrightness =
WidgetsBinding.instance.platformDispatcher.platformBrightness;
if (_themeMode == settings.ThemeMode.system) {
notifyListeners();
}
};
}
Future<void> _initializeSettings() async {
_settingsService = await settings.SettingsService.getInstance();
_themeMode = _settingsService.getThemeMode();
notifyListeners();
}
settings.ThemeMode get themeMode => _themeMode;
ThemeData get lightTheme => monoTheme(dark: false);
ThemeData get darkTheme => monoTheme(dark: true);
ThemeMode get materialThemeMode {
switch (_themeMode) {
case settings.ThemeMode.light:
return ThemeMode.light;
case settings.ThemeMode.dark:
return ThemeMode.dark;
case settings.ThemeMode.system:
return ThemeMode.system;
}
}
bool get isDarkMode {
switch (_themeMode) {
case settings.ThemeMode.light:
return false;
case settings.ThemeMode.dark:
return true;
case settings.ThemeMode.system:
return _systemBrightness == Brightness.dark;
}
}
Future<void> setThemeMode(settings.ThemeMode mode) async {
if (_themeMode != mode) {
_themeMode = mode;
await _settingsService.setThemeMode(mode);
notifyListeners();
}
}
String get themeModeDisplayName {
switch (_themeMode) {
case settings.ThemeMode.light:
return 'Light';
case settings.ThemeMode.dark:
return 'Dark';
case settings.ThemeMode.system:
return 'System';
}
}
IconData get themeModeIcon {
switch (_themeMode) {
case settings.ThemeMode.light:
return Icons.light_mode;
case settings.ThemeMode.dark:
return Icons.dark_mode;
case settings.ThemeMode.system:
return Icons.brightness_auto;
}
}
void toggleTheme() {
switch (_themeMode) {
case settings.ThemeMode.system:
setThemeMode(settings.ThemeMode.light);
break;
case settings.ThemeMode.light:
setThemeMode(settings.ThemeMode.dark);
break;
case settings.ThemeMode.dark:
setThemeMode(settings.ThemeMode.system);
break;
}
}
}
+564
View File
@@ -0,0 +1,564 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../models/plex_home.dart';
import '../models/plex_home_user.dart';
import '../models/plex_user_profile.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../widgets/pin_entry_dialog.dart';
import 'plex_client_provider.dart';
class UserProfileProvider extends ChangeNotifier {
PlexHome? _home;
PlexHomeUser? _currentUser;
PlexUserProfile? _profileSettings;
bool _isLoading = false;
String? _error;
PlexHome? get home => _home;
PlexHomeUser? get currentUser => _currentUser;
PlexUserProfile? get profileSettings => _profileSettings;
bool get isLoading => _isLoading;
String? get error => _error;
bool get hasMultipleUsers {
final result = _home?.hasMultipleUsers ?? false;
appLogger.d(
'hasMultipleUsers: _home=${_home != null}, users count=${_home?.users.length ?? 0}, result=$result',
);
return result;
}
PlexAuthService? _authService;
StorageService? _storageService;
// Callback for data invalidation when switching profiles
VoidCallback? _onDataInvalidationRequested;
/// Set a callback to be called when profile switching requires data invalidation
void setDataInvalidationCallback(VoidCallback? callback) {
_onDataInvalidationRequested = callback;
}
/// Trigger data invalidation for all screens
void _invalidateAllData() {
if (_onDataInvalidationRequested != null) {
_onDataInvalidationRequested!();
appLogger.d('Data invalidation triggered for profile switch');
}
}
Future<void> initialize() async {
appLogger.d('UserProfileProvider: Initializing...');
try {
_authService = await PlexAuthService.create();
_storageService = await StorageService.getInstance();
await _loadCachedData();
// If no cached home data or it's expired, try to load from API
if (_home == null) {
appLogger.d(
'UserProfileProvider: No cached home data, attempting to load from API',
);
try {
await loadHomeUsers();
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to load home users during initialization',
error: e,
);
// Don't set error here as it's not critical for app startup
}
}
// Fetch fresh profile settings from API
appLogger.d('UserProfileProvider: Fetching profile settings from API');
try {
await refreshProfileSettings();
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to fetch profile settings during initialization',
error: e,
);
// Don't set error here, cached profile (if any) was already loaded
}
appLogger.d('UserProfileProvider: Initialization complete');
} catch (e) {
appLogger.e(
'UserProfileProvider: Critical initialization failure',
error: e,
);
_setError('Failed to initialize profile services');
// Ensure services are null on failure
_authService = null;
_storageService = null;
}
}
Future<void> _loadCachedData() async {
if (_storageService == null) return;
// Load cached home users
final cachedHomeData = _storageService!.getHomeUsersCache();
if (cachedHomeData != null) {
try {
_home = PlexHome.fromJson(cachedHomeData);
} catch (e) {
appLogger.w('Failed to load cached home data', error: e);
}
}
// Load current user UUID
final currentUserUUID = _storageService!.getCurrentUserUUID();
if (currentUserUUID != null && _home != null) {
_currentUser = _home!.getUserByUUID(currentUserUUID);
}
// Profile settings are NOT cached - they will be fetched fresh from API
// in refreshProfileSettings()
notifyListeners();
}
/// Fetch the user's profile settings from the API
Future<void> refreshProfileSettings() async {
if (_authService == null || _storageService == null) {
appLogger.w('refreshProfileSettings: Services not initialized, skipping');
return;
}
appLogger.d('Fetching user profile settings from Plex API');
try {
final currentToken = _storageService!.getPlexToken();
if (currentToken == null) {
appLogger.w(
'refreshProfileSettings: No Plex token available, cannot fetch profile',
);
return;
}
final profile = await _authService!.getUserProfile(currentToken);
_profileSettings = profile;
appLogger.i('Successfully fetched user profile settings from API');
notifyListeners();
} catch (e) {
appLogger.w('Failed to fetch user profile settings from API', error: e);
// Don't set error state, profile will remain null or keep existing value
}
}
Future<void> loadHomeUsers({bool forceRefresh = false}) async {
appLogger.d('loadHomeUsers called - forceRefresh: $forceRefresh');
// Auto-initialize services if not ready
if (_authService == null || _storageService == null) {
appLogger.d(
'loadHomeUsers: Services not initialized, initializing services...',
);
_authService = await PlexAuthService.create();
_storageService = await StorageService.getInstance();
await _loadCachedData();
// Double-check after initialization
if (_authService == null || _storageService == null) {
appLogger.e('loadHomeUsers: Failed to initialize services');
_setError('Failed to initialize services');
return;
}
}
// Use cached data if available and not forcing refresh
if (!forceRefresh && _home != null) {
appLogger.d(
'loadHomeUsers: Using cached data, users count: ${_home!.users.length}',
);
return;
}
_setLoading(true);
_clearError();
try {
final currentToken = _storageService!.getPlexToken();
if (currentToken == null) {
throw Exception('No Plex.tv authentication token available');
}
appLogger.d('loadHomeUsers: Using Plex.tv token');
appLogger.d('loadHomeUsers: Fetching home users from API');
final home = await _authService!.getHomeUsers(currentToken);
_home = home;
appLogger.i(
'loadHomeUsers: Success! Home users count: ${home.users.length}',
);
appLogger.d(
'loadHomeUsers: Users: ${home.users.map((u) => u.displayName).join(', ')}',
);
// Cache the home data
await _storageService!.saveHomeUsersCache(home.toJson());
// Set current user if not already set
if (_currentUser == null) {
final currentUserUUID = _storageService!.getCurrentUserUUID();
if (currentUserUUID != null) {
_currentUser = home.getUserByUUID(currentUserUUID);
appLogger.d(
'loadHomeUsers: Set current user from UUID: ${_currentUser?.displayName}',
);
} else {
// Default to admin user if no current user set
_currentUser = home.adminUser;
if (_currentUser != null) {
await _storageService!.saveCurrentUserUUID(_currentUser!.uuid);
appLogger.d(
'loadHomeUsers: Set current user to admin: ${_currentUser?.displayName}',
);
}
}
}
notifyListeners();
} catch (e) {
_setError('Failed to load home users: $e');
appLogger.e('Failed to load home users', error: e);
} finally {
_setLoading(false);
}
}
Future<bool> switchToUser(PlexHomeUser user, BuildContext? context) async {
if (_authService == null || _storageService == null) {
_setError('Services not initialized');
return false;
}
if (user.uuid == _currentUser?.uuid) {
// Already on this user
return true;
}
// Extract client provider before async operations
PlexClientProvider? clientProvider;
if (context != null) {
try {
clientProvider = context.plexClient;
} catch (e) {
appLogger.w('Failed to get PlexClientProvider', error: e);
}
}
_setLoading(true);
_clearError();
return await _attemptUserSwitch(user, context, clientProvider, null);
}
Future<bool> _attemptUserSwitch(
PlexHomeUser user,
BuildContext? context,
PlexClientProvider? clientProvider,
String? errorMessage,
) async {
try {
final currentToken = _storageService!.getPlexToken();
if (currentToken == null) {
throw Exception('No Plex.tv authentication token available');
}
// Check if user requires PIN
String? pin;
if (user.requiresPassword && context != null && context.mounted) {
pin = await showPinEntryDialog(
context,
user.displayName,
errorMessage: errorMessage,
);
// User cancelled the PIN dialog
if (pin == null) {
_setLoading(false);
return false;
}
}
final switchResponse = await _authService!.switchToUser(
user.uuid,
currentToken,
pin: pin,
);
// switchResponse.authToken is the new user's Plex.tv token
// We need to fetch servers with this token to get the proper server access token
appLogger.d('Got new user Plex.tv token, fetching servers...');
final servers = await _authService!.fetchServers(
switchResponse.authToken,
);
if (servers.isEmpty) {
throw Exception('No servers available for this user');
}
// Find the current server from storage
final currentServerData = _storageService!.getServerData();
if (currentServerData == null) {
throw Exception('No current server data found');
}
// Find matching server by name or client identifier
final currentServerName = currentServerData['name'] as String?;
final currentServerClientId =
currentServerData['clientIdentifier'] as String?;
final matchingServer = servers.firstWhere(
(server) =>
server.name == currentServerName ||
server.clientIdentifier == currentServerClientId,
orElse: () => servers.first, // Fallback to first server
);
appLogger.d(
'Found matching server: ${matchingServer.name}, getting access token',
);
// Update storage with new tokens
await _storageService!.updateCurrentUser(
user.uuid,
matchingServer
.accessToken, // Use server access token, not Plex.tv token
);
// Also save the new Plex.tv token for future profile operations
await _storageService!.savePlexToken(switchResponse.authToken);
// Update current user
_currentUser = user;
// Update user profile settings (fresh from API)
_profileSettings = switchResponse.profile;
appLogger.d(
'Updated profile settings for user: ${user.displayName}',
error: {
'defaultAudioLanguage':
_profileSettings?.defaultAudioLanguage ?? 'not set',
'defaultSubtitleLanguage':
_profileSettings?.defaultSubtitleLanguage ?? 'not set',
},
);
// Update PlexClient with proper server access token
if (clientProvider != null) {
try {
clientProvider.updateToken(matchingServer.accessToken);
appLogger.d(
'Updated PlexClient with server access token for user: ${user.displayName}',
);
} catch (e) {
appLogger.w('Failed to update PlexClient token', error: e);
}
}
notifyListeners();
// Invalidate all cached data for the new profile
// This will cause screens to refresh and rebuild widgets with the new token
_invalidateAllData();
appLogger.d(
'Profile switch complete, all data and images should refresh with new token',
);
appLogger.i('Successfully switched to user: ${user.displayName}');
return true;
} catch (e) {
// Check if it's a PIN validation error
if (e is DioException && e.response?.statusCode == 403) {
final errors = e.response?.data['errors'] as List?;
if (errors != null && errors.isNotEmpty) {
final errorCode = errors[0]['code'] as int?;
final errorMessage = errors[0]['message'] as String?;
// Error code 1041 means invalid PIN
if (errorCode == 1041) {
appLogger.w('Invalid PIN for user: ${user.displayName}');
_clearError(); // Clear any previous error state
// Retry with error message if context is still available
if (context != null && context.mounted) {
return await _attemptUserSwitch(
user,
context,
clientProvider,
errorMessage ?? 'Incorrect PIN. Please try again.',
);
}
// If context not available, return false without showing error
appLogger.d('Cannot retry PIN entry - context not available');
return false;
}
}
}
// Only show error for non-PIN validation errors
_setError('Failed to switch user: $e');
appLogger.e('Failed to switch to user: ${user.displayName}', error: e);
return false;
} finally {
_setLoading(false);
}
}
Future<void> refreshCurrentUser() async {
if (_currentUser != null) {
await loadHomeUsers(forceRefresh: true);
// Update current user from refreshed data
if (_home != null) {
_currentUser = _home!.getUserByUUID(_currentUser!.uuid);
notifyListeners();
}
}
}
Future<void> logout() async {
if (_storageService == null) return;
_setLoading(true);
try {
await _storageService!.clearUserData();
// Clear user-specific provider state but keep services for future sign-ins
_home = null;
_currentUser = null;
_profileSettings = null;
_onDataInvalidationRequested = null;
_clearError();
notifyListeners();
appLogger.i('User logged out successfully');
} catch (e) {
appLogger.e('Error during logout', error: e);
} finally {
_setLoading(false);
}
}
/// Refresh provider for new server context
/// Call this when switching servers to ensure provider state is synchronized
Future<void> refreshForNewServer([BuildContext? context]) async {
appLogger.d('UserProfileProvider: Refreshing for new server context');
_setLoading(true);
try {
// Clear cached data from previous server (both memory and storage)
_home = null;
_currentUser = null;
_profileSettings = null;
_clearError();
// Re-initialize services with current storage state
_authService = await PlexAuthService.create();
_storageService = await StorageService.getInstance();
// Clear storage state that's specific to the previous server context
await Future.wait([
// Clear home users cache (server-specific)
_storageService!.clearHomeUsersCache(),
// Clear current user UUID (profile-specific, should not persist across servers)
_storageService!.clearCurrentUserUUID(),
]);
appLogger.d('UserProfileProvider: Cleared previous server storage state');
// Load fresh data for the new server (should be empty after clearing cache)
await _loadCachedData();
// Load from API since we cleared the cache
appLogger.d(
'UserProfileProvider: Loading fresh home users for new server',
);
// Store context reference before async operations to avoid build context warnings
final contextForSwitch = context;
try {
await loadHomeUsers();
// After loading home users, if a current user was set (admin user),
// perform a complete profile switch to ensure tokens are properly updated
if (_currentUser != null && contextForSwitch != null) {
appLogger.d(
'UserProfileProvider: Performing complete profile switch to ${_currentUser!.displayName} for new server',
);
// Perform full profile switch which includes API calls and token updates
final userToSwitchTo = _currentUser!;
// ignore: use_build_context_synchronously
final success = await switchToUser(userToSwitchTo, contextForSwitch);
if (success) {
appLogger.d(
'UserProfileProvider: Successfully switched to admin user for new server',
);
} else {
appLogger.w(
'UserProfileProvider: Failed to complete profile switch for new server',
);
}
} else if (_currentUser != null && contextForSwitch == null) {
appLogger.w(
'UserProfileProvider: Cannot perform complete profile switch - no context provided',
);
// Still try to fetch profile settings even without full switch
try {
await refreshProfileSettings();
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to refresh profile settings for new server',
error: e,
);
}
}
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to load home users for new server',
error: e,
);
// Don't set error as it's not critical
}
appLogger.d('UserProfileProvider: Refresh for new server complete');
} catch (e) {
appLogger.e(
'UserProfileProvider: Failed to refresh for new server',
error: e,
);
_setError('Failed to refresh for new server');
} finally {
_setLoading(false);
}
}
void _setLoading(bool loading) {
_isLoading = loading;
notifyListeners();
}
void _setError(String error) {
_error = error;
notifyListeners();
}
void _clearError() {
_error = null;
}
}
+47 -126
View File
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
import 'licenses_screen.dart';
class AboutScreen extends StatefulWidget {
const AboutScreen({super.key});
@@ -36,113 +36,63 @@ class _AboutScreenState extends State<AboutScreen> {
return Scaffold(
body: CustomScrollView(
slivers: [
DesktopSliverAppBar(
title: const Text('About'),
pinned: true,
leading: const AppBarBackButton(
style: BackButtonStyle.circular,
),
),
CustomAppBar(title: const Text('About'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
// App Icon and Name
Center(
child: Column(
children: [
const SizedBox(height: 24),
Image.asset(
'assets/plezy.png',
width: 80,
height: 80,
),
const SizedBox(height: 16),
Text(
appName,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
// App Icon and Name
Center(
child: Column(
children: [
const SizedBox(height: 24),
Image.asset('assets/plezy.png', width: 80, height: 80),
const SizedBox(height: 16),
Text(
appName,
style: Theme.of(context).textTheme.headlineMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
'Version $appVersion',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 24),
Text(
'A beautiful Plex client for Flutter',
style: Theme.of(context).textTheme.bodyLarge,
textAlign: TextAlign.center,
),
],
),
),
const SizedBox(height: 8),
Text(
'Version $appVersion',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 24),
Text(
'A beautiful Plex client for Flutter',
style: Theme.of(context).textTheme.bodyLarge,
textAlign: TextAlign.center,
),
],
),
),
const SizedBox(height: 40),
const SizedBox(height: 40),
// Open Source Licenses
Card(
child: ListTile(
leading: const Icon(Icons.description),
title: const Text('Open Source Licenses'),
subtitle: const Text('View licenses of third-party libraries'),
trailing: const Icon(Icons.chevron_right),
onTap: () {
showLicensePage(
context: context,
applicationName: appName,
applicationVersion: appVersion,
applicationIcon: Image.asset(
'assets/plezy.png',
width: 48,
height: 48,
),
);
},
),
),
const SizedBox(height: 16),
// Key Dependencies
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Key Dependencies',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
// Open Source Licenses
Card(
child: ListTile(
leading: const Icon(Icons.description),
title: const Text('Open Source Licenses'),
subtitle: const Text(
'View licenses of third-party libraries',
),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const LicensesScreen(),
),
);
},
),
const SizedBox(height: 12),
_buildDependencyItem('http', 'HTTP networking'),
_buildDependencyItem('dio', 'Advanced HTTP client'),
_buildDependencyItem('cached_network_image', 'Image caching'),
_buildDependencyItem('media_kit', 'Video playback'),
_buildDependencyItem('shared_preferences', 'Local storage'),
_buildDependencyItem('xml', 'XML parsing'),
_buildDependencyItem('url_launcher', 'External links'),
_buildDependencyItem(
'window_manager',
'Desktop window management',
),
_buildDependencyItem(
'macos_window_utils',
'macOS window controls',
),
_buildDependencyItem('logger', 'Logging'),
],
),
),
),
),
const SizedBox(height: 24),
const SizedBox(height: 24),
]),
),
),
@@ -150,33 +100,4 @@ class _AboutScreenState extends State<AboutScreen> {
),
);
}
Widget _buildDependencyItem(String name, String description) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
const Icon(Icons.circle, size: 6),
const SizedBox(width: 8),
Expanded(
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: name,
style: const TextStyle(fontWeight: FontWeight.w600),
),
TextSpan(
text: ' - $description',
style: const TextStyle(color: Colors.grey),
),
],
style: const TextStyle(fontSize: 13, color: Colors.white),
),
),
),
],
),
);
}
}
+182 -19
View File
@@ -1,5 +1,8 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import 'server_selection_screen.dart';
@@ -16,6 +19,8 @@ class _AuthScreenState extends State<AuthScreen> {
String? _errorMessage;
late PlexAuthService _authService;
bool _shouldCancelPolling = false;
bool _useQrFlow = false; // whether current auth attempt is QR based
String? _qrAuthUrl; // auth URL rendered as QR
@override
void initState() {
@@ -32,6 +37,10 @@ class _AuthScreenState extends State<AuthScreen> {
_isAuthenticating = true;
_errorMessage = null;
_shouldCancelPolling = false;
// preserve _useQrFlow as chosen prior to calling
if (!_useQrFlow) {
_qrAuthUrl = null; // ensure stale QR cleared for browser flow
}
});
try {
@@ -43,12 +52,19 @@ class _AuthScreenState extends State<AuthScreen> {
// Construct auth URL
final authUrl = _authService.getAuthUrl(pinCode);
// Open browser (in-app for mobile, external for desktop)
final uri = Uri.parse(authUrl);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.inAppBrowserView);
if (_useQrFlow) {
// Display QR instead of launching browser
setState(() {
_qrAuthUrl = authUrl;
});
} else {
throw Exception('Could not launch auth URL');
// Open browser (in-app for mobile, external for desktop)
final uri = Uri.parse(authUrl);
if (await canLaunchUrl(uri)) {
await launchUrl(uri, mode: LaunchMode.inAppBrowserView);
} else {
throw Exception('Could not launch auth URL');
}
}
// Poll for authentication with cancellation support
@@ -71,10 +87,12 @@ class _AuthScreenState extends State<AuthScreen> {
}
// Auto-close the in-app browser on mobile (no-op on desktop)
try {
await closeInAppWebView();
} catch (e) {
// Ignore errors - browser might already be closed or on desktop
if (!_useQrFlow) {
try {
await closeInAppWebView();
} catch (e) {
// Ignore errors - browser might already be closed or on desktop
}
}
// Store the token
@@ -93,6 +111,11 @@ class _AuthScreenState extends State<AuthScreen> {
),
);
}
// Clear QR URL after successful auth
setState(() {
_qrAuthUrl = null;
_useQrFlow = false;
});
} catch (e) {
setState(() {
_isAuthenticating = false;
@@ -105,11 +128,102 @@ class _AuthScreenState extends State<AuthScreen> {
setState(() {
_shouldCancelPolling = true;
_isAuthenticating = false;
_qrAuthUrl = null;
});
// Start new authentication after a brief delay to ensure cleanup
Future.delayed(const Duration(milliseconds: 100), _startAuthentication);
}
void _handleDebugTap() {
if (!kDebugMode) return;
_showDebugTokenDialog();
}
void _showDebugTokenDialog() {
final tokenController = TextEditingController();
String? errorMessage;
showDialog<void>(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setDialogState) {
return AlertDialog(
title: const Text('Debug: Enter Plex Token'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: tokenController,
decoration: InputDecoration(
labelText: 'Plex Auth Token',
hintText: 'Enter your Plex.tv token',
errorText: errorMessage,
border: const OutlineInputBorder(),
),
obscureText: true,
maxLines: 1,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: () async {
final token = tokenController.text.trim();
if (token.isEmpty) {
setDialogState(() {
errorMessage = 'Please enter a token';
});
return;
}
final navigator = Navigator.of(context);
try {
final isValid = await _authService.verifyToken(token);
if (!isValid) {
setDialogState(() {
errorMessage = 'Invalid token';
});
return;
}
// Store the token
final storage = await StorageService.getInstance();
await storage.savePlexToken(token);
// Close dialog and navigate
if (mounted) {
navigator.pop();
navigator.pushReplacement(
MaterialPageRoute(
builder: (context) => ServerSelectionScreen(
authService: _authService,
plexToken: token,
),
),
);
}
} catch (e) {
setDialogState(() {
errorMessage = 'Failed to verify token: $e';
});
}
},
child: const Text('Authenticate'),
),
],
);
},
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -121,11 +235,7 @@ class _AuthScreenState extends State<AuthScreen> {
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Image.asset(
'assets/plezy.png',
width: 120,
height: 120,
),
Image.asset('assets/plezy.png', width: 120, height: 120),
const SizedBox(height: 24),
Text(
'Plezy',
@@ -138,20 +248,42 @@ class _AuthScreenState extends State<AuthScreen> {
if (_isAuthenticating) ...[
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 16),
const Text(
'Waiting for authentication...\nPlease complete sign-in in your browser.',
Text(
_useQrFlow
? 'Scan this QR code with a device logged into Plex to authenticate.'
: 'Waiting for authentication...\nPlease complete sign-in in your browser.',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
style: const TextStyle(color: Colors.grey),
),
if (_useQrFlow && _qrAuthUrl != null) ...[
const SizedBox(height: 24),
Center(
child: QrImageView(
data: _qrAuthUrl!,
size: 200,
version: QrVersions.auto,
backgroundColor: Colors.white,
),
),
const SizedBox(height: 16),
SelectableText(
_qrAuthUrl!,
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 10, color: Colors.grey),
),
],
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: const Text('Retry'),
),
] else ...[
] else ...[ // add QR button here
ElevatedButton(
onPressed: _startAuthentication,
style: ElevatedButton.styleFrom(
@@ -159,6 +291,37 @@ class _AuthScreenState extends State<AuthScreen> {
),
child: const Text('Sign in with Plex'),
),
const SizedBox(height: 12),
OutlinedButton(
onPressed: () {
setState(() {
_useQrFlow = true;
});
_startAuthentication();
},
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
),
child: const Text('Show QR Code'),
),
if (kDebugMode) ...[
const SizedBox(height: 12),
OutlinedButton(
onPressed: _handleDebugTap,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12),
side: BorderSide(
color: Theme.of(
context,
).colorScheme.outline.withValues(alpha: 0.5),
),
),
child: const Text(
'Debug: Enter Token',
style: TextStyle(fontSize: 12),
),
),
],
if (_errorMessage != null) ...[
const SizedBox(height: 16),
Text(
File diff suppressed because it is too large Load Diff
+356
View File
@@ -0,0 +1,356 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_hub.dart';
import '../models/plex_metadata.dart';
import '../models/plex_sort.dart';
import '../providers/settings_provider.dart';
import '../services/settings_service.dart';
import '../utils/provider_extensions.dart';
import '../utils/app_logger.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/sort_bottom_sheet.dart';
import '../mixins/refreshable.dart';
/// Screen to display full content of a recommendation hub
class HubDetailScreen extends StatefulWidget {
final PlexHub hub;
const HubDetailScreen({super.key, required this.hub});
@override
State<HubDetailScreen> createState() => _HubDetailScreenState();
}
class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
PlexClient get client => context.clientSafe;
List<PlexMetadata> _items = [];
List<PlexMetadata> _filteredItems = [];
List<PlexSort> _sortOptions = [];
PlexSort? _selectedSort;
bool _isSortDescending = false;
bool _isLoading = false;
String? _errorMessage;
@override
void initState() {
super.initState();
// Start with items already loaded in the hub
_items = widget.hub.items;
_filteredItems = widget.hub.items;
// Load more items if available
if (widget.hub.more) {
_loadMoreItems();
}
// Load sorts based on the library type
_loadSorts();
}
Future<void> _loadSorts() async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
// Get the library key from the hub key
// Hub keys can have various formats:
// - /hubs/sections/1/...
// - /library/sections/1/all?...
final hubKey = widget.hub.hubKey;
appLogger.d('Hub key: $hubKey');
// Try different patterns
RegExpMatch? match = RegExp(r'/hubs/sections/(\d+)').firstMatch(hubKey);
match ??= RegExp(r'/library/sections/(\d+)').firstMatch(hubKey);
match ??= RegExp(r'sections/(\d+)').firstMatch(hubKey);
if (match != null) {
final sectionId = match.group(1)!;
appLogger.d('Loading sorts for section: $sectionId');
// Load sorts for this library
final sorts = await client.getLibrarySorts(sectionId);
appLogger.d('Loaded ${sorts.length} sorts');
setState(() {
_sortOptions = sorts.isNotEmpty ? sorts : _getDefaultSortOptions();
// Don't set a default sort - let items stay in original order
});
} else {
appLogger.w('Could not extract section ID from hub key: $hubKey');
// Provide default sort options even if we can't get library-specific ones
setState(() {
_sortOptions = _getDefaultSortOptions();
// Don't set a default sort - let items stay in original order
});
}
} catch (e) {
appLogger.e('Failed to load sorts', error: e);
// Provide default sort options on error
setState(() {
_sortOptions = _getDefaultSortOptions();
// Don't set a default sort - let items stay in original order
});
}
}
List<PlexSort> _getDefaultSortOptions() {
return [
PlexSort(key: 'titleSort', title: 'Title', defaultDirection: 'asc'),
PlexSort(
key: 'year',
descKey: 'year:desc',
title: 'Release Year',
defaultDirection: 'desc',
),
PlexSort(
key: 'addedAt',
descKey: 'addedAt:desc',
title: 'Date Added',
defaultDirection: 'desc',
),
PlexSort(
key: 'rating',
descKey: 'rating:desc',
title: 'Rating',
defaultDirection: 'desc',
),
];
}
void _applySort() {
setState(() {
_filteredItems = List.from(_items);
// Apply sorting
if (_selectedSort != null) {
final sortKey = _selectedSort!.key;
_filteredItems.sort((a, b) {
int comparison = 0;
switch (sortKey) {
case 'titleSort':
case 'title':
comparison = a.title.compareTo(b.title);
break;
case 'addedAt':
comparison = (a.addedAt ?? 0).compareTo(b.addedAt ?? 0);
break;
case 'originallyAvailableAt':
case 'year':
comparison = (a.year ?? 0).compareTo(b.year ?? 0);
break;
case 'rating':
comparison = (a.rating ?? 0).compareTo(b.rating ?? 0);
break;
default:
comparison = a.title.compareTo(b.title);
}
return _isSortDescending ? -comparison : comparison;
});
}
});
}
void _showSortBottomSheet() {
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (context) => SortBottomSheet(
sortOptions: _sortOptions,
selectedSort: _selectedSort,
isSortDescending: _isSortDescending,
onSortChanged: (sort, descending) {
setState(() {
_selectedSort = sort;
_isSortDescending = descending;
});
_applySort();
},
onClear: () {
setState(() {
// Reset to no sorting (original order)
_selectedSort = null;
_isSortDescending = false;
});
_applySort();
},
),
);
}
Future<void> _loadMoreItems() async {
if (_isLoading) return;
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// Fetch more items from the hub using the hubKey
final response = await client.getHubContent(widget.hub.hubKey);
setState(() {
_items = response;
_filteredItems = response;
_isLoading = false;
});
// Apply any existing sort
_applySort();
appLogger.d(
'Loaded ${response.length} items for hub: ${widget.hub.title}',
);
} catch (e) {
appLogger.e('Failed to load hub content', error: e);
setState(() {
_errorMessage = 'Failed to load content: $e';
_isLoading = false;
});
}
}
void _handleItemRefresh(String ratingKey) {
// Refresh the specific item in the list
setState(() {
final index = _items.indexWhere((item) => item.ratingKey == ratingKey);
if (index != -1) {
// The item will be refreshed by the MediaCard itself
appLogger.d('Item refresh requested for: $ratingKey');
}
});
}
@override
void refresh() {
_loadMoreItems();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: Text(widget.hub.title),
pinned: true,
actions: [
IconButton(
icon: const Icon(Icons.swap_vert, semanticLabel: 'Sort'),
onPressed: _showSortBottomSheet,
),
],
),
if (_errorMessage != null)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.error_outline,
size: 48,
color: Colors.red,
),
const SizedBox(height: 16),
Text(_errorMessage!),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadMoreItems,
child: const Text('Retry'),
),
],
),
),
)
else if (_filteredItems.isEmpty && _isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (_filteredItems.isEmpty)
const SliverFillRemaining(
child: Center(child: Text('No items found')),
)
else
SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: _getMaxCrossAxisExtent(
context,
context.watch<SettingsProvider>().libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
delegate: SliverChildBuilderDelegate((context, index) {
return MediaCard(
item: _filteredItems[index],
onRefresh: _handleItemRefresh,
);
}, childCount: _filteredItems.length),
),
),
],
),
);
}
double _getMaxCrossAxisExtent(BuildContext context, LibraryDensity density) {
final screenWidth = MediaQuery.of(context).size.width;
final padding = 16.0; // 8px left + 8px right
final availableWidth = screenWidth - padding;
if (screenWidth >= 900) {
// Wide screens (desktop/large tablet landscape): Responsive division
double divisor;
double maxItemWidth;
switch (density) {
case LibraryDensity.comfortable:
divisor = 6.5;
maxItemWidth = 280;
break;
case LibraryDensity.normal:
divisor = 8.0;
maxItemWidth = 200;
break;
case LibraryDensity.compact:
divisor = 10.0;
maxItemWidth = 160;
break;
}
return (availableWidth / divisor).clamp(0, maxItemWidth);
} else if (screenWidth >= 600) {
// Medium screens (tablets): Fixed 4-5-6 items
int targetItemCount = switch (density) {
LibraryDensity.comfortable => 4,
LibraryDensity.normal => 5,
LibraryDensity.compact => 6,
};
return availableWidth / targetItemCount;
} else {
// Small screens (phones): Fixed 2-3-4 items
int targetItemCount = switch (density) {
LibraryDensity.comfortable => 2,
LibraryDensity.normal => 3,
LibraryDensity.compact => 4,
};
return availableWidth / targetItemCount;
}
}
}
File diff suppressed because it is too large Load Diff
+216
View File
@@ -0,0 +1,216 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../widgets/desktop_app_bar.dart';
class MergedLicenseEntry {
final String packageName;
final List<LicenseEntry> licenseEntries;
final Set<String> allPackageNames;
MergedLicenseEntry({
required this.packageName,
required this.licenseEntries,
required this.allPackageNames,
});
}
class LicensesScreen extends StatefulWidget {
const LicensesScreen({super.key});
@override
State<LicensesScreen> createState() => _LicensesScreenState();
}
class _LicensesScreenState extends State<LicensesScreen> {
List<MergedLicenseEntry> _mergedLicenses = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadLicenses();
}
Future<void> _loadLicenses() async {
final licenseMap = <String, List<LicenseEntry>>{};
final allPackageNames = <String, Set<String>>{};
await for (final license in LicenseRegistry.licenses) {
for (final packageName in license.packages) {
if (!licenseMap.containsKey(packageName)) {
licenseMap[packageName] = [];
allPackageNames[packageName] = <String>{};
}
licenseMap[packageName]!.add(license);
allPackageNames[packageName]!.addAll(license.packages);
}
}
final mergedLicenses = licenseMap.entries.map((entry) {
return MergedLicenseEntry(
packageName: entry.key,
licenseEntries: entry.value,
allPackageNames: allPackageNames[entry.key]!,
);
}).toList();
mergedLicenses.sort((a, b) => a.packageName.compareTo(b.packageName));
if (mounted) {
setState(() {
_mergedLicenses = mergedLicenses;
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Licenses'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final mergedLicense = _mergedLicenses[index];
final packageName = mergedLicense.packageName;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
title: Text(
packageName,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
subtitle: mergedLicense.licenseEntries.length > 1
? Text(
'${mergedLicense.licenseEntries.length} licenses',
)
: null,
trailing: const Icon(Icons.chevron_right),
onTap: () => _showLicenseDetail(mergedLicense),
),
);
}, childCount: _mergedLicenses.length),
),
),
],
),
);
}
void _showLicenseDetail(MergedLicenseEntry mergedLicense) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
_LicenseDetailScreen(mergedLicense: mergedLicense),
),
);
}
}
class _LicenseDetailScreen extends StatelessWidget {
final MergedLicenseEntry mergedLicense;
const _LicenseDetailScreen({required this.mergedLicense});
@override
Widget build(BuildContext context) {
final packageName = mergedLicense.packageName;
final licenseEntries = mergedLicense.licenseEntries;
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(packageName), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
// Package info card
if (mergedLicense.allPackageNames.length > 1)
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Related Packages',
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
mergedLicense.allPackageNames.join(', '),
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
),
if (mergedLicense.allPackageNames.length > 1)
const SizedBox(height: 16),
// License cards
...licenseEntries.asMap().entries.map((entry) {
final index = entry.key;
final license = entry.value;
final isMultipleLicenses = licenseEntries.length > 1;
return Column(
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isMultipleLicenses
? 'License ${index + 1}'
: 'License',
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
...license.paragraphs.map((paragraph) {
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: SelectableText(
paragraph.text,
style: TextStyle(
fontFamily: paragraph.indent > 0
? 'monospace'
: null,
fontSize: 14,
),
),
);
}),
],
),
),
),
if (index < licenseEntries.length - 1)
const SizedBox(height: 16),
],
);
}),
]),
),
),
],
),
);
}
}
+318
View File
@@ -0,0 +1,318 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:logger/logger.dart';
import '../utils/app_logger.dart';
import '../widgets/desktop_app_bar.dart';
class LogsScreen extends StatefulWidget {
const LogsScreen({super.key});
@override
State<LogsScreen> createState() => _LogsScreenState();
}
class _LogsScreenState extends State<LogsScreen> {
List<LogEntry> _logs = [];
@override
void initState() {
super.initState();
_loadLogs();
}
void _loadLogs() {
setState(() {
_logs = MemoryLogOutput.getLogs();
});
}
String _formatTime(DateTime time) {
final hour = time.hour.toString().padLeft(2, '0');
final minute = time.minute.toString().padLeft(2, '0');
final second = time.second.toString().padLeft(2, '0');
final millisecond = time.millisecond.toString().padLeft(3, '0');
return '$hour:$minute:$second.$millisecond';
}
void _clearLogs() {
setState(() {
MemoryLogOutput.clearLogs();
_logs = [];
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Logs cleared')),
);
}
void _copyAllLogs() {
final buffer = StringBuffer();
bool isFirst = true;
for (final log in _logs.reversed) {
if (!isFirst) {
buffer.write('\n');
}
isFirst = false;
buffer.write(
'[${_formatTime(log.timestamp)}] [${log.level.name.toUpperCase()}] ${log.message}');
if (log.error != null) {
buffer.write('\nError: ${log.error}');
}
if (log.stackTrace != null) {
buffer.write('\nStack trace:\n${log.stackTrace}');
}
}
Clipboard.setData(ClipboardData(text: buffer.toString()));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Logs copied to clipboard')),
);
}
Color _getLevelColor(Level level) {
switch (level) {
case Level.error:
case Level.fatal:
return Colors.red;
case Level.warning:
return Colors.orange;
case Level.info:
return Colors.blue;
case Level.debug:
case Level.trace:
return Colors.grey;
default:
return Colors.grey;
}
}
IconData _getLevelIcon(Level level) {
switch (level) {
case Level.error:
case Level.fatal:
return Icons.error;
case Level.warning:
return Icons.warning;
case Level.info:
return Icons.info;
case Level.debug:
case Level.trace:
return Icons.bug_report;
default:
return Icons.circle;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: const Text('Logs'),
pinned: true,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _loadLogs,
tooltip: 'Refresh',
),
IconButton(
icon: const Icon(Icons.copy),
onPressed: _logs.isNotEmpty ? _copyAllLogs : null,
tooltip: 'Copy All',
),
IconButton(
icon: const Icon(Icons.delete_outline),
onPressed: _logs.isNotEmpty ? _clearLogs : null,
tooltip: 'Clear Logs',
),
],
),
if (_logs.isEmpty)
const SliverFillRemaining(
child: Center(
child: Text('No logs available'),
),
)
else
SliverPadding(
padding: const EdgeInsets.all(8),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final log = _logs[index];
return _LogEntryCard(
log: log,
formatTime: _formatTime,
levelColor: _getLevelColor(log.level),
levelIcon: _getLevelIcon(log.level),
);
},
childCount: _logs.length,
),
),
),
],
),
);
}
}
class _LogEntryCard extends StatefulWidget {
final LogEntry log;
final String Function(DateTime) formatTime;
final Color levelColor;
final IconData levelIcon;
const _LogEntryCard({
required this.log,
required this.formatTime,
required this.levelColor,
required this.levelIcon,
});
@override
State<_LogEntryCard> createState() => _LogEntryCardState();
}
class _LogEntryCardState extends State<_LogEntryCard> {
bool _isExpanded = false;
@override
Widget build(BuildContext context) {
final hasErrorOrStackTrace =
widget.log.error != null || widget.log.stackTrace != null;
return Card(
margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 0),
child: InkWell(
onTap: hasErrorOrStackTrace
? () => setState(() => _isExpanded = !_isExpanded)
: null,
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
widget.levelIcon,
color: widget.levelColor,
size: 20,
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
widget.log.level.name.toUpperCase(),
style: TextStyle(
fontWeight: FontWeight.bold,
color: widget.levelColor,
fontSize: 12,
),
),
const SizedBox(width: 8),
Text(
widget.formatTime(widget.log.timestamp),
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: Theme.of(context)
.textTheme
.bodySmall
?.color
?.withValues(alpha: 0.6),
),
),
],
),
const SizedBox(height: 4),
Text(
widget.log.message,
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
if (hasErrorOrStackTrace)
Icon(
_isExpanded
? Icons.expand_less
: Icons.expand_more,
color: Theme.of(context)
.iconTheme
.color
?.withValues(alpha: 0.6),
),
],
),
if (_isExpanded && hasErrorOrStackTrace) ...[
const SizedBox(height: 12),
const Divider(),
const SizedBox(height: 8),
if (widget.log.error != null) ...[
Text(
'Error:',
style: Theme.of(context).textTheme.titleSmall?.copyWith(
color: widget.levelColor,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).brightness == Brightness.dark
? Colors.grey[900]
: Colors.grey[200],
borderRadius: BorderRadius.circular(4),
),
child: SelectableText(
widget.log.error.toString(),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontFamily: 'monospace',
),
),
),
],
if (widget.log.stackTrace != null) ...[
const SizedBox(height: 12),
Text(
'Stack Trace:',
style: Theme.of(context).textTheme.titleSmall?.copyWith(
color: widget.levelColor,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Theme.of(context).brightness == Brightness.dark
? Colors.grey[900]
: Colors.grey[200],
borderRadius: BorderRadius.circular(4),
),
child: SelectableText(
widget.log.stackTrace.toString(),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontFamily: 'monospace',
),
),
),
],
],
],
),
),
),
);
}
}
+47 -7
View File
@@ -1,18 +1,18 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_user_profile.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../main.dart';
import '../mixins/refreshable.dart';
import 'discover_screen.dart';
import 'libraries_screen.dart';
import 'search_screen.dart';
import 'settings_screen.dart';
class MainScreen extends StatefulWidget {
final PlexClient client;
final PlexUserProfile? userProfile;
const MainScreen({super.key, required this.client, this.userProfile});
const MainScreen({super.key, required this.client});
@override
State<MainScreen> createState() => _MainScreenState();
@@ -23,6 +23,9 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
late final List<Widget> _screens;
final GlobalKey<State<DiscoverScreen>> _discoverKey = GlobalKey();
final GlobalKey<State<LibrariesScreen>> _librariesKey = GlobalKey();
final GlobalKey<State<SearchScreen>> _searchKey = GlobalKey();
final GlobalKey<State<SettingsScreen>> _settingsKey = GlobalKey();
@override
void initState() {
@@ -31,13 +34,22 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
_screens = [
DiscoverScreen(
key: _discoverKey,
client: widget.client,
userProfile: widget.userProfile,
onBecameVisible: _onDiscoverBecameVisible,
),
LibrariesScreen(client: widget.client, userProfile: widget.userProfile),
SearchScreen(client: widget.client, userProfile: widget.userProfile),
LibrariesScreen(key: _librariesKey),
SearchScreen(key: _searchKey),
SettingsScreen(key: _settingsKey),
];
// Set up data invalidation callback for profile switching
WidgetsBinding.instance.addPostFrameCallback((_) async {
// Initialize UserProfileProvider to ensure it's ready after sign-in
final userProfileProvider = context.userProfile;
await userProfileProvider.initialize();
// Set up data invalidation callback for profile switching
userProfileProvider.setDataInvalidationCallback(_invalidateAllScreens);
});
}
@override
@@ -77,6 +89,29 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
}
}
/// Invalidate all cached data across all screens when profile is switched
void _invalidateAllScreens() {
appLogger.d('Invalidating all screen data due to profile switch');
// Refresh discover screen
final discoverState = _discoverKey.currentState;
if (discoverState != null && discoverState is Refreshable) {
(discoverState as Refreshable).refresh();
}
// Refresh libraries screen
final librariesState = _librariesKey.currentState;
if (librariesState != null && librariesState is Refreshable) {
(librariesState as Refreshable).refresh();
}
// Refresh search screen
final searchState = _searchKey.currentState;
if (searchState != null && searchState is Refreshable) {
(searchState as Refreshable).refresh();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -108,6 +143,11 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
selectedIcon: Icon(Icons.search),
label: 'Search',
),
NavigationDestination(
icon: Icon(Icons.settings_outlined),
selectedIcon: Icon(Icons.settings),
label: 'Settings',
),
],
),
);
+351 -207
View File
@@ -1,26 +1,23 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../client/plex_client.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
import '../widgets/media_context_menu.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/content_rating_formatter.dart';
import '../utils/shuffle_play_helper.dart';
import '../theme/theme_helper.dart';
import 'season_detail_screen.dart';
import 'video_player_screen.dart';
class MediaDetailScreen extends StatefulWidget {
final PlexClient client;
final PlexMetadata metadata;
final PlexUserProfile? userProfile;
const MediaDetailScreen({
super.key,
required this.client,
required this.metadata,
this.userProfile,
});
const MediaDetailScreen({super.key, required this.metadata});
@override
State<MediaDetailScreen> createState() => _MediaDetailScreenState();
@@ -32,21 +29,36 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
PlexMetadata? _fullMetadata;
PlexMetadata? _onDeckEpisode;
bool _isLoadingMetadata = true;
late final ScrollController _scrollController;
bool _watchStateChanged = false;
@override
void initState() {
super.initState();
_scrollController = ScrollController();
_loadFullMetadata();
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
Future<void> _loadFullMetadata() async {
setState(() {
_isLoadingMetadata = true;
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// Fetch full metadata with clearLogo and OnDeck episode
final result = await widget.client.getMetadataWithImagesAndOnDeck(
final result = await client.getMetadataWithImagesAndOnDeck(
widget.metadata.ratingKey,
);
final metadata = result['metadata'] as PlexMetadata?;
@@ -94,9 +106,13 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
});
try {
final seasons = await widget.client.getChildren(
widget.metadata.ratingKey,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final seasons = await client.getChildren(widget.metadata.ratingKey);
setState(() {
_seasons = seasons;
_isLoadingSeasons = false;
@@ -108,8 +124,50 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
}
}
/// Update watch state without full screen rebuild
/// This preserves scroll position and only updates watch-related data
Future<void> _updateWatchState() async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final metadata = await client.getMetadataWithImages(
widget.metadata.ratingKey,
);
if (metadata != null) {
// For shows, also refetch seasons to update their watch counts
List<PlexMetadata>? updatedSeasons;
if (metadata.type.toLowerCase() == 'show') {
updatedSeasons = await client.getChildren(widget.metadata.ratingKey);
}
// Single setState to minimize rebuilds - scroll position is preserved by controller
setState(() {
_fullMetadata = metadata;
if (updatedSeasons != null) {
_seasons = updatedSeasons;
}
});
}
} catch (e) {
appLogger.e('Failed to update watch state', error: e);
// Silently fail - user can manually refresh if needed
}
}
Future<void> _playFirstEpisode() async {
try {
// Extract context dependencies before async operations
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// If seasons aren't loaded yet, wait for them or load them
if (_seasons.isEmpty && !_isLoadingSeasons) {
await _loadSeasons();
@@ -133,7 +191,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
final firstSeason = _seasons.first;
// Get episodes of the first season
final episodes = await widget.client.getChildren(firstSeason.ratingKey);
final episodes = await client.getChildren(firstSeason.ratingKey);
if (episodes.isEmpty) {
if (mounted) {
@@ -147,17 +205,12 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
// Play the first episode
final firstEpisode = episodes.first;
if (mounted) {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Playing first episode: ${firstEpisode.title}');
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: firstEpisode,
userProfile: widget.userProfile,
),
),
);
await navigateToVideoPlayer(context, metadata: firstEpisode);
appLogger.d('Returned from playback, refreshing metadata');
// Refresh metadata when returning from video player
_loadFullMetadata();
@@ -192,13 +245,15 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
return Scaffold(
body: CustomScrollView(
controller: _scrollController,
slivers: [
// Hero header with background art
DesktopSliverAppBar(
expandedHeight: headerHeight,
pinned: true,
leading: const AppBarBackButton(
leading: AppBarBackButton(
style: BackButtonStyle.circular,
onPressed: () => Navigator.pop(context, _watchStateChanged),
),
flexibleSpace: FlexibleSpaceBar(
background: Stack(
@@ -206,19 +261,31 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
children: [
// Background Art
if (metadata.art != null)
CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(metadata.art),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(metadata.art),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
);
},
)
else
Container(
@@ -260,42 +327,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
SizedBox(
height: 120,
width: 400,
child: CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(
metadata.clearLogo,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
placeholder: (context, url) => Align(
alignment: Alignment.centerLeft,
child: Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white.withValues(
alpha: 0.3,
),
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
errorWidget: (context, url, error) {
return Align(
alignment: Alignment.centerLeft,
child: Text(
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Text(
metadata.title,
style: Theme.of(context)
.textTheme
@@ -303,17 +339,66 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(alpha: 0.5),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
metadata.clearLogo,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
placeholder: (context, url) => Align(
alignment: Alignment.centerLeft,
child: Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white.withValues(
alpha: 0.3,
),
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(alpha: 0.5),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
errorWidget: (context, url, error) {
return Align(
alignment: Alignment.centerLeft,
child: Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
);
},
);
},
),
@@ -378,7 +463,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
borderRadius: BorderRadius.circular(6),
),
child: Text(
metadata.contentRating!,
formatContentRating(metadata.contentRating!),
style: const TextStyle(
color: Colors.white,
fontSize: 13,
@@ -438,18 +523,20 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
// Otherwise, play the first episode of the first season
if (metadata.type.toLowerCase() == 'show') {
if (_onDeckEpisode != null) {
appLogger.d('Playing on deck episode: ${_onDeckEpisode!.title}');
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: _onDeckEpisode!,
userProfile: widget.userProfile,
),
),
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d(
'Playing on deck episode: ${_onDeckEpisode!.title}',
);
await navigateToVideoPlayer(
context,
metadata: _onDeckEpisode!,
);
appLogger.d(
'Returned from playback, refreshing metadata',
);
appLogger.d('Returned from playback, refreshing metadata');
// Refresh metadata when returning from video player
_loadFullMetadata();
} else {
@@ -457,19 +544,19 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
await _playFirstEpisode();
}
} else {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Playing: ${metadata.title}');
// For movies or episodes, play directly
await Navigator.push(
await navigateToVideoPlayer(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: metadata,
userProfile: widget.userProfile,
),
),
metadata: metadata,
);
appLogger.d(
'Returned from playback, refreshing metadata',
);
appLogger.d('Returned from playback, refreshing metadata');
// Refresh metadata when returning from video player
_loadFullMetadata();
}
@@ -488,20 +575,40 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
),
),
const SizedBox(width: 12),
// Shuffle button (only for shows and seasons)
if (metadata.type.toLowerCase() == 'show' ||
metadata.type.toLowerCase() == 'season') ...[
IconButton.filledTonal(
onPressed: () async {
await handleShufflePlay(context, metadata);
},
icon: const Icon(Icons.shuffle),
tooltip: 'Shuffle play',
iconSize: 20,
style: IconButton.styleFrom(
minimumSize: const Size(48, 48),
maximumSize: const Size(48, 48),
),
),
const SizedBox(width: 12),
],
IconButton.filledTonal(
onPressed: () async {
try {
await widget.client.markAsWatched(
metadata.ratingKey,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
await client.markAsWatched(metadata.ratingKey);
if (context.mounted) {
_watchStateChanged = true;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Marked as watched'),
),
);
// Refresh metadata to update UI
_loadFullMetadata();
// Update watch state without full rebuild
_updateWatchState();
}
} catch (e) {
if (context.mounted) {
@@ -523,17 +630,20 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
IconButton.filledTonal(
onPressed: () async {
try {
await widget.client.markAsUnwatched(
metadata.ratingKey,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
await client.markAsUnwatched(metadata.ratingKey);
if (context.mounted) {
_watchStateChanged = true;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Marked as unwatched'),
),
);
// Refresh metadata to update UI
_loadFullMetadata();
// Update watch state without full rebuild
_updateWatchState();
}
} catch (e) {
if (context.mounted) {
@@ -624,7 +734,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
const SizedBox(height: 12),
],
if (metadata.contentRating != null) ...[
_buildInfoRow('Rating', metadata.contentRating!),
_buildInfoRow('Rating', formatContentRating(metadata.contentRating!)),
const SizedBox(height: 12),
],
],
@@ -640,108 +750,142 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
return Card(
clipBehavior: Clip.antiAlias,
child: MediaContextMenu(
client: widget.client,
metadata: season,
onRefresh: _loadFullMetadata,
onTap: () {
Navigator.push(
onRefresh: (ratingKey) {
_watchStateChanged = true;
_updateWatchState();
},
onTap: () async {
final watchStateChanged = await Navigator.push<bool>(
context,
MaterialPageRoute(
builder: (context) =>
SeasonDetailScreen(client: widget.client, season: season),
builder: (context) => SeasonDetailScreen(season: season),
),
);
if (watchStateChanged == true) {
_watchStateChanged = true;
_updateWatchState();
}
},
child: InkWell(
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
// Season poster
if (season.thumb != null)
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(season.thumb),
width: 80,
height: 120,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
),
)
else
Container(
width: 80,
height: 120,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: Semantics(
label: "media-season-${season.ratingKey}",
identifier: "media-season-${season.ratingKey}",
button: true,
hint: "Tap to view ${season.title}",
child: InkWell(
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
// Season poster
if (season.thumb != null)
ClipRRect(
borderRadius: BorderRadius.circular(6),
),
child: const Icon(Icons.movie, size: 32),
),
const SizedBox(width: 16),
// Season info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
season.title,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
if (season.leafCount != null)
Text(
'${season.leafCount} episodes',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 8),
if (season.viewedLeafCount != null &&
season.leafCount != null)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
LinearProgressIndicator(
value:
season.viewedLeafCount! / season.leafCount!,
backgroundColor: Theme.of(
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(season.thumb),
width: 80,
height: 120,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
const SizedBox(height: 4),
Text(
'${season.viewedLeafCount}/${season.leafCount} watched',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(color: Colors.grey),
errorWidget: (context, url, error) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
],
),
],
),
),
);
},
),
)
else
Container(
width: 80,
height: 120,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
),
child: const Icon(Icons.movie, size: 32),
),
const SizedBox(width: 16),
const Icon(Icons.chevron_right),
],
// Season info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
season.title,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
if (season.leafCount != null)
Text(
'${season.leafCount} episodes',
style: Theme.of(context).textTheme.bodyMedium
?.copyWith(color: Colors.grey),
),
const SizedBox(height: 8),
if (season.viewedLeafCount != null &&
season.leafCount != null)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 200,
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value:
season.viewedLeafCount! /
season.leafCount!,
backgroundColor: tokens(context).outline,
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary,
),
minHeight: 6,
),
),
),
const SizedBox(height: 4),
Text(
'${season.viewedLeafCount}/${season.leafCount} watched',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(color: Colors.grey),
),
],
),
],
),
),
const Icon(Icons.chevron_right),
],
),
),
),
),
+124
View File
@@ -0,0 +1,124 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/profile_list_tile.dart';
import '../widgets/desktop_app_bar.dart';
class ProfileSwitchScreen extends StatelessWidget {
const ProfileSwitchScreen({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Switch Profile')),
SliverFillRemaining(
child: Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
final users = userProvider.home?.users ?? [];
if (userProvider.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (userProvider.error != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
userProvider.error!,
style: TextStyle(color: theme.colorScheme.error),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
userProvider.refreshCurrentUser();
},
child: const Text('Retry'),
),
],
),
);
}
if (users.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.person_off,
size: 64,
color: theme.colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'No profiles available',
style: theme.textTheme.titleMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 8),
Text(
'Contact your Plex administrator to add profiles',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
],
),
);
}
return ListView.builder(
itemCount: users.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
final user = users[index];
final isCurrentUser =
user.uuid == userProvider.currentUser?.uuid;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Card(
child: ProfileListTile(
user: user,
isCurrentUser: isCurrentUser,
onTap: () => _switchToUser(context, user),
),
),
);
},
);
},
),
),
],
),
);
}
void _switchToUser(BuildContext context, PlexHomeUser user) async {
final userProvider = context.userProfile;
final success = await userProvider.switchToUser(user, context);
if (success && context.mounted) {
Navigator.of(context).pop();
} else if (!success && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to switch to ${user.displayName}'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
}
}
+124 -25
View File
@@ -1,28 +1,34 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../services/settings_service.dart';
import '../providers/settings_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../mixins/refreshable.dart';
import '../mixins/item_updatable.dart';
class SearchScreen extends StatefulWidget {
final PlexClient client;
final PlexUserProfile? userProfile;
const SearchScreen({super.key, required this.client, this.userProfile});
const SearchScreen({super.key});
@override
State<SearchScreen> createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> with Refreshable {
class _SearchScreenState extends State<SearchScreen>
with Refreshable, ItemUpdatable {
@override
PlexClient get client => context.clientSafe;
final _searchController = TextEditingController();
List<PlexMetadata> _searchResults = [];
bool _isSearching = false;
bool _hasSearched = false;
Timer? _debounceTimer;
String _lastSearchedQuery = '';
@override
void initState() {
@@ -49,10 +55,16 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
_searchResults = [];
_hasSearched = false;
_isSearching = false;
_lastSearchedQuery = '';
});
return;
}
// Only search if the query has actually changed
if (query.trim() == _lastSearchedQuery.trim()) {
return;
}
// Start new timer
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
_performSearch(query);
@@ -74,11 +86,18 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
});
try {
final results = await widget.client.search(query);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final results = await client.search(query);
if (mounted) {
setState(() {
_searchResults = results;
_isSearching = false;
_lastSearchedQuery = query.trim();
});
}
} catch (e) {
@@ -101,6 +120,16 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
}
}
@override
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
final index = _searchResults.indexWhere(
(item) => item.ratingKey == ratingKey,
);
if (index != -1) {
_searchResults[index] = updatedMetadata;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -184,29 +213,99 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
),
)
else
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 180,
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = _searchResults[index];
return MediaCard(
client: widget.client,
item: item,
onRefresh: refresh,
userProfile: widget.userProfile,
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
},
childCount: _searchResults.length,
),
),
);
}, childCount: _searchResults.length),
),
} else {
return SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: _getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
),
delegate: SliverChildBuilderDelegate((context, index) {
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
item: item,
onRefresh: updateItem,
);
}, childCount: _searchResults.length),
),
);
}
},
),
],
),
),
);
}
double _getMaxCrossAxisExtent(BuildContext context, LibraryDensity density) {
final screenWidth = MediaQuery.of(context).size.width;
final padding = 32.0; // 16px left + 16px right from SliverPadding
final availableWidth = screenWidth - padding;
if (screenWidth >= 900) {
// Wide screens (desktop/large tablet landscape): Responsive division
double divisor;
double maxItemWidth;
switch (density) {
case LibraryDensity.comfortable:
divisor = 6.5;
maxItemWidth = 280;
break;
case LibraryDensity.normal:
divisor = 8.0;
maxItemWidth = 200;
break;
case LibraryDensity.compact:
divisor = 10.0;
maxItemWidth = 160;
break;
}
return (availableWidth / divisor).clamp(0, maxItemWidth);
} else if (screenWidth >= 600) {
// Medium screens (tablets): Fixed 4-5-6 items
int targetItemCount = switch (density) {
LibraryDensity.comfortable => 4,
LibraryDensity.normal => 5,
LibraryDensity.compact => 6,
};
return availableWidth / targetItemCount;
} else {
// Small screens (phones): Fixed 2-3-4 items
int targetItemCount = switch (density) {
LibraryDensity.comfortable => 2,
LibraryDensity.normal => 3,
LibraryDensity.compact => 4,
};
return availableWidth / targetItemCount;
}
}
}
+140 -119
View File
@@ -1,31 +1,33 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
import 'video_player_screen.dart';
import '../widgets/media_context_menu.dart';
import '../mixins/item_updatable.dart';
import '../theme/theme_helper.dart';
class SeasonDetailScreen extends StatefulWidget {
final PlexClient client;
final PlexMetadata season;
final PlexUserProfile? userProfile;
const SeasonDetailScreen({
super.key,
required this.client,
required this.season,
this.userProfile,
});
const SeasonDetailScreen({super.key, required this.season});
@override
State<SeasonDetailScreen> createState() => _SeasonDetailScreenState();
}
class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
class _SeasonDetailScreenState extends State<SeasonDetailScreen>
with ItemUpdatable {
@override
PlexClient get client => context.clientSafe;
List<PlexMetadata> _episodes = [];
bool _isLoadingEpisodes = false;
bool _watchStateChanged = false;
@override
void initState() {
@@ -39,7 +41,13 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
});
try {
final episodes = await widget.client.getChildren(widget.season.ratingKey);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final episodes = await client.getChildren(widget.season.ratingKey);
setState(() {
_episodes = episodes;
_isLoadingEpisodes = false;
@@ -51,17 +59,29 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
}
}
@override
Future<void> updateItem(String ratingKey) async {
_watchStateChanged = true;
await super.updateItem(ratingKey);
}
@override
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
final index = _episodes.indexWhere((item) => item.ratingKey == ratingKey);
if (index != -1) {
_episodes[index] = updatedMetadata;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
DesktopSliverAppBar(
CustomAppBar(
title: Text(widget.season.title),
pinned: true,
leading: const AppBarBackButton(
style: BackButtonStyle.circular,
),
onBackPressed: () => Navigator.pop(context, _watchStateChanged),
),
if (_isLoadingEpisodes)
const SliverFillRemaining(
@@ -73,35 +93,28 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icon(
Icons.movie_outlined,
size: 64,
color: Colors.grey,
color: tokens(context).textMuted,
),
const SizedBox(height: 16),
Text(
'No episodes found',
style: Theme.of(
context,
).textTheme.titleLarge?.copyWith(color: Colors.grey),
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: tokens(context).textMuted,
),
),
],
),
),
)
else
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
if (index.isOdd) {
return const SizedBox(height: 12);
}
final episodeIndex = index ~/ 2;
final episode = _episodes[episodeIndex];
return _buildEpisodeCard(episode);
}, childCount: _episodes.length * 2 - 1),
),
SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final episode = _episodes[index];
return _buildEpisodeCard(episode);
}, childCount: _episodes.length),
),
],
),
@@ -117,25 +130,26 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
? episode.viewOffset! / episode.duration!
: 0.0;
return Card(
clipBehavior: Clip.antiAlias,
return MediaContextMenu(
metadata: episode,
onRefresh: updateItem,
onTap: () async {
await navigateToVideoPlayer(context, metadata: episode);
// Refresh episodes when returning from video player
_loadEpisodes();
},
child: InkWell(
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: episode,
userProfile: widget.userProfile,
),
key: Key(episode.ratingKey),
hoverColor: Theme.of(
context,
).colorScheme.surface.withValues(alpha: 0.05),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: tokens(context).outline, width: 0.5),
),
);
// Refresh episodes when returning from video player
_loadEpisodes();
},
child: Padding(
padding: const EdgeInsets.all(12),
),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -149,22 +163,42 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
child: AspectRatio(
aspectRatio: 16 / 9,
child: episode.thumb != null
? CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(
episode.thumb,
),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
? Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Center(
child: Icon(Icons.movie, size: 40),
),
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
episode.thumb,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) =>
Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(
Icons.movie,
size: 32,
),
),
);
},
)
: Container(
color: Theme.of(
@@ -206,31 +240,6 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
),
),
// Watched indicator
if (episode.isWatched)
Positioned(
top: 4,
right: 4,
child: Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: Colors.green,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.3),
blurRadius: 4,
),
],
),
child: const Icon(
Icons.check,
color: Colors.white,
size: 12,
),
),
),
// Progress bar at bottom
if (hasProgress && !episode.isWatched)
Positioned(
@@ -244,36 +253,11 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
),
child: LinearProgressIndicator(
value: progress,
backgroundColor: Colors.grey.withValues(alpha: 0.3),
backgroundColor: tokens(context).outline,
minHeight: 3,
),
),
),
// Duration badge
if (episode.duration != null)
Positioned(
bottom: 4,
right: 4,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 2,
),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(3),
),
child: Text(
_formatDuration(episode.duration!),
style: const TextStyle(
color: Colors.white,
fontSize: 10,
fontWeight: FontWeight.w600,
),
),
),
),
],
),
),
@@ -331,13 +315,50 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
Text(
episode.summary!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.grey,
color: tokens(context).textMuted,
height: 1.3,
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
],
// Metadata row (duration, watched status)
const SizedBox(height: 8),
Row(
children: [
if (episode.duration != null)
Text(
_formatDuration(episode.duration!),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
if (episode.duration != null && episode.isWatched) ...[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Text(
'•',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
),
Text(
'Watched ✓',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
],
],
),
],
),
),
+157 -73
View File
@@ -1,10 +1,11 @@
import 'package:flutter/material.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../client/plex_client.dart';
import '../config/plex_config.dart';
import '../services/server_connection_service.dart';
import '../widgets/server_list_tile.dart';
import '../widgets/desktop_app_bar.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import 'main_screen.dart';
class ServerSelectionScreen extends StatefulWidget {
@@ -25,13 +26,26 @@ class _ServerSelectionScreenState extends State<ServerSelectionScreen> {
List<PlexServer>? _servers;
bool _isLoading = true;
String? _errorMessage;
String? _currentServerUrl;
@override
void initState() {
super.initState();
_loadCurrentServerUrl();
_loadServers();
}
Future<void> _loadCurrentServerUrl() async {
try {
final storage = await StorageService.getInstance();
setState(() {
_currentServerUrl = storage.getServerUrl();
});
} catch (e) {
appLogger.w('Failed to load current server URL', error: e);
}
}
Future<void> _loadServers() async {
try {
final servers = await widget.authService.fetchServers(widget.plexToken);
@@ -59,100 +73,170 @@ class _ServerSelectionScreenState extends State<ServerSelectionScreen> {
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text('Testing connections...'),
Text('Connecting to server...'),
],
),
),
);
}
// Test connections to find best working one
final connection = await server.findBestWorkingConnection();
try {
// Get client identifier and storage
final storage = await StorageService.getInstance();
final clientId =
storage.getClientIdentifier() ?? widget.authService.clientIdentifier;
// Close loading dialog
if (mounted) {
Navigator.pop(context);
}
// Get current profile context to maintain profile across server switch
final currentUserUUID = storage.getCurrentUserUUID();
if (connection == null) {
PlexServer serverWithCorrectToken = server;
// If we have a current profile, get a profile-specific token for this server
if (currentUserUUID != null) {
try {
// Switch to the current profile on the new server to get the correct token
final switchResponse = await widget.authService.switchToUser(
currentUserUUID,
widget.plexToken,
);
// Get servers with the profile's Plex.tv token to get profile-specific server tokens
final servers = await widget.authService.fetchServers(
switchResponse.authToken,
);
// Find the matching server with the profile-specific token
final matchingServer = servers.firstWhere(
(s) =>
s.name == server.name ||
s.clientIdentifier == server.clientIdentifier,
orElse: () => server, // Fallback to original server
);
serverWithCorrectToken = matchingServer;
appLogger.d(
'Got profile-specific token for server ${server.name} and user UUID $currentUserUUID',
);
} catch (e) {
appLogger.w(
'Failed to get profile-specific token, using default server token',
error: e,
);
// Continue with original server token as fallback
}
}
// Connect using the server with the correct token
final result = await ServerConnectionService.connectToServer(
serverWithCorrectToken,
clientIdentifier: clientId,
plexToken: widget.plexToken,
);
// Close loading dialog
if (mounted) {
Navigator.pop(context);
}
// Handle result
if (result.isSuccess) {
// Set client in provider before navigation (same pattern as auto-login)
if (mounted) {
context.plexClient.setClient(result.client!);
// Navigate to main app and clear navigation stack
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: result.client!),
),
(route) => false, // Remove all routes
);
}
} else {
// Show error
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(result.error ?? 'Connection failed')),
);
}
}
} catch (e) {
// Close loading dialog on error
if (mounted) {
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('No working connections found for this server'),
),
SnackBar(content: Text('Failed to connect to server: $e')),
);
}
return;
appLogger.e('Server selection failed', error: e);
}
}
// Store server information
final storage = await StorageService.getInstance();
await storage.saveServerData(server.toJson());
await storage.saveServerUrl(connection.uri);
await storage.saveServerAccessToken(server.accessToken);
await storage.savePlexToken(widget.plexToken);
bool _isCurrentServer(PlexServer server) {
if (_currentServerUrl == null) return false;
// Get client identifier
final clientId =
storage.getClientIdentifier() ?? widget.authService.clientIdentifier;
// Create client and navigate to main app
final config = await PlexConfig.create(
baseUrl: connection.uri,
token: server.accessToken,
clientIdentifier: clientId,
);
final client = PlexClient(config);
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => MainScreen(client: client)),
);
// Check all server connections to see if any match the current server URL
for (final connection in server.connections) {
if (connection.uri == _currentServerUrl) {
return true;
}
}
return false;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const DesktopAppBar(title: Text('Select Server')),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_errorMessage!,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Select Server')),
SliverFillRemaining(
child: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_errorMessage!,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadServers,
child: const Text('Retry'),
),
],
),
textAlign: TextAlign.center,
)
: _servers == null || _servers!.isEmpty
? const Center(child: Text('No servers found'))
: ListView.builder(
itemCount: _servers!.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
final server = _servers![index];
final isCurrentServer = _isCurrentServer(server);
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Card(
child: ServerListTile(
server: server,
isCurrentServer: isCurrentServer,
onTap: () => _selectServer(server),
),
),
);
},
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadServers,
child: const Text('Retry'),
),
],
),
)
: _servers == null || _servers!.isEmpty
? const Center(child: Text('No servers found'))
: ListView.builder(
itemCount: _servers!.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
final server = _servers![index];
return Card(
child: ServerListTile(
server: server,
onTap: () => _selectServer(server),
),
);
},
),
),
],
),
);
}
}
File diff suppressed because it is too large Load Diff
+328
View File
@@ -0,0 +1,328 @@
import 'package:flutter/material.dart';
import 'package:flex_color_picker/flex_color_picker.dart';
import '../services/settings_service.dart';
import '../widgets/desktop_app_bar.dart';
class SubtitleStylingScreen extends StatefulWidget {
const SubtitleStylingScreen({super.key});
@override
State<SubtitleStylingScreen> createState() => _SubtitleStylingScreenState();
}
class _SubtitleStylingScreenState extends State<SubtitleStylingScreen> {
static const EdgeInsets _sliderPadding = EdgeInsets.fromLTRB(16, 16, 16, 8);
late SettingsService _settingsService;
bool _isLoading = true;
int _fontSize = 55;
String _textColor = '#FFFFFF';
int _borderSize = 3;
String _borderColor = '#000000';
String _backgroundColor = '#000000';
int _backgroundOpacity = 0;
@override
void initState() {
super.initState();
_loadSettings();
}
Future<void> _loadSettings() async {
_settingsService = await SettingsService.getInstance();
setState(() {
_fontSize = _settingsService.getSubtitleFontSize();
_textColor = _settingsService.getSubtitleTextColor();
_borderSize = _settingsService.getSubtitleBorderSize();
_borderColor = _settingsService.getSubtitleBorderColor();
_backgroundColor = _settingsService.getSubtitleBackgroundColor();
_backgroundOpacity = _settingsService.getSubtitleBackgroundOpacity();
_isLoading = false;
});
}
Color _hexToColor(String hexString) {
final buffer = StringBuffer();
if (hexString.length == 7) buffer.write('ff');
buffer.write(hexString.replaceFirst('#', ''));
return Color(int.parse(buffer.toString(), radix: 16));
}
String _colorToHex(Color color) {
return '#${color.red.toRadixString(16).padLeft(2, '0')}${color.green.toRadixString(16).padLeft(2, '0')}${color.blue.toRadixString(16).padLeft(2, '0')}'.toUpperCase();
}
Future<void> _showColorPicker(String title, String currentColor, Function(String) onColorSelected) async {
Color initialColor = _hexToColor(currentColor);
final Color? selectedColor = await showColorPickerDialog(
context,
initialColor,
title: Text(title),
barrierColor: Colors.black54,
width: 40,
height: 40,
spacing: 0,
runSpacing: 0,
borderRadius: 4,
wheelDiameter: 165,
enableOpacity: false,
showColorCode: true,
colorCodeHasColor: true,
pickersEnabled: const <ColorPickerType, bool>{
ColorPickerType.both: false,
ColorPickerType.primary: true,
ColorPickerType.accent: false,
ColorPickerType.wheel: true,
ColorPickerType.custom: false,
},
actionButtons: const ColorPickerActionButtons(
okButton: true,
closeButton: true,
dialogActionButtons: false,
),
);
if (selectedColor != null) {
final hexColor = _colorToHex(selectedColor);
onColorSelected(hexColor);
}
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Subtitle Styling'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildStylingCard(),
const SizedBox(height: 24),
]),
),
),
],
),
);
}
Widget _buildStylingCard() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Styling Options',
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
// Font Size Slider
Padding(
padding: _sliderPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Font Size'),
Text('$_fontSize'),
],
),
const SizedBox(height: 8),
Row(
children: [
const Text('30', style: TextStyle(fontSize: 12, color: Colors.grey)),
Expanded(
child: Slider(
value: _fontSize.toDouble(),
min: 30,
max: 80,
divisions: 50,
label: _fontSize.toString(),
onChanged: (value) {
setState(() {
_fontSize = value.toInt();
});
},
onChangeEnd: (value) {
_settingsService.setSubtitleFontSize(_fontSize);
},
),
),
const Text('80', style: TextStyle(fontSize: 12, color: Colors.grey)),
],
),
],
),
),
const Divider(),
// Text Color
ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: _hexToColor(_textColor),
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(4),
),
),
title: const Text('Text Color'),
subtitle: Text(_textColor),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showColorPicker('Text Color', _textColor, (color) {
setState(() {
_textColor = color;
});
_settingsService.setSubtitleTextColor(color);
});
},
),
const Divider(),
// Border Size Slider
Padding(
padding: _sliderPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Border Size'),
Text('$_borderSize'),
],
),
const SizedBox(height: 8),
Row(
children: [
const Text('0', style: TextStyle(fontSize: 12, color: Colors.grey)),
Expanded(
child: Slider(
value: _borderSize.toDouble(),
min: 0,
max: 5,
divisions: 5,
label: _borderSize.toString(),
onChanged: (value) {
setState(() {
_borderSize = value.toInt();
});
},
onChangeEnd: (value) {
_settingsService.setSubtitleBorderSize(_borderSize);
},
),
),
const Text('5', style: TextStyle(fontSize: 12, color: Colors.grey)),
],
),
],
),
),
const Divider(),
// Border Color
ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: _hexToColor(_borderColor),
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(4),
),
),
title: const Text('Border Color'),
subtitle: Text(_borderColor),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showColorPicker('Border Color', _borderColor, (color) {
setState(() {
_borderColor = color;
});
_settingsService.setSubtitleBorderColor(color);
});
},
),
const Divider(),
// Background Opacity Slider
Padding(
padding: _sliderPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text('Background Opacity'),
Text('$_backgroundOpacity%'),
],
),
const SizedBox(height: 8),
Row(
children: [
const Text('0%', style: TextStyle(fontSize: 12, color: Colors.grey)),
Expanded(
child: Slider(
value: _backgroundOpacity.toDouble(),
min: 0,
max: 100,
divisions: 20,
label: '$_backgroundOpacity%',
onChanged: (value) {
setState(() {
_backgroundOpacity = value.toInt();
});
},
onChangeEnd: (value) {
_settingsService.setSubtitleBackgroundOpacity(_backgroundOpacity);
},
),
),
const Text('100%', style: TextStyle(fontSize: 12, color: Colors.grey)),
],
),
],
),
),
const Divider(),
// Background Color
ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: _hexToColor(_backgroundColor),
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(4),
),
),
title: const Text('Background Color'),
subtitle: Text(_backgroundColor),
trailing: const Icon(Icons.chevron_right),
onTap: () {
_showColorPicker('Background Color', _backgroundColor, (color) {
setState(() {
_backgroundColor = color;
});
_settingsService.setSubtitleBackgroundColor(color);
});
},
),
],
),
);
}
}
File diff suppressed because it is too large Load Diff
+186
View File
@@ -0,0 +1,186 @@
import 'package:audio_service/audio_service.dart';
import 'package:media_kit/media_kit.dart';
import '../models/plex_metadata.dart';
import '../utils/app_logger.dart';
import 'media_kit_audio_handler.dart';
/// Global singleton manager for audio service
/// Ensures AudioService.init() is only called once and the handler is reused
class AudioServiceManager {
static AudioServiceManager? _instance;
MediaKitAudioHandler? _handler;
bool _isInitialized = false;
bool _isInitializing = false;
AudioServiceManager._();
static AudioServiceManager get instance {
_instance ??= AudioServiceManager._();
return _instance!;
}
/// Initialize the audio service with the given player and configuration
/// This should only be called once - subsequent calls will reuse the existing handler
Future<void> initialize({
required Player player,
required String plexServerUrl,
required String authToken,
Future<void> Function()? onSkipToNext,
Future<void> Function()? onSkipToPrevious,
}) async {
// If already initialized, update the player reference and callbacks
if (_isInitialized && _handler != null) {
appLogger.d('Audio service already initialized, updating player reference and callbacks');
// Update the player reference (critical for episode switching)
await _handler!.updatePlayer(player);
// Update navigation callbacks
_handler!.onSkipToNext = onSkipToNext;
_handler!.onSkipToPrevious = onSkipToPrevious;
return;
}
// Prevent concurrent initialization
if (_isInitializing) {
appLogger.d('Audio service initialization already in progress, waiting...');
// Wait for initialization to complete
while (_isInitializing) {
await Future.delayed(const Duration(milliseconds: 100));
}
return;
}
try {
_isInitializing = true;
appLogger.d('Initializing audio service for the first time');
final handler = await AudioService.init(
builder: () => MediaKitAudioHandler(
player: player,
plexServerUrl: plexServerUrl,
authToken: authToken,
onSkipToNext: onSkipToNext,
onSkipToPrevious: onSkipToPrevious,
),
config: const AudioServiceConfig(
androidNotificationChannelId: 'com.edde746.plezy.audio',
androidNotificationChannelName: 'Plezy Playback',
androidNotificationOngoing: true,
androidShowNotificationBadge: true,
),
);
_handler = handler;
_isInitialized = true;
appLogger.d('Audio service initialized successfully');
} catch (e) {
appLogger.e('Failed to initialize audio service', error: e);
rethrow;
} finally {
_isInitializing = false;
}
}
/// Update the current media item being played
void updateMediaItem(PlexMetadata metadata) {
if (_handler == null) {
appLogger.w('Cannot update media item: audio handler not initialized');
return;
}
_handler!.updateCurrentMediaItem(metadata);
}
/// Update navigation callbacks for next/previous episode
void updateNavigation({
Future<void> Function()? onNext,
Future<void> Function()? onPrevious,
}) {
if (_handler == null) {
appLogger.w('Cannot update navigation: audio handler not initialized');
return;
}
_handler!.updateNavigationCallbacks(
onNext: onNext,
onPrevious: onPrevious,
);
}
/// Pause playback but keep the media session active
Future<void> pause() async {
if (_handler == null) {
appLogger.w('Cannot pause: audio handler not initialized');
return;
}
await _handler!.pause();
}
/// Clear the notification but keep the audio service singleton alive
/// This is used when exiting the video player but not closing the app
Future<void> clearNotification() async {
if (_handler == null) {
appLogger.w('Cannot clear notification: audio handler not initialized');
return;
}
appLogger.d('Clearing notification while keeping audio service alive');
// Broadcast idle state to remove notification
_handler!.playbackState.add(PlaybackState(
processingState: AudioProcessingState.idle,
playing: false,
controls: [],
systemActions: const {},
updatePosition: Duration.zero,
bufferedPosition: Duration.zero,
speed: 1.0,
));
// Clear media item
_handler!.mediaItem.add(null);
// IMPORTANT: DON'T reset _isInitialized or _handler
// Keep the singleton alive for next playback
appLogger.d('Notification cleared, audio service remains initialized');
}
/// Stop playback completely and remove the notification
/// This should only be called when the app is closing or user explicitly stops
Future<void> shutdown() async {
if (_handler == null) {
appLogger.w('Cannot shutdown: audio handler not initialized');
return;
}
appLogger.d('Shutting down audio service and removing notification');
// Broadcast idle state to remove notification
_handler!.playbackState.add(PlaybackState(
processingState: AudioProcessingState.idle,
playing: false,
controls: [],
systemActions: const {},
updatePosition: Duration.zero,
bufferedPosition: Duration.zero,
speed: 1.0,
));
// Clear media item
_handler!.mediaItem.add(null);
// Dispose the handler
await _handler!.dispose();
_handler = null;
_isInitialized = false;
appLogger.d('Audio service shutdown complete');
}
/// Check if the audio service is initialized
bool get isInitialized => _isInitialized;
/// Get the current handler (for advanced use cases)
MediaKitAudioHandler? get handler => _handler;
}
@@ -0,0 +1,400 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import 'settings_service.dart';
class KeyboardShortcutsService {
static KeyboardShortcutsService? _instance;
late SettingsService _settingsService;
Map<String, String> _shortcuts =
{}; // Legacy string shortcuts for backward compatibility
Map<String, HotKey> _hotkeys = {}; // New HotKey objects
int _seekTimeSmall = 10; // Default, loaded from settings
int _seekTimeLarge = 30; // Default, loaded from settings
KeyboardShortcutsService._();
static Future<KeyboardShortcutsService> getInstance() async {
if (_instance == null) {
_instance = KeyboardShortcutsService._();
await _instance!._init();
}
return _instance!;
}
Future<void> _init() async {
_settingsService = await SettingsService.getInstance();
// Ensure settings service is fully initialized before loading data
await Future.delayed(Duration.zero); // Allow event loop to complete
_shortcuts = _settingsService
.getKeyboardShortcuts(); // Keep for legacy compatibility
_hotkeys = await _settingsService.getKeyboardHotkeys(); // Primary method
_seekTimeSmall = _settingsService.getSeekTimeSmall();
_seekTimeLarge = _settingsService.getSeekTimeLarge();
}
Map<String, String> get shortcuts => Map.from(_shortcuts);
Map<String, HotKey> get hotkeys => Map.from(_hotkeys);
String getShortcut(String action) {
return _shortcuts[action] ?? '';
}
HotKey? getHotkey(String action) {
return _hotkeys[action];
}
Future<void> setShortcut(String action, String key) async {
_shortcuts[action] = key;
await _settingsService.setKeyboardShortcuts(_shortcuts);
}
Future<void> setHotkey(String action, HotKey hotkey) async {
// Update local cache first
_hotkeys[action] = hotkey;
// Save to persistent storage
await _settingsService.setKeyboardHotkey(action, hotkey);
// Verify local cache is still correct
if (_hotkeys[action] != hotkey) {
_hotkeys[action] = hotkey; // Restore correct value
}
}
Future<void> refreshFromStorage() async {
_hotkeys = await _settingsService.getKeyboardHotkeys();
_seekTimeSmall = _settingsService.getSeekTimeSmall();
_seekTimeLarge = _settingsService.getSeekTimeLarge();
}
Future<void> resetToDefaults() async {
_shortcuts = _settingsService.getDefaultKeyboardShortcuts();
_hotkeys = _settingsService.getDefaultKeyboardHotkeys();
await _settingsService.setKeyboardShortcuts(_shortcuts);
await _settingsService.setKeyboardHotkeys(_hotkeys);
// Refresh cache to ensure consistency
await refreshFromStorage();
}
// Format HotKey for display
String formatHotkey(HotKey? hotKey) {
if (hotKey == null) return 'No shortcut set';
final modifiers = <String>[];
for (final modifier in hotKey.modifiers ?? []) {
switch (modifier) {
case HotKeyModifier.alt:
modifiers.add('Alt');
break;
case HotKeyModifier.control:
modifiers.add('Ctrl');
break;
case HotKeyModifier.shift:
modifiers.add('Shift');
break;
case HotKeyModifier.meta:
modifiers.add('Meta');
break;
case HotKeyModifier.capsLock:
modifiers.add('CapsLock');
break;
case HotKeyModifier.fn:
modifiers.add('Fn');
break;
}
}
// Format the key name
String keyName = hotKey.key.keyLabel;
if (keyName.startsWith('PhysicalKeyboardKey#')) {
keyName = keyName.substring(20, keyName.length - 1);
}
if (keyName.startsWith('key')) {
keyName = keyName.substring(3).toUpperCase();
}
// Special cases for common keys
switch (keyName.toLowerCase()) {
case 'space':
keyName = 'Space';
break;
case 'arrowup':
keyName = 'Arrow Up';
break;
case 'arrowdown':
keyName = 'Arrow Down';
break;
case 'arrowleft':
keyName = 'Arrow Left';
break;
case 'arrowright':
keyName = 'Arrow Right';
break;
case 'equal':
keyName = 'Plus';
break;
case 'minus':
keyName = 'Minus';
break;
}
return modifiers.isEmpty ? keyName : '${modifiers.join(' + ')} + $keyName';
}
// Handle keyboard input for video player
KeyEventResult handleVideoPlayerKeyEvent(
KeyEvent event,
Player player,
VoidCallback? onToggleFullscreen,
VoidCallback? onToggleSubtitles,
VoidCallback? onNextAudioTrack,
VoidCallback? onNextSubtitleTrack,
VoidCallback? onNextChapter,
VoidCallback? onPreviousChapter,
) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
final physicalKey = event.physicalKey;
final isShiftPressed = HardwareKeyboard.instance.isShiftPressed;
final isControlPressed = HardwareKeyboard.instance.isControlPressed;
final isAltPressed = HardwareKeyboard.instance.isAltPressed;
final isMetaPressed = HardwareKeyboard.instance.isMetaPressed;
// Check each hotkey
for (final entry in _hotkeys.entries) {
final action = entry.key;
final hotkey = entry.value;
// Check if the physical key matches
if (physicalKey != hotkey.key) continue;
// Check if modifiers match
final requiredModifiers = hotkey.modifiers ?? [];
bool modifiersMatch = true;
// Check each required modifier
for (final modifier in requiredModifiers) {
switch (modifier) {
case HotKeyModifier.shift:
if (!isShiftPressed) modifiersMatch = false;
break;
case HotKeyModifier.control:
if (!isControlPressed) modifiersMatch = false;
break;
case HotKeyModifier.alt:
if (!isAltPressed) modifiersMatch = false;
break;
case HotKeyModifier.meta:
if (!isMetaPressed) modifiersMatch = false;
break;
case HotKeyModifier.capsLock:
// CapsLock is typically not used for shortcuts, ignore for now
break;
case HotKeyModifier.fn:
// Fn key is typically not used for shortcuts, ignore for now
break;
}
if (!modifiersMatch) break;
}
// Check that no extra modifiers are pressed
if (modifiersMatch) {
final hasShift = requiredModifiers.contains(HotKeyModifier.shift);
final hasControl = requiredModifiers.contains(HotKeyModifier.control);
final hasAlt = requiredModifiers.contains(HotKeyModifier.alt);
final hasMeta = requiredModifiers.contains(HotKeyModifier.meta);
if (isShiftPressed != hasShift ||
isControlPressed != hasControl ||
isAltPressed != hasAlt ||
isMetaPressed != hasMeta) {
continue;
}
_executeAction(
action,
player,
onToggleFullscreen,
onToggleSubtitles,
onNextAudioTrack,
onNextSubtitleTrack,
onNextChapter,
onPreviousChapter,
);
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
/// Seeks by the given offset (can be positive or negative) while clamping
/// the result between 0 and the video duration
void _seekWithClamping(Player player, Duration offset) {
final currentPosition = player.state.position;
final duration = player.state.duration;
final newPosition = currentPosition + offset;
// Clamp between 0 and video duration
final clampedPosition = newPosition.isNegative
? Duration.zero
: (newPosition > duration ? duration : newPosition);
player.seek(clampedPosition);
}
void _executeAction(
String action,
Player player,
VoidCallback? onToggleFullscreen,
VoidCallback? onToggleSubtitles,
VoidCallback? onNextAudioTrack,
VoidCallback? onNextSubtitleTrack,
VoidCallback? onNextChapter,
VoidCallback? onPreviousChapter,
) {
switch (action) {
case 'play_pause':
player.playOrPause();
break;
case 'volume_up':
final newVolume = (player.state.volume + 10).clamp(0.0, 100.0);
player.setVolume(newVolume);
_settingsService.setVolume(newVolume);
break;
case 'volume_down':
final newVolume = (player.state.volume - 10).clamp(0.0, 100.0);
player.setVolume(newVolume);
_settingsService.setVolume(newVolume);
break;
case 'seek_forward':
_seekWithClamping(player, Duration(seconds: _seekTimeSmall));
break;
case 'seek_backward':
_seekWithClamping(player, Duration(seconds: -_seekTimeSmall));
break;
case 'seek_forward_large':
_seekWithClamping(player, Duration(seconds: _seekTimeLarge));
break;
case 'seek_backward_large':
_seekWithClamping(player, Duration(seconds: -_seekTimeLarge));
break;
case 'fullscreen_toggle':
onToggleFullscreen?.call();
break;
case 'mute_toggle':
final newVolume = player.state.volume > 0 ? 0.0 : 100.0;
player.setVolume(newVolume);
_settingsService.setVolume(newVolume);
break;
case 'subtitle_toggle':
onToggleSubtitles?.call();
break;
case 'audio_track_next':
onNextAudioTrack?.call();
break;
case 'subtitle_track_next':
onNextSubtitleTrack?.call();
break;
case 'chapter_next':
onNextChapter?.call();
break;
case 'chapter_previous':
onPreviousChapter?.call();
break;
case 'speed_increase':
final newRate = (player.state.rate + 0.1).clamp(0.1, 3.0);
player.setRate(newRate);
break;
case 'speed_decrease':
final newRate = (player.state.rate - 0.1).clamp(0.1, 3.0);
player.setRate(newRate);
break;
case 'speed_reset':
player.setRate(1.0);
break;
}
}
// Get human-readable action names
String getActionDisplayName(String action) {
switch (action) {
case 'play_pause':
return 'Play/Pause';
case 'volume_up':
return 'Volume Up';
case 'volume_down':
return 'Volume Down';
case 'seek_forward':
return 'Seek Forward (${_seekTimeSmall}s)';
case 'seek_backward':
return 'Seek Backward (${_seekTimeSmall}s)';
case 'seek_forward_large':
return 'Seek Forward (${_seekTimeLarge}s)';
case 'seek_backward_large':
return 'Seek Backward (${_seekTimeLarge}s)';
case 'fullscreen_toggle':
return 'Toggle Fullscreen';
case 'mute_toggle':
return 'Toggle Mute';
case 'subtitle_toggle':
return 'Toggle Subtitles';
case 'audio_track_next':
return 'Next Audio Track';
case 'subtitle_track_next':
return 'Next Subtitle Track';
case 'chapter_next':
return 'Next Chapter';
case 'chapter_previous':
return 'Previous Chapter';
case 'speed_increase':
return 'Increase Speed';
case 'speed_decrease':
return 'Decrease Speed';
case 'speed_reset':
return 'Reset Speed';
default:
return action;
}
}
// Validate if a key combination is valid (legacy method for backward compatibility)
bool isValidKeyShortcut(String keyString) {
// For backward compatibility, assume all non-empty strings are valid
// The new system will use HotKey objects for validation
return keyString.isNotEmpty;
}
// Check if a shortcut is already assigned to another action
String? getActionForShortcut(String keyString) {
for (final entry in _shortcuts.entries) {
if (entry.value == keyString) {
return entry.key;
}
}
return null;
}
// Check if a hotkey is already assigned to another action
String? getActionForHotkey(HotKey hotkey) {
for (final entry in _hotkeys.entries) {
if (_hotkeyEquals(entry.value, hotkey)) {
return entry.key;
}
}
return null;
}
// Helper method to compare two HotKey objects
bool _hotkeyEquals(HotKey a, HotKey b) {
if (a.key != b.key) return false;
final aModifiers = Set.from(a.modifiers ?? []);
final bModifiers = Set.from(b.modifiers ?? []);
return aModifiers.length == bModifiers.length &&
aModifiers.every((modifier) => bModifiers.contains(modifier));
}
}
+314
View File
@@ -0,0 +1,314 @@
import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:media_kit/media_kit.dart';
import 'package:rxdart/rxdart.dart';
import '../models/plex_metadata.dart';
import '../utils/app_logger.dart';
/// Audio handler that bridges media_kit player with OS media controls
class MediaKitAudioHandler extends BaseAudioHandler with SeekHandler {
Player _player;
final String plexServerUrl;
final String authToken;
// Getter for player
Player get player => _player;
// Callback functions for episode navigation
Future<void> Function()? onSkipToNext;
Future<void> Function()? onSkipToPrevious;
// Stream subscriptions
StreamSubscription<bool>? _playingSubscription;
StreamSubscription<Duration>? _positionSubscription;
StreamSubscription<Duration>? _durationSubscription;
StreamSubscription<Duration>? _bufferSubscription;
// Queue management
final BehaviorSubject<List<MediaItem>> _queueSubject = BehaviorSubject.seeded([]);
MediaKitAudioHandler({
required Player player,
required this.plexServerUrl,
required this.authToken,
this.onSkipToNext,
this.onSkipToPrevious,
}) : _player = player {
_init();
}
void _init() {
// Map player state to playback state
_playingSubscription = _player.stream.playing.listen((isPlaying) {
_updatePlaybackState();
});
_positionSubscription = _player.stream.position.listen((_) {
_updatePlaybackState();
});
_durationSubscription = _player.stream.duration.listen((_) {
_updatePlaybackState();
});
_bufferSubscription = _player.stream.buffer.listen((_) {
_updatePlaybackState();
});
// Set initial state
_updatePlaybackState();
}
/// Update media item with current playing content
void updateCurrentMediaItem(PlexMetadata metadata) {
final artworkUrl = _getArtworkUrl(metadata);
final newMediaItem = MediaItem(
id: metadata.ratingKey,
title: metadata.title,
album: _getAlbumName(metadata),
artist: _getArtistName(metadata),
duration: metadata.duration != null
? Duration(milliseconds: metadata.duration!)
: null,
artUri: artworkUrl != null ? Uri.parse(artworkUrl) : null,
extras: {
'ratingKey': metadata.ratingKey,
'type': metadata.type,
},
);
mediaItem.add(newMediaItem);
appLogger.d('Updated media item: ${metadata.title}');
}
/// Update navigation callbacks
void updateNavigationCallbacks({
Future<void> Function()? onNext,
Future<void> Function()? onPrevious,
}) {
onSkipToNext = onNext;
onSkipToPrevious = onPrevious;
_updatePlaybackState();
}
/// Update the queue with episodes
void updateEpisodeQueue(List<PlexMetadata> episodes, int currentIndex) {
final items = episodes.map((episode) {
final artworkUrl = _getArtworkUrl(episode);
return MediaItem(
id: episode.ratingKey,
title: episode.title,
album: _getAlbumName(episode),
artist: _getArtistName(episode),
duration: episode.duration != null
? Duration(milliseconds: episode.duration!)
: null,
artUri: artworkUrl != null ? Uri.parse(artworkUrl) : null,
extras: {
'ratingKey': episode.ratingKey,
'type': episode.type,
},
);
}).toList();
_queueSubject.add(items);
queue.add(items);
if (currentIndex >= 0 && currentIndex < items.length) {
mediaItem.add(items[currentIndex]);
}
appLogger.d('Updated queue with ${items.length} episodes, current index: $currentIndex');
}
String? _getArtworkUrl(PlexMetadata metadata) {
String? thumbPath;
// For episodes, prefer show poster over episode thumbnail
if (metadata.type.toLowerCase() == 'episode') {
thumbPath = metadata.grandparentThumb ?? metadata.thumb;
} else {
thumbPath = metadata.thumb;
}
if (thumbPath == null) return null;
// Build full URL with authentication
return '$plexServerUrl$thumbPath?X-Plex-Token=$authToken';
}
String _getAlbumName(PlexMetadata metadata) {
// For episodes: "Show Name - Season X"
if (metadata.type.toLowerCase() == 'episode') {
final showName = metadata.grandparentTitle ?? '';
final seasonNum = metadata.parentIndex;
if (seasonNum != null) {
return '$showName - Season $seasonNum';
}
return showName;
}
// For movies: studio or year
return metadata.studio ?? metadata.year?.toString() ?? '';
}
String _getArtistName(PlexMetadata metadata) {
// For episodes: show episode info
if (metadata.type.toLowerCase() == 'episode') {
final seasonNum = metadata.parentIndex;
final episodeNum = metadata.index;
if (seasonNum != null && episodeNum != null) {
return 'S${seasonNum.toString().padLeft(2, '0')}E${episodeNum.toString().padLeft(2, '0')}';
}
}
return '';
}
void _updatePlaybackState() {
final isPlaying = _player.state.playing;
final position = _player.state.position;
final bufferedPosition = _player.state.buffer;
// Determine processing state
AudioProcessingState processingState;
if (_player.state.buffering) {
processingState = AudioProcessingState.buffering;
} else if (_player.state.completed) {
processingState = AudioProcessingState.completed;
} else {
processingState = AudioProcessingState.ready;
}
// Build controls based on state and available navigation
final controls = <MediaControl>[
if (onSkipToPrevious != null) MediaControl.skipToPrevious,
MediaControl.rewind,
if (isPlaying) MediaControl.pause else MediaControl.play,
MediaControl.fastForward,
if (onSkipToNext != null) MediaControl.skipToNext,
];
playbackState.add(PlaybackState(
controls: controls,
systemActions: const {
MediaAction.seek,
MediaAction.seekForward,
MediaAction.seekBackward,
},
androidCompactActionIndices: [
if (onSkipToPrevious != null) 0,
onSkipToPrevious != null ? 2 : 1, // Play/Pause button
if (onSkipToNext != null)
onSkipToPrevious != null ? 4 : 3,
].where((i) => i < controls.length).toList(),
processingState: processingState,
playing: isPlaying,
updatePosition: position,
bufferedPosition: bufferedPosition,
speed: 1.0,
queueIndex: 0, // TODO: Update based on actual queue position
));
}
@override
Future<void> play() async {
appLogger.d('Audio handler: play');
await _player.play();
}
@override
Future<void> pause() async {
appLogger.d('Audio handler: pause');
await _player.pause();
}
@override
Future<void> seek(Duration position) async {
appLogger.d('Audio handler: seek to ${position.inSeconds}s');
await _player.seek(position);
}
@override
Future<void> stop() async {
appLogger.d('Audio handler: stop');
await _player.stop();
}
@override
Future<void> fastForward() async {
appLogger.d('Audio handler: fast forward');
final newPosition = _player.state.position + const Duration(seconds: 10);
await _player.seek(newPosition);
}
@override
Future<void> rewind() async {
appLogger.d('Audio handler: rewind');
final newPosition = _player.state.position - const Duration(seconds: 10);
await _player.seek(newPosition > Duration.zero ? newPosition : Duration.zero);
}
@override
Future<void> skipToNext() async {
appLogger.d('Audio handler: skip to next');
if (onSkipToNext != null) {
await onSkipToNext!();
}
}
@override
Future<void> skipToPrevious() async {
appLogger.d('Audio handler: skip to previous');
if (onSkipToPrevious != null) {
await onSkipToPrevious!();
}
}
/// Update the player reference when switching episodes
/// This ensures the handler stays in sync with the current player instance
Future<void> updatePlayer(Player newPlayer) async {
appLogger.d('Audio handler: updating player reference');
// Cancel old subscriptions
await _playingSubscription?.cancel();
await _positionSubscription?.cancel();
await _durationSubscription?.cancel();
await _bufferSubscription?.cancel();
// Update player reference
_player = newPlayer;
// Create new subscriptions with the new player
_playingSubscription = _player.stream.playing.listen((isPlaying) {
_updatePlaybackState();
});
_positionSubscription = _player.stream.position.listen((_) {
_updatePlaybackState();
});
_durationSubscription = _player.stream.duration.listen((_) {
_updatePlaybackState();
});
_bufferSubscription = _player.stream.buffer.listen((_) {
_updatePlaybackState();
});
// Update playback state immediately
_updatePlaybackState();
appLogger.d('Audio handler: player reference updated successfully');
}
Future<void> dispose() async {
// Cancel subscriptions
await _playingSubscription?.cancel();
await _positionSubscription?.cancel();
await _durationSubscription?.cancel();
await _bufferSubscription?.cancel();
await _queueSubject.close();
}
}
+301 -110
View File
@@ -4,6 +4,8 @@ import 'package:uuid/uuid.dart';
import 'storage_service.dart';
import '../client/plex_client.dart';
import '../models/plex_user_profile.dart';
import '../models/plex_home.dart';
import '../models/user_switch_response.dart';
class PlexAuthService {
static const String _appName = 'Plezy';
@@ -11,7 +13,7 @@ class PlexAuthService {
static const String _clientsApi = 'https://clients.plex.tv/api/v2';
final Dio _dio;
late final String _clientIdentifier;
final String _clientIdentifier;
PlexAuthService._(this._dio, this._clientIdentifier);
@@ -20,33 +22,43 @@ class PlexAuthService {
final dio = Dio();
// Get or create client identifier
String? clientId = storage.getClientIdentifier();
if (clientId == null) {
clientId = const Uuid().v4();
await storage.saveClientIdentifier(clientId);
String? clientIdentifier = storage.getClientIdentifier();
if (clientIdentifier == null) {
clientIdentifier = const Uuid().v4();
await storage.saveClientIdentifier(clientIdentifier);
}
return PlexAuthService._(dio, clientId);
return PlexAuthService._(dio, clientIdentifier);
}
String get clientIdentifier => _clientIdentifier;
Options _getCommonOptions({String? authToken}) {
final headers = {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
};
if (authToken != null) {
headers['X-Plex-Token'] = authToken;
}
return Options(headers: headers);
}
Future<Response> _getUser(String authToken) {
return _dio.get(
'$_plexApiBase/user',
options: _getCommonOptions(authToken: authToken),
);
}
/// Verify if a plex.tv token is valid
Future<bool> verifyToken(String token) async {
Future<bool> verifyToken(String authToken) async {
try {
final response = await _dio.get(
'$_plexApiBase/user',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Token': token,
},
validateStatus: (status) => status != null && status < 500,
),
);
return response.statusCode == 200;
await _getUser(authToken);
return true;
} catch (e) {
return false;
}
@@ -56,13 +68,7 @@ class PlexAuthService {
Future<Map<String, dynamic>> createPin() async {
final response = await _dio.post(
'$_plexApiBase/pins?strong=true',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
},
),
options: _getCommonOptions(),
);
return response.data as Map<String, dynamic>;
@@ -91,12 +97,7 @@ class PlexAuthService {
try {
final response = await _dio.get(
'$_plexApiBase/pins/$pinId',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Client-Identifier': _clientIdentifier,
},
),
options: _getCommonOptions(),
);
final data = response.data as Map<String, dynamic>;
@@ -133,17 +134,10 @@ class PlexAuthService {
}
/// Fetch available Plex servers for the authenticated user
Future<List<PlexServer>> fetchServers(String plexToken) async {
Future<List<PlexServer>> fetchServers(String authToken) async {
final response = await _dio.get(
'$_clientsApi/resources?includeHttps=1&includeRelay=1&includeIPv6=1',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Token': plexToken,
},
),
options: _getCommonOptions(authToken: authToken),
);
final List<dynamic> resources = response.data as List<dynamic>;
@@ -156,38 +150,78 @@ class PlexAuthService {
}
/// Get user information
Future<Map<String, dynamic>> getUserInfo(String token) async {
final response = await _dio.get(
'$_plexApiBase/user',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Token': token,
},
),
);
Future<Map<String, dynamic>> getUserInfo(String authToken) async {
final response = await _getUser(authToken);
return response.data as Map<String, dynamic>;
}
/// Get user profile with preferences (audio/subtitle settings)
Future<PlexUserProfile> getUserProfile(String token) async {
Future<PlexUserProfile> getUserProfile(String authToken) async {
final response = await _dio.get(
'$_clientsApi/user',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Token': token,
},
),
options: _getCommonOptions(authToken: authToken),
);
return PlexUserProfile.fromJson(response.data as Map<String, dynamic>);
}
/// Get home users for the authenticated user
Future<PlexHome> getHomeUsers(String authToken) async {
final response = await _dio.get(
'$_clientsApi/home/users',
options: _getCommonOptions(authToken: authToken),
);
return PlexHome.fromJson(response.data as Map<String, dynamic>);
}
/// Switch to a different user in the home
Future<UserSwitchResponse> switchToUser(
String userUUID,
String currentToken, {
String? pin,
}) async {
final queryParams = {
'includeSubscriptions': '1',
'includeProviders': '1',
'includeSettings': '1',
'includeSharedSettings': '1',
'X-Plex-Product': _appName,
'X-Plex-Version': '1.1.0',
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Platform': 'Flutter',
'X-Plex-Platform-Version': '3.8.1',
'X-Plex-Token': currentToken,
'X-Plex-Language': 'en',
if (pin != null) 'pin': pin,
};
final queryString = queryParams.entries
.map(
(e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}',
)
.join('&');
final response = await _dio.post(
'$_clientsApi/home/users/$userUUID/switch?$queryString',
options: Options(
headers: {'Accept': 'application/json', 'Content-Length': '0'},
),
);
return UserSwitchResponse.fromJson(response.data as Map<String, dynamic>);
}
}
/// Helper class to track connection candidates during testing
class _ConnectionCandidate {
final PlexConnection connection;
final String url;
final bool isPlexDirectUri;
_ConnectionCandidate(this.connection, this.url, this.isPlexDirectUri);
}
/// Represents a Plex Media Server
@@ -216,9 +250,18 @@ class PlexServer {
factory PlexServer.fromJson(Map<String, dynamic> json) {
final List<dynamic> connectionsJson = json['connections'] as List<dynamic>;
final connections = connectionsJson
.map((c) => PlexConnection.fromJson(c as Map<String, dynamic>))
.toList();
final connections = <PlexConnection>[];
// Parse connections and generate HTTP fallbacks for HTTPS connections
for (final c in connectionsJson) {
final connection = PlexConnection.fromJson(c as Map<String, dynamic>);
connections.add(connection);
// Generate HTTP fallback for HTTPS connections
if (connection.protocol == 'https') {
connections.add(connection.toHttpFallback());
}
}
DateTime? lastSeenAt;
if (json['lastSeenAt'] != null) {
@@ -259,68 +302,196 @@ class PlexServer {
/// Check if server is online using the presence field
bool get isOnline => presence;
PlexConnection? _selectBest(Iterable<PlexConnection> candidates) {
final local = candidates.where((c) => c.local && !c.relay).toList();
if (local.isNotEmpty) return local.first;
final remote = candidates.where((c) => !c.local && !c.relay).toList();
if (remote.isNotEmpty) return remote.first;
final relay = candidates.where((c) => c.relay).toList();
if (relay.isNotEmpty) return relay.first;
if (candidates.isNotEmpty) return candidates.first;
return null;
}
/// Get the best connection URL
/// Priority: local > remote > relay
PlexConnection? getBestConnection() {
if (connections.isEmpty) return null;
// Try to find local connection first
final local = connections.where((c) => c.local && !c.relay).toList();
if (local.isNotEmpty) return local.first;
// Try remote (non-relay) connection
final remote = connections.where((c) => !c.local && !c.relay).toList();
if (remote.isNotEmpty) return remote.first;
// Fall back to relay as last resort
final relay = connections.where((c) => c.relay).toList();
if (relay.isNotEmpty) return relay.first;
// Return any connection
return connections.first;
return _selectBest(connections);
}
/// Find the best working connection by testing them
/// Tests ALL connections simultaneously and returns the best working one
/// Priority: local > remote > relay (from successful connections)
Future<PlexConnection?> findBestWorkingConnection() async {
if (connections.isEmpty) return null;
/// Returns a Stream that emits connections progressively:
/// 1. First emission: The first connection that responds successfully
/// 2. Second emission (optional): The best connection after latency testing
/// Priority: local > remote > relay, then HTTPS > HTTP, then lowest latency
/// Tests both plex.direct URI and direct IP for each connection
/// HTTPS connections are tested first, with HTTP as fallback
Stream<PlexConnection> findBestWorkingConnection() async* {
if (connections.isEmpty) return;
// Test all connections simultaneously
final results = await Future.wait(
connections.map((connection) async {
final works = await PlexClient.testConnectionUrl(
connection.uri,
// Create candidates: test both uri and directUrl for each connection
// Separate HTTPS and HTTP candidates to prioritize HTTPS first
final httpsCandidates = <_ConnectionCandidate>[];
final httpCandidates = <_ConnectionCandidate>[];
for (final connection in connections) {
final uriCandidate = _ConnectionCandidate(connection, connection.uri, true);
final directCandidate = _ConnectionCandidate(connection, connection.directUrl, false);
if (connection.protocol == 'https') {
httpsCandidates.add(uriCandidate);
httpsCandidates.add(directCandidate);
} else {
httpCandidates.add(uriCandidate);
httpCandidates.add(directCandidate);
}
}
// Combine candidates with HTTPS first, then HTTP
final candidates = [...httpsCandidates, ...httpCandidates];
// Phase 1: Race to find first working connection
final completer = Completer<_ConnectionCandidate?>();
_ConnectionCandidate? firstCandidate;
int completedTests = 0;
// Start testing all candidates simultaneously
for (final candidate in candidates) {
PlexClient.testConnectionWithLatency(candidate.url, accessToken).then((
result,
) {
completedTests++;
// If this is the first successful connection, emit it immediately
if (result.success && !completer.isCompleted) {
completer.complete(candidate);
}
// If all tests complete without success, complete with null
if (completedTests == candidates.length && !completer.isCompleted) {
completer.complete(null);
}
});
}
// Wait for and emit the first successful connection
firstCandidate = await completer.future;
if (firstCandidate == null) {
return; // No working connections found
}
// Update the connection object to use the working URL
final firstConnection = _updateConnectionUrl(
firstCandidate.connection,
firstCandidate.url,
);
yield firstConnection;
// Phase 2: Continue testing in background to find best connection
// Test each candidate 2-3 times and average the latency
final candidateResults = <_ConnectionCandidate, ConnectionTestResult>{};
await Future.wait(
candidates.map((candidate) async {
final result = await PlexClient.testConnectionWithAverageLatency(
candidate.url,
accessToken,
attempts: 2,
);
return works ? connection : null;
if (result.success) {
candidateResults[candidate] = result;
}
}),
);
// Filter out failed connections
final workingConnections = results
.where((c) => c != null)
.cast<PlexConnection>()
// If no connections succeeded, we're done
if (candidateResults.isEmpty) {
return;
}
// Find the best connection considering priority, latency, and URL type
final bestCandidate = _selectBestCandidateWithLatency(candidateResults);
// Emit the best connection if it's different from the first one
if (bestCandidate != null) {
final bestConnection = _updateConnectionUrl(
bestCandidate.connection,
bestCandidate.url,
);
if (bestConnection.uri != firstConnection.uri) {
yield bestConnection;
}
}
}
/// Update a connection's URI to use the specified URL
PlexConnection _updateConnectionUrl(PlexConnection connection, String url) {
// If the URL matches the original URI, return as-is
if (url == connection.uri) {
return connection;
}
// Otherwise, create a new connection with the directUrl as the uri
return PlexConnection(
protocol: connection.protocol,
address: connection.address,
port: connection.port,
uri: url,
local: connection.local,
relay: connection.relay,
ipv6: connection.ipv6,
);
}
/// Select the best candidate considering priority, latency, and URL type preference
_ConnectionCandidate? _selectBestCandidateWithLatency(
Map<_ConnectionCandidate, ConnectionTestResult> results,
) {
// Group candidates by connection type (local/remote/relay)
final localCandidates = results.entries
.where((e) => e.key.connection.local && !e.key.connection.relay)
.toList();
final remoteCandidates = results.entries
.where((e) => !e.key.connection.local && !e.key.connection.relay)
.toList();
final relayCandidates = results.entries
.where((e) => e.key.connection.relay)
.toList();
if (workingConnections.isEmpty) return null;
// Find best in each category
return _findLowestLatencyCandidate(localCandidates) ??
_findLowestLatencyCandidate(remoteCandidates) ??
_findLowestLatencyCandidate(relayCandidates);
}
// From working connections, prefer local > remote > relay
final localWorking = workingConnections
.where((c) => c.local && !c.relay)
.toList();
if (localWorking.isNotEmpty) return localWorking.first;
/// Find the candidate with lowest latency, preferring HTTPS and plex.direct URI on tie
_ConnectionCandidate? _findLowestLatencyCandidate(
List<MapEntry<_ConnectionCandidate, ConnectionTestResult>> entries,
) {
if (entries.isEmpty) return null;
final remoteWorking = workingConnections
.where((c) => !c.local && !c.relay)
.toList();
if (remoteWorking.isNotEmpty) return remoteWorking.first;
// Sort by latency first, then by protocol (HTTPS > HTTP), then by URL type (prefer plex.direct)
entries.sort((a, b) {
final latencyCompare = a.value.latencyMs.compareTo(b.value.latencyMs);
if (latencyCompare != 0) return latencyCompare;
final relayWorking = workingConnections.where((c) => c.relay).toList();
if (relayWorking.isNotEmpty) return relayWorking.first;
// If latencies are equal, prefer HTTPS over HTTP
final aIsHttps = a.key.connection.protocol == 'https';
final bIsHttps = b.key.connection.protocol == 'https';
if (aIsHttps && !bIsHttps) return -1;
if (!aIsHttps && bIsHttps) return 1;
// Fallback to any working connection
return workingConnections.first;
// If latencies and protocols are equal, prefer plex.direct URI (isPlexDirectUri = true)
if (a.key.isPlexDirectUri && !b.key.isPlexDirectUri) return -1;
if (!a.key.isPlexDirectUri && b.key.isPlexDirectUri) return 1;
return 0;
});
return entries.first.key;
}
}
@@ -368,9 +539,29 @@ class PlexConnection {
};
}
/// Get the direct URL constructed from address and port
/// This bypasses plex.direct DNS and connects directly to the IP
String get directUrl => '$protocol://$address:$port';
String get displayType {
if (relay) return 'Relay';
if (local) return 'Local';
return 'Remote';
}
/// Create an HTTP fallback version of this HTTPS connection
/// This allows testing HTTP when HTTPS is unavailable (e.g., certificate issues)
PlexConnection toHttpFallback() {
assert(protocol == 'https', 'Can only create HTTP fallback for HTTPS connections');
return PlexConnection(
protocol: 'http',
address: address,
port: port,
uri: uri.replaceFirst('https://', 'http://'),
local: local,
relay: relay,
ipv6: ipv6,
);
}
}
+151
View File
@@ -0,0 +1,151 @@
import 'plex_auth_service.dart';
import 'storage_service.dart';
import '../client/plex_client.dart';
import '../config/plex_config.dart';
import '../models/plex_user_profile.dart';
import '../utils/app_logger.dart';
/// Result of a server connection attempt
class ServerConnectionResult {
final PlexClient? client;
final PlexUserProfile? userProfile;
final String? error;
ServerConnectionResult({this.client, this.userProfile, this.error});
bool get isSuccess => client != null;
}
/// Service for handling optimized server connections
/// Implements fast-first connection with background optimization
class ServerConnectionService {
/// Connect to a Plex server with optimized connection testing
///
/// Returns immediately with first working connection, then continues
/// testing in background to find the optimal connection.
///
/// Parameters:
/// - [server]: The PlexServer to connect to
/// - [clientIdentifier]: Client identifier for the PlexClient
/// - [plexToken]: Optional plex.tv token to save to storage
/// - [verifyServer]: Whether to verify server is accessible before returning
/// - [fetchUserProfile]: Whether to fetch and cache user profile
/// - [onProgress]: Callback for progress updates (e.g., show/hide loading)
static Future<ServerConnectionResult> connectToServer(
PlexServer server, {
required String clientIdentifier,
String? plexToken,
bool verifyServer = false,
bool fetchUserProfile = false,
void Function(String message)? onProgress,
}) async {
PlexConnection? firstConnection;
final storage = await StorageService.getInstance();
try {
// Listen to the connection stream for progressive connection testing
await for (final connection in server.findBestWorkingConnection()) {
if (firstConnection == null) {
// First emission - use this connection immediately
firstConnection = connection;
if (onProgress != null) {
onProgress('Connected to ${connection.displayType} endpoint');
}
// Save server information to storage
await storage.saveServerData(server.toJson());
await storage.saveServerUrl(connection.uri);
await storage.saveServerAccessToken(server.accessToken);
// Save plex token if provided
if (plexToken != null) {
await storage.savePlexToken(plexToken);
}
// Create client with working connection
final config = await PlexConfig.create(
baseUrl: connection.uri,
token: server.accessToken,
clientIdentifier: clientIdentifier,
);
final client = PlexClient(config);
// Verify server is accessible if requested
if (verifyServer) {
try {
await client.getServerIdentity();
} catch (e) {
appLogger.w('Server identity verification failed', error: e);
await storage.clearCredentials();
return ServerConnectionResult(
error: 'Server is not accessible: $e',
);
}
}
// Fetch user profile if requested
PlexUserProfile? userProfile;
if (fetchUserProfile && plexToken != null) {
userProfile = await _fetchUserProfile(plexToken);
}
// Return success result
// Note: Stream continues in background to find better connection
return ServerConnectionResult(
client: client,
userProfile: userProfile,
);
} else {
// Second emission - better connection found
// Update stored connection seamlessly for future app launches
await storage.saveServerUrl(connection.uri);
appLogger.d(
'Switched to better connection: ${connection.displayType} (${connection.uri})',
);
}
}
// Handle case where no connections were found
if (firstConnection == null) {
return ServerConnectionResult(
error: 'No working connections found for this server',
);
}
// Should never reach here due to return in the stream loop
return ServerConnectionResult(
error: 'Unexpected error in connection flow',
);
} catch (e) {
appLogger.e('Error connecting to server', error: e);
return ServerConnectionResult(error: 'Connection failed: $e');
}
}
/// Fetch user profile from Plex API
static Future<PlexUserProfile?> _fetchUserProfile(String plexToken) async {
appLogger.d('Fetching user profile from Plex API');
try {
final authService = await PlexAuthService.create();
final profile = await authService.getUserProfile(plexToken);
appLogger.i(
'Successfully fetched user profile from API',
error: {
'autoSelectAudio': profile.autoSelectAudio,
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
'autoSelectSubtitle': profile.autoSelectSubtitle,
'defaultSubtitleLanguage':
profile.defaultSubtitleLanguage ?? 'not set',
'defaultSubtitleForced': profile.defaultSubtitleForced,
},
);
return profile;
} catch (e) {
appLogger.w('Failed to fetch user profile from API', error: e);
return null;
}
}
}
+876
View File
@@ -0,0 +1,876 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import 'package:plezy/utils/app_logger.dart';
enum ThemeMode { system, light, dark }
enum LibraryDensity { compact, normal, comfortable }
enum ViewMode { grid, list }
class SettingsService {
static const String _keyThemeMode = 'theme_mode';
static const String _keyEnableDebugLogging = 'enable_debug_logging';
static const String _keyBufferSize = 'buffer_size';
static const String _keyKeyboardShortcuts = 'keyboard_shortcuts';
static const String _keyKeyboardHotkeys = 'keyboard_hotkeys';
static const String _keyEnableHardwareDecoding = 'enable_hardware_decoding';
static const String _keyPreferredVideoCodec = 'preferred_video_codec';
static const String _keyPreferredAudioCodec = 'preferred_audio_codec';
static const String _keyLibraryDensity = 'library_density';
static const String _keyViewMode = 'view_mode';
static const String _keyUseSeasonPoster = 'use_season_poster';
static const String _keySeekTimeSmall = 'seek_time_small';
static const String _keySeekTimeLarge = 'seek_time_large';
static const String _keyMediaVersionPreferences = 'media_version_preferences';
static const String _keyShowHeroSection = 'show_hero_section';
static const String _keySleepTimerDuration = 'sleep_timer_duration';
static const String _keyAudioSyncOffset = 'audio_sync_offset';
static const String _keySubtitleSyncOffset = 'subtitle_sync_offset';
static const String _keyVolume = 'volume';
static const String _keyRotationLocked = 'rotation_locked';
static const String _keySubtitleFontSize = 'subtitle_font_size';
static const String _keySubtitleTextColor = 'subtitle_text_color';
static const String _keySubtitleBorderSize = 'subtitle_border_size';
static const String _keySubtitleBorderColor = 'subtitle_border_color';
static const String _keySubtitleBackgroundColor = 'subtitle_background_color';
static const String _keySubtitleBackgroundOpacity = 'subtitle_background_opacity';
static const String _keyShuffleUnwatchedOnly = 'shuffle_unwatched_only';
static const String _keyShuffleOrderNavigation = 'shuffle_order_navigation';
static const String _keyShuffleLoopQueue = 'shuffle_loop_queue';
static SettingsService? _instance;
late SharedPreferences _prefs;
SettingsService._();
static Future<SettingsService> getInstance() async {
if (_instance == null) {
_instance = SettingsService._();
await _instance!._init();
}
return _instance!;
}
Future<void> _init() async {
_prefs = await SharedPreferences.getInstance();
}
// Theme Mode
Future<void> setThemeMode(ThemeMode mode) async {
await _prefs.setString(_keyThemeMode, mode.name);
}
ThemeMode getThemeMode() {
final modeString = _prefs.getString(_keyThemeMode);
return ThemeMode.values.firstWhere(
(mode) => mode.name == modeString,
orElse: () => ThemeMode.system,
);
}
// Debug Logging
Future<void> setEnableDebugLogging(bool enabled) async {
await _prefs.setBool(_keyEnableDebugLogging, enabled);
// Update logger level immediately when setting changes
setLoggerLevel(enabled);
}
bool getEnableDebugLogging() {
return _prefs.getBool(_keyEnableDebugLogging) ?? false;
}
// Buffer Size (in MB)
Future<void> setBufferSize(int sizeInMB) async {
await _prefs.setInt(_keyBufferSize, sizeInMB);
}
int getBufferSize() {
return _prefs.getInt(_keyBufferSize) ?? 128; // Default 128MB
}
// Hardware Decoding
Future<void> setEnableHardwareDecoding(bool enabled) async {
await _prefs.setBool(_keyEnableHardwareDecoding, enabled);
}
bool getEnableHardwareDecoding() {
return _prefs.getBool(_keyEnableHardwareDecoding) ??
true; // Default enabled
}
// Preferred Video Codec
Future<void> setPreferredVideoCodec(String codec) async {
await _prefs.setString(_keyPreferredVideoCodec, codec);
}
String getPreferredVideoCodec() {
return _prefs.getString(_keyPreferredVideoCodec) ?? 'auto';
}
// Preferred Audio Codec
Future<void> setPreferredAudioCodec(String codec) async {
await _prefs.setString(_keyPreferredAudioCodec, codec);
}
String getPreferredAudioCodec() {
return _prefs.getString(_keyPreferredAudioCodec) ?? 'auto';
}
// Library Density
Future<void> setLibraryDensity(LibraryDensity density) async {
await _prefs.setString(_keyLibraryDensity, density.name);
}
LibraryDensity getLibraryDensity() {
final densityString = _prefs.getString(_keyLibraryDensity);
return LibraryDensity.values.firstWhere(
(density) => density.name == densityString,
orElse: () => LibraryDensity.normal,
);
}
// View Mode
Future<void> setViewMode(ViewMode mode) async {
await _prefs.setString(_keyViewMode, mode.name);
}
ViewMode getViewMode() {
final modeString = _prefs.getString(_keyViewMode);
return ViewMode.values.firstWhere(
(mode) => mode.name == modeString,
orElse: () => ViewMode.grid,
);
}
// Use Season Poster
Future<void> setUseSeasonPoster(bool enabled) async {
await _prefs.setBool(_keyUseSeasonPoster, enabled);
}
bool getUseSeasonPoster() {
return _prefs.getBool(_keyUseSeasonPoster) ??
false; // Default: false (use series poster)
}
// Show Hero Section
Future<void> setShowHeroSection(bool enabled) async {
await _prefs.setBool(_keyShowHeroSection, enabled);
}
bool getShowHeroSection() {
return _prefs.getBool(_keyShowHeroSection) ??
true; // Default: true (show hero section)
}
// Seek Time Small (in seconds)
Future<void> setSeekTimeSmall(int seconds) async {
await _prefs.setInt(_keySeekTimeSmall, seconds);
}
int getSeekTimeSmall() {
return _prefs.getInt(_keySeekTimeSmall) ?? 10; // Default: 10 seconds
}
// Seek Time Large (in seconds)
Future<void> setSeekTimeLarge(int seconds) async {
await _prefs.setInt(_keySeekTimeLarge, seconds);
}
int getSeekTimeLarge() {
return _prefs.getInt(_keySeekTimeLarge) ?? 30; // Default: 30 seconds
}
// Sleep Timer Duration (in minutes)
Future<void> setSleepTimerDuration(int minutes) async {
await _prefs.setInt(_keySleepTimerDuration, minutes);
}
int getSleepTimerDuration() {
return _prefs.getInt(_keySleepTimerDuration) ?? 30; // Default: 30 minutes
}
// Audio Sync Offset (in milliseconds)
Future<void> setAudioSyncOffset(int milliseconds) async {
await _prefs.setInt(_keyAudioSyncOffset, milliseconds);
}
int getAudioSyncOffset() {
return _prefs.getInt(_keyAudioSyncOffset) ?? 0; // Default: 0ms (no offset)
}
// Subtitle Sync Offset (in milliseconds)
Future<void> setSubtitleSyncOffset(int milliseconds) async {
await _prefs.setInt(_keySubtitleSyncOffset, milliseconds);
}
int getSubtitleSyncOffset() {
return _prefs.getInt(_keySubtitleSyncOffset) ??
0; // Default: 0ms (no offset)
}
// Volume (0.0 to 100.0)
Future<void> setVolume(double volume) async {
await _prefs.setDouble(_keyVolume, volume);
}
double getVolume() {
return _prefs.getDouble(_keyVolume) ?? 100.0; // Default: full volume
}
// Rotation Lock (mobile only)
Future<void> setRotationLocked(bool locked) async {
await _prefs.setBool(_keyRotationLocked, locked);
}
bool getRotationLocked() {
return _prefs.getBool(_keyRotationLocked) ?? true; // Default: locked (landscape only)
}
// Subtitle Styling Settings
// Font Size (30-80, default 55)
Future<void> setSubtitleFontSize(int size) async {
await _prefs.setInt(_keySubtitleFontSize, size);
}
int getSubtitleFontSize() {
return _prefs.getInt(_keySubtitleFontSize) ?? 55;
}
// Text Color (hex format #RRGGBB, default white)
Future<void> setSubtitleTextColor(String color) async {
await _prefs.setString(_keySubtitleTextColor, color);
}
String getSubtitleTextColor() {
return _prefs.getString(_keySubtitleTextColor) ?? '#FFFFFF';
}
// Border Size (0-5, default 3)
Future<void> setSubtitleBorderSize(int size) async {
await _prefs.setInt(_keySubtitleBorderSize, size);
}
int getSubtitleBorderSize() {
return _prefs.getInt(_keySubtitleBorderSize) ?? 3;
}
// Border Color (hex format #RRGGBB, default black)
Future<void> setSubtitleBorderColor(String color) async {
await _prefs.setString(_keySubtitleBorderColor, color);
}
String getSubtitleBorderColor() {
return _prefs.getString(_keySubtitleBorderColor) ?? '#000000';
}
// Background Color (hex format #RRGGBB, default black)
Future<void> setSubtitleBackgroundColor(String color) async {
await _prefs.setString(_keySubtitleBackgroundColor, color);
}
String getSubtitleBackgroundColor() {
return _prefs.getString(_keySubtitleBackgroundColor) ?? '#000000';
}
// Background Opacity (0-100, default 0 for transparent)
Future<void> setSubtitleBackgroundOpacity(int opacity) async {
await _prefs.setInt(_keySubtitleBackgroundOpacity, opacity);
}
int getSubtitleBackgroundOpacity() {
return _prefs.getInt(_keySubtitleBackgroundOpacity) ?? 0;
}
// Keyboard Shortcuts (Legacy String-based)
Map<String, String> getDefaultKeyboardShortcuts() {
return {
'play_pause': 'Space',
'volume_up': 'Arrow Up',
'volume_down': 'Arrow Down',
'seek_forward': 'Arrow Right',
'seek_backward': 'Arrow Left',
'seek_forward_large': 'Shift+Arrow Right',
'seek_backward_large': 'Shift+Arrow Left',
'fullscreen_toggle': 'F',
'mute_toggle': 'M',
'subtitle_toggle': 'S',
'audio_track_next': 'A',
'subtitle_track_next': 'Shift+S',
'chapter_next': 'N',
'chapter_previous': 'P',
'speed_increase': 'Plus',
'speed_decrease': 'Minus',
'speed_reset': 'R',
};
}
// HotKey Objects (New implementation)
Map<String, HotKey> getDefaultKeyboardHotkeys() {
return {
'play_pause': HotKey(key: PhysicalKeyboardKey.space),
'volume_up': HotKey(key: PhysicalKeyboardKey.arrowUp),
'volume_down': HotKey(key: PhysicalKeyboardKey.arrowDown),
'seek_forward': HotKey(key: PhysicalKeyboardKey.arrowRight),
'seek_backward': HotKey(key: PhysicalKeyboardKey.arrowLeft),
'seek_forward_large': HotKey(
key: PhysicalKeyboardKey.arrowRight,
modifiers: [HotKeyModifier.shift],
),
'seek_backward_large': HotKey(
key: PhysicalKeyboardKey.arrowLeft,
modifiers: [HotKeyModifier.shift],
),
'fullscreen_toggle': HotKey(key: PhysicalKeyboardKey.keyF),
'mute_toggle': HotKey(key: PhysicalKeyboardKey.keyM),
'subtitle_toggle': HotKey(key: PhysicalKeyboardKey.keyS),
'audio_track_next': HotKey(key: PhysicalKeyboardKey.keyA),
'subtitle_track_next': HotKey(
key: PhysicalKeyboardKey.keyS,
modifiers: [HotKeyModifier.shift],
),
'chapter_next': HotKey(key: PhysicalKeyboardKey.keyN),
'chapter_previous': HotKey(key: PhysicalKeyboardKey.keyP),
'speed_increase': HotKey(key: PhysicalKeyboardKey.equal),
'speed_decrease': HotKey(key: PhysicalKeyboardKey.minus),
'speed_reset': HotKey(key: PhysicalKeyboardKey.keyR),
};
}
Future<void> setKeyboardShortcuts(Map<String, String> shortcuts) async {
final jsonString = json.encode(shortcuts);
await _prefs.setString(_keyKeyboardShortcuts, jsonString);
}
Map<String, String> getKeyboardShortcuts() {
final jsonString = _prefs.getString(_keyKeyboardShortcuts);
if (jsonString == null) return getDefaultKeyboardShortcuts();
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
final shortcuts = decoded.map(
(key, value) => MapEntry(key, value.toString()),
);
// Merge with defaults to ensure all keys exist
final defaults = getDefaultKeyboardShortcuts();
defaults.addAll(shortcuts);
return defaults;
} catch (e) {
return getDefaultKeyboardShortcuts();
}
}
Future<void> setKeyboardShortcut(String action, String key) async {
final shortcuts = getKeyboardShortcuts();
shortcuts[action] = key;
await setKeyboardShortcuts(shortcuts);
}
String getKeyboardShortcut(String action) {
final shortcuts = getKeyboardShortcuts();
return shortcuts[action] ?? '';
}
Future<void> resetKeyboardShortcuts() async {
await setKeyboardShortcuts(getDefaultKeyboardShortcuts());
}
// HotKey Objects Methods
Future<void> setKeyboardHotkeys(Map<String, HotKey> hotkeys) async {
final Map<String, Map<String, dynamic>> serializedHotkeys = {};
for (final entry in hotkeys.entries) {
serializedHotkeys[entry.key] = _serializeHotKey(entry.value);
}
final jsonString = json.encode(serializedHotkeys);
await _prefs.setString(_keyKeyboardHotkeys, jsonString);
}
Future<Map<String, HotKey>> getKeyboardHotkeys() async {
final jsonString = _prefs.getString(_keyKeyboardHotkeys);
if (jsonString == null) {
return getDefaultKeyboardHotkeys();
}
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
final Map<String, HotKey> hotkeys = {};
for (final entry in decoded.entries) {
final hotKey = _deserializeHotKey(entry.value as Map<String, dynamic>);
if (hotKey != null) {
hotkeys[entry.key] = hotKey;
}
}
// Merge with defaults to ensure all keys exist, but keep saved hotkeys priority
final defaults = getDefaultKeyboardHotkeys();
final result = <String, HotKey>{};
// Start with defaults
result.addAll(defaults);
// Override with saved hotkeys (this preserves user customizations)
result.addAll(hotkeys);
return result;
} catch (e) {
return getDefaultKeyboardHotkeys();
}
}
Future<void> setKeyboardHotkey(String action, HotKey hotKey) async {
final hotkeys = await getKeyboardHotkeys();
hotkeys[action] = hotKey;
await setKeyboardHotkeys(hotkeys);
}
Future<HotKey?> getKeyboardHotkey(String action) async {
final hotkeys = await getKeyboardHotkeys();
return hotkeys[action];
}
Future<void> resetKeyboardHotkeys() async {
await setKeyboardHotkeys(getDefaultKeyboardHotkeys());
}
// Helper methods for HotKey serialization
Map<String, dynamic> _serializeHotKey(HotKey hotKey) {
return {
'key': hotKey.key.toString(),
'modifiers': hotKey.modifiers?.map((m) => m.name).toList() ?? [],
};
}
HotKey? _deserializeHotKey(Map<String, dynamic> data) {
try {
final keyString = data['key'] as String;
final modifierNames = (data['modifiers'] as List<dynamic>).cast<String>();
final modifiers = modifierNames
.map((name) {
switch (name) {
case 'alt':
return HotKeyModifier.alt;
case 'control':
return HotKeyModifier.control;
case 'shift':
return HotKeyModifier.shift;
case 'meta':
return HotKeyModifier.meta;
case 'capsLock':
return HotKeyModifier.capsLock;
case 'fn':
return HotKeyModifier.fn;
default:
return null;
}
})
.where((m) => m != null)
.cast<HotKeyModifier>()
.toList();
final key = _findKeyByString(keyString);
if (key != null) {
return HotKey(
key: key,
modifiers: modifiers.isNotEmpty ? modifiers : null,
);
}
} catch (e) {
// Ignore deserialization errors
}
return null;
}
// Helper method to find PhysicalKeyboardKey by string representation
PhysicalKeyboardKey? _findKeyByString(String keyString) {
// Handle exact string matches first for better performance
const keyMap = {
'PhysicalKeyboardKey#0002c': PhysicalKeyboardKey.space,
'PhysicalKeyboardKey#7002a': PhysicalKeyboardKey.backspace,
'PhysicalKeyboardKey#7004c': PhysicalKeyboardKey.delete,
'PhysicalKeyboardKey#70028': PhysicalKeyboardKey.enter,
'PhysicalKeyboardKey#70029': PhysicalKeyboardKey.escape,
'PhysicalKeyboardKey#7002b': PhysicalKeyboardKey.tab,
'PhysicalKeyboardKey#7004a': PhysicalKeyboardKey.home,
'PhysicalKeyboardKey#7004d': PhysicalKeyboardKey.end,
'PhysicalKeyboardKey#7004b': PhysicalKeyboardKey.pageUp,
'PhysicalKeyboardKey#7004e': PhysicalKeyboardKey.pageDown,
'PhysicalKeyboardKey#70050': PhysicalKeyboardKey.arrowLeft,
'PhysicalKeyboardKey#70052': PhysicalKeyboardKey.arrowUp,
'PhysicalKeyboardKey#7004f': PhysicalKeyboardKey.arrowRight,
'PhysicalKeyboardKey#70051': PhysicalKeyboardKey.arrowDown,
};
// Check exact matches first
if (keyMap.containsKey(keyString)) {
return keyMap[keyString];
}
// Alternative approach: extract USB HID usage code from the toString() output
// Format: PhysicalKeyboardKey#ec9ed(usbHidUsage: "0x0007002c", debugName: "Space")
try {
final usbHidMatch = RegExp(
r'usbHidUsage: "0x([0-9a-fA-F]+)"',
).firstMatch(keyString);
if (usbHidMatch != null) {
final usbHidCode = usbHidMatch.group(1)!.toLowerCase();
// Map USB HID codes to PhysicalKeyboardKey objects
const usbHidMap = {
'0007002c': PhysicalKeyboardKey.space,
'0007002a': PhysicalKeyboardKey.backspace,
'0007004c': PhysicalKeyboardKey.delete,
'00070028': PhysicalKeyboardKey.enter,
'00070029': PhysicalKeyboardKey.escape,
'0007002b': PhysicalKeyboardKey.tab,
'00070039': PhysicalKeyboardKey.capsLock,
// Function keys
'0007003a': PhysicalKeyboardKey.f1,
'0007003b': PhysicalKeyboardKey.f2,
'0007003c': PhysicalKeyboardKey.f3,
'0007003d': PhysicalKeyboardKey.f4,
'0007003e': PhysicalKeyboardKey.f5,
'0007003f': PhysicalKeyboardKey.f6,
'00070040': PhysicalKeyboardKey.f7,
'00070041': PhysicalKeyboardKey.f8,
'00070042': PhysicalKeyboardKey.f9,
'00070043': PhysicalKeyboardKey.f10,
'00070044': PhysicalKeyboardKey.f11,
'00070045': PhysicalKeyboardKey.f12,
// Number keys
'00070027': PhysicalKeyboardKey.digit0,
'0007001e': PhysicalKeyboardKey.digit1,
'0007001f': PhysicalKeyboardKey.digit2,
'00070020': PhysicalKeyboardKey.digit3,
'00070021': PhysicalKeyboardKey.digit4,
'00070022': PhysicalKeyboardKey.digit5,
'00070023': PhysicalKeyboardKey.digit6,
'00070024': PhysicalKeyboardKey.digit7,
'00070025': PhysicalKeyboardKey.digit8,
'00070026': PhysicalKeyboardKey.digit9,
// Letter keys
'00070004': PhysicalKeyboardKey.keyA,
'00070005': PhysicalKeyboardKey.keyB,
'00070006': PhysicalKeyboardKey.keyC,
'00070007': PhysicalKeyboardKey.keyD,
'00070008': PhysicalKeyboardKey.keyE,
'00070009': PhysicalKeyboardKey.keyF,
'0007000a': PhysicalKeyboardKey.keyG,
'0007000b': PhysicalKeyboardKey.keyH,
'0007000c': PhysicalKeyboardKey.keyI,
'0007000d': PhysicalKeyboardKey.keyJ,
'0007000e': PhysicalKeyboardKey.keyK,
'0007000f': PhysicalKeyboardKey.keyL,
'00070010': PhysicalKeyboardKey.keyM,
'00070011': PhysicalKeyboardKey.keyN,
'00070012': PhysicalKeyboardKey.keyO,
'00070013': PhysicalKeyboardKey.keyP,
'00070014': PhysicalKeyboardKey.keyQ,
'00070015': PhysicalKeyboardKey.keyR,
'00070016': PhysicalKeyboardKey.keyS,
'00070017': PhysicalKeyboardKey.keyT,
'00070018': PhysicalKeyboardKey.keyU,
'00070019': PhysicalKeyboardKey.keyV,
'0007001a': PhysicalKeyboardKey.keyW,
'0007001b': PhysicalKeyboardKey.keyX,
'0007001c': PhysicalKeyboardKey.keyY,
'0007001d': PhysicalKeyboardKey.keyZ,
// Arrow keys
'00070050': PhysicalKeyboardKey.arrowLeft,
'00070052': PhysicalKeyboardKey.arrowUp,
'0007004f': PhysicalKeyboardKey.arrowRight,
'00070051': PhysicalKeyboardKey.arrowDown,
// Other common keys
'0007002d': PhysicalKeyboardKey.equal,
'0007002e': PhysicalKeyboardKey.minus,
'0007004a': PhysicalKeyboardKey.home,
'0007004d': PhysicalKeyboardKey.end,
'0007004b': PhysicalKeyboardKey.pageUp,
'0007004e': PhysicalKeyboardKey.pageDown,
};
if (usbHidMap.containsKey(usbHidCode)) {
return usbHidMap[usbHidCode];
}
}
} catch (e) {
// Ignore parsing errors
}
// Fall back to contains() checks for partial matches
if (keyString.contains('space')) {
return PhysicalKeyboardKey.space;
} else if (keyString.contains('arrowUp')) {
return PhysicalKeyboardKey.arrowUp;
} else if (keyString.contains('arrowDown')) {
return PhysicalKeyboardKey.arrowDown;
} else if (keyString.contains('arrowLeft')) {
return PhysicalKeyboardKey.arrowLeft;
} else if (keyString.contains('arrowRight')) {
return PhysicalKeyboardKey.arrowRight;
} else if (keyString.contains('equal')) {
return PhysicalKeyboardKey.equal;
} else if (keyString.contains('minus')) {
return PhysicalKeyboardKey.minus;
} else if (keyString.contains('escape')) {
return PhysicalKeyboardKey.escape;
} else if (keyString.contains('enter')) {
return PhysicalKeyboardKey.enter;
} else if (keyString.contains('tab')) {
return PhysicalKeyboardKey.tab;
} else if (keyString.contains('backspace')) {
return PhysicalKeyboardKey.backspace;
} else if (keyString.contains('delete')) {
return PhysicalKeyboardKey.delete;
} else if (keyString.contains('home')) {
return PhysicalKeyboardKey.home;
} else if (keyString.contains('end')) {
return PhysicalKeyboardKey.end;
} else if (keyString.contains('pageUp')) {
return PhysicalKeyboardKey.pageUp;
} else if (keyString.contains('pageDown')) {
return PhysicalKeyboardKey.pageDown;
} else {
// Try function keys F1-F12
for (int i = 1; i <= 12; i++) {
if (keyString.contains('f$i') || keyString.contains('F$i')) {
switch (i) {
case 1:
return PhysicalKeyboardKey.f1;
case 2:
return PhysicalKeyboardKey.f2;
case 3:
return PhysicalKeyboardKey.f3;
case 4:
return PhysicalKeyboardKey.f4;
case 5:
return PhysicalKeyboardKey.f5;
case 6:
return PhysicalKeyboardKey.f6;
case 7:
return PhysicalKeyboardKey.f7;
case 8:
return PhysicalKeyboardKey.f8;
case 9:
return PhysicalKeyboardKey.f9;
case 10:
return PhysicalKeyboardKey.f10;
case 11:
return PhysicalKeyboardKey.f11;
case 12:
return PhysicalKeyboardKey.f12;
}
}
}
// Try number keys 0-9
for (int i = 0; i <= 9; i++) {
if (keyString.contains('digit$i') || keyString.contains('Digit$i')) {
switch (i) {
case 0:
return PhysicalKeyboardKey.digit0;
case 1:
return PhysicalKeyboardKey.digit1;
case 2:
return PhysicalKeyboardKey.digit2;
case 3:
return PhysicalKeyboardKey.digit3;
case 4:
return PhysicalKeyboardKey.digit4;
case 5:
return PhysicalKeyboardKey.digit5;
case 6:
return PhysicalKeyboardKey.digit6;
case 7:
return PhysicalKeyboardKey.digit7;
case 8:
return PhysicalKeyboardKey.digit8;
case 9:
return PhysicalKeyboardKey.digit9;
}
}
}
// Try letter keys A-Z (both upper and lower case patterns)
const letterKeys = {
'A': PhysicalKeyboardKey.keyA,
'B': PhysicalKeyboardKey.keyB,
'C': PhysicalKeyboardKey.keyC,
'D': PhysicalKeyboardKey.keyD,
'E': PhysicalKeyboardKey.keyE,
'F': PhysicalKeyboardKey.keyF,
'G': PhysicalKeyboardKey.keyG,
'H': PhysicalKeyboardKey.keyH,
'I': PhysicalKeyboardKey.keyI,
'J': PhysicalKeyboardKey.keyJ,
'K': PhysicalKeyboardKey.keyK,
'L': PhysicalKeyboardKey.keyL,
'M': PhysicalKeyboardKey.keyM,
'N': PhysicalKeyboardKey.keyN,
'O': PhysicalKeyboardKey.keyO,
'P': PhysicalKeyboardKey.keyP,
'Q': PhysicalKeyboardKey.keyQ,
'R': PhysicalKeyboardKey.keyR,
'S': PhysicalKeyboardKey.keyS,
'T': PhysicalKeyboardKey.keyT,
'U': PhysicalKeyboardKey.keyU,
'V': PhysicalKeyboardKey.keyV,
'W': PhysicalKeyboardKey.keyW,
'X': PhysicalKeyboardKey.keyX,
'Y': PhysicalKeyboardKey.keyY,
'Z': PhysicalKeyboardKey.keyZ,
};
for (final entry in letterKeys.entries) {
if (keyString.contains('key${entry.key}') ||
keyString.contains('Key${entry.key}')) {
return entry.value;
}
}
return null;
}
}
// Media Version Preferences
/// Save media version preference for a series
/// [seriesRatingKey] is the grandparentRatingKey for TV series, or ratingKey for movies
/// [mediaIndex] is the index of the selected media version
Future<void> setMediaVersionPreference(
String seriesRatingKey,
int mediaIndex,
) async {
final preferences = _getMediaVersionPreferences();
preferences[seriesRatingKey] = mediaIndex;
final jsonString = json.encode(preferences);
await _prefs.setString(_keyMediaVersionPreferences, jsonString);
}
/// Get saved media version preference for a series
/// Returns null if no preference is saved
int? getMediaVersionPreference(String seriesRatingKey) {
final preferences = _getMediaVersionPreferences();
return preferences[seriesRatingKey];
}
/// Clear media version preference for a series
Future<void> clearMediaVersionPreference(String seriesRatingKey) async {
final preferences = _getMediaVersionPreferences();
preferences.remove(seriesRatingKey);
final jsonString = json.encode(preferences);
await _prefs.setString(_keyMediaVersionPreferences, jsonString);
}
/// Get all media version preferences
Map<String, int> _getMediaVersionPreferences() {
final jsonString = _prefs.getString(_keyMediaVersionPreferences);
if (jsonString == null) return {};
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
return decoded.map((key, value) => MapEntry(key, value as int));
} catch (e) {
return {};
}
}
// Shuffle Play Settings
/// Shuffle Unwatched Only - Filter shuffle queue to unwatched episodes only
Future<void> setShuffleUnwatchedOnly(bool enabled) async {
await _prefs.setBool(_keyShuffleUnwatchedOnly, enabled);
}
bool getShuffleUnwatchedOnly() {
return _prefs.getBool(_keyShuffleUnwatchedOnly) ?? true; // Default: true
}
/// Shuffle Order Navigation - Next/previous buttons follow shuffled order
Future<void> setShuffleOrderNavigation(bool enabled) async {
await _prefs.setBool(_keyShuffleOrderNavigation, enabled);
}
bool getShuffleOrderNavigation() {
return _prefs.getBool(_keyShuffleOrderNavigation) ?? true; // Default: true
}
/// Shuffle Loop Queue - Restart queue when reaching the end
Future<void> setShuffleLoopQueue(bool enabled) async {
await _prefs.setBool(_keyShuffleLoopQueue, enabled);
}
bool getShuffleLoopQueue() {
return _prefs.getBool(_keyShuffleLoopQueue) ?? false; // Default: false
}
// Reset all settings to defaults
Future<void> resetAllSettings() async {
await Future.wait([
_prefs.remove(_keyThemeMode),
_prefs.remove(_keyEnableDebugLogging),
_prefs.remove(_keyBufferSize),
_prefs.remove(_keyKeyboardShortcuts),
_prefs.remove(_keyKeyboardHotkeys),
_prefs.remove(_keyEnableHardwareDecoding),
_prefs.remove(_keyPreferredVideoCodec),
_prefs.remove(_keyPreferredAudioCodec),
_prefs.remove(_keyLibraryDensity),
_prefs.remove(_keyViewMode),
_prefs.remove(_keyUseSeasonPoster),
_prefs.remove(_keyShowHeroSection),
_prefs.remove(_keySeekTimeSmall),
_prefs.remove(_keySeekTimeLarge),
_prefs.remove(_keyMediaVersionPreferences),
_prefs.remove(_keySleepTimerDuration),
_prefs.remove(_keyAudioSyncOffset),
_prefs.remove(_keySubtitleSyncOffset),
_prefs.remove(_keyVolume),
_prefs.remove(_keySubtitleFontSize),
_prefs.remove(_keySubtitleTextColor),
_prefs.remove(_keySubtitleBorderSize),
_prefs.remove(_keySubtitleBorderColor),
_prefs.remove(_keySubtitleBackgroundColor),
_prefs.remove(_keySubtitleBackgroundOpacity),
_prefs.remove(_keyShuffleUnwatchedOnly),
_prefs.remove(_keyShuffleOrderNavigation),
_prefs.remove(_keyShuffleLoopQueue),
]);
}
// Clear cache (for storage cleanup)
Future<void> clearCache() async {
// This would be expanded to clear various cache directories
// For now, we'll just clear any cache-related preferences
await Future.wait([
// Add cache clearing logic here
]);
}
// Get all settings as a map for debugging/export
Future<Map<String, dynamic>> getAllSettings() async {
final hotkeys = await getKeyboardHotkeys();
return {
'themeMode': getThemeMode().name,
'enableDebugLogging': getEnableDebugLogging(),
'bufferSize': getBufferSize(),
'enableHardwareDecoding': getEnableHardwareDecoding(),
'preferredVideoCodec': getPreferredVideoCodec(),
'preferredAudioCodec': getPreferredAudioCodec(),
'libraryDensity': getLibraryDensity().name,
'viewMode': getViewMode().name,
'useSeasonPoster': getUseSeasonPoster(),
'seekTimeSmall': getSeekTimeSmall(),
'seekTimeLarge': getSeekTimeLarge(),
'keyboardShortcuts': getKeyboardShortcuts(),
'keyboardHotkeys': hotkeys.map(
(key, value) => MapEntry(key, _serializeHotKey(value)),
),
};
}
}
+105
View File
@@ -0,0 +1,105 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../utils/app_logger.dart';
/// Service to manage sleep timer functionality
/// Allows setting a timer to pause/stop playback after a specified duration
class SleepTimerService extends ChangeNotifier {
static final SleepTimerService _instance = SleepTimerService._internal();
factory SleepTimerService() => _instance;
SleepTimerService._internal();
Timer? _timer;
DateTime? _endTime;
Duration? _duration;
VoidCallback? _onTimerComplete;
/// Whether a timer is currently active
bool get isActive => _timer != null && _timer!.isActive;
/// The time when the timer will complete
DateTime? get endTime => _endTime;
/// The original duration of the timer
Duration? get duration => _duration;
/// Remaining time on the timer
Duration? get remainingTime {
if (_endTime == null) return null;
final remaining = _endTime!.difference(DateTime.now());
return remaining.isNegative ? Duration.zero : remaining;
}
/// Start a sleep timer with the specified duration
/// [duration] - How long until the timer completes
/// [onComplete] - Callback to execute when timer completes
void startTimer(Duration duration, VoidCallback onComplete) {
// Cancel any existing timer
cancelTimer();
_duration = duration;
_endTime = DateTime.now().add(duration);
_onTimerComplete = onComplete;
appLogger.d('Sleep timer started: ${duration.inMinutes} minutes');
// Create a periodic timer to update remaining time
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
final remaining = remainingTime;
if (remaining == null || remaining.inSeconds <= 0) {
appLogger.d('Sleep timer completed');
_executeCallback();
cancelTimer();
} else {
// Notify listeners to update UI
notifyListeners();
}
});
notifyListeners();
}
/// Cancel the active timer
void cancelTimer() {
if (_timer != null) {
appLogger.d('Sleep timer cancelled');
_timer?.cancel();
_timer = null;
_endTime = null;
_duration = null;
_onTimerComplete = null;
notifyListeners();
}
}
/// Extend the current timer by the specified duration
void extendTimer(Duration additionalTime) {
if (_endTime != null) {
_endTime = _endTime!.add(additionalTime);
_duration = _duration != null
? _duration! + additionalTime
: additionalTime;
appLogger.d(
'Sleep timer extended by ${additionalTime.inMinutes} minutes',
);
notifyListeners();
}
}
void _executeCallback() {
if (_onTimerComplete != null) {
try {
_onTimerComplete!();
} catch (e) {
appLogger.e('Error executing sleep timer callback', error: e);
}
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
}
+137 -1
View File
@@ -8,8 +8,14 @@ class StorageService {
static const String _keyServerData = 'server_data';
static const String _keyClientId = 'client_identifier';
static const String _keySelectedLibraryIndex = 'selected_library_index';
static const String _keySelectedLibraryKey = 'selected_library_key';
static const String _keyLibraryFilters = 'library_filters';
static const String _keyLibraryOrder = 'library_order';
static const String _keyUserProfile = 'user_profile';
static const String _keyCurrentUserUUID = 'current_user_uuid';
static const String _keyHomeUsersCache = 'home_users_cache';
static const String _keyHomeUsersCacheExpiry = 'home_users_cache_expiry';
static const String _keyHiddenLibraries = 'hidden_libraries';
static StorageService? _instance;
late SharedPreferences _prefs;
@@ -117,6 +123,9 @@ class StorageService {
_prefs.remove(_keyServerData),
_prefs.remove(_keyClientId),
_prefs.remove(_keyUserProfile),
_prefs.remove(_keyCurrentUserUUID),
_prefs.remove(_keyHomeUsersCache),
_prefs.remove(_keyHomeUsersCacheExpiry),
]);
}
@@ -129,7 +138,7 @@ class StorageService {
};
}
// Selected Library Index
// Selected Library Index (deprecated - use library key instead)
Future<void> saveSelectedLibraryIndex(int index) async {
await _prefs.setInt(_keySelectedLibraryIndex, index);
}
@@ -138,6 +147,15 @@ class StorageService {
return _prefs.getInt(_keySelectedLibraryIndex);
}
// Selected Library Key (replaces index-based selection)
Future<void> saveSelectedLibraryKey(String key) async {
await _prefs.setString(_keySelectedLibraryKey, key);
}
String? getSelectedLibraryKey() {
return _prefs.getString(_keySelectedLibraryKey);
}
// Library Filters (stored as JSON string)
Future<void> saveLibraryFilters(Map<String, String> filters) async {
final jsonString = json.encode(filters);
@@ -156,12 +174,66 @@ class StorageService {
}
}
// Library Sort (per-library, stored individually)
Future<void> saveLibrarySort(String sectionId, String sortKey) async {
await _prefs.setString('library_sort_$sectionId', sortKey);
}
String getLibrarySort(String sectionId) {
// Return saved sort or default to titleSort (alphabetical)
return _prefs.getString('library_sort_$sectionId') ?? 'titleSort';
}
// Hidden Libraries (stored as JSON array of library section IDs)
Future<void> saveHiddenLibraries(Set<String> libraryKeys) async {
final list = libraryKeys.toList();
final jsonString = json.encode(list);
await _prefs.setString(_keyHiddenLibraries, jsonString);
}
Set<String> getHiddenLibraries() {
final jsonString = _prefs.getString(_keyHiddenLibraries);
if (jsonString == null) return {};
try {
final list = json.decode(jsonString) as List<dynamic>;
return list.map((e) => e.toString()).toSet();
} catch (e) {
return {};
}
}
// Clear library preferences
Future<void> clearLibraryPreferences() async {
await Future.wait([
_prefs.remove(_keySelectedLibraryIndex),
_prefs.remove(_keyLibraryFilters),
_prefs.remove(_keyLibraryOrder),
_prefs.remove(_keyHiddenLibraries),
]);
// Also clear all library sort preferences
final keys = _prefs.getKeys();
final sortKeys = keys.where((key) => key.startsWith('library_sort_'));
await Future.wait(sortKeys.map((key) => _prefs.remove(key)));
}
// Library Order (stored as JSON list of library keys)
Future<void> saveLibraryOrder(List<String> libraryKeys) async {
final jsonString = json.encode(libraryKeys);
await _prefs.setString(_keyLibraryOrder, jsonString);
}
List<String>? getLibraryOrder() {
final jsonString = _prefs.getString(_keyLibraryOrder);
if (jsonString == null) return null;
try {
final decoded = json.decode(jsonString) as List<dynamic>;
return decoded.map((e) => e.toString()).toList();
} catch (e) {
return null;
}
}
// User Profile (stored as JSON string)
@@ -180,4 +252,68 @@ class StorageService {
return null;
}
}
// Current User UUID
Future<void> saveCurrentUserUUID(String uuid) async {
await _prefs.setString(_keyCurrentUserUUID, uuid);
}
String? getCurrentUserUUID() {
return _prefs.getString(_keyCurrentUserUUID);
}
// Home Users Cache (stored as JSON string with expiry)
Future<void> saveHomeUsersCache(Map<String, dynamic> homeData) async {
final jsonString = json.encode(homeData);
await _prefs.setString(_keyHomeUsersCache, jsonString);
// Set cache expiry to 1 hour from now
final expiry = DateTime.now()
.add(const Duration(hours: 1))
.millisecondsSinceEpoch;
await _prefs.setInt(_keyHomeUsersCacheExpiry, expiry);
}
Map<String, dynamic>? getHomeUsersCache() {
final expiry = _prefs.getInt(_keyHomeUsersCacheExpiry);
if (expiry == null || DateTime.now().millisecondsSinceEpoch > expiry) {
// Cache expired, clear it
clearHomeUsersCache();
return null;
}
final jsonString = _prefs.getString(_keyHomeUsersCache);
if (jsonString == null) return null;
try {
return json.decode(jsonString) as Map<String, dynamic>;
} catch (e) {
return null;
}
}
Future<void> clearHomeUsersCache() async {
await Future.wait([
_prefs.remove(_keyHomeUsersCache),
_prefs.remove(_keyHomeUsersCacheExpiry),
]);
}
// Clear current user UUID (for server switching)
Future<void> clearCurrentUserUUID() async {
await _prefs.remove(_keyCurrentUserUUID);
}
// Clear all user-related data (for logout)
Future<void> clearUserData() async {
await Future.wait([clearCredentials(), clearLibraryPreferences()]);
}
// Update current user after switching
Future<void> updateCurrentUser(String userUUID, String authToken) async {
await Future.wait([
saveCurrentUserUUID(userUUID),
saveToken(authToken), // Update the main token
]);
}
}
+269
View File
@@ -0,0 +1,269 @@
import '../models/plex_media_info.dart';
import '../models/plex_user_profile.dart';
/// Service for selecting audio and subtitle tracks based on user preferences
class TrackSelectionService {
/// Selects the best audio track based on user preferences
///
/// Returns the selected audio track, or null if no suitable track is found
static PlexAudioTrack? selectAudioTrack(
List<PlexAudioTrack> tracks,
PlexUserProfile profile,
) {
if (tracks.isEmpty) return null;
// If auto-select is disabled, use Plex's selected track
if (!profile.autoSelectAudio) {
return tracks.firstWhere(
(track) => track.selected,
orElse: () => tracks.first,
);
}
// Build list of preferred language codes
final preferredLanguages = <String>[];
if (profile.defaultAudioLanguage != null) {
preferredLanguages.add(profile.defaultAudioLanguage!);
}
if (profile.defaultAudioLanguages != null) {
preferredLanguages.addAll(profile.defaultAudioLanguages!);
}
// If no preferred languages, return first track
if (preferredLanguages.isEmpty) {
return tracks.first;
}
// Try to find a track matching preferred languages
for (final language in preferredLanguages) {
final matchingTrack = tracks.firstWhere(
(track) => _matchesLanguage(track.languageCode, language),
orElse: () => tracks.first,
);
if (matchingTrack != tracks.first ||
_matchesLanguage(matchingTrack.languageCode, language)) {
return matchingTrack;
}
}
// Fallback to first track
return tracks.first;
}
/// Selects the best subtitle track based on user preferences
///
/// Returns the selected subtitle track, or null if subtitles should be disabled
static PlexSubtitleTrack? selectSubtitleTrack(
List<PlexSubtitleTrack> tracks,
PlexUserProfile profile,
PlexAudioTrack? selectedAudioTrack,
) {
if (tracks.isEmpty) return null;
// Mode 0: Manually selected - return null to disable subtitles
if (profile.autoSelectSubtitle == 0) {
return null;
}
// Mode 1: Shown with foreign audio
if (profile.autoSelectSubtitle == 1) {
// Check if audio language matches user's preferred subtitle language
if (selectedAudioTrack != null && profile.defaultSubtitleLanguage != null) {
final audioLang = selectedAudioTrack.languageCode;
final prefLang = profile.defaultSubtitleLanguage;
// If audio matches preferred language, no subtitles needed
if (_matchesLanguage(audioLang, prefLang)) {
return null;
}
}
// Foreign audio detected, enable subtitles
return _findBestSubtitle(tracks, profile);
}
// Mode 2: Always enabled
if (profile.autoSelectSubtitle == 2) {
return _findBestSubtitle(tracks, profile);
}
return null;
}
/// Finds the best subtitle track matching user preferences
static PlexSubtitleTrack? _findBestSubtitle(
List<PlexSubtitleTrack> tracks,
PlexUserProfile profile,
) {
// Build list of preferred language codes
final preferredLanguages = <String>[];
if (profile.defaultSubtitleLanguage != null) {
preferredLanguages.add(profile.defaultSubtitleLanguage!);
}
if (profile.defaultSubtitleLanguages != null) {
preferredLanguages.addAll(profile.defaultSubtitleLanguages!);
}
// Filter tracks based on preferences
var candidateTracks = tracks;
// Apply SDH (hearing impaired) filtering
candidateTracks = _filterBySDH(candidateTracks, profile.defaultSubtitleAccessibility);
// Apply forced subtitle filtering
candidateTracks = _filterByForced(candidateTracks, profile.defaultSubtitleForced);
// If no candidates after filtering, relax filters
if (candidateTracks.isEmpty) {
candidateTracks = tracks;
}
// If no preferred languages, return first candidate
if (preferredLanguages.isEmpty) {
return candidateTracks.firstOrNull;
}
// Try to find a track matching preferred languages
for (final language in preferredLanguages) {
final matchingTrack = candidateTracks.firstWhere(
(track) => _matchesLanguage(track.languageCode, language),
orElse: () => candidateTracks.first,
);
if (matchingTrack != candidateTracks.first ||
_matchesLanguage(matchingTrack.languageCode, language)) {
return matchingTrack;
}
}
// Fallback to first candidate
return candidateTracks.firstOrNull;
}
/// Filters subtitle tracks based on SDH (hearing impaired) preference
///
/// Values:
/// - 0: Prefer non-SDH subtitles
/// - 1: Prefer SDH subtitles
/// - 2: Only show SDH subtitles
/// - 3: Only show non-SDH subtitles
static List<PlexSubtitleTrack> _filterBySDH(
List<PlexSubtitleTrack> tracks,
int preference,
) {
if (preference == 0 || preference == 1) {
// Prefer but don't require
final preferSDH = preference == 1;
final preferred = tracks.where((t) => _isSDH(t) == preferSDH).toList();
return preferred.isNotEmpty ? preferred : tracks;
} else if (preference == 2) {
// Only SDH
return tracks.where(_isSDH).toList();
} else if (preference == 3) {
// Only non-SDH
return tracks.where((t) => !_isSDH(t)).toList();
}
return tracks;
}
/// Filters subtitle tracks based on forced subtitle preference
///
/// Values:
/// - 0: Prefer non-forced subtitles
/// - 1: Prefer forced subtitles
/// - 2: Only show forced subtitles
/// - 3: Only show non-forced subtitles
static List<PlexSubtitleTrack> _filterByForced(
List<PlexSubtitleTrack> tracks,
int preference,
) {
if (preference == 0 || preference == 1) {
// Prefer but don't require
final preferForced = preference == 1;
final preferred = tracks.where((t) => t.forced == preferForced).toList();
return preferred.isNotEmpty ? preferred : tracks;
} else if (preference == 2) {
// Only forced
return tracks.where((t) => t.forced).toList();
} else if (preference == 3) {
// Only non-forced
return tracks.where((t) => !t.forced).toList();
}
return tracks;
}
/// Checks if a subtitle track is SDH (Subtitles for Deaf or Hard-of-Hearing)
///
/// Since Plex API may not expose this directly, we infer from the title/displayTitle
static bool _isSDH(PlexSubtitleTrack track) {
final title = track.title?.toLowerCase() ?? '';
final displayTitle = track.displayTitle?.toLowerCase() ?? '';
// Look for common SDH indicators
return title.contains('sdh') ||
displayTitle.contains('sdh') ||
title.contains('cc') ||
displayTitle.contains('cc') ||
title.contains('hearing impaired') ||
displayTitle.contains('hearing impaired');
}
/// Checks if a language code matches a preferred language
///
/// Handles both 2-letter (ISO 639-1) and 3-letter (ISO 639-2) codes
static bool _matchesLanguage(String? trackLanguage, String? preferredLanguage) {
if (trackLanguage == null || preferredLanguage == null) {
return false;
}
final track = trackLanguage.toLowerCase();
final preferred = preferredLanguage.toLowerCase();
// Direct match
if (track == preferred) return true;
// Handle common 2-letter to 3-letter mappings
final languageMap = {
'en': 'eng',
'es': 'spa',
'fr': 'fra',
'de': 'deu',
'it': 'ita',
'pt': 'por',
'ja': 'jpn',
'ko': 'kor',
'zh': 'zho',
'ru': 'rus',
'ar': 'ara',
'hi': 'hin',
'nl': 'nld',
'pl': 'pol',
'tr': 'tur',
'sv': 'swe',
'no': 'nor',
'da': 'dan',
'fi': 'fin',
'cs': 'ces',
'hu': 'hun',
'ro': 'ron',
'th': 'tha',
'vi': 'vie',
'id': 'ind',
'uk': 'ukr',
'el': 'ell',
'he': 'heb',
};
// Try mapping preferred to 3-letter and compare
if (languageMap[preferred] == track) return true;
// Try mapping track to 3-letter and compare with preferred 3-letter
if (languageMap[track] == preferred) return true;
// Try reverse mapping (3-letter to 2-letter)
final reverseMap = languageMap.map((k, v) => MapEntry(v, k));
if (reverseMap[preferred] == track) return true;
if (reverseMap[track] == preferred) return true;
return false;
}
}
+177
View File
@@ -0,0 +1,177 @@
import 'package:package_info_plus/package_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// Service to check for new versions on GitHub
/// Only enabled when ENABLE_UPDATE_CHECK build flag is set
class UpdateService {
static final Logger _logger = Logger();
static const String _githubRepo = 'edde746/plezy';
// SharedPreferences keys
static const String _keySkippedVersion = 'update_skipped_version';
static const String _keyLastCheckTime = 'update_last_check_time';
// Check cooldown: 6 hours
static const Duration _checkCooldown = Duration(hours: 6);
/// Check if update checking is enabled via build flag
static bool get isUpdateCheckEnabled {
const enabled = bool.fromEnvironment('ENABLE_UPDATE_CHECK', defaultValue: false);
return enabled;
}
/// Skip a specific version
static Future<void> skipVersion(String version) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keySkippedVersion, version);
}
/// Get the skipped version
static Future<String?> getSkippedVersion() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString(_keySkippedVersion);
}
/// Clear skipped version
static Future<void> clearSkippedVersion() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_keySkippedVersion);
}
/// Check if cooldown period has passed since last check
static Future<bool> shouldCheckForUpdates() async {
final prefs = await SharedPreferences.getInstance();
final lastCheckString = prefs.getString(_keyLastCheckTime);
if (lastCheckString == null) return true;
final lastCheck = DateTime.parse(lastCheckString);
final now = DateTime.now();
final timeSinceLastCheck = now.difference(lastCheck);
return timeSinceLastCheck >= _checkCooldown;
}
/// Update the last check timestamp
static Future<void> _updateLastCheckTime() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_keyLastCheckTime, DateTime.now().toIso8601String());
}
/// Check for updates on GitHub (manual check, ignores cooldown)
/// Returns a map with update info, or null if no update or error
static Future<Map<String, dynamic>?> checkForUpdates({bool silent = false}) async {
if (!isUpdateCheckEnabled) {
return null;
}
try {
final packageInfo = await PackageInfo.fromPlatform();
final currentVersion = packageInfo.version;
final dio = Dio();
final response = await dio.get(
'https://api.github.com/repos/$_githubRepo/releases/latest',
options: Options(
headers: {
'Accept': 'application/vnd.github+json',
},
),
);
if (response.statusCode == 200) {
final data = response.data;
final latestVersion = data['tag_name'] as String;
// Remove 'v' prefix if present
final cleanVersion = latestVersion.startsWith('v')
? latestVersion.substring(1)
: latestVersion;
final hasUpdate = _isNewerVersion(cleanVersion, currentVersion);
if (hasUpdate) {
// Check if this version was skipped (always check, regardless of silent mode)
final skippedVersion = await getSkippedVersion();
if (skippedVersion == cleanVersion) {
return null;
}
return {
'hasUpdate': true,
'currentVersion': currentVersion,
'latestVersion': cleanVersion,
'releaseUrl': data['html_url'] as String,
'releaseName': data['name'] as String? ?? 'Version $cleanVersion',
'releaseNotes': data['body'] as String? ?? '',
'publishedAt': data['published_at'] as String,
};
}
}
} catch (e) {
_logger.e('Failed to check for updates: $e');
}
return null;
}
/// Check for updates on startup (respects cooldown and skipped versions)
/// Returns update info if available, null otherwise
static Future<Map<String, dynamic>?> checkForUpdatesOnStartup() async {
if (!isUpdateCheckEnabled) {
return null;
}
// Check cooldown
if (!await shouldCheckForUpdates()) {
return null;
}
// Perform the check
final updateInfo = await checkForUpdates(silent: true);
// Update last check time
await _updateLastCheckTime();
return updateInfo;
}
/// Compare two version strings
/// Returns true if newVersion is newer than currentVersion
static bool _isNewerVersion(String newVersion, String currentVersion) {
try {
// Split by '.' and parse as integers
final newParts = newVersion.split('.').map((p) {
// Handle versions like "1.2.3+4" by taking only the numeric part
final numPart = p.split('+').first.split('-').first;
return int.tryParse(numPart) ?? 0;
}).toList();
final currentParts = currentVersion.split('.').map((p) {
final numPart = p.split('+').first.split('-').first;
return int.tryParse(numPart) ?? 0;
}).toList();
// Compare each part
final maxLength = newParts.length > currentParts.length
? newParts.length
: currentParts.length;
for (int i = 0; i < maxLength; i++) {
final newPart = i < newParts.length ? newParts[i] : 0;
final currentPart = i < currentParts.length ? currentParts[i] : 0;
if (newPart > currentPart) return true;
if (newPart < currentPart) return false;
}
return false; // Versions are equal
} catch (e) {
_logger.e('Error comparing versions: $e');
return false;
}
}
}
+167
View File
@@ -0,0 +1,167 @@
import 'package:flutter/material.dart';
import 'mono_tokens.dart';
ThemeData monoTheme({required bool dark}) {
// neutral greys tuned for crisp contrast
final c = dark
? (
bg: const Color(0xFF0E0F12),
surface: const Color(0xFF15171C),
outline: const Color(0x1FFFFFFF),
text: const Color(0xFFEDEDED),
textMuted: const Color(0x99EDEDED),
)
: (
bg: const Color(0xFFF7F7F8),
surface: const Color(0xFFFFFFFF),
outline: const Color(0x19000000),
text: const Color(0xFF111111),
textMuted: const Color(0x99111111),
);
final base = ThemeData(
useMaterial3: true,
brightness: dark ? Brightness.dark : Brightness.light,
colorScheme: ColorScheme(
brightness: dark ? Brightness.dark : Brightness.light,
primary: c.text,
onPrimary: dark ? const Color(0xFF0E0F12) : Colors.white,
secondary: c.text,
onSecondary: c.bg,
surface: c.surface,
onSurface: c.text,
error: const Color(0xFFB00020),
onError: Colors.white,
tertiary: c.text,
onTertiary: c.bg,
primaryContainer: c.surface,
onPrimaryContainer: c.text,
secondaryContainer: c.surface,
onSecondaryContainer: c.text,
surfaceContainerHighest: c.surface,
surfaceContainerLow: c.bg,
surfaceDim: c.bg,
surfaceBright: c.surface,
outline: c.outline,
shadow: Colors.transparent,
scrim: Colors.black,
inverseSurface: c.text,
onInverseSurface: c.bg,
inversePrimary: c.bg,
),
// remove "Material feel"
splashFactory: NoSplash.splashFactory,
highlightColor: Colors.transparent,
dividerColor: c.outline,
scaffoldBackgroundColor: c.bg,
appBarTheme: AppBarTheme(
backgroundColor: c.bg,
elevation: 0,
scrolledUnderElevation: 0,
centerTitle: false,
foregroundColor: c.text,
titleTextStyle: TextStyle(
color: c.text,
fontSize: 18,
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
),
textTheme: Typography.englishLike2021
.apply(bodyColor: c.text, displayColor: c.text)
.copyWith(
displayLarge: const TextStyle(
fontWeight: FontWeight.w700,
letterSpacing: -0.5,
),
titleMedium: const TextStyle(fontWeight: FontWeight.w600),
bodyMedium: TextStyle(color: c.text),
bodySmall: TextStyle(color: c.textMuted),
),
cardTheme: CardThemeData(
color: c.surface,
elevation: 0,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: c.surface,
isDense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: c.outline),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: c.outline),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: c.text.withValues(alpha: 0.5)),
),
hintStyle: TextStyle(color: c.textMuted),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ButtonStyle(
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 18, vertical: 14),
),
elevation: const WidgetStatePropertyAll(0),
backgroundColor: WidgetStatePropertyAll(c.text),
foregroundColor: WidgetStatePropertyAll(dark ? c.bg : Colors.white),
shape: const WidgetStatePropertyAll(StadiumBorder()),
),
),
filledButtonTheme: FilledButtonThemeData(
style: ButtonStyle(
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 18, vertical: 14),
),
elevation: const WidgetStatePropertyAll(0),
backgroundColor: WidgetStatePropertyAll(c.text),
foregroundColor: WidgetStatePropertyAll(dark ? c.bg : Colors.white),
shape: const WidgetStatePropertyAll(StadiumBorder()),
),
),
dividerTheme: DividerThemeData(space: 0, thickness: 1, color: c.outline),
listTileTheme: ListTileThemeData(
dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
iconColor: c.text,
textColor: c.text,
),
// minimal bottom bar
navigationBarTheme: NavigationBarThemeData(
backgroundColor: c.bg,
elevation: 0,
indicatorColor: Colors.transparent,
labelTextStyle: WidgetStatePropertyAll(
TextStyle(color: c.textMuted, fontSize: 11),
),
iconTheme: WidgetStateProperty.resolveWith((states) {
final active = states.contains(WidgetState.selected);
return IconThemeData(opacity: active ? 1 : .6, size: 22, color: c.text);
}),
),
);
return base.copyWith(
extensions: [
MonoTokens(
radiusSm: 8,
radiusMd: 12,
space: 12,
fast: const Duration(milliseconds: 120),
normal: const Duration(milliseconds: 200),
bg: c.bg,
surface: c.surface,
outline: c.outline,
text: c.text,
textMuted: c.textMuted,
splashFactory: NoSplash.splashFactory,
),
],
);
}
+89
View File
@@ -0,0 +1,89 @@
import 'dart:ui';
import 'package:flutter/material.dart';
@immutable
class MonoTokens extends ThemeExtension<MonoTokens> {
final double radiusSm;
final double radiusMd;
final double space;
final Duration fast;
final Duration normal;
final Color bg;
final Color surface;
final Color outline;
final Color text;
final Color textMuted;
final InteractiveInkFeatureFactory? splashFactory;
const MonoTokens({
required this.radiusSm,
required this.radiusMd,
required this.space,
required this.fast,
required this.normal,
required this.bg,
required this.surface,
required this.outline,
required this.text,
required this.textMuted,
required this.splashFactory,
});
@override
MonoTokens copyWith({
double? radiusSm,
double? radiusMd,
double? space,
Duration? fast,
Duration? normal,
Color? bg,
Color? surface,
Color? outline,
Color? text,
Color? textMuted,
InteractiveInkFeatureFactory? splashFactory,
}) => MonoTokens(
radiusSm: radiusSm ?? this.radiusSm,
radiusMd: radiusMd ?? this.radiusMd,
space: space ?? this.space,
fast: fast ?? this.fast,
normal: normal ?? this.normal,
bg: bg ?? this.bg,
surface: surface ?? this.surface,
outline: outline ?? this.outline,
text: text ?? this.text,
textMuted: textMuted ?? this.textMuted,
splashFactory: splashFactory ?? this.splashFactory,
);
@override
ThemeExtension<MonoTokens> lerp(covariant MonoTokens? other, double t) {
if (other == null) return this;
Color lerpC(Color a, Color b) => Color.lerp(a, b, t)!;
return MonoTokens(
radiusSm: lerpDouble(radiusSm, other.radiusSm, t)!,
radiusMd: lerpDouble(radiusMd, other.radiusMd, t)!,
space: lerpDouble(space, other.space, t)!,
fast: Duration(
milliseconds: lerpDouble(
fast.inMilliseconds.toDouble(),
other.fast.inMilliseconds.toDouble(),
t,
)!.round(),
),
normal: Duration(
milliseconds: lerpDouble(
normal.inMilliseconds.toDouble(),
other.normal.inMilliseconds.toDouble(),
t,
)!.round(),
),
bg: lerpC(bg, other.bg),
surface: lerpC(surface, other.surface),
outline: lerpC(outline, other.outline),
text: lerpC(text, other.text),
textMuted: lerpC(textMuted, other.textMuted),
splashFactory: other.splashFactory,
);
}
}
+6
View File
@@ -0,0 +1,6 @@
import 'package:flutter/material.dart';
import 'mono_tokens.dart';
/// Helper function to access MonoTokens from context
MonoTokens tokens(BuildContext context) =>
Theme.of(context).extension<MonoTokens>()!;
+222 -9
View File
@@ -1,5 +1,204 @@
import 'package:logger/logger.dart';
/// Redacts sensitive information from log messages
String _redactSensitiveData(String message) {
String redacted = message;
// Redact Plex tokens (alphanumeric strings typically 20+ characters)
// Pattern: X-Plex-Token=... or token=... or accessToken=... or similar
redacted = redacted.replaceAllMapped(
RegExp(r'([Tt]oken[=:]\s*)([A-Za-z0-9_-]{10,})', caseSensitive: false),
(match) => '${match.group(1)}[REDACTED]',
);
// Redact authorization headers
redacted = redacted.replaceAllMapped(
RegExp(r'([Aa]uthorization[=:]\s*)([A-Za-z0-9_\-\.]+)', caseSensitive: false),
(match) => '${match.group(1)}[REDACTED]',
);
// Redact API keys
redacted = redacted.replaceAllMapped(
RegExp(r'([Aa]pi[Kk]ey[=:]\s*)([A-Za-z0-9_-]{10,})', caseSensitive: false),
(match) => '${match.group(1)}[REDACTED]',
);
// Redact passwords
redacted = redacted.replaceAllMapped(
RegExp(r'([Pp]assword[=:]\s*)([^\s&,;]+)', caseSensitive: false),
(match) => '${match.group(1)}[REDACTED]',
);
// Redact full URLs with tokens in query parameters
redacted = redacted.replaceAllMapped(
RegExp(r'(https?://[^\s]*[?&])([Xx]-[Pp]lex-[Tt]oken|token)=([A-Za-z0-9_-]+)'),
(match) => '${match.group(1)}${match.group(2)}=[REDACTED]',
);
// Redact IP addresses in dot notation (e.g., 192.168.1.100)
redacted = redacted.replaceAllMapped(
RegExp(r'\b(\d{1,3}\.)(\d{1,3}\.)(\d{1,3}\.)(\d{1,3})\b'),
(match) => '${match.group(1)}***.***.${match.group(4)}',
);
// Redact IP addresses in dash notation (e.g., 192-168-1-11)
redacted = redacted.replaceAllMapped(
RegExp(r'\b(\d{1,3}-)(\d{1,3}-)(\d{1,3}-)(\d{1,3})\b'),
(match) => '${match.group(1)}***-***-${match.group(4)}',
);
// Redact standalone token-like strings (20+ alphanumeric characters)
// Only if they appear in common token contexts
redacted = redacted.replaceAllMapped(
RegExp(r'\b([A-Za-z0-9_-]{20,})\b'),
(match) {
final token = match.group(1)!;
// Only redact if it looks like a token (mixed case or contains hyphens/underscores)
if (token.contains(RegExp(r'[A-Z]')) && token.contains(RegExp(r'[a-z]')) ||
token.contains('_') || token.contains('-')) {
return '[REDACTED_TOKEN]';
}
return token;
},
);
return redacted;
}
/// Represents a single log entry stored in memory
class LogEntry {
final DateTime timestamp;
final Level level;
final String message;
final Object? error;
final StackTrace? stackTrace;
LogEntry({
required this.timestamp,
required this.level,
required this.message,
this.error,
this.stackTrace,
});
/// Estimate the memory size of this log entry in bytes
int get estimatedSize {
int size = 0;
// DateTime: ~8 bytes
size += 8;
// Level enum: ~4 bytes
size += 4;
// Message string: 2 bytes per character (UTF-16)
size += message.length * 2;
// Error string: 2 bytes per character if present
if (error != null) {
size += error.toString().length * 2;
}
// Stack trace string: 2 bytes per character if present
if (stackTrace != null) {
size += stackTrace.toString().length * 2;
}
return size;
}
}
/// Custom log output that stores logs in memory with a circular buffer
class MemoryLogOutput extends LogOutput {
static const int maxLogSizeBytes = 5 * 1024 * 1024; // 5 MB
static final List<LogEntry> _logs = [];
static int _currentSize = 0;
/// Get all stored logs (newest first)
static List<LogEntry> getLogs() => List.unmodifiable(_logs.reversed);
/// Clear all stored logs
static void clearLogs() {
_logs.clear();
_currentSize = 0;
}
/// Get current log buffer size in bytes
static int getCurrentSize() => _currentSize;
/// Get current log buffer size in MB
static double getCurrentSizeMB() => _currentSize / (1024 * 1024);
@override
void output(OutputEvent event) {
// Extract relevant information from the log event
for (var line in event.lines) {
final logEntry = LogEntry(
timestamp: DateTime.now(),
level: event.level,
message: _redactSensitiveData(line),
);
_logs.add(logEntry);
_currentSize += logEntry.estimatedSize;
// Maintain buffer size limit (remove oldest entries)
while (_currentSize > maxLogSizeBytes && _logs.isNotEmpty) {
final removed = _logs.removeAt(0);
_currentSize -= removed.estimatedSize;
}
}
}
}
/// Custom log printer that also stores error and stack trace information
class MemoryAwareLogPrinter extends LogPrinter {
final LogPrinter _wrappedPrinter;
MemoryAwareLogPrinter(this._wrappedPrinter);
@override
List<String> log(LogEvent event) {
// Store the log with error and stack trace if available
final message = _redactSensitiveData(event.message.toString());
final error = event.error != null
? _redactSensitiveData(event.error.toString())
: null;
final logEntry = LogEntry(
timestamp: DateTime.now(),
level: event.level,
message: message,
error: error,
stackTrace: event.stackTrace,
);
MemoryLogOutput._logs.add(logEntry);
MemoryLogOutput._currentSize += logEntry.estimatedSize;
// Maintain buffer size limit (remove oldest entries)
while (MemoryLogOutput._currentSize > MemoryLogOutput.maxLogSizeBytes &&
MemoryLogOutput._logs.isNotEmpty) {
final removed = MemoryLogOutput._logs.removeAt(0);
MemoryLogOutput._currentSize -= removed.estimatedSize;
}
// Delegate to wrapped printer for console output
return _wrappedPrinter.log(event);
}
}
/// Custom production filter that respects our level setting even in release mode
class ProductionFilter extends LogFilter {
Level _currentLevel = Level.debug;
void setLevel(Level level) {
_currentLevel = level;
}
@override
bool shouldLog(LogEvent event) {
return event.level.value >= _currentLevel.value;
}
}
/// Global filter instance
final _productionFilter = ProductionFilter();
/// Centralized logger instance for the application.
///
/// Usage:
@@ -11,14 +210,28 @@ import 'package:logger/logger.dart';
/// appLogger.w('Warning message');
/// appLogger.e('Error message', error: e, stackTrace: stackTrace);
/// ```
final appLogger = Logger(
printer: PrettyPrinter(
methodCount: 2,
errorMethodCount: 8,
lineLength: 120,
colors: true,
printEmojis: true,
dateTimeFormat: DateTimeFormat.onlyTimeAndSinceStart,
),
Logger appLogger = Logger(
printer: MemoryAwareLogPrinter(SimplePrinter()),
filter: _productionFilter,
level: Level.debug,
);
/// Update the logger's level dynamically based on debug setting
/// Recreates the logger instance to ensure it works in release mode
void setLoggerLevel(bool debugEnabled) {
final newLevel = debugEnabled ? Level.debug : Level.info;
// Update the filter level
_productionFilter.setLevel(newLevel);
// Recreate the logger instance with the new level
// This ensures it works in release mode where Logger.level might be optimized away
appLogger = Logger(
printer: MemoryAwareLogPrinter(SimplePrinter()),
filter: _productionFilter,
level: newLevel,
);
// Also set the static level for consistency
Logger.level = newLevel;
}
+17
View File
@@ -0,0 +1,17 @@
/// Utility function to format content ratings by removing country prefixes
String formatContentRating(String? contentRating) {
if (contentRating == null || contentRating.isEmpty) {
return '';
}
// Remove common country prefixes like "gb/", "us/", "de/", etc.
// The pattern matches: lowercase letters followed by a forward slash
final regex = RegExp(r'^[a-z]{2,3}/(.+)$', caseSensitive: false);
final match = regex.firstMatch(contentRating);
if (match != null && match.groupCount >= 1) {
return match.group(1) ?? contentRating;
}
return contentRating;
}
+21 -10
View File
@@ -12,24 +12,33 @@ class DesktopWindowPadding {
/// Right padding for macOS to prevent actions from being too close to edge
static const double macOSRight = 16.0;
/// Right padding for mobile devices to prevent actions from being too close to edge
static const double mobileRight = 6.0;
}
/// Helper class for adjusting app bar widgets to account for desktop window controls
class DesktopAppBarHelper {
/// Builds actions list with appropriate right padding for macOS
/// Builds actions list with appropriate right padding for macOS and mobile
static List<Widget>? buildAdjustedActions(List<Widget>? actions) {
if (!Platform.isMacOS) {
double? rightPadding;
if (Platform.isMacOS) {
rightPadding = DesktopWindowPadding.macOSRight;
} else if (Platform.isIOS || Platform.isAndroid) {
rightPadding = DesktopWindowPadding.mobileRight;
}
// If no platform-specific padding needed, return original actions
if (rightPadding == null) {
return actions;
}
// macOS: Add padding to keep actions away from edge
// Add padding to keep actions away from edge
if (actions != null) {
return [
...actions,
SizedBox(width: DesktopWindowPadding.macOSRight),
];
return [...actions, SizedBox(width: rightPadding)];
} else {
return [SizedBox(width: DesktopWindowPadding.macOSRight)];
return [SizedBox(width: rightPadding)];
}
}
@@ -60,7 +69,8 @@ class DesktopAppBarHelper {
if (includeGestureDetector) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) {}, // Consume pan gestures to prevent window dragging
onPanDown:
(_) {}, // Consume pan gestures to prevent window dragging
child: paddedWidget,
);
}
@@ -135,7 +145,8 @@ class DesktopTitleBarPadding extends StatelessWidget {
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
// In fullscreen, use minimal padding since traffic lights auto-hide
final left = leftPadding ??
final left =
leftPadding ??
(isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
: DesktopWindowPadding.macOSLeft);
+50
View File
@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'platform_detector.dart';
/// Helper class for managing device orientation preferences across the app.
class OrientationHelper {
/// Restores default orientation preferences based on device type.
///
/// For phones: Locks to portrait-only (up and down)
/// For tablets/desktop: Allows all orientations
///
/// This should be called when leaving full-screen experiences like
/// the video player to restore the app's default orientation behavior.
static void restoreDefaultOrientations(BuildContext context) {
final isPhone = PlatformDetector.isPhone(context);
if (isPhone) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
} else {
// For tablets and desktop, allow all orientations
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
}
/// Sets orientation to landscape-only mode.
///
/// Used by the video player to force landscape orientation during playback.
static void setLandscapeOrientation() {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
/// Restores edge-to-edge system UI mode.
///
/// Should be called when exiting full-screen mode.
static void restoreSystemUI() {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
}
}
+37
View File
@@ -0,0 +1,37 @@
import 'package:flutter/material.dart';
import 'dart:math';
/// Utility class for platform detection
class PlatformDetector {
/// Detects if running on a mobile platform (iOS or Android)
/// Uses Theme for consistent platform detection across the app
static bool isMobile(BuildContext context) {
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.android;
}
/// Detects if running on a desktop platform (Windows, macOS, or Linux)
static bool isDesktop(BuildContext context) {
return !isMobile(context);
}
/// Detects if the device is likely a tablet based on screen size
/// Uses diagonal screen size to determine if device is a tablet
static bool isTablet(BuildContext context) {
final data = MediaQuery.of(context);
final size = data.size;
final diagonal = sqrt(size.width * size.width + size.height * size.height);
final devicePixelRatio = data.devicePixelRatio;
// Convert diagonal from logical pixels to inches (assuming 160 DPI as baseline)
final diagonalInches = diagonal / (devicePixelRatio * 160 / 2.54);
// Consider devices with diagonal >= 7 inches as tablets
return diagonalInches >= 7.0;
}
/// Detects if the device is a phone (mobile but not tablet)
static bool isPhone(BuildContext context) {
return isMobile(context) && !isTablet(context);
}
}
-37
View File
@@ -1,37 +0,0 @@
/// Utility class for building Plex API headers
class PlexHeaders {
/// Standard Plex headers required for API requests
static const String plexClientIdentifier = 'X-Plex-Client-Identifier';
static const String plexProduct = 'X-Plex-Product';
static const String plexVersion = 'X-Plex-Version';
static const String plexToken = 'X-Plex-Token';
static const String plexPlatform = 'X-Plex-Platform';
static const String plexPlatformVersion = 'X-Plex-Platform-Version';
static const String plexDevice = 'X-Plex-Device';
/// Builds standard Plex headers with optional token
static Map<String, String> buildHeaders({
required String clientIdentifier,
String? token,
String product = 'Plezy',
String version = '1.0',
String platform = 'Flutter',
String platformVersion = '1.0',
String device = 'Mobile',
}) {
final headers = {
plexClientIdentifier: clientIdentifier,
plexProduct: product,
plexVersion: version,
plexPlatform: platform,
plexPlatformVersion: platformVersion,
plexDevice: device,
};
if (token != null) {
headers[plexToken] = token;
}
return headers;
}
}
+36
View File
@@ -0,0 +1,36 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/plex_client_provider.dart';
import '../providers/user_profile_provider.dart';
import '../providers/hidden_libraries_provider.dart';
import '../client/plex_client.dart';
import '../models/plex_user_profile.dart';
extension ProviderExtensions on BuildContext {
PlexClientProvider get plexClient =>
Provider.of<PlexClientProvider>(this, listen: false);
UserProfileProvider get userProfile =>
Provider.of<UserProfileProvider>(this, listen: false);
PlexClientProvider watchPlexClient() =>
Provider.of<PlexClientProvider>(this, listen: true);
UserProfileProvider watchUserProfile() =>
Provider.of<UserProfileProvider>(this, listen: true);
HiddenLibrariesProvider get hiddenLibraries =>
Provider.of<HiddenLibrariesProvider>(this, listen: false);
HiddenLibrariesProvider watchHiddenLibraries() =>
Provider.of<HiddenLibrariesProvider>(this, listen: true);
// Direct client access (nullable)
PlexClient? get client => plexClient.client;
// Null-safe client access
PlexClient get clientSafe => plexClient.client!;
// Direct profile settings access (nullable)
PlexUserProfile? get profileSettings => userProfile.profileSettings;
}
+115
View File
@@ -0,0 +1,115 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/playback_state_provider.dart';
import '../providers/settings_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
/// Handle shuffle play action for shows and seasons
///
/// Fetches episodes based on user settings (unwatched only or including watched),
/// shuffles them, and starts playback from the first shuffled episode.
/// The shuffle queue is stored in the PlaybackStateProvider for continuous shuffle playback.
Future<void> handleShufflePlay(
BuildContext context,
PlexMetadata metadata,
) async {
final client = context.client;
if (client == null) return;
final playbackState = context.read<PlaybackStateProvider>();
final settingsProvider = context.read<SettingsProvider>();
final itemType = metadata.type.toLowerCase();
// Get shuffle setting
final unwatchedOnly = settingsProvider.shuffleUnwatchedOnly;
try {
// Show loading indicator
if (context.mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) =>
const Center(child: CircularProgressIndicator()),
);
}
// Get episodes based on type and settings
List<PlexMetadata> episodes;
if (itemType == 'show') {
if (unwatchedOnly) {
// Get only unwatched episodes
episodes = await client.getAllUnwatchedEpisodes(
metadata.ratingKey,
);
} else {
// Get all episodes from all seasons
final allEpisodes = <PlexMetadata>[];
final seasons = await client.getChildren(metadata.ratingKey);
for (final season in seasons) {
if (season.type == 'season') {
final seasonEpisodes = await client.getChildren(season.ratingKey);
final episodesOnly = seasonEpisodes
.where((ep) => ep.type == 'episode')
.toList();
allEpisodes.addAll(episodesOnly);
}
}
episodes = allEpisodes;
}
} else {
// season
if (unwatchedOnly) {
// Get only unwatched episodes
episodes = await client.getUnwatchedEpisodesInSeason(
metadata.ratingKey,
);
} else {
// Get all episodes in season
final seasonEpisodes = await client.getChildren(metadata.ratingKey);
episodes = seasonEpisodes
.where((ep) => ep.type == 'episode')
.toList();
}
}
// Close loading indicator
if (context.mounted) {
Navigator.pop(context);
}
if (episodes.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No episodes found')),
);
}
return;
}
// Shuffle the episodes
episodes.shuffle();
// Store shuffle queue in provider
playbackState.setShuffleQueue(episodes, metadata.ratingKey);
// Navigate to first episode
if (context.mounted) {
await navigateToVideoPlayer(context, metadata: episodes.first);
}
} catch (e) {
// Close loading indicator if it's still open
if (context.mounted && Navigator.canPop(context)) {
Navigator.pop(context);
}
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error starting shuffle play: $e')),
);
}
}
}
+28
View File
@@ -0,0 +1,28 @@
import 'package:flutter/material.dart';
import '../models/plex_home_user.dart';
import 'provider_extensions.dart';
class UserSwitchingUtils {
static Future<bool> switchToUser(
BuildContext context,
PlexHomeUser user, {
bool popOnSuccess = false,
}) async {
final userProvider = context.userProfile;
final success = await userProvider.switchToUser(user, context);
if (success && context.mounted && popOnSuccess) {
Navigator.of(context).pop();
} else if (!success && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to switch to ${user.displayName}'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
return success;
}
}
+70
View File
@@ -0,0 +1,70 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../models/plex_metadata.dart';
import '../screens/video_player_screen.dart';
import '../services/settings_service.dart';
/// Navigates to the VideoPlayerScreen with instant transitions to prevent white flash.
///
/// This utility function provides a consistent way to navigate to the video player
/// across the app, using PageRouteBuilder with zero-duration transitions to eliminate
/// the white flash that occurs with MaterialPageRoute.
///
/// Parameters:
/// - [context]: The build context for navigation
/// - [metadata]: The Plex metadata for the content to play
/// - [preferredAudioTrack]: Optional audio track to select on playback start
/// - [preferredSubtitleTrack]: Optional subtitle track to select on playback start
/// - [preferredPlaybackRate]: Optional playback speed to set on playback start
/// - [selectedMediaIndex]: Optional media version index to use; if not provided,
/// loads the saved preference for the series/movie. Defaults to 0 if no preference exists.
/// - [usePushReplacement]: If true, replaces current route instead of pushing;
/// useful for episode-to-episode navigation. Defaults to false.
///
/// Returns a Future that completes with a boolean indicating whether the content
/// was watched, or null if navigation was cancelled.
Future<bool?> navigateToVideoPlayer(
BuildContext context, {
required PlexMetadata metadata,
AudioTrack? preferredAudioTrack,
SubtitleTrack? preferredSubtitleTrack,
double? preferredPlaybackRate,
int? selectedMediaIndex,
bool usePushReplacement = false,
}) async {
// Extract navigator before any async operations
final navigator = Navigator.of(context);
// Load saved media version preference if not explicitly provided
int mediaIndex = selectedMediaIndex ?? 0;
if (selectedMediaIndex == null) {
try {
final settingsService = await SettingsService.getInstance();
final seriesKey = metadata.grandparentRatingKey ?? metadata.ratingKey;
final savedPreference = settingsService.getMediaVersionPreference(seriesKey);
if (savedPreference != null) {
mediaIndex = savedPreference;
}
} catch (e) {
// Ignore errors loading preference, use default
}
}
final route = PageRouteBuilder<bool>(
pageBuilder: (context, animation, secondaryAnimation) => VideoPlayerScreen(
metadata: metadata,
preferredAudioTrack: preferredAudioTrack,
preferredSubtitleTrack: preferredSubtitleTrack,
preferredPlaybackRate: preferredPlaybackRate,
selectedMediaIndex: mediaIndex,
),
transitionDuration: Duration.zero,
reverseTransitionDuration: Duration.zero,
);
if (usePushReplacement) {
return navigator.pushReplacement<bool, bool>(route);
} else {
return navigator.push<bool>(route);
}
}
+98 -44
View File
@@ -23,7 +23,7 @@ enum BackButtonStyle {
/// ```dart
/// AppBarBackButton(style: BackButtonStyle.circular)
/// ```
class AppBarBackButton extends StatelessWidget {
class AppBarBackButton extends StatefulWidget {
/// Creates a back button with the specified style.
///
/// [style] determines the visual appearance of the back button.
@@ -45,9 +45,44 @@ class AppBarBackButton extends StatelessWidget {
/// The color of the back arrow icon. If null, uses style-appropriate default.
final Color? color;
void _handlePressed(BuildContext context) {
if (onPressed != null) {
onPressed!();
@override
State<AppBarBackButton> createState() => _AppBarBackButtonState();
}
class _AppBarBackButtonState extends State<AppBarBackButton>
with TickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _backgroundAnimation;
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: const Duration(milliseconds: 150),
vsync: this,
);
_backgroundAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _onHoverChange(bool isHovered) {
if (isHovered) {
_animationController.forward();
} else {
_animationController.reverse();
}
}
void _handlePressed() {
if (widget.onPressed != null) {
widget.onPressed!();
} else {
Navigator.of(context).pop();
}
@@ -55,53 +90,72 @@ class AppBarBackButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
switch (style) {
case BackButtonStyle.circular:
return _buildCircularBackButton(context);
final theme = Theme.of(context);
final isDarkTheme = theme.brightness == Brightness.dark;
final Color effectiveColor;
switch (widget.style) {
case BackButtonStyle.plain:
return _buildPlainBackButton(context);
effectiveColor =
widget.color ?? (isDarkTheme ? Colors.white : Colors.black);
break;
case BackButtonStyle.circular:
case BackButtonStyle.video:
return _buildVideoBackButton(context);
effectiveColor = widget.color ?? Colors.white;
break;
}
}
/// Builds a back button with circular semi-transparent background
Widget _buildCircularBackButton(BuildContext context) {
return SafeArea(
child: Container(
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: IconButton(
icon: Icon(Icons.arrow_back, color: color ?? Colors.white),
onPressed: () => _handlePressed(context),
padding: EdgeInsets.zero,
tooltip: 'Back',
final Color baseColor;
final Color hoverColor;
switch (widget.style) {
case BackButtonStyle.circular:
baseColor = Colors.black.withValues(alpha: 0.3);
hoverColor = Colors.black.withValues(alpha: 0.5);
break;
case BackButtonStyle.plain:
hoverColor = (isDarkTheme ? Colors.white : Colors.black).withValues(
alpha: 0.2,
);
baseColor = Colors.transparent;
break;
case BackButtonStyle.video:
baseColor = Colors.transparent;
hoverColor = Colors.black.withValues(alpha: 0.3);
break;
}
final button = MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) => _onHoverChange(true),
onExit: (_) => _onHoverChange(false),
child: GestureDetector(
onTap: _handlePressed,
child: AnimatedBuilder(
animation: _backgroundAnimation,
builder: (context, child) {
final currentColor = Color.lerp(
baseColor,
hoverColor,
_backgroundAnimation.value,
);
return Container(
margin: const EdgeInsets.all(8),
width: 40,
height: 40,
decoration: BoxDecoration(
color: currentColor,
shape: BoxShape.circle,
),
child: Icon(Icons.arrow_back, color: effectiveColor, size: 20),
);
},
),
),
);
}
/// Builds a plain back button without background
Widget _buildPlainBackButton(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back, color: color),
onPressed: () => _handlePressed(context),
tooltip: 'Back',
);
}
/// Builds a back button styled for video player overlay
Widget _buildVideoBackButton(BuildContext context) {
return Container(
margin: const EdgeInsets.only(left: 8),
child: IconButton(
icon: Icon(Icons.arrow_back, color: color ?? Colors.white),
onPressed: () => _handlePressed(context),
tooltip: 'Back',
),
);
return widget.style == BackButtonStyle.circular
? SafeArea(child: button)
: button;
}
}
+193
View File
@@ -0,0 +1,193 @@
import 'package:flutter/material.dart';
import '../utils/platform_detector.dart';
/// A menu action item for context menus
class ContextMenuItem {
final String value;
final IconData icon;
final String label;
final bool requiresConfirmation;
final String? confirmationTitle;
final String? confirmationMessage;
final bool isDestructive;
const ContextMenuItem({
required this.value,
required this.icon,
required this.label,
this.requiresConfirmation = false,
this.confirmationTitle,
this.confirmationMessage,
this.isDestructive = false,
});
}
/// A wrapper widget that shows context menus differently based on platform.
/// On mobile (iOS/Android): Shows a bottom sheet on long-press
/// On desktop (Windows/macOS/Linux): Shows a popup menu on right-click or long-press
class ContextMenuWrapper extends StatefulWidget {
final Widget child;
final List<ContextMenuItem> menuItems;
final Function(String)? onMenuItemSelected;
final VoidCallback? onTap;
final String? title;
final bool forceBottomSheet;
const ContextMenuWrapper({
super.key,
required this.child,
required this.menuItems,
this.onMenuItemSelected,
this.onTap,
this.title,
this.forceBottomSheet = false,
});
@override
State<ContextMenuWrapper> createState() => _ContextMenuWrapperState();
}
class _ContextMenuWrapperState extends State<ContextMenuWrapper> {
Offset _tapPosition = Offset.zero;
void _storeTapPosition(TapDownDetails details) {
_tapPosition = details.globalPosition;
}
Future<bool> _showConfirmationDialog({
required String title,
required String message,
required bool isDestructive,
}) async {
final result = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: Text(message),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
style: isDestructive
? TextButton.styleFrom(foregroundColor: Colors.red)
: null,
child: const Text('Confirm'),
),
],
),
);
return result ?? false;
}
Future<void> _showContextMenu(BuildContext context) async {
final useBottomSheet =
widget.forceBottomSheet || PlatformDetector.isMobile(context);
String? selected;
if (useBottomSheet) {
// Mobile: Show bottom sheet
selected = await showModalBottomSheet<String>(
context: context,
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (widget.title != null)
Padding(
padding: const EdgeInsets.all(16),
child: Text(
widget.title!,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
...widget.menuItems.map(
(item) => ListTile(
leading: Icon(item.icon),
title: Text(item.label),
onTap: () => Navigator.pop(context, item.value),
),
),
],
),
),
);
} else {
// Desktop: Show popup menu
final RenderBox overlay =
Overlay.of(context).context.findRenderObject() as RenderBox;
final overlayRect = Rect.fromPoints(
_tapPosition,
_tapPosition.translate(1, 1),
);
final menuItems = widget.menuItems
.map(
(item) => PopupMenuItem<String>(
value: item.value,
child: Row(
children: [
Icon(item.icon, size: 20),
const SizedBox(width: 12),
Expanded(child: Text(item.label)),
],
),
),
)
.toList();
selected = await showMenu<String>(
context: context,
position: RelativeRect.fromRect(
overlayRect,
Offset.zero & overlay.size,
),
items: menuItems,
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
popUpAnimationStyle: AnimationStyle(
duration: const Duration(milliseconds: 150),
reverseDuration: const Duration(milliseconds: 100),
),
);
}
if (selected != null && widget.onMenuItemSelected != null) {
// Find the selected item to check if confirmation is needed
final selectedItem = widget.menuItems.firstWhere(
(item) => item.value == selected,
);
if (selectedItem.requiresConfirmation) {
final confirmed = await _showConfirmationDialog(
title: selectedItem.confirmationTitle ?? 'Confirm Action',
message:
selectedItem.confirmationMessage ??
'Are you sure you want to perform this action?',
isDestructive: selectedItem.isDestructive,
);
if (!confirmed) return;
}
widget.onMenuItemSelected!(selected);
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onTap,
onTapDown: _storeTapPosition,
onLongPress: () => _showContextMenu(context),
onSecondaryTapDown: _storeTapPosition,
onSecondaryTap: () => _showContextMenu(context),
child: widget.child,
);
}
}
+171 -6
View File
@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
import '../utils/desktop_window_padding.dart';
import '../services/fullscreen_state_manager.dart';
import 'app_bar_back_button.dart';
/// A custom app bar that automatically handles desktop window controls spacing.
/// Use this instead of AppBar for consistent desktop platform behavior.
@@ -30,7 +32,12 @@ class DesktopAppBar extends StatelessWidget implements PreferredSizeWidget {
@override
Widget build(BuildContext context) {
final appBar = AppBar(
title: title != null ? DesktopTitleBarPadding(child: title!) : null,
title: title != null
? DesktopTitleBarPadding(
leftPadding: leading != null ? 0 : null,
child: title!,
)
: null,
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
leading: DesktopAppBarHelper.buildAdjustedLeading(leading),
automaticallyImplyLeading: automaticallyImplyLeading,
@@ -86,15 +93,39 @@ class DesktopSliverAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Determine the effective leading widget
Widget? effectiveLeading = leading;
// If no leading is provided but automaticallyImplyLeading is true,
// create a back button manually so it goes through our padding logic
if (leading == null && automaticallyImplyLeading) {
final parentRoute = ModalRoute.of(context);
final canPop = parentRoute?.canPop ?? false;
if (canPop) {
effectiveLeading = IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
);
}
}
return SliverAppBar(
title: title != null ? DesktopTitleBarPadding(child: title!) : null,
title: title != null
? DesktopTitleBarPadding(
leftPadding: effectiveLeading != null ? 0 : null,
child: title!,
)
: null,
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
leading: DesktopAppBarHelper.buildAdjustedLeading(
leading,
effectiveLeading,
includeGestureDetector: true,
),
leadingWidth: DesktopAppBarHelper.calculateLeadingWidth(leading),
automaticallyImplyLeading: automaticallyImplyLeading,
leadingWidth: DesktopAppBarHelper.calculateLeadingWidth(effectiveLeading),
automaticallyImplyLeading:
false, // Always false since we handle it manually
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
@@ -103,8 +134,142 @@ class DesktopSliverAppBar extends StatelessWidget {
floating: floating,
pinned: pinned,
expandedHeight: expandedHeight,
flexibleSpace: DesktopAppBarHelper.buildAdjustedFlexibleSpace(flexibleSpace),
flexibleSpace: DesktopAppBarHelper.buildAdjustedFlexibleSpace(
flexibleSpace,
),
bottom: bottom,
);
}
}
/// Convenient wrapper for DesktopAppBar with built-in back button handling
class PlexAppBar extends StatelessWidget implements PreferredSizeWidget {
final Widget? title;
final List<Widget>? actions;
final VoidCallback? onBackPressed;
final double? elevation;
final Color? backgroundColor;
final Color? surfaceTintColor;
final Color? shadowColor;
final double? scrolledUnderElevation;
const PlexAppBar({
super.key,
this.title,
this.actions,
this.onBackPressed,
this.elevation,
this.backgroundColor,
this.surfaceTintColor,
this.shadowColor,
this.scrolledUnderElevation,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
return DesktopAppBar(
key: ValueKey('plex_app_bar_$isFullscreen'),
title: title,
actions: actions,
leading: _shouldShowBackButton(context)
? AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: onBackPressed,
)
: null,
automaticallyImplyLeading: false,
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
scrolledUnderElevation: scrolledUnderElevation,
);
},
);
}
bool _shouldShowBackButton(BuildContext context) {
final parentRoute = ModalRoute.of(context);
return parentRoute?.canPop ?? false;
}
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
/// Convenient wrapper for DesktopSliverAppBar with built-in back button handling
class CustomAppBar extends StatelessWidget {
final Widget? title;
final List<Widget>? actions;
final VoidCallback? onBackPressed;
final double? elevation;
final Color? backgroundColor;
final Color? surfaceTintColor;
final Color? shadowColor;
final double? scrolledUnderElevation;
final bool floating;
final bool pinned;
final double? expandedHeight;
final Widget? flexibleSpace;
final PreferredSizeWidget? bottom;
const CustomAppBar({
super.key,
this.title,
this.actions,
this.onBackPressed,
this.elevation,
this.backgroundColor,
this.surfaceTintColor,
this.shadowColor,
this.scrolledUnderElevation,
this.floating = false,
this.pinned = false,
this.expandedHeight,
this.flexibleSpace,
this.bottom,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
return DesktopSliverAppBar(
key: ValueKey('plex_sliver_app_bar_$isFullscreen'),
title: title,
actions: actions,
leading: _shouldShowBackButton(context)
? AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: onBackPressed,
)
: null,
automaticallyImplyLeading: false,
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
scrolledUnderElevation: scrolledUnderElevation,
floating: floating,
pinned: pinned,
expandedHeight: expandedHeight,
flexibleSpace: flexibleSpace,
bottom: bottom,
);
},
);
}
bool _shouldShowBackButton(BuildContext context) {
final parentRoute = ModalRoute.of(context);
return parentRoute?.canPop ?? false;
}
}
+179
View File
@@ -0,0 +1,179 @@
import 'package:flutter/material.dart';
import '../models/plex_file_info.dart';
class FileInfoBottomSheet extends StatelessWidget {
final PlexFileInfo fileInfo;
final String title;
const FileInfoBottomSheet({
super.key,
required this.fileInfo,
required this.title,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.grey[900],
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
),
),
child: SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
// Header
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(
Icons.info_outline,
color: Colors.white,
size: 24,
),
const SizedBox(width: 12),
Expanded(
child: Text(
'File Info',
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.grey, height: 1),
// Content
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
// Title
if (title.isNotEmpty) ...[
Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 20),
],
// Video Section
_buildSectionHeader('Video'),
const SizedBox(height: 8),
_buildInfoRow('Codec', fileInfo.videoCodec ?? 'Unknown'),
_buildInfoRow('Resolution', fileInfo.resolutionFormatted),
_buildInfoRow('Bitrate', fileInfo.bitrateFormatted),
_buildInfoRow('Frame Rate', fileInfo.frameRateFormatted),
_buildInfoRow('Aspect Ratio', fileInfo.aspectRatioFormatted),
if (fileInfo.videoProfile != null)
_buildInfoRow('Profile', fileInfo.videoProfile!),
if (fileInfo.bitDepth != null)
_buildInfoRow('Bit Depth', '${fileInfo.bitDepth} bit'),
if (fileInfo.colorSpace != null)
_buildInfoRow('Color Space', fileInfo.colorSpace!),
if (fileInfo.colorRange != null)
_buildInfoRow('Color Range', fileInfo.colorRange!),
if (fileInfo.colorPrimaries != null)
_buildInfoRow('Color Primaries', fileInfo.colorPrimaries!),
if (fileInfo.chromaSubsampling != null)
_buildInfoRow('Chroma Subsampling', fileInfo.chromaSubsampling!),
const SizedBox(height: 20),
// Audio Section
_buildSectionHeader('Audio'),
const SizedBox(height: 8),
_buildInfoRow('Codec', fileInfo.audioCodec ?? 'Unknown'),
_buildInfoRow('Channels', fileInfo.audioChannelsFormatted),
if (fileInfo.audioProfile != null)
_buildInfoRow('Profile', fileInfo.audioProfile!),
const SizedBox(height: 20),
// File Section
_buildSectionHeader('File'),
const SizedBox(height: 8),
if (fileInfo.filePath != null)
_buildInfoRow('Path', fileInfo.filePath!, isMonospace: true),
_buildInfoRow('Size', fileInfo.fileSizeFormatted),
_buildInfoRow('Container', fileInfo.container ?? 'Unknown'),
_buildInfoRow('Duration', fileInfo.durationFormatted),
const SizedBox(height: 20),
// Advanced Section
_buildSectionHeader('Advanced'),
const SizedBox(height: 8),
_buildInfoRow(
'Optimized for Streaming',
fileInfo.optimizedForStreaming == true ? 'Yes' : 'No',
),
_buildInfoRow(
'64-bit Offsets',
fileInfo.has64bitOffsets == true ? 'Yes' : 'No',
),
],
),
),
],
),
),
),
);
}
Widget _buildSectionHeader(String title) {
return Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
);
}
Widget _buildInfoRow(String label, String value, {bool isMonospace = false}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 140,
child: Text(
label,
style: TextStyle(
color: Colors.grey[400],
fontSize: 14,
),
),
),
Expanded(
child: Text(
value,
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontFamily: isMonospace ? 'monospace' : null,
),
),
),
],
),
);
}
}
@@ -0,0 +1,194 @@
import 'package:flutter/material.dart';
import '../utils/platform_detector.dart';
/// A wrapper widget that adds hover-activated navigation arrows to horizontal scrolling content.
/// The arrows only appear on desktop/web platforms and hide at scroll boundaries.
///
/// This widget creates and manages its own ScrollController internally. Use the [builder]
/// constructor to access the ScrollController for the scrollable child widget.
class HorizontalScrollWithArrows extends StatefulWidget {
final Widget Function(ScrollController) builder;
final double scrollAmount;
const HorizontalScrollWithArrows({
super.key,
required this.builder,
this.scrollAmount = 0.8, // Scroll by 80% of viewport width by default
});
@override
State<HorizontalScrollWithArrows> createState() =>
_HorizontalScrollWithArrowsState();
}
class _HorizontalScrollWithArrowsState
extends State<HorizontalScrollWithArrows> {
late final ScrollController _scrollController;
bool _isHovering = false;
bool _canScrollLeft = false;
bool _canScrollRight = false;
@override
void initState() {
super.initState();
_scrollController = ScrollController();
_scrollController.addListener(_updateScrollState);
// Initial state update after first frame
WidgetsBinding.instance.addPostFrameCallback((_) => _updateScrollState());
}
@override
void dispose() {
_scrollController.removeListener(_updateScrollState);
_scrollController.dispose();
super.dispose();
}
void _updateScrollState() {
if (!mounted) return;
final position = _scrollController.position;
setState(() {
_canScrollLeft = position.pixels > 0;
_canScrollRight = position.pixels < position.maxScrollExtent;
});
}
void _scrollLeft() {
final position = _scrollController.position;
final targetScroll = (position.pixels -
(position.viewportDimension * widget.scrollAmount))
.clamp(0.0, position.maxScrollExtent);
_scrollController.animateTo(
targetScroll,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
void _scrollRight() {
final position = _scrollController.position;
final targetScroll = (position.pixels +
(position.viewportDimension * widget.scrollAmount))
.clamp(0.0, position.maxScrollExtent);
_scrollController.animateTo(
targetScroll,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
@override
Widget build(BuildContext context) {
final child = widget.builder(_scrollController);
if (!PlatformDetector.isDesktop(context)) {
// On mobile, just return the child without arrows
return child;
}
return MouseRegion(
onEnter: (_) => setState(() => _isHovering = true),
onExit: (_) => setState(() => _isHovering = false),
child: Stack(
children: [
child,
// Left arrow
Positioned(
left: 8,
top: 0,
bottom: 0,
child: Center(
child: AnimatedOpacity(
opacity: (_isHovering && _canScrollLeft) ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
child: IgnorePointer(
ignoring: !(_isHovering && _canScrollLeft),
child: _NavigationArrow(
icon: Icons.chevron_left,
onPressed: _scrollLeft,
),
),
),
),
),
// Right arrow
Positioned(
right: 8,
top: 0,
bottom: 0,
child: Center(
child: AnimatedOpacity(
opacity: (_isHovering && _canScrollRight) ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
child: IgnorePointer(
ignoring: !(_isHovering && _canScrollRight),
child: _NavigationArrow(
icon: Icons.chevron_right,
onPressed: _scrollRight,
),
),
),
),
),
],
),
);
}
}
class _NavigationArrow extends StatefulWidget {
final IconData icon;
final VoidCallback onPressed;
const _NavigationArrow({
required this.icon,
required this.onPressed,
});
@override
State<_NavigationArrow> createState() => _NavigationArrowState();
}
class _NavigationArrowState extends State<_NavigationArrow> {
bool _isPressed = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTapDown: (_) => setState(() => _isPressed = true),
onTapUp: (_) {
setState(() => _isPressed = false);
widget.onPressed();
},
onTapCancel: () => setState(() => _isPressed = false),
child: Container(
width: 48,
height: 48,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black.withValues(alpha: _isPressed ? 0.9 : 0.7),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.3),
blurRadius: 8,
spreadRadius: 0,
),
],
),
child: Icon(
widget.icon,
color: Colors.white,
size: 32,
),
),
),
);
}
}

Some files were not shown because too many files have changed in this diff Show More