Compare commits

...
42 Commits
Author SHA1 Message Date
github-actions[bot] 8d0d220d78 chore: bump version to 1.8.0+20 2025-11-22 23:36:51 +00:00
edde746 3e0379996c ci: release workflow 2025-11-23 00:36:02 +01:00
edde746 6aecaaa44a refactor: simplify server tracking 2025-11-22 23:41:46 +01:00
edde746 21627f7a97 fix: android resume issue 2025-11-22 22:32:07 +01:00
edde746 cb8e0bfa79 ci: dead code checks 2025-11-22 16:03:51 +01:00
edde746 19601e87c7 refactor: clean up 2025-11-22 07:54:52 +01:00
edde746 3945aa7b58 fix: multi-server connectivity optimization 2025-11-22 06:52:21 +01:00
edde746 b455db4bdf refactor: clean up 2025-11-22 06:33:49 +01:00
edde746 38a447f57a refactor: format & split video controls 2025-11-22 05:58:08 +01:00
edde746 8a24157832 fix: library manager 2025-11-22 04:42:11 +01:00
edde746 166654d374 refactor: use play queues & other improvements 2025-11-22 03:24:01 +01:00
edde746 6e8a1a373e feat: remove server switcher 2025-11-21 23:59:39 +01:00
edde746 b1bed439eb fix: defer clearShuffle call to avoid setState during build 2025-11-21 03:52:59 +01:00
edde746 2562d3d4b6 fix: linux audio output issues 2025-11-21 02:36:37 +01:00
edde746 c27d9d09e4 fix: linux crash 2025-11-21 02:03:36 +01:00
edde746 3cb8b522f6 chore: bump version 2025-11-20 19:10:18 +01:00
edde746 9115db5e15 fix: ios media controls 2025-11-20 19:08:31 +01:00
edde746 d63c10482c chore: bump version 2025-11-20 15:56:48 +01:00
edde746 bd283dd039 fix: inactive pause fixes 2025-11-20 15:54:13 +01:00
edde746andGitHub 0403acc9d3 Merge pull request #123 from Doezer/main
Add missing translations
2025-11-19 23:34:54 +01:00
DoezerandGitHub b81eee7f34 Merge pull request #11 from Doezer/copilot/check-untranslated-strings
Translate 126 untranslated strings across SV, NL, IT, and ZH locales
2025-11-19 22:31:05 +01:00
copilot-swe-agent[bot]andDoezer 8cef2d9cb0 Translate untranslated strings across all languages
- Swedish (SV): Translated 29 strings including video controls and accessibility labels
- Dutch (NL): Translated 36 strings including video controls, auth, and navigation
- Italian (IT): Translated 32 strings including video controls and discover section
- Chinese (ZH): Translated 29 strings with complete video player UI localization
- German (DE): Already well-translated, verified existing translations

Total: 126 strings translated across all languages
Remaining untranslated strings are intentional (brand names, technical terms, format strings)

Co-authored-by: Doezer <11655673+Doezer@users.noreply.github.com>
2025-11-19 20:41:52 +00:00
copilot-swe-agent[bot] 2e042922f4 Initial plan 2025-11-19 20:35:39 +00:00
edde746 79fb716551 fix: linux media controls 2025-11-19 09:23:39 +01:00
edde746 37b0cf65b2 fix: https required servers issue 2025-11-18 20:47:31 +01:00
edde746andGitHub b8a7d8610c Merge pull request #119 from jamal2362/main1
Update german translation
2025-11-18 20:38:11 +01:00
Jamal ad3f26de30 Update german translation 2025-11-18 19:48:08 +01:00
edde746 f23ab5b96e fix: media card playlist compatibility 2025-11-18 19:03:17 +01:00
edde746 f4c52f4069 Merge branch 'accessibility' 2025-11-18 14:44:30 +01:00
edde746 9af87d2e02 refactor: wrap buttons in semantics 2025-11-18 14:44:00 +01:00
edde746 adbf126430 chore: bump version 2025-11-18 13:38:45 +01:00
edde746 61817ed14e fix: subtitle cropping adjustments 2025-11-18 13:38:08 +01:00
edde746 0eff03a66e fix: macos crash 2025-11-18 13:37:39 +01:00
Manuel Cortez 6417a37366 Added semantics to app bar's back button. Fixed conflicts 2025-11-17 23:12:42 -06:00
Manuel Cortez e519304f2e added translation for 'tap to play' hint on media cards 2025-11-17 22:42:11 -06:00
Manuel Cortez d0bfcb107d Enhance semantic labels to hero section on discover screen 2025-11-17 22:30:49 -06:00
Manuel Cortez 2f307ee613 added proper semantic labels to media cards 2025-11-17 22:29:08 -06:00
Manuel Cortez e23f248427 Merge branch 'main' into accessibility 2025-11-15 22:36:14 -06:00
Manuel Cortez c6bd1ef867 Added missing translation file 2025-11-15 22:22:24 -06:00
Manuel Cortez 931bc9b931 Added semantic labels to media player controls 2025-11-15 22:17:04 -06:00
Manuel Cortez 3f4d5c2923 video_control_button: sets a semantic label properly for IconButtons 2025-11-15 22:07:30 -06:00
Manuel Cortez 1220dca88e Prepared translation files with new addition for accessibility enhancements 2025-11-15 22:05:41 -06:00
110 changed files with 20095 additions and 12274 deletions
+35 -4
View File
@@ -53,10 +53,17 @@ jobs:
find lib $([ -d test ] && echo test) -name "*.dart" ! -name "*.g.dart" ! -name "*.freezed.dart" -type f 2>/dev/null -print0 | xargs -0 dart format --output=none --set-exit-if-changed
- name: Analyze code
run: |
# Run flutter analyze and filter out info-level warnings
# Only fail on errors and warnings, not on info messages
# Run flutter analyze
# Fails on any errors or warnings (info messages are allowed)
flutter analyze 2>&1 | tee analyze_output.txt
# Check if there are any errors (not just info)
# Check the exit status
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "❌ Analysis failed"
exit 1
fi
# Also verify no warnings or errors in output
if grep -q "error •" analyze_output.txt; then
echo "❌ Analysis failed with errors"
exit 1
@@ -64,10 +71,34 @@ jobs:
echo "⚠️ Analysis completed with warnings"
exit 1
else
echo "✅ Analysis passed (info messages are allowed)"
echo "✅ Analysis passed - no issues found!"
exit 0
fi
- name: Check for unused code
run: |
echo "🔍 Checking for unused code..."
dart run dart_code_linter:metrics check-unused-code lib 2>&1 | tee unused_code.txt
if grep -qi "no unused code found" unused_code.txt; then
echo "✅ No unused code found"
else
echo "❌ Found unused code:"
cat unused_code.txt
exit 1
fi
- name: Check for unused files
run: |
echo "🔍 Checking for unused files..."
dart run dart_code_linter:metrics check-unused-files lib 2>&1 | tee unused_files.txt
if grep -qi "no unused files found" unused_files.txt; then
echo "✅ No unused files found"
else
echo "❌ Found unused files:"
cat unused_files.txt
exit 1
fi
test:
name: Unit Tests
runs-on: ubuntu-latest
+82
View File
@@ -0,0 +1,82 @@
name: Release
on:
workflow_dispatch:
inputs:
version:
description: 'Version number (e.g., 1.9.0)'
required: true
type: string
permissions:
contents: write
actions: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Validate version format
run: |
if ! echo "${{ inputs.version }}" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "Error: Version must be in semantic versioning format (e.g., 1.9.0)"
exit 1
fi
- name: Extract current build number
id: get_build
run: |
# Extract current build number from pubspec.yaml
CURRENT_VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //')
CURRENT_BUILD=$(echo "$CURRENT_VERSION" | cut -d'+' -f2)
NEW_BUILD=$((CURRENT_BUILD + 1))
echo "current_build=$CURRENT_BUILD" >> $GITHUB_OUTPUT
echo "new_build=$NEW_BUILD" >> $GITHUB_OUTPUT
echo "Current build: $CURRENT_BUILD"
echo "New build: $NEW_BUILD"
- name: Update pubspec.yaml
run: |
NEW_VERSION="${{ inputs.version }}+${{ steps.get_build.outputs.new_build }}"
sed -i "s/^version: .*/version: $NEW_VERSION/" pubspec.yaml
echo "Updated version to: $NEW_VERSION"
cat pubspec.yaml | grep '^version:'
- name: Configure Git
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
- name: Commit version bump
run: |
git add pubspec.yaml
git commit -m "chore: bump version to ${{ inputs.version }}+${{ steps.get_build.outputs.new_build }}"
- name: Create Git tag
run: |
git tag "${{ inputs.version }}"
echo "Created tag: ${{ inputs.version }}"
- name: Push changes and tag
run: |
git push origin main
git push origin "${{ inputs.version }}"
- name: Trigger build workflow
run: |
curl -L \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/${{ github.repository }}/actions/workflows/build.yml/dispatches \
-d '{"ref":"main"}'
echo "Build workflow triggered successfully"
+6
View File
@@ -4,3 +4,9 @@ analyzer:
exclude:
- "**/*.g.dart"
- "**/*.freezed.dart"
plugins:
- dart_code_linter
dart_code_linter:
rules:
- avoid-unused-parameters
+1 -2
View File
@@ -6,7 +6,6 @@ PODS:
- Flutter
- media_kit_video (0.0.1):
- Flutter
- media_kit_libs_ios_video
- os_media_controls (0.0.1):
- Flutter
- package_info_plus (0.4.5):
@@ -71,7 +70,7 @@ SPEC CHECKSUMS:
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
media_kit_libs_ios_video: 5a18affdb97d1f5d466dc79988b13eff6c5e2854
media_kit_video: 6235abf1d299037d23692ad47119b89e05346b23
media_kit_video: 1746e198cb697d1ffb734b1d05ec429d1fcd1474
os_media_controls: 86dceab6245a5325af90fc0fdebe243c42d789b4
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
+51 -76
View File
@@ -32,6 +32,12 @@ class PlexClient {
final EndpointFailoverManager? _endpointManager;
final Future<void> Function(String newBaseUrl)? _onEndpointChanged;
/// Server identifier - all PlexMetadata items created by this client are tagged with this
final String serverId;
/// Server name - all PlexMetadata items created by this client are tagged with this
final String? serverName;
/// Custom response decoder that handles malformed UTF-8 gracefully
static String _lenientUtf8Decoder(
List<int> responseBytes,
@@ -43,6 +49,8 @@ class PlexClient {
PlexClient(
this.config, {
required this.serverId,
this.serverName,
List<String>? prioritizedEndpoints,
Future<void> Function(String newBaseUrl)? onEndpointChanged,
}) : _endpointManager =
@@ -1102,82 +1110,6 @@ class PlexClient {
}
}
/// Find adjacent episode in a given direction
///
/// [direction]: +1 for next episode, -1 for previous episode
///
/// Handles navigation within current season and across seasons automatically.
Future<PlexMetadata?> findAdjacentEpisode(
PlexMetadata currentEpisode,
int direction,
) async {
if (currentEpisode.type.toLowerCase() != 'episode') {
return null;
}
final parentKey = currentEpisode.parentRatingKey;
final grandparentKey = currentEpisode.grandparentRatingKey;
if (parentKey == null || grandparentKey == null) {
return null;
}
try {
// Get all episodes in the current season
final episodes = await getChildren(parentKey);
// Find the current episode index
final currentIndex = episodes.indexWhere(
(e) => e.ratingKey == currentEpisode.ratingKey,
);
if (currentIndex == -1) return null;
final targetIndex = currentIndex + direction;
// Check if target episode is within current season
if (targetIndex >= 0 && targetIndex < episodes.length) {
return episodes[targetIndex];
}
// Need to move to adjacent season
final isAtBoundary = direction > 0
? currentIndex == episodes.length - 1
: currentIndex == 0;
if (isAtBoundary) {
// Get all seasons
final seasons = await getChildren(grandparentKey);
final currentSeasonIndex = seasons.indexWhere(
(s) => s.ratingKey == parentKey,
);
if (currentSeasonIndex == -1) return null;
final targetSeasonIndex = currentSeasonIndex + direction;
// Check if target season exists
if (targetSeasonIndex >= 0 && targetSeasonIndex < seasons.length) {
final targetSeason = seasons[targetSeasonIndex];
final targetSeasonEpisodes = await getChildren(
targetSeason.ratingKey,
);
if (targetSeasonEpisodes.isNotEmpty) {
// Return first episode for next season, last for previous
return direction > 0
? targetSeasonEpisodes.first
: targetSeasonEpisodes.last;
}
}
}
} catch (e) {
// Silently handle errors
}
return null;
}
/// Get library hubs (recommendations for a specific library section)
/// Returns a list of recommendation hubs like "Trending Movies", "Top in Genre", etc.
Future<List<PlexHub>> getLibraryHubs(
@@ -1726,6 +1658,49 @@ class PlexClient {
}
}
/// Create a play queue for a TV show (all episodes)
///
/// This is a convenience method that creates a play queue from a show's URI.
/// Perfect for sequential or shuffle playback of an entire series.
///
/// Parameters:
/// - [showRatingKey]: The rating key of the show
/// - [shuffle]: Whether to shuffle the episodes (0 = off, 1 = on)
/// - [startingEpisodeKey]: Optional rating key of episode to start from
///
/// Returns a PlayQueueResponse with all episodes from the show
Future<PlayQueueResponse?> createShowPlayQueue({
required String showRatingKey,
int shuffle = 0,
String? startingEpisodeKey,
}) async {
try {
// Get machine identifier for building the URI
final machineId =
config.machineIdentifier ?? await getMachineIdentifier();
if (machineId == null) {
throw Exception('Could not get server machine identifier');
}
// Build the URI for the show's episodes
final uri =
'server://$machineId/com.plexapp.plugins.library/library/metadata/$showRatingKey/children';
// Create the play queue with optional starting episode
return await createPlayQueue(
uri: uri,
type: 'video',
shuffle: shuffle,
key: startingEpisodeKey != null
? '/library/metadata/$startingEpisodeKey'
: null,
);
} catch (e) {
appLogger.e('Failed to create show play queue', error: e);
return null;
}
}
/// Extract both Metadata and Directory entries from response
/// Folders can come back as either type
List<PlexMetadata> _extractMetadataAndDirectories(Response response) {
-60
View File
@@ -11,15 +11,6 @@ class ScreenBreakpoints {
static const double largeDesktop = 1600;
}
/// Pagination constants
class PaginationConstants {
/// Default page size for library items
static const int defaultPageSize = 1000;
/// Page size for search results
static const int searchPageSize = 50;
}
/// Grid layout constants
class GridLayoutConstants {
/// Maximum cross-axis extent for grid items in comfortable density mode
@@ -44,54 +35,3 @@ class GridLayoutConstants {
static const double crossAxisSpacing = 0;
static const double mainAxisSpacing = 0;
}
/// Padding and spacing constants
class SpacingConstants {
/// Extra small spacing (4px)
static const double xs = 4;
/// Small spacing (8px)
static const double sm = 8;
/// Medium spacing (12px)
static const double md = 12;
/// Large spacing (16px)
static const double lg = 16;
/// Extra large spacing (24px)
static const double xl = 24;
/// Double extra large spacing (32px)
static const double xxl = 32;
}
/// Icon size constants
class IconSizeConstants {
/// Small icon size (16px)
static const double sm = 16;
/// Medium icon size (24px)
static const double md = 24;
/// Large icon size (32px)
static const double lg = 32;
/// Extra large icon size (48px)
static const double xl = 48;
}
/// Border radius constants
class BorderRadiusConstants {
/// Small border radius (4px)
static const double sm = 4;
/// Medium border radius (8px)
static const double md = 8;
/// Large border radius (12px)
static const double lg = 12;
/// Extra large border radius (16px)
static const double xl = 16;
}
+12351 -5827
View File
File diff suppressed because it is too large Load Diff
+39 -3
View File
@@ -44,7 +44,6 @@
},
"screens": {
"licenses": "Licenses",
"selectServer": "Select Server",
"switchProfile": "Switch Profile",
"subtitleStyling": "Subtitle Styling",
"search": "Search",
@@ -184,6 +183,16 @@
"shufflePlay": "Shuffle Play",
"fileInfo": "File Info"
},
"accessibility": {
"mediaCardMovie": "${title}, movie",
"mediaCardShow": "${title}, TV show",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "watched",
"mediaCardPartiallyWatched": "${percent} percent watched",
"mediaCardUnwatched": "unwatched",
"tapToPlay": "Tap to play"
},
"tooltips": {
"shufflePlay": "Shuffle play",
"markAsWatched": "Mark as watched",
@@ -206,7 +215,30 @@
"sleepTimer": "Sleep Timer",
"timerActive": "Timer Active",
"playbackWillPauseIn": "Playback will pause in ${duration}",
"sleepTimerCompleted": "Sleep timer completed - playback paused"
"sleepTimerCompleted": "Sleep timer completed - playback paused",
"playButton": "Play",
"pauseButton": "Pause",
"seekBackwardButton": "Seek backward ${seconds} seconds",
"seekForwardButton": "Seek forward ${seconds} seconds",
"previousButton": "Previous episode",
"nextButton": "Next episode",
"previousChapterButton": "Previous chapter",
"nextChapterButton": "Next chapter",
"volumeButton": "Volume",
"muteButton": "Mute",
"unmuteButton": "Unmute",
"settingsButton": "Video settings",
"audioTrackButton": "Audio tracks",
"subtitlesButton": "Subtitles",
"chaptersButton": "Chapters",
"versionsButton": "Video versions",
"aspectRatioButton": "Aspect ratio",
"fullscreenButton": "Enter fullscreen",
"exitFullscreenButton": "Exit fullscreen",
"rotationLockButton": "Rotation lock",
"timelineSlider": "Video timeline",
"volumeSlider": "Volume level",
"backButton": "Back"
},
"userStatus": {
"admin": "Admin",
@@ -267,7 +299,6 @@
"discover": {
"title": "Discover",
"switchProfile": "Switch Profile",
"switchServer": "Switch Server",
"logout": "Logout",
"noContentAvailable": "No content available",
"addMediaToLibraries": "Add some media to your libraries",
@@ -366,6 +397,11 @@
},
"serverSelection": {
"connectingToServer": "Connecting to server...",
"connectingToAllServers": "Connecting to all servers...",
"connectToAllServers": "Connect to All Servers",
"allServerConnectionsFailed": "Failed to connect to any servers. Please check your network and try again.",
"foundServers": "Found ${count} server(s)",
"orSelectIndividually": "Or select a server individually:",
"serverDebugCopied": "Server debug data copied to clipboard",
"copyDebugData": "Copy Debug Data",
"noServersFound": "No servers found",
+42 -4
View File
@@ -184,6 +184,16 @@
"shufflePlay": "Zufallswiedergabe",
"fileInfo": "Dateiinfo"
},
"accessibility": {
"mediaCardMovie": "${title}, Film",
"mediaCardShow": "${title}, Serie",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "angesehen",
"mediaCardPartiallyWatched": "${percent} Prozent angesehen",
"mediaCardUnwatched": "ungeschaut",
"tapToPlay": "Zum Abspielen tippen"
},
"tooltips": {
"shufflePlay": "Zufallswiedergabe",
"markAsWatched": "Als gesehen markieren",
@@ -203,10 +213,33 @@
"stretch": "Strecken",
"lockRotation": "Rotation sperren",
"unlockRotation": "Rotation entsperren",
"sleepTimer": "Schlaf-Timer",
"timerActive": "Timer aktiv",
"playbackWillPauseIn": "Wiedergabe wird pausiert in ${duration}",
"sleepTimerCompleted": "Schlaf-Timer abgelaufen - Wiedergabe pausiert"
"sleepTimer": "Schlaftimer",
"timerActive": "Schlaftimer aktiv",
"playbackWillPauseIn": "Wiedergabe wird in ${duration} pausiert",
"sleepTimerCompleted": "Schlaftimer abgelaufen – Wiedergabe pausiert",
"playButton": "Wiedergeben",
"pauseButton": "Pause",
"seekBackwardButton": "${seconds} Sekunden zurück",
"seekForwardButton": "${seconds} Sekunden vor",
"previousButton": "Vorherige Episode",
"nextButton": "Nächste Episode",
"previousChapterButton": "Vorheriges Kapitel",
"nextChapterButton": "Nächstes Kapitel",
"volumeButton": "Lautstärke",
"muteButton": "Stumm schalten",
"unmuteButton": "Stummschaltung aufheben",
"settingsButton": "Videoeinstellungen",
"audioTrackButton": "Tonspuren",
"subtitlesButton": "Untertitel",
"chaptersButton": "Kapitel",
"versionsButton": "Videoversionen",
"aspectRatioButton": "Seitenverhältnis",
"fullscreenButton": "Vollbild aktivieren",
"exitFullscreenButton": "Vollbild verlassen",
"rotationLockButton": "Dreh­sperre",
"timelineSlider": "Video-Zeitleiste",
"volumeSlider": "Lautstärkepegel",
"backButton": "Zurück"
},
"userStatus": {
"admin": "Eigentümer",
@@ -366,6 +399,11 @@
},
"serverSelection": {
"connectingToServer": "Verbinde mit Server...",
"connectingToAllServers": "Verbinde mit allen Servern...",
"connectToAllServers": "Mit allen Servern verbinden",
"allServerConnectionsFailed": "Verbindung zu allen Servern fehlgeschlagen. Bitte Netzwerk prüfen und erneut versuchen.",
"foundServers": "${count} Server gefunden",
"orSelectIndividually": "Oder einzelnen Server auswählen:",
"serverDebugCopied": "Server-Debugdaten kopiert",
"copyDebugData": "Debugdaten kopieren",
"noServersFound": "Keine Server gefunden",
+44 -6
View File
@@ -48,7 +48,7 @@
"switchProfile": "Cambia profilo",
"subtitleStyling": "Stile sottotitoli",
"search": "Cerca",
"logs": "Logs"
"logs": "Registro"
},
"update": {
"available": "Aggiornamento disponibile",
@@ -184,6 +184,16 @@
"shufflePlay": "Riproduzione casuale",
"fileInfo": "Info sul file"
},
"accessibility": {
"mediaCardMovie": "${title}, film",
"mediaCardShow": "${title}, serie TV",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "visto",
"mediaCardPartiallyWatched": "${percent} percento visto",
"mediaCardUnwatched": "non visto",
"tapToPlay": "Tocca per riprodurre"
},
"tooltips": {
"shufflePlay": "Riproduzione casuale",
"markAsWatched": "Segna come visto",
@@ -197,7 +207,7 @@
"minusTime": "-${amount}${unit}",
"playsLater": "${label} riprodotto dopo",
"playsEarlier": "${label} riprodotto prima",
"noOffset": "No offset",
"noOffset": "Nessun offset",
"letterbox": "Letterbox",
"fillScreen": "Riempi schermo",
"stretch": "Allunga",
@@ -206,7 +216,30 @@
"sleepTimer": "Timer di spegnimento",
"timerActive": "Timer attivo",
"playbackWillPauseIn": "La riproduzione si interromperà tra ${duration}",
"sleepTimerCompleted": "Timer di spegnimento completato - riproduzione in pausa"
"sleepTimerCompleted": "Timer di spegnimento completato - riproduzione in pausa",
"playButton": "Riproduci",
"pauseButton": "Pausa",
"seekBackwardButton": "Riavvolgi di ${seconds} secondi",
"seekForwardButton": "Avanza di ${seconds} secondi",
"previousButton": "Episodio precedente",
"nextButton": "Episodio successivo",
"previousChapterButton": "Capitolo precedente",
"nextChapterButton": "Capitolo successivo",
"volumeButton": "Volume",
"muteButton": "Silenzia",
"unmuteButton": "Riattiva audio",
"settingsButton": "Impostazioni video",
"audioTrackButton": "Tracce audio",
"subtitlesButton": "Sottotitoli",
"chaptersButton": "Capitoli",
"versionsButton": "Versioni video",
"aspectRatioButton": "Proporzioni",
"fullscreenButton": "Attiva schermo intero",
"exitFullscreenButton": "Esci da schermo intero",
"rotationLockButton": "Blocco rotazione",
"timelineSlider": "Timeline video",
"volumeSlider": "Livello volume",
"backButton": "Indietro"
},
"userStatus": {
"admin": "Admin",
@@ -265,7 +298,7 @@
"playNow": "Riproduci ora"
},
"discover": {
"title": "Discover",
"title": "Esplora",
"switchProfile": "Cambia profilo",
"switchServer": "Cambia server",
"logout": "Disconnetti",
@@ -279,7 +312,7 @@
"resumeEpisode": "Riprendi S${season}, E${episode}",
"pause": "Pausa",
"overview": "Panoramica",
"cast": "Cast",
"cast": "Attori",
"seasons": "Stagioni",
"studio": "Studio",
"rating": "Classificazione",
@@ -366,6 +399,11 @@
},
"serverSelection": {
"connectingToServer": "Connessione al server...",
"connectingToAllServers": "Connessione a tutti i server...",
"connectToAllServers": "Connetti a tutti i server",
"allServerConnectionsFailed": "Impossibile connettersi a nessun server. Controlla la tua rete e riprova.",
"foundServers": "Trovati ${count} server",
"orSelectIndividually": "Oppure seleziona un server singolarmente:",
"serverDebugCopied": "Dati di debug del server copiati negli appunti",
"copyDebugData": "Copia dati di debug",
"noServersFound": "Nessun server trovato",
@@ -386,7 +424,7 @@
"noItemsFound": "Nessun elemento trovato"
},
"logs": {
"title": "Log",
"title": "Registro",
"clearLogs": "Cancella log",
"copyLogs": "Copia log",
"exportLogs": "Esporta log",
+47 -9
View File
@@ -10,7 +10,7 @@
"authenticate": "Authenticeren",
"retry": "Opnieuw proberen",
"debugEnterToken": "Debug: Voer Plex Token in",
"plexTokenLabel": "Plex Auth Token",
"plexTokenLabel": "Plex Authenticatietoken",
"plexTokenHint": "Voer je Plex.tv token in",
"authenticationTimeout": "Authenticatie verlopen. Probeer opnieuw.",
"scanQRCodeInstruction": "Scan deze QR-code met een apparaat dat is ingelogd op Plex om te authenticeren.",
@@ -39,7 +39,7 @@
"no": "Nee",
"server": "Server",
"delete": "Verwijderen",
"shuffle": "Shuffle",
"shuffle": "Willekeurig",
"addTo": "Toevoegen aan..."
},
"screens": {
@@ -48,7 +48,7 @@
"switchProfile": "Wissel van profiel",
"subtitleStyling": "Ondertitel opmaak",
"search": "Zoeken",
"logs": "Logs"
"logs": "Logbestanden"
},
"update": {
"available": "Update beschikbaar",
@@ -184,6 +184,16 @@
"shufflePlay": "Willekeurig afspelen",
"fileInfo": "Bestand info"
},
"accessibility": {
"mediaCardMovie": "${title}, film",
"mediaCardShow": "${title}, TV-serie",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "bekeken",
"mediaCardPartiallyWatched": "${percent} procent bekeken",
"mediaCardUnwatched": "niet bekeken",
"tapToPlay": "Tik om af te spelen"
},
"tooltips": {
"shufflePlay": "Willekeurig afspelen",
"markAsWatched": "Markeer als gekeken",
@@ -206,7 +216,30 @@
"sleepTimer": "Slaaptimer",
"timerActive": "Timer actief",
"playbackWillPauseIn": "Afspelen wordt gepauzeerd over ${duration}",
"sleepTimerCompleted": "Slaaptimer voltooid - afspelen gepauzeerd"
"sleepTimerCompleted": "Slaaptimer voltooid - afspelen gepauzeerd",
"playButton": "Afspelen",
"pauseButton": "Pauzeren",
"seekBackwardButton": "Terugspoelen ${seconds} seconden",
"seekForwardButton": "Vooruitspoelen ${seconds} seconden",
"previousButton": "Vorige aflevering",
"nextButton": "Volgende aflevering",
"previousChapterButton": "Vorig hoofdstuk",
"nextChapterButton": "Volgend hoofdstuk",
"volumeButton": "Volume",
"muteButton": "Dempen",
"unmuteButton": "Dempen opheffen",
"settingsButton": "Video-instellingen",
"audioTrackButton": "Audiosporen",
"subtitlesButton": "Ondertitels",
"chaptersButton": "Hoofdstukken",
"versionsButton": "Videoversies",
"aspectRatioButton": "Beeldverhouding",
"fullscreenButton": "Volledig scherm activeren",
"exitFullscreenButton": "Volledig scherm verlaten",
"rotationLockButton": "Rotatievergrendeling",
"timelineSlider": "Videotijdlijn",
"volumeSlider": "Volumeniveau",
"backButton": "Terug"
},
"userStatus": {
"admin": "Beheerder",
@@ -279,7 +312,7 @@
"resumeEpisode": "Hervat S${season}, E${episode}",
"pause": "Pauzeren",
"overview": "Overzicht",
"cast": "Cast",
"cast": "Acteurs",
"seasons": "Seizoenen",
"studio": "Studio",
"rating": "Leeftijd",
@@ -366,6 +399,11 @@
},
"serverSelection": {
"connectingToServer": "Verbinden met server...",
"connectingToAllServers": "Verbinden met alle servers...",
"connectToAllServers": "Verbind met alle servers",
"allServerConnectionsFailed": "Kon niet verbinden met servers. Controleer je netwerk en probeer opnieuw.",
"foundServers": "${count} server(s) gevonden",
"orSelectIndividually": "Of selecteer een server individueel:",
"serverDebugCopied": "Server debug gegevens gekopieerd naar klembord",
"copyDebugData": "Kopieer debug gegevens",
"noServersFound": "Geen servers gevonden",
@@ -386,13 +424,13 @@
"noItemsFound": "Geen items gevonden"
},
"logs": {
"title": "Logs",
"title": "Logbestanden",
"clearLogs": "Wis logs",
"copyLogs": "Kopieer logs",
"exportLogs": "Exporteer logs",
"noLogsToShow": "Geen logs om te tonen",
"error": "Fout:",
"stackTrace": "Stack Trace:"
"stackTrace": "Stacktracering:"
},
"licenses": {
"relatedPackages": "Gerelateerde pakketten",
@@ -401,7 +439,7 @@
"licensesCount": "${count} licenties"
},
"navigation": {
"home": "Home",
"home": "Thuis",
"search": "Zoeken",
"libraries": "Bibliotheken",
"settings": "Instellingen"
@@ -420,7 +458,7 @@
"removeItem": "Verwijderen uit afspeellijst",
"clearPlaylist": "Afspeellijst wissen",
"playAll": "Alles afspelen",
"shuffle": "Shuffle",
"shuffle": "Willekeurig",
"smartPlaylist": "Slimme afspeellijst",
"regularPlaylist": "Normale afspeellijst",
"itemCount": "${count} items",
+39 -1
View File
@@ -184,6 +184,16 @@
"shufflePlay": "Blanda uppspelning",
"fileInfo": "Filinformation"
},
"accessibility": {
"mediaCardMovie": "${title}, film",
"mediaCardShow": "${title}, TV-serie",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "sedd",
"mediaCardPartiallyWatched": "${percent} procent sedd",
"mediaCardUnwatched": "osedd",
"tapToPlay": "Tryck för att spela"
},
"tooltips": {
"shufflePlay": "Blanda uppspelning",
"markAsWatched": "Markera som sedd",
@@ -206,7 +216,30 @@
"sleepTimer": "Sovtimer",
"timerActive": "Timer aktiv",
"playbackWillPauseIn": "Uppspelningen pausas om ${duration}",
"sleepTimerCompleted": "Sovtimer slutförd - uppspelning pausad"
"sleepTimerCompleted": "Sovtimer slutförd - uppspelning pausad",
"playButton": "Spela",
"pauseButton": "Pausa",
"seekBackwardButton": "Spola bakåt ${seconds} sekunder",
"seekForwardButton": "Spola framåt ${seconds} sekunder",
"previousButton": "Föregående avsnitt",
"nextButton": "Nästa avsnitt",
"previousChapterButton": "Föregående kapitel",
"nextChapterButton": "Nästa kapitel",
"volumeButton": "Volym",
"muteButton": "Tysta",
"unmuteButton": "Slå på ljud",
"settingsButton": "Videoinställningar",
"audioTrackButton": "Ljudspår",
"subtitlesButton": "Undertexter",
"chaptersButton": "Kapitel",
"versionsButton": "Videoversioner",
"aspectRatioButton": "Bildförhållande",
"fullscreenButton": "Aktivera helskärm",
"exitFullscreenButton": "Avsluta helskärm",
"rotationLockButton": "Rotationslås",
"timelineSlider": "Videotidslinje",
"volumeSlider": "Volymnivå",
"backButton": "Tillbaka"
},
"userStatus": {
"admin": "Admin",
@@ -366,6 +399,11 @@
},
"serverSelection": {
"connectingToServer": "Ansluter till server...",
"connectingToAllServers": "Ansluter till alla servrar...",
"connectToAllServers": "Anslut till alla servrar",
"allServerConnectionsFailed": "Misslyckades att ansluta till servrar. Kontrollera ditt nätverk och försök igen.",
"foundServers": "Hittade ${count} server(ar)",
"orSelectIndividually": "Eller välj en server individuellt:",
"serverDebugCopied": "Server-felsökningsdata kopierad till urklipp",
"copyDebugData": "Kopiera felsökningsdata",
"noServersFound": "Inga servrar hittades",
+39 -1
View File
@@ -184,6 +184,16 @@
"shufflePlay": "随机播放",
"fileInfo": "文件信息"
},
"accessibility": {
"mediaCardMovie": "${title}, 电影",
"mediaCardShow": "${title}, 电视剧",
"mediaCardEpisode": "${title}, ${episodeInfo}",
"mediaCardSeason": "${title}, ${seasonInfo}",
"mediaCardWatched": "已观看",
"mediaCardPartiallyWatched": "已观看 ${percent} 百分比",
"mediaCardUnwatched": "未观看",
"tapToPlay": "点击播放"
},
"tooltips": {
"shufflePlay": "随机播放",
"markAsWatched": "标记为已观看",
@@ -206,7 +216,30 @@
"sleepTimer": "睡眠定时器",
"timerActive": "定时器已激活",
"playbackWillPauseIn": "播放将在 ${duration} 后暂停",
"sleepTimerCompleted": "睡眠定时器已完成 - 播放已暂停"
"sleepTimerCompleted": "睡眠定时器已完成 - 播放已暂停",
"playButton": "播放",
"pauseButton": "暂停",
"seekBackwardButton": "后退 ${seconds} 秒",
"seekForwardButton": "前进 ${seconds} 秒",
"previousButton": "上一集",
"nextButton": "下一集",
"previousChapterButton": "上一章节",
"nextChapterButton": "下一章节",
"volumeButton": "音量",
"muteButton": "静音",
"unmuteButton": "取消静音",
"settingsButton": "视频设置",
"audioTrackButton": "音轨",
"subtitlesButton": "字幕",
"chaptersButton": "章节",
"versionsButton": "视频版本",
"aspectRatioButton": "宽高比",
"fullscreenButton": "进入全屏",
"exitFullscreenButton": "退出全屏",
"rotationLockButton": "旋转锁定",
"timelineSlider": "视频时间轴",
"volumeSlider": "音量调节",
"backButton": "返回"
},
"userStatus": {
"admin": "管理员",
@@ -366,6 +399,11 @@
},
"serverSelection": {
"connectingToServer": "正在连接服务器...",
"connectingToAllServers": "正在连接所有服务器...",
"connectToAllServers": "连接所有服务器",
"allServerConnectionsFailed": "无法连接到任何服务器。请检查你的网络并重试。",
"foundServers": "找到 ${count} 个服务器",
"orSelectIndividually": "或单独选择一个服务器:",
"serverDebugCopied": "服务器调试数据已复制到剪贴板",
"copyDebugData": "复制调试数据",
"noServersFound": "未找到服务器",
+104 -75
View File
@@ -7,21 +7,23 @@ 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 'services/update_service.dart';
import 'services/settings_service.dart';
import 'providers/user_profile_provider.dart';
import 'providers/plex_client_provider.dart';
import 'providers/multi_server_provider.dart';
import 'providers/server_state_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 'services/multi_server_manager.dart';
import 'services/data_aggregation_service.dart';
import 'services/server_registry.dart';
import 'utils/language_codes.dart';
import 'utils/app_logger.dart';
import 'utils/provider_extensions.dart';
import 'utils/orientation_helper.dart';
import 'i18n/strings.g.dart';
@@ -77,9 +79,21 @@ class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Initialize multi-server infrastructure
final serverManager = MultiServerManager();
final aggregationService = DataAggregationService(serverManager);
return MultiProvider(
providers: [
// Legacy provider for backward compatibility
ChangeNotifierProvider(create: (context) => PlexClientProvider()),
// New multi-server providers
ChangeNotifierProvider(
create: (context) =>
MultiServerProvider(serverManager, aggregationService),
),
ChangeNotifierProvider(create: (context) => ServerStateProvider()),
// Existing providers
ChangeNotifierProvider(
create: (context) => UserProfileProvider()..initialize(),
),
@@ -219,86 +233,101 @@ class _SetupScreenState extends State<SetupScreen> {
Future<void> _loadSavedCredentials() async {
final storage = await StorageService.getInstance();
final registry = ServerRegistry(storage);
// Check if we have server data
final serverData = storage.getServerData();
final clientId = storage.getClientIdentifier();
final plexToken = storage.getPlexToken();
// Migrate from single-server to multi-server if needed
await registry.migrateFromSingleServer();
// Get current user's server token (prioritize over original server token)
final currentUserToken = storage.getToken();
// Load enabled servers
final servers = await registry.getEnabledServers();
if (serverData != null && clientId != null) {
try {
// Recreate PlexServer from stored data
final server = PlexServer.fromJson(serverData);
// Use current user's token if available, fallback to server's original token
final tokenToUse = currentUserToken ?? server.accessToken;
appLogger.d(
'App startup token selection: currentUserToken=${currentUserToken != null ? 'present' : 'null'}, using=${currentUserToken != null ? 'current user' : 'original server'} token',
if (servers.isEmpty) {
// No servers configured - show auth screen
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const AuthScreen()),
);
// 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,
);
// 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,
);
// Handle result
if (result.isSuccess) {
// Success! Set client in provider
if (mounted) {
context.plexClient.setClient(result.client!);
// 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: result.client!),
),
);
}
}
return;
} else {
// 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();
}
return;
}
// No saved credentials or auto-login failed - show auth screen
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const AuthScreen()),
// Get multi-server provider
if (!mounted) return;
final multiServerProvider = Provider.of<MultiServerProvider>(
context,
listen: false,
);
try {
appLogger.i('Connecting to ${servers.length} enabled servers...');
// Get or generate client identifier
final clientId = storage.getClientIdentifier();
// Connect to all servers in parallel
final connectedCount = await multiServerProvider.serverManager
.connectToAllServers(
servers,
clientIdentifier: clientId,
timeout: const Duration(seconds: 10),
onServerConnected: (serverId, client) {
// Set first connected client in legacy provider for backward compatibility
final legacyProvider = Provider.of<PlexClientProvider>(
context,
listen: false,
);
if (legacyProvider.client == null) {
legacyProvider.setClient(client);
}
},
);
if (connectedCount > 0) {
// At least one server connected successfully
appLogger.i('Successfully connected to $connectedCount servers');
if (mounted) {
// Check for updates BEFORE navigation
_checkForUpdatesOnStartup();
// Navigate to main screen
// Get first connected client for backward compatibility
final firstClient =
multiServerProvider.serverManager.onlineClients.values.first;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: firstClient),
),
);
}
} else {
// All connections failed
appLogger.w('Failed to connect to any servers');
if (mounted) {
// Show auth screen to re-authenticate
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const AuthScreen()),
);
}
}
} catch (e, stackTrace) {
appLogger.e(
'Error during multi-server connection',
error: e,
stackTrace: stackTrace,
);
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => const AuthScreen()),
);
}
}
}
+7 -55
View File
@@ -1,63 +1,15 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_library.dart';
import '../models/plex_metadata.dart';
import '../utils/provider_extensions.dart';
/// Mixin providing common state management for library tab screens
/// Standardizes loading, error handling, and lifecycle management
/// Mixin providing common functionality for library tab screens
/// Provides server-specific client resolution for multi-server support
mixin LibraryTabStateMixin<T extends StatefulWidget> on State<T> {
/// The list of items to display
List<PlexMetadata> get items;
set items(List<PlexMetadata> value);
/// Whether data is currently loading
bool get isLoading;
set isLoading(bool value);
/// Error message if loading failed
String? get errorMessage;
set errorMessage(String? value);
/// The library being displayed
PlexLibrary get library;
/// Load or reload the content
Future<void> loadContent();
/// Common lifecycle: reload if library changed
@mustCallSuper
void didUpdateLibrary(PlexLibrary oldLibrary) {
if (oldLibrary.key != library.key) {
loadContent();
}
}
/// Helper to set loading state
void setLoadingState(bool loading) {
if (mounted) {
setState(() {
isLoading = loading;
});
}
}
/// Helper to set error state
void setErrorState(String? error) {
if (mounted) {
setState(() {
errorMessage = error;
isLoading = false;
});
}
}
/// Helper to set success state with items
void setSuccessState(List<PlexMetadata> newItems) {
if (mounted) {
setState(() {
items = newItems;
isLoading = false;
errorMessage = null;
});
}
}
/// Get the correct PlexClient for this library's server
/// Throws an exception if no client is available
PlexClient getClientForLibrary() => context.getClientForLibrary(library);
}
-31
View File
@@ -1,31 +0,0 @@
import 'package:json_annotation/json_annotation.dart';
import 'plex_metadata.dart';
import 'plex_library.dart';
part 'media_container.g.dart';
@JsonSerializable()
class MediaContainer<T> {
final int? size;
final int? totalSize;
final int? offset;
final String? identifier;
@JsonKey(name: 'Directory')
final List<PlexLibrary>? directories;
@JsonKey(name: 'Metadata')
final List<PlexMetadata>? metadata;
MediaContainer({
this.size,
this.totalSize,
this.offset,
this.identifier,
this.directories,
this.metadata,
});
factory MediaContainer.fromJson(Map<String, dynamic> json) =>
_$MediaContainerFromJson(json);
Map<String, dynamic> toJson() => _$MediaContainerToJson(this);
}
-31
View File
@@ -1,31 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'media_container.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
MediaContainer<T> _$MediaContainerFromJson<T>(Map<String, dynamic> json) =>
MediaContainer<T>(
size: (json['size'] as num?)?.toInt(),
totalSize: (json['totalSize'] as num?)?.toInt(),
offset: (json['offset'] as num?)?.toInt(),
identifier: json['identifier'] as String?,
directories: (json['Directory'] as List<dynamic>?)
?.map((e) => PlexLibrary.fromJson(e as Map<String, dynamic>))
.toList(),
metadata: (json['Metadata'] as List<dynamic>?)
?.map((e) => PlexMetadata.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> _$MediaContainerToJson<T>(MediaContainer<T> instance) =>
<String, dynamic>{
'size': instance.size,
'totalSize': instance.totalSize,
'offset': instance.offset,
'identifier': instance.identifier,
'Directory': instance.directories,
'Metadata': instance.metadata,
};
@@ -0,0 +1,15 @@
import 'package:json_annotation/json_annotation.dart';
/// Mixin that provides multi-server support fields for models.
///
/// This mixin adds serverId and serverName fields that are excluded from
/// JSON serialization but can be used to track which server an item belongs to.
mixin MultiServerFields {
/// Server machine identifier (not from API)
@JsonKey(includeFromJson: false, includeToJson: false)
String? get serverId;
/// Server display name (not from API)
@JsonKey(includeFromJson: false, includeToJson: false)
String? get serverName;
}
+30 -2
View File
@@ -49,10 +49,38 @@ class PlayQueueResponse {
this.items,
});
factory PlayQueueResponse.fromJson(Map<String, dynamic> json) {
factory PlayQueueResponse.fromJson(
Map<String, dynamic> json, {
String? serverId,
String? serverName,
}) {
// The API returns data wrapped in MediaContainer
final container = json['MediaContainer'] as Map<String, dynamic>? ?? json;
return _$PlayQueueResponseFromJson(container);
final response = _$PlayQueueResponseFromJson(container);
// Tag all items with server info
if (response.items != null && (serverId != null || serverName != null)) {
final taggedItems = response.items!
.map(
(item) => item.copyWith(serverId: serverId, serverName: serverName),
)
.toList();
return PlayQueueResponse(
playQueueID: response.playQueueID,
playQueueSelectedItemID: response.playQueueSelectedItemID,
playQueueSelectedItemOffset: response.playQueueSelectedItemOffset,
playQueueSelectedMetadataItemID:
response.playQueueSelectedMetadataItemID,
playQueueShuffled: response.playQueueShuffled,
playQueueSourceURI: response.playQueueSourceURI,
playQueueTotalCount: response.playQueueTotalCount,
playQueueVersion: response.playQueueVersion,
size: response.size,
items: taggedItems,
);
}
return response;
}
/// Get the current selected item from the queue
+6
View File
@@ -10,6 +10,10 @@ class PlexHub {
final bool more;
final List<PlexMetadata> items;
// Multi-server support fields
final String? serverId; // Server machine identifier
final String? serverName; // Server display name
PlexHub({
required this.hubKey,
required this.title,
@@ -18,6 +22,8 @@ class PlexHub {
required this.size,
required this.more,
required this.items,
this.serverId,
this.serverName,
});
factory PlexHub.fromJson(Map<String, dynamic> json) {
+16 -1
View File
@@ -1,9 +1,11 @@
import 'package:json_annotation/json_annotation.dart';
import 'mixins/multi_server_fields.dart';
part 'plex_library.g.dart';
@JsonSerializable()
class PlexLibrary {
class PlexLibrary with MultiServerFields {
final String key;
final String title;
final String type;
@@ -15,6 +17,17 @@ class PlexLibrary {
final int? createdAt;
final int? hidden;
// Multi-server support fields (from MultiServerFields mixin)
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverId;
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverName;
/// Global unique identifier across all servers (serverId:key)
String get globalKey => serverId != null ? '$serverId:$key' : key;
PlexLibrary({
required this.key,
required this.title,
@@ -26,6 +39,8 @@ class PlexLibrary {
this.updatedAt,
this.createdAt,
this.hidden,
this.serverId,
this.serverName,
});
factory PlexLibrary.fromJson(Map<String, dynamic> json) =>
+23 -1
View File
@@ -1,11 +1,12 @@
import 'package:json_annotation/json_annotation.dart';
import 'mixins/multi_server_fields.dart';
import 'plex_role.dart';
part 'plex_metadata.g.dart';
@JsonSerializable()
class PlexMetadata {
class PlexMetadata with MultiServerFields {
final String ratingKey;
final String key;
final String? guid;
@@ -22,6 +23,7 @@ class PlexMetadata {
final int? duration;
final int? addedAt;
final int? updatedAt;
final int? lastViewedAt; // Timestamp when item was last viewed
final String? grandparentTitle; // Show title for episodes
final String? grandparentThumb; // Show poster for episodes
final String? grandparentArt; // Show art for episodes
@@ -45,10 +47,21 @@ class PlexMetadata {
final int? playQueueItemID; // Play queue item ID (unique even for duplicates)
final int? librarySectionID; // Library section ID this item belongs to
// Multi-server support fields (from MultiServerFields mixin)
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverId;
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverName;
// Transient field for clear logo (extracted from Image array)
String? _clearLogo;
String? get clearLogo => _clearLogo;
/// Global unique identifier across all servers (serverId:ratingKey)
String get globalKey => serverId != null ? '$serverId:$ratingKey' : ratingKey;
PlexMetadata({
required this.ratingKey,
required this.key,
@@ -66,6 +79,7 @@ class PlexMetadata {
this.duration,
this.addedAt,
this.updatedAt,
this.lastViewedAt,
this.grandparentTitle,
this.grandparentThumb,
this.grandparentArt,
@@ -87,6 +101,8 @@ class PlexMetadata {
this.playlistItemID,
this.playQueueItemID,
this.librarySectionID,
this.serverId,
this.serverName,
});
/// Create a copy of this metadata with optional field overrides
@@ -107,6 +123,7 @@ class PlexMetadata {
int? duration,
int? addedAt,
int? updatedAt,
int? lastViewedAt,
String? grandparentTitle,
String? grandparentThumb,
String? grandparentArt,
@@ -128,6 +145,8 @@ class PlexMetadata {
int? playlistItemID,
int? playQueueItemID,
int? librarySectionID,
String? serverId,
String? serverName,
}) {
final copy = PlexMetadata(
ratingKey: ratingKey ?? this.ratingKey,
@@ -146,6 +165,7 @@ class PlexMetadata {
duration: duration ?? this.duration,
addedAt: addedAt ?? this.addedAt,
updatedAt: updatedAt ?? this.updatedAt,
lastViewedAt: lastViewedAt ?? this.lastViewedAt,
grandparentTitle: grandparentTitle ?? this.grandparentTitle,
grandparentThumb: grandparentThumb ?? this.grandparentThumb,
grandparentArt: grandparentArt ?? this.grandparentArt,
@@ -167,6 +187,8 @@ class PlexMetadata {
playlistItemID: playlistItemID ?? this.playlistItemID,
playQueueItemID: playQueueItemID ?? this.playQueueItemID,
librarySectionID: librarySectionID ?? this.librarySectionID,
serverId: serverId ?? this.serverId,
serverName: serverName ?? this.serverName,
);
// Preserve clearLogo
copy._clearLogo = _clearLogo;
+2
View File
@@ -23,6 +23,7 @@ PlexMetadata _$PlexMetadataFromJson(Map<String, dynamic> json) => PlexMetadata(
duration: (json['duration'] as num?)?.toInt(),
addedAt: (json['addedAt'] as num?)?.toInt(),
updatedAt: (json['updatedAt'] as num?)?.toInt(),
lastViewedAt: (json['lastViewedAt'] as num?)?.toInt(),
grandparentTitle: json['grandparentTitle'] as String?,
grandparentThumb: json['grandparentThumb'] as String?,
grandparentArt: json['grandparentArt'] as String?,
@@ -66,6 +67,7 @@ Map<String, dynamic> _$PlexMetadataToJson(PlexMetadata instance) =>
'duration': instance.duration,
'addedAt': instance.addedAt,
'updatedAt': instance.updatedAt,
'lastViewedAt': instance.lastViewedAt,
'grandparentTitle': instance.grandparentTitle,
'grandparentThumb': instance.grandparentThumb,
'grandparentArt': instance.grandparentArt,
+92 -1
View File
@@ -1,9 +1,11 @@
import 'package:json_annotation/json_annotation.dart';
import 'mixins/multi_server_fields.dart';
part 'plex_playlist.g.dart';
@JsonSerializable()
class PlexPlaylist {
class PlexPlaylist with MultiServerFields {
final String ratingKey;
final String key;
final String type; // "playlist"
@@ -22,6 +24,14 @@ class PlexPlaylist {
final String? guid;
final String? thumb;
// Multi-server support fields (from MultiServerFields mixin)
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverId;
@override
@JsonKey(includeFromJson: false, includeToJson: false)
final String? serverName;
PlexPlaylist({
required this.ratingKey,
required this.key,
@@ -40,16 +50,97 @@ class PlexPlaylist {
this.content,
this.guid,
this.thumb,
this.serverId,
this.serverName,
});
/// Helper to get display image (composite or thumb)
String? get displayImage => composite ?? thumb;
/// Helper to get display title (consistent with PlexMetadata)
String get displayTitle => title;
/// Helper to determine if playlist is editable
bool get isEditable => !smart;
/// Get globally unique key across all servers
String get globalKey => serverId != null ? '$serverId:$ratingKey' : ratingKey;
// Properties for MediaCard compatibility with PlexMetadata interface
/// Playlists are not "watched" in the traditional sense
bool get isWatched => false;
/// Playlists don't have resume positions
int? get viewOffset => null;
/// Playlists don't have parent/episode indices
int? get parentIndex => null;
int? get index => null;
/// Playlists don't have parent titles or subtitles
String? get parentTitle => null;
String? get displaySubtitle => null;
/// Playlists don't have year, rating, or content metadata
int? get year => null;
String? get contentRating => null;
double? get rating => null;
String? get studio => null;
/// Use leafCount as the equivalent of childCount
int? get childCount => leafCount;
/// Playlists don't track viewed leaf count
int? get viewedLeafCount => null;
factory PlexPlaylist.fromJson(Map<String, dynamic> json) =>
_$PlexPlaylistFromJson(json);
Map<String, dynamic> toJson() => _$PlexPlaylistToJson(this);
/// Create a copy with optional field updates
PlexPlaylist copyWith({
String? ratingKey,
String? key,
String? type,
String? title,
String? summary,
bool? smart,
String? playlistType,
int? duration,
int? leafCount,
String? composite,
int? addedAt,
int? updatedAt,
int? lastViewedAt,
int? viewCount,
String? content,
String? guid,
String? thumb,
String? serverId,
String? serverName,
}) {
return PlexPlaylist(
ratingKey: ratingKey ?? this.ratingKey,
key: key ?? this.key,
type: type ?? this.type,
title: title ?? this.title,
summary: summary ?? this.summary,
smart: smart ?? this.smart,
playlistType: playlistType ?? this.playlistType,
duration: duration ?? this.duration,
leafCount: leafCount ?? this.leafCount,
composite: composite ?? this.composite,
addedAt: addedAt ?? this.addedAt,
updatedAt: updatedAt ?? this.updatedAt,
lastViewedAt: lastViewedAt ?? this.lastViewedAt,
viewCount: viewCount ?? this.viewCount,
content: content ?? this.content,
guid: guid ?? this.guid,
thumb: thumb ?? this.thumb,
serverId: serverId ?? this.serverId,
serverName: serverName ?? this.serverName,
);
}
}
-29
View File
@@ -1,29 +0,0 @@
import 'package:json_annotation/json_annotation.dart';
part 'plex_server_info.g.dart';
@JsonSerializable()
class PlexServerInfo {
final String name;
final String? host;
final int? port;
final String? machineIdentifier;
final String version;
final bool? owned;
final bool? https;
PlexServerInfo({
required this.name,
this.host,
this.port,
this.machineIdentifier,
required this.version,
this.owned,
this.https,
});
factory PlexServerInfo.fromJson(Map<String, dynamic> json) =>
_$PlexServerInfoFromJson(json);
Map<String, dynamic> toJson() => _$PlexServerInfoToJson(this);
}
-29
View File
@@ -1,29 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'plex_server_info.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
PlexServerInfo _$PlexServerInfoFromJson(Map<String, dynamic> json) =>
PlexServerInfo(
name: json['name'] as String,
host: json['host'] as String?,
port: (json['port'] as num?)?.toInt(),
machineIdentifier: json['machineIdentifier'] as String?,
version: json['version'] as String,
owned: json['owned'] as bool?,
https: json['https'] as bool?,
);
Map<String, dynamic> _$PlexServerInfoToJson(PlexServerInfo instance) =>
<String, dynamic>{
'name': instance.name,
'host': instance.host,
'port': instance.port,
'machineIdentifier': instance.machineIdentifier,
'version': instance.version,
'owned': instance.owned,
'https': instance.https,
};
+84
View File
@@ -0,0 +1,84 @@
import 'package:flutter/foundation.dart';
import '../client/plex_client.dart';
import '../services/data_aggregation_service.dart';
import '../services/multi_server_manager.dart';
import '../utils/app_logger.dart';
/// Provider for multi-server Plex connections
/// Manages multiple PlexClient instances and provides data aggregation
class MultiServerProvider extends ChangeNotifier {
final MultiServerManager _serverManager;
final DataAggregationService _aggregationService;
MultiServerProvider(this._serverManager, this._aggregationService) {
// Listen to server status changes
_serverManager.statusStream.listen((_) {
notifyListeners();
});
}
/// Get the multi-server manager
MultiServerManager get serverManager => _serverManager;
/// Get the data aggregation service
DataAggregationService get aggregationService => _aggregationService;
/// Get client for specific server
PlexClient? getClientForServer(String serverId) {
return _serverManager.getClient(serverId);
}
/// Get all online server IDs
List<String> get onlineServerIds => _serverManager.onlineServerIds;
/// Get all server IDs
List<String> get serverIds => _serverManager.serverIds;
/// Check if a server is online
bool isServerOnline(String serverId) {
return _serverManager.isServerOnline(serverId);
}
/// Get number of online servers
int get onlineServerCount => _serverManager.onlineServerIds.length;
/// Get number of total servers
int get totalServerCount => _serverManager.serverIds.length;
/// Check if any servers are connected
bool get hasConnectedServers => onlineServerCount > 0;
/// Update token for a specific server
void updateTokenForServer(String serverId, String newToken) {
final client = _serverManager.getClient(serverId);
if (client != null) {
client.updateToken(newToken);
appLogger.d('MultiServerProvider: Token updated for server $serverId');
notifyListeners();
} else {
appLogger.w(
'MultiServerProvider: Cannot update token - server $serverId not found',
);
}
}
/// Clear all server connections
void clearAllConnections() {
_serverManager.disconnectAll();
appLogger.d('MultiServerProvider: All connections cleared');
notifyListeners();
}
/// Check server health for all connected servers
Future<void> checkServerHealth() async {
await _serverManager.checkServerHealth();
// notifyListeners() will be called automatically via status stream
}
@override
void dispose() {
_serverManager.dispose();
super.dispose();
}
}
+37 -34
View File
@@ -4,10 +4,10 @@ import '../models/play_queue_response.dart';
import '../client/plex_client.dart';
/// Playback mode types
///
/// All playback now uses Plex play queues.
enum PlaybackMode {
none, // No active playback queue
sequential, // Normal episode-to-episode playback (uses Plex API)
playQueue, // Play queue-based playback (playlists, collections, shuffle)
playQueue, // Play queue-based playback (sequential, shuffle, playlists, collections)
}
/// Result of trying to locate the current queue index.
@@ -38,13 +38,13 @@ class PlaybackStateProvider with ChangeNotifier {
// Legacy state for backward compatibility
String? _contextKey; // The show/season/playlist ratingKey for this session
PlaybackMode _playbackMode = PlaybackMode.none;
PlaybackMode? _playbackMode;
// Client reference for loading more items
PlexClient? _client;
/// Current playback mode
PlaybackMode get playbackMode => _playbackMode;
/// Current playback mode (null if no queue active)
PlaybackMode? get playbackMode => _playbackMode;
/// Whether shuffle mode is currently active
bool get isShuffleActive => _playQueueShuffled;
@@ -92,8 +92,10 @@ class PlaybackStateProvider with ChangeNotifier {
/// Call this after creating a play queue via the API
Future<void> setPlaybackFromPlayQueue(
PlayQueueResponse playQueue,
String? contextKey,
) async {
String? contextKey, {
String? serverId,
String? serverName,
}) async {
_playQueueId = playQueue.playQueueID;
// Use size or items length as fallback if totalCount is null
_playQueueTotalCount =
@@ -102,31 +104,12 @@ class PlaybackStateProvider with ChangeNotifier {
(playQueue.items?.length ?? 0);
_playQueueShuffled = playQueue.playQueueShuffled;
_currentPlayQueueItemID = playQueue.playQueueSelectedItemID;
_loadedItems = playQueue.items ?? [];
_contextKey = contextKey;
_playbackMode = PlaybackMode.playQueue;
notifyListeners();
}
/// Legacy method for backward compatibility with shuffle play
/// This now creates a play queue on the server
@Deprecated('Use createPlayQueueFromUri instead')
void setShuffleQueue(List<PlexMetadata> episodes, String contextKey) {
// This is kept for backward compatibility but should not be used
// New code should use the play queue API
_loadedItems = List.from(episodes);
_contextKey = contextKey;
_playbackMode = PlaybackMode.playQueue;
notifyListeners();
}
// Preserve serverId/serverName on all items
_loadedItems = (playQueue.items ?? []).map((item) {
return item.copyWith(serverId: serverId, serverName: serverName);
}).toList();
/// Legacy method for backward compatibility with playlist playback
/// This now creates a play queue on the server
@Deprecated('Use createPlayQueueFromUri instead')
void setPlaybackQueue(List<PlexMetadata> items, String contextKey) {
// This is kept for backward compatibility but should not be used
// New code should use the play queue API
_loadedItems = List.from(items);
_contextKey = contextKey;
_playbackMode = PlaybackMode.playQueue;
notifyListeners();
@@ -153,7 +136,17 @@ class PlaybackStateProvider with ChangeNotifier {
);
if (response != null && response.items != null) {
_loadedItems = response.items!;
// Preserve serverId from existing items
final serverId = _loadedItems.isNotEmpty
? _loadedItems.first.serverId
: null;
final serverName = _loadedItems.isNotEmpty
? _loadedItems.first.serverName
: null;
_loadedItems = response.items!.map((item) {
return item.copyWith(serverId: serverId, serverName: serverName);
}).toList();
// Use size or items length as fallback if totalCount is null
_playQueueTotalCount =
response.playQueueTotalCount ??
@@ -245,7 +238,17 @@ class PlaybackStateProvider with ChangeNotifier {
if (response != null &&
response.items != null &&
response.items!.isNotEmpty) {
_loadedItems = response.items!;
// Preserve serverId when looping
final serverId = _loadedItems.isNotEmpty
? _loadedItems.first.serverId
: null;
final serverName = _loadedItems.isNotEmpty
? _loadedItems.first.serverName
: null;
_loadedItems = response.items!.map((item) {
return item.copyWith(serverId: serverId, serverName: serverName);
}).toList();
final firstItem = _loadedItems.first;
// Don't update _currentPlayQueueItemID here - let setCurrentItem do it when playback starts
return firstItem;
@@ -318,7 +321,7 @@ class PlaybackStateProvider with ChangeNotifier {
_currentPlayQueueItemID = null;
_loadedItems = [];
_contextKey = null;
_playbackMode = PlaybackMode.none;
_playbackMode = null;
notifyListeners();
}
}
+76
View File
@@ -0,0 +1,76 @@
import 'package:flutter/foundation.dart';
/// Provider for tracking server-specific UI state
/// Manages which server is currently in context for detail views
class ServerStateProvider extends ChangeNotifier {
String? _currentServerId;
final Map<String, bool> _serverConnectionStates = {};
final Map<String, String?> _serverErrors = {};
/// Get the currently selected server ID (for detail views)
String? get currentServerId => _currentServerId;
/// Set the current server context (e.g., when viewing a library from a specific server)
void setCurrentServer(String? serverId) {
if (_currentServerId != serverId) {
_currentServerId = serverId;
notifyListeners();
}
}
/// Clear the current server selection
void clearCurrentServer() {
if (_currentServerId != null) {
_currentServerId = null;
notifyListeners();
}
}
/// Get connection state for a server
bool isServerConnected(String serverId) {
return _serverConnectionStates[serverId] ?? false;
}
/// Update connection state for a server
void updateServerConnectionState(String serverId, bool isConnected) {
if (_serverConnectionStates[serverId] != isConnected) {
_serverConnectionStates[serverId] = isConnected;
notifyListeners();
}
}
/// Get error message for a server (null if no error)
String? getServerError(String serverId) {
return _serverErrors[serverId];
}
/// Set error for a server
void setServerError(String serverId, String? error) {
_serverErrors[serverId] = error;
notifyListeners();
}
/// Clear error for a server
void clearServerError(String serverId) {
if (_serverErrors.containsKey(serverId)) {
_serverErrors.remove(serverId);
notifyListeners();
}
}
/// Clear all server errors
void clearAllServerErrors() {
if (_serverErrors.isNotEmpty) {
_serverErrors.clear();
notifyListeners();
}
}
/// Reset all state
void reset() {
_currentServerId = null;
_serverConnectionStates.clear();
_serverErrors.clear();
notifyListeners();
}
}
-33
View File
@@ -7,9 +7,6 @@ class SettingsProvider extends ChangeNotifier {
ViewMode _viewMode = ViewMode.grid;
bool _useSeasonPoster = false;
bool _showHeroSection = true;
bool _shuffleUnwatchedOnly = true;
bool _shuffleOrderNavigation = true;
bool _shuffleLoopQueue = false;
SettingsProvider() {
_initializeSettings();
@@ -21,9 +18,6 @@ class SettingsProvider extends ChangeNotifier {
_viewMode = _settingsService.getViewMode();
_useSeasonPoster = _settingsService.getUseSeasonPoster();
_showHeroSection = _settingsService.getShowHeroSection();
_shuffleUnwatchedOnly = _settingsService.getShuffleUnwatchedOnly();
_shuffleOrderNavigation = _settingsService.getShuffleOrderNavigation();
_shuffleLoopQueue = _settingsService.getShuffleLoopQueue();
notifyListeners();
}
@@ -31,9 +25,6 @@ class SettingsProvider extends ChangeNotifier {
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) {
@@ -67,30 +58,6 @@ class SettingsProvider extends ChangeNotifier {
}
}
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:
+83 -22
View File
@@ -1,12 +1,17 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.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 '../services/server_registry.dart';
import '../providers/multi_server_provider.dart';
import '../providers/plex_client_provider.dart';
import '../i18n/strings.g.dart';
import 'server_selection_screen.dart';
import '../utils/app_logger.dart';
import 'main_screen.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({super.key});
@@ -33,6 +38,76 @@ class _AuthScreenState extends State<AuthScreen> {
_authService = await PlexAuthService.create();
}
/// Connect to all available servers and navigate to main screen
Future<void> _connectToAllServersAndNavigate(String plexToken) async {
if (!mounted) return;
setState(() {
_isAuthenticating = true;
_errorMessage = null;
});
try {
// Fetch all servers for this user
final servers = await _authService.fetchServers(plexToken);
if (servers.isEmpty) {
setState(() {
_isAuthenticating = false;
_errorMessage = t.serverSelection.noServersFound;
});
return;
}
// Save all servers to registry and enable them
final storage = await StorageService.getInstance();
final registry = ServerRegistry(storage);
await registry.saveServers(servers);
// Enable all servers
final serverIds = servers.map((s) => s.clientIdentifier).toSet();
await registry.saveEnabledServerIds(serverIds);
// Connect to all servers
if (!mounted) return;
final multiServerProvider = context.read<MultiServerProvider>();
final connectedCount = await multiServerProvider.serverManager
.connectToAllServers(servers);
if (connectedCount == 0) {
setState(() {
_isAuthenticating = false;
_errorMessage = t.serverSelection.allServerConnectionsFailed;
});
return;
}
// Get the first connected client for backward compatibility
if (!mounted) return;
final firstClient =
multiServerProvider.serverManager.onlineClients.values.first;
// Set it as the legacy client
final plexClientProvider = context.read<PlexClientProvider>();
plexClientProvider.setClient(firstClient);
// Navigate to main screen
if (!mounted) return;
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: firstClient),
),
);
} catch (e) {
appLogger.e('Failed to connect to servers', error: e);
setState(() {
_isAuthenticating = false;
_errorMessage = t.serverSelection.failedToLoadServers(error: e);
});
}
}
Future<void> _startAuthentication() async {
setState(() {
_isAuthenticating = true;
@@ -100,23 +175,16 @@ class _AuthScreenState extends State<AuthScreen> {
final storage = await StorageService.getInstance();
await storage.savePlexToken(token);
// Navigate to server selection
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => ServerSelectionScreen(
authService: _authService,
plexToken: token,
),
),
);
}
// Clear QR URL after successful auth
setState(() {
_qrAuthUrl = null;
_useQrFlow = false;
});
// Connect to all servers and navigate to main screen
if (mounted) {
await _connectToAllServersAndNavigate(token);
}
} catch (e) {
setState(() {
_isAuthenticating = false;
@@ -197,17 +265,10 @@ class _AuthScreenState extends State<AuthScreen> {
final storage = await StorageService.getInstance();
await storage.savePlexToken(token);
// Close dialog and navigate
// Close dialog and connect to all servers
if (mounted) {
navigator.pop();
navigator.pushReplacement(
MaterialPageRoute(
builder: (context) => ServerSelectionScreen(
authService: _authService,
plexToken: token,
),
),
);
await _connectToAllServersAndNavigate(token);
}
} catch (e) {
setDialogState(() {
+183 -4
View File
@@ -3,8 +3,10 @@ import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../utils/provider_extensions.dart';
import '../utils/collection_playlist_play_helper.dart';
import '../utils/app_logger.dart';
import '../mixins/refreshable.dart';
import '../mixins/item_updatable.dart';
import '../i18n/strings.g.dart';
/// Abstract base class for screens displaying media lists (collections/playlists)
/// Provides common state management and playback functionality
@@ -17,7 +19,7 @@ abstract class BaseMediaListDetailScreen<T extends StatefulWidget>
String? errorMessage;
@override
PlexClient get client => context.clientSafe;
PlexClient get client => _getClientForMediaItem();
/// The media item being displayed (collection or playlist)
dynamic get mediaItem;
@@ -28,6 +30,30 @@ abstract class BaseMediaListDetailScreen<T extends StatefulWidget>
/// Message to show when list is empty
String get emptyMessage;
/// Optional icon to show when list is empty
IconData? get emptyIcon => null;
/// Get the correct PlexClient for this media item's server
PlexClient _getClientForMediaItem() {
// Try to get serverId from the media item
String? serverId;
// Check if mediaItem has serverId property
if (mediaItem is PlexMetadata) {
serverId = (mediaItem as PlexMetadata).serverId;
} else if (mediaItem != null) {
// For playlists or other types, use dynamic access
try {
final dynamic item = mediaItem;
serverId = item.serverId as String?;
} catch (_) {
// Ignore if serverId is not available
}
}
return context.getClientForServer(serverId);
}
@override
void initState() {
super.initState();
@@ -54,9 +80,7 @@ abstract class BaseMediaListDetailScreen<T extends StatefulWidget>
return;
}
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final client = _getClientForMediaItem();
await playCollectionOrPlaylist(
context: context,
@@ -82,4 +106,159 @@ abstract class BaseMediaListDetailScreen<T extends StatefulWidget>
void refresh() {
loadItems();
}
/// Build common error/loading/empty state slivers
/// Returns a list of slivers to display based on current state
List<Widget> buildStateSlivers() {
if (errorMessage != null) {
return [
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: loadItems,
child: Text(t.common.retry),
),
],
),
),
),
];
}
if (items.isEmpty && isLoading) {
return [
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
),
];
}
if (items.isEmpty) {
final icon = emptyIcon;
return [
SliverFillRemaining(
child: Center(
child: icon != null
? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(
emptyMessage,
style: const TextStyle(
fontSize: 16,
color: Colors.grey,
),
),
],
)
: Text(emptyMessage),
),
),
];
}
return [];
}
/// Build standard app bar actions (play, shuffle, delete)
/// Subclasses can override to customize actions
List<Widget> buildAppBarActions({
VoidCallback? onDelete,
String? deleteTooltip,
Color? deleteColor,
bool showDelete = true,
}) {
return [
// Play button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.play_arrow),
tooltip: t.discover.play,
onPressed: playItems,
),
// Shuffle button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.shuffle),
tooltip: t.common.shuffle,
onPressed: shufflePlayItems,
),
// Delete button
if (showDelete && onDelete != null)
IconButton(
icon: const Icon(Icons.delete),
tooltip: deleteTooltip ?? t.common.delete,
onPressed: onDelete,
color: deleteColor ?? Colors.red,
),
];
}
}
/// Mixin that provides standard loadItems implementation for media lists
/// Handles the common pattern of fetching, tagging, and setting items
mixin StandardItemLoader<T extends StatefulWidget>
on BaseMediaListDetailScreen<T> {
/// Fetch items from the API (must be implemented by subclass)
Future<List<PlexMetadata>> fetchItems();
/// Get error message for failed load (can be overridden)
String getLoadErrorMessage(Object error) {
return 'Failed to load items: ${error.toString()}';
}
/// Get log message for successful load (can be overridden)
String getLoadSuccessMessage(int itemCount) {
return 'Loaded $itemCount items';
}
@override
Future<void> loadItems() async {
if (mounted) {
setState(() {
isLoading = true;
errorMessage = null;
});
}
try {
final newItems = await fetchItems();
// Tag items with server info for correct client resolution
final serverId = (mediaItem as dynamic).serverId as String?;
final serverName = (mediaItem as dynamic).serverName as String?;
final taggedItems = newItems
.map(
(item) => item.copyWith(serverId: serverId, serverName: serverName),
)
.toList();
if (mounted) {
setState(() {
items = taggedItems;
isLoading = false;
});
}
appLogger.d(getLoadSuccessMessage(newItems.length));
} catch (e) {
appLogger.e('Failed to load items', error: e);
if (mounted) {
setState(() {
errorMessage = getLoadErrorMessage(e);
isLoading = false;
});
}
}
}
}
+16 -92
View File
@@ -2,13 +2,12 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/settings_provider.dart';
import '../utils/app_logger.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../i18n/strings.g.dart';
import '../utils/grid_size_calculator.dart';
import '../utils/dialogs.dart';
import '../utils/provider_extensions.dart';
import '../utils/app_logger.dart';
import 'base_media_list_detail_screen.dart';
/// Screen to display the contents of a collection
@@ -22,7 +21,8 @@ class CollectionDetailScreen extends StatefulWidget {
}
class _CollectionDetailScreenState
extends BaseMediaListDetailScreen<CollectionDetailScreen> {
extends BaseMediaListDetailScreen<CollectionDetailScreen>
with StandardItemLoader<CollectionDetailScreen> {
@override
PlexMetadata get mediaItem => widget.collection;
@@ -33,39 +33,18 @@ class _CollectionDetailScreenState
String get emptyMessage => t.collections.empty;
@override
Future<void> loadItems() async {
if (mounted) {
setState(() {
isLoading = true;
errorMessage = null;
});
}
Future<List<PlexMetadata>> fetchItems() async {
return await client.getCollectionItems(widget.collection.ratingKey);
}
try {
final client = this.client;
final newItems = await client.getCollectionItems(
widget.collection.ratingKey,
);
@override
String getLoadErrorMessage(Object error) {
return t.collections.failedToLoadItems(error: error.toString());
}
if (mounted) {
setState(() {
items = newItems;
isLoading = false;
});
}
appLogger.d(
'Loaded ${newItems.length} items for collection: ${widget.collection.title}',
);
} catch (e) {
appLogger.e('Failed to load collection items', error: e);
if (mounted) {
setState(() {
errorMessage = t.collections.failedToLoadItems(error: e.toString());
isLoading = false;
});
}
}
@override
String getLoadSuccessMessage(int itemCount) {
return 'Loaded $itemCount items for collection: ${widget.collection.title}';
}
Future<void> _deleteCollection() async {
@@ -97,10 +76,6 @@ class _CollectionDetailScreenState
if (!mounted) return;
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final success = await client.deleteCollection(
sectionId.toString(),
widget.collection.ratingKey,
@@ -145,61 +120,10 @@ class _CollectionDetailScreenState
CustomAppBar(
title: Text(widget.collection.title),
pinned: true,
actions: [
// Play button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.play_arrow),
tooltip: t.discover.play,
onPressed: playItems,
),
// Shuffle button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.shuffle),
tooltip: t.common.shuffle,
onPressed: shufflePlayItems,
),
// Delete button
IconButton(
icon: const Icon(Icons.delete),
tooltip: t.common.delete,
onPressed: _deleteCollection,
color: Colors.red,
),
],
actions: buildAppBarActions(onDelete: _deleteCollection),
),
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: loadItems,
child: Text(t.common.retry),
),
],
),
),
)
else if (items.isEmpty && isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (items.isEmpty)
SliverFillRemaining(
child: Center(child: Text(t.collections.noItems)),
)
else
...buildStateSlivers(),
if (items.isNotEmpty)
SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
sliver: Consumer<SettingsProvider>(
+56 -127
View File
@@ -5,16 +5,13 @@ import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_hub.dart';
import '../providers/plex_client_provider.dart';
import '../services/storage_service.dart';
import '../services/plex_auth_service.dart';
import '../providers/multi_server_provider.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/user_avatar_widget.dart';
import '../widgets/horizontal_scroll_with_arrows.dart';
import '../widgets/hub_section.dart';
import 'profile_switch_screen.dart';
import 'server_selection_screen.dart';
import '../providers/user_profile_provider.dart';
import '../providers/settings_provider.dart';
import '../mixins/refreshable.dart';
@@ -40,7 +37,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
static const Duration _heroAutoScrollDuration = Duration(seconds: 8);
@override
PlexClient get client => context.clientSafe;
PlexClient get client => _getClientForItem(null);
List<PlexMetadata> _onDeck = [];
List<PlexHub> _hubs = [];
@@ -53,6 +50,11 @@ class _DiscoverScreenState extends State<DiscoverScreen>
late AnimationController _indicatorAnimationController;
bool _isAutoScrollPaused = false;
/// Get the correct PlexClient for an item's server
PlexClient _getClientForItem(PlexMetadata? item) {
return context.getClientForServer(item?.serverId);
}
@override
void initState() {
super.initState();
@@ -160,61 +162,51 @@ class _DiscoverScreenState extends State<DiscoverScreen>
}
Future<void> _loadContent() async {
appLogger.d('Loading discover content');
appLogger.d('Loading discover content from all servers');
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
appLogger.d('Fetching onDeck and hubs from Plex');
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
appLogger.d('Fetching onDeck and hubs from all Plex servers');
final multiServerProvider = Provider.of<MultiServerProvider>(
context,
listen: false,
);
if (!multiServerProvider.hasConnectedServers) {
throw Exception('No servers available');
}
final onDeck = await client.getOnDeck();
// Fetch on deck and hubs from all servers in parallel for optimal performance
final results = await Future.wait([
multiServerProvider.aggregationService.getOnDeckFromAllServers(
limit: 20,
),
multiServerProvider.aggregationService.getHubsFromAllServers(),
]);
// Load hubs from all libraries
final libraries = await client.getLibraries();
final allHubs = <PlexHub>[];
final onDeck = results[0] as List<PlexMetadata>;
final allHubs = results[1] as List<PlexHub>;
for (final library in libraries) {
// Skip libraries that are not movie/show or are hidden
if (library.type != 'movie' && library.type != 'show') continue;
if (library.hidden != 0) continue;
try {
final libraryHubs = await client.getLibraryHubs(
library.key,
limit: 12,
);
// Filter out duplicate hubs that we already fetch separately
final filteredHubs = libraryHubs.where((hub) {
final hubId = hub.hubIdentifier?.toLowerCase() ?? '';
final title = hub.title.toLowerCase();
// Skip "Continue Watching" and "On Deck" hubs (we handle these separately)
return !hubId.contains('ondeck') &&
!hubId.contains('continue') &&
!title.contains('continue watching') &&
!title.contains('on deck');
}).toList();
allHubs.addAll(filteredHubs);
} catch (e) {
appLogger.w(
'Failed to load hubs for library ${library.title}',
error: e,
);
}
}
// Filter out duplicate hubs that we already fetch separately
final filteredHubs = allHubs.where((hub) {
final hubId = hub.hubIdentifier?.toLowerCase() ?? '';
final title = hub.title.toLowerCase();
// Skip "Continue Watching" and "On Deck" hubs (we handle these separately)
return !hubId.contains('ondeck') &&
!hubId.contains('continue') &&
!title.contains('continue watching') &&
!title.contains('on deck');
}).toList();
appLogger.d(
'Received ${onDeck.length} on deck items and ${allHubs.length} hubs',
'Received ${onDeck.length} on deck items and ${filteredHubs.length} hubs from all servers',
);
setState(() {
_onDeck = onDeck;
_hubs = allHubs;
_hubs = filteredHubs;
_isLoading = false;
// Reset hero index to avoid sync issues
@@ -239,17 +231,17 @@ class _DiscoverScreenState extends State<DiscoverScreen>
/// Refresh only the Continue Watching section in the background
/// This is called when returning to the home screen to avoid blocking UI
Future<void> _refreshContinueWatching() async {
appLogger.d('Refreshing Continue Watching in background');
appLogger.d('Refreshing Continue Watching in background from all servers');
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
appLogger.w('No client available for background refresh');
final multiServerProvider = context.read<MultiServerProvider>();
if (!multiServerProvider.hasConnectedServers) {
appLogger.w('No servers available for background refresh');
return;
}
final onDeck = await client.getOnDeck();
final onDeck = await multiServerProvider.aggregationService
.getOnDeckFromAllServers(limit: 20);
if (mounted) {
setState(() {
@@ -406,43 +398,6 @@ class _DiscoverScreenState extends State<DiscoverScreen>
}
}
Future<void> _handleSwitchServer() async {
final storage = await StorageService.getInstance();
final plexToken = storage.getPlexToken();
if (plexToken == null) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(t.messages.noPlexToken)));
}
return;
}
try {
final authService = await PlexAuthService.create();
// Navigate to server selection screen
if (mounted) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ServerSelectionScreen(
authService: authService,
plexToken: plexToken,
),
),
);
}
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.messages.errorLoading(error: e.toString()))),
);
}
}
}
Future<void> _handleLogout() async {
final confirm = await showDialog<bool>(
context: context,
@@ -523,8 +478,6 @@ class _DiscoverScreenState extends State<DiscoverScreen>
onSelected: (value) {
if (value == 'switch_profile') {
_handleSwitchProfile(context);
} else if (value == 'switch_server') {
_handleSwitchServer();
} else if (value == 'logout') {
_handleLogout();
}
@@ -542,16 +495,6 @@ class _DiscoverScreenState extends State<DiscoverScreen>
],
),
),
PopupMenuItem(
value: 'switch_server',
child: Row(
children: [
Icon(Icons.swap_horiz),
SizedBox(width: 8),
Text(t.discover.switchServer),
],
),
),
PopupMenuItem(
value: 'logout',
child: Row(
@@ -807,17 +750,17 @@ class _DiscoverScreenState extends State<DiscoverScreen>
? t.discover.movie
: t.discover.tvShow;
// Build semantic label for hero item
final heroLabel = isEpisode
? "${heroItem.grandparentTitle}, ${heroItem.title}"
: heroItem.title;
return Semantics(
label: "media-hero-${heroItem.ratingKey}",
identifier: "media-hero-${heroItem.ratingKey}",
label: heroLabel,
button: true,
hint: "Tap to play ${heroItem.title}",
hint: t.accessibility.tapToPlay,
child: GestureDetector(
onTap: () {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Navigating to VideoPlayerScreen for: ${heroItem.title}');
navigateToVideoPlayer(context, metadata: heroItem);
},
@@ -861,16 +804,9 @@ class _DiscoverScreenState extends State<DiscoverScreen>
child: Opacity(opacity: value, child: child),
);
},
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
);
}
child: Builder(
builder: (context) {
final client = _getClientForItem(heroItem);
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
heroItem.art ?? heroItem.grandparentArt,
@@ -934,12 +870,9 @@ class _DiscoverScreenState extends State<DiscoverScreen>
SizedBox(
height: 120,
width: 400,
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container();
}
child: Builder(
builder: (context) {
final client = _getClientForItem(heroItem);
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
heroItem.clearLogo,
@@ -1139,10 +1072,6 @@ class _DiscoverScreenState extends State<DiscoverScreen>
return InkWell(
onTap: () {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Playing: ${heroItem.title}');
navigateToVideoPlayer(context, metadata: heroItem);
},
+13 -16
View File
@@ -25,7 +25,7 @@ class HubDetailScreen extends StatefulWidget {
}
class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
PlexClient get client => context.clientSafe;
PlexClient get client => _getClientForHub();
List<PlexMetadata> _items = [];
List<PlexMetadata> _filteredItems = [];
@@ -35,6 +35,11 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
bool _isLoading = false;
String? _errorMessage;
/// Get the correct PlexClient for this hub's server
PlexClient _getClientForHub() {
return context.getClientForServer(widget.hub.serverId);
}
@override
void initState() {
super.initState();
@@ -51,9 +56,7 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
Future<void> _loadSorts() async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final client = _getClientForHub();
// Get the library key from the hub key
// Hub keys can have various formats:
@@ -197,27 +200,21 @@ class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final client = _getClientForHub();
// Fetch more items from the hub using the hubKey
final response = await client.getHubContent(widget.hub.hubKey);
// Fetch items from the hub, tagged with server info at the source
final items = await client.getHubContent(widget.hub.hubKey);
setState(() {
_items = response;
_filteredItems = response;
_items = items;
_filteredItems = items;
_isLoading = false;
});
// Apply any existing sort
_applySort();
appLogger.d(
'Loaded ${response.length} items for hub: ${widget.hub.title}',
);
appLogger.d('Loaded ${items.length} items for hub: ${widget.hub.title}');
} catch (e) {
appLogger.e('Failed to load hub content', error: e);
setState(() {
+502 -173
View File
@@ -6,10 +6,12 @@ import '../models/plex_library.dart';
import '../models/plex_metadata.dart';
import '../models/plex_sort.dart';
import '../providers/hidden_libraries_provider.dart';
import '../utils/provider_extensions.dart';
import '../providers/multi_server_provider.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/context_menu_wrapper.dart';
import '../widgets/server_badge.dart';
import '../services/storage_service.dart';
import '../mixins/refreshable.dart';
import '../mixins/item_updatable.dart';
@@ -31,7 +33,7 @@ class LibrariesScreen extends StatefulWidget {
class _LibrariesScreenState extends State<LibrariesScreen>
with Refreshable, ItemUpdatable, SingleTickerProviderStateMixin {
@override
PlexClient get client => context.clientSafe;
PlexClient get client => context.getClientForServer(null);
late TabController _tabController;
@@ -44,8 +46,9 @@ class _LibrariesScreenState extends State<LibrariesScreen>
List<PlexLibrary> _allLibraries = []; // All libraries from API (unfiltered)
bool _isLoadingLibraries = true;
String? _errorMessage;
String? _selectedLibraryKey;
String? _selectedLibraryGlobalKey;
bool _isInitialLoad = true;
List<String>? _serverOrder; // Cached server order from storage
Map<String, String> _selectedFilters = {};
PlexSort? _selectedSort;
@@ -67,9 +70,12 @@ class _LibrariesScreenState extends State<LibrariesScreen>
void _onTabChanged() {
// Save tab index when changed
if (_selectedLibraryKey != null && !_tabController.indexIsChanging) {
if (_selectedLibraryGlobalKey != null && !_tabController.indexIsChanging) {
StorageService.getInstance().then((storage) {
storage.saveLibraryTab(_selectedLibraryKey!, _tabController.index);
storage.saveLibraryTab(
_selectedLibraryGlobalKey!,
_tabController.index,
);
});
}
// Rebuild to update chip selection state
@@ -98,9 +104,52 @@ class _LibrariesScreenState extends State<LibrariesScreen>
return mapUnexpectedErrorToMessage(error, context: context);
}
/// Check if libraries come from multiple servers
bool get _hasMultipleServers {
final uniqueServerIds = _allLibraries
.where((lib) => lib.serverId != null)
.map((lib) => lib.serverId)
.toSet();
return uniqueServerIds.length > 1;
}
/// Get ordered list of server IDs from libraries
List<String> _getOrderedServerIds(List<PlexLibrary> libraries) {
// Get unique server IDs from libraries
final serverIds = libraries
.where((lib) => lib.serverId != null)
.map((lib) => lib.serverId!)
.toSet()
.toList();
if (_serverOrder == null || _serverOrder!.isEmpty) {
return serverIds;
}
// Apply saved order, but include any new servers not in the saved order
final ordered = <String>[];
for (final id in _serverOrder!) {
if (serverIds.contains(id)) {
ordered.add(id);
}
}
// Add any servers not in saved order
for (final id in serverIds) {
if (!ordered.contains(id)) {
ordered.add(id);
}
}
return ordered;
}
Future<void> _loadLibraries() async {
// Extract context dependencies before async gap
final clientProvider = context.plexClient;
final multiServerProvider = Provider.of<MultiServerProvider>(
context,
listen: false,
);
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(
context,
listen: false,
@@ -112,13 +161,16 @@ class _LibrariesScreenState extends State<LibrariesScreen>
});
try {
final client = clientProvider.client;
if (client == null) {
// Check if we have any connected servers
if (!multiServerProvider.hasConnectedServers) {
throw Exception(t.errors.noClientAvailable);
}
final storage = await StorageService.getInstance();
final allLibraries = await client.getLibraries();
// Fetch libraries from all servers
final allLibraries = await multiServerProvider.aggregationService
.getLibrariesFromAllServers();
// Filter out music libraries (type: 'artist') since music playback is not yet supported
// Only show movie and TV show libraries
@@ -133,9 +185,13 @@ class _LibrariesScreenState extends State<LibrariesScreen>
savedOrder,
);
// Load saved server order
final savedServerOrder = storage.getServerOrder();
_updateState(() {
_allLibraries =
orderedLibraries; // Store all libraries with ordering applied
_serverOrder = savedServerOrder;
_isLoadingLibraries = false;
});
@@ -143,37 +199,37 @@ class _LibrariesScreenState extends State<LibrariesScreen>
// Compute visible libraries for initial load
final hiddenKeys = hiddenLibrariesProvider.hiddenLibraryKeys;
final visibleLibraries = allLibraries
.where((lib) => !hiddenKeys.contains(lib.key))
.where((lib) => !hiddenKeys.contains(lib.globalKey))
.toList();
// Load saved preferences
final savedLibraryKey = storage.getSelectedLibraryKey();
// Find the library by key in visible libraries
String? libraryKeyToLoad;
String? libraryGlobalKeyToLoad;
if (savedLibraryKey != null) {
// Check if saved library exists and is visible
final libraryExists = visibleLibraries.any(
(lib) => lib.key == savedLibraryKey,
(lib) => lib.globalKey == savedLibraryKey,
);
if (libraryExists) {
libraryKeyToLoad = savedLibraryKey;
libraryGlobalKeyToLoad = savedLibraryKey;
}
}
// Fallback to first visible library if saved key not found
if (libraryKeyToLoad == null && visibleLibraries.isNotEmpty) {
libraryKeyToLoad = visibleLibraries.first.key;
if (libraryGlobalKeyToLoad == null && visibleLibraries.isNotEmpty) {
libraryGlobalKeyToLoad = visibleLibraries.first.globalKey;
}
if (libraryKeyToLoad != null && mounted) {
if (libraryGlobalKeyToLoad != null && mounted) {
final savedFilters = storage.getLibraryFilters(
sectionId: libraryKeyToLoad,
sectionId: libraryGlobalKeyToLoad,
);
if (savedFilters.isNotEmpty) {
_selectedFilters = Map.from(savedFilters);
}
_loadLibraryContent(libraryKeyToLoad);
_loadLibraryContent(libraryGlobalKeyToLoad);
}
}
} catch (e) {
@@ -193,7 +249,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
}
// Create a map for quick lookup
final libraryMap = {for (var lib in libraries) lib.key: lib};
final libraryMap = {for (var lib in libraries) lib.globalKey: lib};
// Build ordered list based on saved order
final orderedLibraries = <PlexLibrary>[];
@@ -209,7 +265,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
// Add any new libraries that weren't in the saved order
for (final library in libraries) {
if (!addedKeys.contains(library.key)) {
if (!addedKeys.contains(library.globalKey)) {
orderedLibraries.add(library);
}
}
@@ -219,11 +275,11 @@ class _LibrariesScreenState extends State<LibrariesScreen>
Future<void> _saveLibraryOrder() async {
final storage = await StorageService.getInstance();
final libraryKeys = _allLibraries.map((lib) => lib.key).toList();
final libraryKeys = _allLibraries.map((lib) => lib.globalKey).toList();
await storage.saveLibraryOrder(libraryKeys);
}
Future<void> _loadLibraryContent(String libraryKey) async {
Future<void> _loadLibraryContent(String libraryGlobalKey) async {
// Compute visible libraries based on current provider state
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(
context,
@@ -231,30 +287,25 @@ class _LibrariesScreenState extends State<LibrariesScreen>
);
final hiddenKeys = hiddenLibrariesProvider.hiddenLibraryKeys;
final visibleLibraries = _allLibraries
.where((lib) => !hiddenKeys.contains(lib.key))
.where((lib) => !hiddenKeys.contains(lib.globalKey))
.toList();
// Find the library by key
final libraryIndex = visibleLibraries.indexWhere(
(lib) => lib.key == libraryKey,
(lib) => lib.globalKey == libraryGlobalKey,
);
if (libraryIndex == -1) return; // Library not found or hidden
final isChangingLibrary =
!_isInitialLoad && _selectedLibraryKey != libraryKey;
final library = visibleLibraries[libraryIndex];
// Extract context dependencies before async operations
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
_updateState(() {
_errorMessage = t.errors.noClientAvailable;
});
return;
}
final isChangingLibrary =
!_isInitialLoad && _selectedLibraryGlobalKey != libraryGlobalKey;
// Get the correct client for this library's server
final client = context.getClientForLibrary(library);
_updateState(() {
_selectedLibraryKey = libraryKey;
_selectedLibraryGlobalKey = libraryGlobalKey;
_errorMessage = null;
// Only clear filters when explicitly changing library (not on initial load)
if (isChangingLibrary) {
@@ -269,10 +320,10 @@ class _LibrariesScreenState extends State<LibrariesScreen>
// Save selected library key and restore saved tab
final storage = await StorageService.getInstance();
await storage.saveSelectedLibraryKey(libraryKey);
await storage.saveSelectedLibraryKey(libraryGlobalKey);
// Restore saved tab index for this library
final savedTabIndex = storage.getLibraryTab(libraryKey);
final savedTabIndex = storage.getLibraryTab(libraryGlobalKey);
if (savedTabIndex != null && savedTabIndex >= 0 && savedTabIndex < 4) {
_updateState(() {
_tabController.index = savedTabIndex;
@@ -281,7 +332,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
// Clear filters in storage when changing library
if (isChangingLibrary) {
await storage.saveLibraryFilters({}, sectionId: libraryKey);
await storage.saveLibraryFilters({}, sectionId: libraryGlobalKey);
}
// Cancel any existing requests
@@ -298,13 +349,13 @@ class _LibrariesScreenState extends State<LibrariesScreen>
try {
// Load sort options for the new library
await _loadSortOptions(libraryKey);
await _loadSortOptions(library);
final filtersWithSort = _buildFiltersWithSort();
// Load pages sequentially
await _loadAllPagesSequentially(
libraryKey,
library,
filtersWithSort,
currentRequestId,
client,
@@ -323,7 +374,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
/// Load all pages sequentially until all items are fetched
Future<void> _loadAllPagesSequentially(
String libraryKey,
PlexLibrary library,
Map<String, String> filtersWithSort,
int requestId,
PlexClient client,
@@ -331,22 +382,32 @@ class _LibrariesScreenState extends State<LibrariesScreen>
while (_hasMoreItems && requestId == _requestId) {
try {
final items = await client.getLibraryContent(
libraryKey,
library.key,
start: _currentPage * _pageSize,
size: _pageSize,
filters: filtersWithSort,
cancelToken: _cancelToken,
);
// Tag items with server info for multi-server support
final taggedItems = items
.map(
(item) => item.copyWith(
serverId: library.serverId,
serverName: library.serverName,
),
)
.toList();
// Check if request is still valid
if (requestId != _requestId) {
return; // Request was superseded
}
_updateState(() {
_items.addAll(items);
_items.addAll(taggedItems);
_currentPage++;
_hasMoreItems = items.length >= _pageSize;
_hasMoreItems = taggedItems.length >= _pageSize;
});
} catch (e) {
// Check if it's a cancellation
@@ -363,19 +424,15 @@ class _LibrariesScreenState extends State<LibrariesScreen>
}
}
Future<void> _loadSortOptions(String libraryKey) async {
Future<void> _loadSortOptions(PlexLibrary library) async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final client = context.getClientForLibrary(library);
final sortOptions = await client.getLibrarySorts(libraryKey);
final sortOptions = await client.getLibrarySorts(library.key);
// Load saved sort preference for this library
final storage = await StorageService.getInstance();
final savedSortData = storage.getLibrarySort(libraryKey);
final savedSortData = storage.getLibrarySort(library.globalKey);
// Find the saved sort in the options
PlexSort? savedSort;
@@ -466,7 +523,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
void fullRefresh() {
appLogger.d('LibrariesScreen.fullRefresh() called - reloading all content');
// Reload libraries and clear any selected library/filters
_selectedLibraryKey = null;
_selectedLibraryGlobalKey = null;
_selectedFilters.clear();
_items.clear();
_loadLibraries();
@@ -478,29 +535,31 @@ class _LibrariesScreenState extends State<LibrariesScreen>
listen: false,
);
final isHidden = hiddenLibrariesProvider.hiddenLibraryKeys.contains(
library.key,
library.globalKey,
);
if (isHidden) {
await hiddenLibrariesProvider.unhideLibrary(library.key);
await hiddenLibrariesProvider.unhideLibrary(library.globalKey);
} else {
// Check if we're hiding the currently selected library
final isCurrentlySelected = _selectedLibraryKey == library.key;
final isCurrentlySelected =
_selectedLibraryGlobalKey == library.globalKey;
await hiddenLibrariesProvider.hideLibrary(library.key);
await hiddenLibrariesProvider.hideLibrary(library.globalKey);
// If we just hid the selected library, select the first visible one
if (isCurrentlySelected) {
// Compute visible libraries after hiding
final visibleLibraries = _allLibraries
.where(
(lib) =>
!hiddenLibrariesProvider.hiddenLibraryKeys.contains(lib.key),
(lib) => !hiddenLibrariesProvider.hiddenLibraryKeys.contains(
lib.globalKey,
),
)
.toList();
if (visibleLibraries.isNotEmpty) {
_loadLibraryContent(visibleLibraries.first.key);
_loadLibraryContent(visibleLibraries.first.globalKey);
}
}
}
@@ -603,11 +662,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
required String Function(Object error) failureMessage,
}) async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final client = context.getClientForLibrary(library);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
@@ -684,6 +739,115 @@ class _LibrariesScreenState extends State<LibrariesScreen>
);
}
/// Build grouped dropdown menu items with server sections
List<PopupMenuEntry<String>> _buildGroupedLibraryMenuItems(
List<PlexLibrary> visibleLibraries,
) {
final List<PopupMenuEntry<String>> menuItems = [];
if (!_hasMultipleServers) {
// Single server: flat list
return visibleLibraries.map((library) {
final isSelected = library.globalKey == _selectedLibraryGlobalKey;
return PopupMenuItem<String>(
value: library.globalKey,
child: Row(
children: [
Icon(
_getLibraryIcon(library.type),
size: 20,
color: isSelected
? Theme.of(context).colorScheme.primary
: null,
),
const SizedBox(width: 12),
Text(
library.title,
style: TextStyle(
fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
color: isSelected
? Theme.of(context).colorScheme.primary
: null,
),
),
],
),
);
}).toList();
}
// Multiple servers: group by server
final Map<String, List<PlexLibrary>> groupedLibraries = {};
for (final library in visibleLibraries) {
final serverKey = library.serverId ?? 'unknown';
groupedLibraries.putIfAbsent(serverKey, () => []).add(library);
}
// Use ordered server keys
final serverKeys = _getOrderedServerIds(visibleLibraries);
for (int i = 0; i < serverKeys.length; i++) {
final serverKey = serverKeys[i];
final libraries = groupedLibraries[serverKey]!;
final serverName = libraries.first.serverName ?? 'Unknown Server';
// Add server header
menuItems.add(
PopupMenuItem<String>(
enabled: false,
height: 24,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Text(
serverName,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.primary,
),
),
),
);
// Add libraries for this server
for (final library in libraries) {
final isSelected = library.globalKey == _selectedLibraryGlobalKey;
menuItems.add(
PopupMenuItem<String>(
value: library.globalKey,
child: Row(
children: [
const SizedBox(width: 12), // Indent library items
Icon(
_getLibraryIcon(library.type),
size: 20,
color: isSelected
? Theme.of(context).colorScheme.primary
: null,
),
const SizedBox(width: 12),
Text(
library.title,
style: TextStyle(
fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
color: isSelected
? Theme.of(context).colorScheme.primary
: null,
),
),
],
),
),
);
}
// Add divider between server groups (except after last)
if (i < serverKeys.length - 1) {
menuItems.add(const PopupMenuDivider());
}
}
return menuItems;
}
Widget _buildTabChip(String label, int index) {
final isSelected = _tabController.index == index;
final t = tokens(context);
@@ -711,54 +875,46 @@ class _LibrariesScreenState extends State<LibrariesScreen>
Widget _buildLibraryDropdownTitle(List<PlexLibrary> visibleLibraries) {
final selectedLibrary = visibleLibraries.firstWhere(
(lib) => lib.key == _selectedLibraryKey,
(lib) => lib.globalKey == _selectedLibraryGlobalKey,
orElse: () => visibleLibraries.first,
);
return PopupMenuButton<String>(
offset: const Offset(0, 48),
tooltip: t.libraries.selectLibrary,
onSelected: (libraryKey) {
_loadLibraryContent(libraryKey);
},
itemBuilder: (context) {
return visibleLibraries.map((library) {
final isSelected = library.key == _selectedLibraryKey;
return PopupMenuItem<String>(
value: library.key,
child: Row(
children: [
Icon(
_getLibraryIcon(library.type),
size: 20,
color: isSelected
? Theme.of(context).colorScheme.primary
: null,
),
const SizedBox(width: 12),
Text(
library.title,
style: TextStyle(
fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
color: isSelected
? Theme.of(context).colorScheme.primary
: null,
),
),
],
),
);
}).toList();
onSelected: (libraryGlobalKey) {
_loadLibraryContent(libraryGlobalKey);
},
itemBuilder: (context) => _buildGroupedLibraryMenuItems(visibleLibraries),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(_getLibraryIcon(selectedLibrary.type), size: 20),
const SizedBox(width: 8),
Text(
selectedLibrary.title,
style: Theme.of(context).textTheme.titleLarge,
),
if (_hasMultipleServers && selectedLibrary.serverName != null)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
selectedLibrary.title,
style: Theme.of(context).textTheme.titleMedium,
),
Text(
selectedLibrary.serverName!,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Theme.of(
context,
).textTheme.bodySmall?.color?.withValues(alpha: 0.6),
),
),
],
)
else
Text(
selectedLibrary.title,
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(width: 4),
const Icon(Icons.arrow_drop_down, size: 24),
],
@@ -774,14 +930,15 @@ class _LibrariesScreenState extends State<LibrariesScreen>
// Compute visible libraries (filtered from all libraries)
final visibleLibraries = _allLibraries
.where((lib) => !hiddenKeys.contains(lib.key))
.where((lib) => !hiddenKeys.contains(lib.globalKey))
.toList();
return Scaffold(
body: CustomScrollView(
slivers: [
DesktopSliverAppBar(
title: visibleLibraries.isNotEmpty && _selectedLibraryKey != null
title:
visibleLibraries.isNotEmpty && _selectedLibraryGlobalKey != null
? _buildLibraryDropdownTitle(visibleLibraries)
: Text(t.libraries.title),
floating: true,
@@ -850,7 +1007,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
)
else ...[
// Tab selector chips
if (_selectedLibraryKey != null)
if (_selectedLibraryGlobalKey != null)
SliverToBoxAdapter(
child: Container(
padding: const EdgeInsets.symmetric(
@@ -875,7 +1032,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
),
// Tab content
if (_selectedLibraryKey != null)
if (_selectedLibraryGlobalKey != null)
SliverFillRemaining(
child: TabBarView(
controller: _tabController,
@@ -883,25 +1040,25 @@ class _LibrariesScreenState extends State<LibrariesScreen>
LibraryRecommendedTab(
key: _recommendedTabKey,
library: _allLibraries.firstWhere(
(lib) => lib.key == _selectedLibraryKey,
(lib) => lib.globalKey == _selectedLibraryGlobalKey,
),
),
LibraryBrowseTab(
key: _browseTabKey,
library: _allLibraries.firstWhere(
(lib) => lib.key == _selectedLibraryKey,
(lib) => lib.globalKey == _selectedLibraryGlobalKey,
),
),
LibraryCollectionsTab(
key: _collectionsTabKey,
library: _allLibraries.firstWhere(
(lib) => lib.key == _selectedLibraryKey,
(lib) => lib.globalKey == _selectedLibraryGlobalKey,
),
),
LibraryPlaylistsTab(
key: _playlistsTabKey,
library: _allLibraries.firstWhere(
(lib) => lib.key == _selectedLibraryKey,
(lib) => lib.globalKey == _selectedLibraryGlobalKey,
),
),
],
@@ -953,11 +1110,77 @@ class _LibraryManagementSheet extends StatefulWidget {
class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
late List<PlexLibrary> _tempLibraries;
List<String>? _serverOrder;
@override
void initState() {
super.initState();
_tempLibraries = List.from(widget.allLibraries);
_loadServerOrder();
}
/// Load server order from storage
Future<void> _loadServerOrder() async {
final storage = await StorageService.getInstance();
final savedOrder = storage.getServerOrder();
if (mounted) {
setState(() {
_serverOrder = savedOrder;
});
}
}
/// Save server order to storage
Future<void> _saveServerOrder(List<String> serverIds) async {
final storage = await StorageService.getInstance();
await storage.saveServerOrder(serverIds);
if (mounted) {
setState(() {
_serverOrder = serverIds;
});
}
}
/// Get ordered list of server IDs
List<String> _getOrderedServerIds() {
// Get unique server IDs from libraries
final serverIds = _tempLibraries
.where((lib) => lib.serverId != null)
.map((lib) => lib.serverId!)
.toSet()
.toList();
if (_serverOrder == null || _serverOrder!.isEmpty) {
return serverIds;
}
// Apply saved order, but include any new servers not in the saved order
final ordered = <String>[];
for (final id in _serverOrder!) {
if (serverIds.contains(id)) {
ordered.add(id);
}
}
// Add any servers not in saved order
for (final id in serverIds) {
if (!ordered.contains(id)) {
ordered.add(id);
}
}
return ordered;
}
/// Check if libraries come from multiple servers
bool get _hasMultipleServers {
final uniqueServerIds = _tempLibraries
.where((lib) => lib.serverId != null)
.map((lib) => lib.serverId)
.toSet();
return uniqueServerIds.length > 1;
}
void _reorderLibraries(int oldIndex, int newIndex) {
@@ -1104,74 +1327,180 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
),
),
// Reorderable library list
// Library list (grouped by server if multiple servers)
Expanded(
child: ReorderableListView.builder(
scrollController: scrollController,
onReorder: _reorderLibraries,
itemCount: _tempLibraries.length,
padding: const EdgeInsets.symmetric(vertical: 8),
buildDefaultDragHandles: false,
itemBuilder: (context, index) {
final library = _tempLibraries[index];
final isHidden = hiddenLibraryKeys.contains(library.key);
return Opacity(
key: ValueKey(library.key),
opacity: isHidden ? 0.5 : 1.0,
child: ListTile(
leading: Row(
mainAxisSize: MainAxisSize.min,
children: [
ReorderableDragStartListener(
index: index,
child: Padding(
padding: const EdgeInsets.only(right: 12),
child: Icon(
Icons.drag_indicator,
color: Theme.of(context)
.textTheme
.bodyMedium
?.color
?.withValues(alpha: 0.5),
),
),
),
const SizedBox(width: 8),
Icon(_getLibraryIcon(library.type)),
],
),
title: Text(library.title),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(
isHidden
? Icons.visibility_off
: Icons.visibility,
),
onPressed: () => widget.onToggleVisibility(library),
tooltip: isHidden
? t.libraries.showLibrary
: t.libraries.hideLibrary,
),
IconButton(
icon: const Icon(Icons.more_vert),
onPressed: () =>
_showLibraryMenuBottomSheet(context, library),
tooltip: t.libraries.libraryOptions,
),
],
),
),
);
},
),
child: _hasMultipleServers
? _buildGroupedLibraryList(
scrollController,
hiddenLibraryKeys,
)
: _buildFlatLibraryList(scrollController, hiddenLibraryKeys),
),
],
);
},
);
}
/// Build flat library list (single server)
Widget _buildFlatLibraryList(
ScrollController scrollController,
Set<String> hiddenLibraryKeys,
) {
return ReorderableListView.builder(
scrollController: scrollController,
onReorder: _reorderLibraries,
itemCount: _tempLibraries.length,
padding: const EdgeInsets.symmetric(vertical: 8),
buildDefaultDragHandles: false,
itemBuilder: (context, index) {
final library = _tempLibraries[index];
return _buildLibraryTile(library, index, hiddenLibraryKeys);
},
);
}
/// Build grouped library list (multiple servers)
Widget _buildGroupedLibraryList(
ScrollController scrollController,
Set<String> hiddenLibraryKeys,
) {
// Group libraries by server
final Map<String, List<PlexLibrary>> groupedLibraries = {};
for (final library in _tempLibraries) {
final serverKey = library.serverId ?? 'unknown';
groupedLibraries.putIfAbsent(serverKey, () => []).add(library);
}
// Use ordered server keys
final serverKeys = _getOrderedServerIds();
return ReorderableListView.builder(
scrollController: scrollController,
padding: const EdgeInsets.symmetric(vertical: 8),
buildDefaultDragHandles: false,
onReorder: (oldIndex, newIndex) {
// Reorder servers
final reorderedServerIds = List<String>.from(serverKeys);
if (newIndex > oldIndex) {
newIndex -= 1;
}
final serverId = reorderedServerIds.removeAt(oldIndex);
reorderedServerIds.insert(newIndex, serverId);
_saveServerOrder(reorderedServerIds);
},
itemCount: serverKeys.length,
itemBuilder: (context, serverIndex) {
final serverKey = serverKeys[serverIndex];
final libraries = groupedLibraries[serverKey]!;
final serverName = libraries.first.serverName ?? 'Unknown Server';
return Column(
key: ValueKey(serverKey),
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
// Server header with drag handle
ListTile(
leading: ReorderableDragStartListener(
index: serverIndex,
child: Icon(
Icons.drag_indicator,
color: Theme.of(
context,
).textTheme.bodyMedium?.color?.withValues(alpha: 0.5),
),
),
title: Text(
serverName,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.primary,
),
),
),
// Libraries for this server (reorderable within server)
...libraries.asMap().entries.map((entry) {
final index = entry.key;
final library = entry.value;
return _buildLibraryTile(
library,
index,
hiddenLibraryKeys,
showServerBadge: false,
enableDrag: false, // Disable drag for individual libraries
);
}),
],
);
},
);
}
/// Build a single library tile
Widget _buildLibraryTile(
PlexLibrary library,
int index,
Set<String> hiddenLibraryKeys, {
bool showServerBadge = true,
bool enableDrag = true,
}) {
final isHidden = hiddenLibraryKeys.contains(library.globalKey);
return Opacity(
key: ValueKey(library.globalKey),
opacity: isHidden ? 0.5 : 1.0,
child: ListTile(
leading: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (enableDrag)
ReorderableDragStartListener(
index: index,
child: Padding(
padding: const EdgeInsets.only(right: 12),
child: Icon(
Icons.drag_indicator,
color: Theme.of(
context,
).textTheme.bodyMedium?.color?.withValues(alpha: 0.5),
),
),
),
if (enableDrag) const SizedBox(width: 8),
if (!enableDrag) const SizedBox(width: 12),
Icon(_getLibraryIcon(library.type)),
],
),
title: Row(
children: [
Expanded(child: Text(library.title)),
if (showServerBadge &&
_hasMultipleServers &&
library.serverName != null)
ServerBadge(serverName: library.serverName, showFullName: true),
],
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(isHidden ? Icons.visibility_off : Icons.visibility),
onPressed: () => widget.onToggleVisibility(library),
tooltip: isHidden
? t.libraries.showLibrary
: t.libraries.hideLibrary,
),
IconButton(
icon: const Icon(Icons.more_vert),
onPressed: () => _showLibraryMenuBottomSheet(context, library),
tooltip: t.libraries.libraryOptions,
),
],
),
),
);
}
}
@@ -0,0 +1,157 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../models/plex_library.dart';
import '../../utils/app_logger.dart';
import '../../mixins/library_tab_state.dart';
import '../../mixins/refreshable.dart';
import '../../widgets/content_state_builder.dart';
/// Base class for library tab screens that provides common state management
/// and lifecycle handling for tabs that display library content.
///
/// Type parameter T: The type of items this tab displays
///
/// Subclasses must implement:
/// - [loadData]: Load data from the Plex API
/// - [buildContent]: Build the UI for displaying loaded items
///
/// Optional overrides:
/// - [emptyIcon]: Icon to show when there are no items
/// - [emptyMessage]: Message to show when there are no items
/// - [errorContext]: Context for error messages (defaults to "content")
/// - [getRefreshStream]: Stream to listen for refresh events
abstract class BaseLibraryTab<T> extends StatefulWidget {
final PlexLibrary library;
final String? viewMode;
final String? density;
const BaseLibraryTab({
super.key,
required this.library,
this.viewMode,
this.density,
});
}
/// State mixin that provides the common implementation for library tabs
/// This preserves AutomaticKeepAliveClientMixin functionality
abstract class BaseLibraryTabState<T, W extends BaseLibraryTab<T>>
extends State<W>
with AutomaticKeepAliveClientMixin, Refreshable, LibraryTabStateMixin {
@override
bool get wantKeepAlive => true;
@override
PlexLibrary get library => widget.library;
@override
void refresh() {
loadItems();
}
// State management
List<T> _items = [];
bool _isLoading = false;
String? _errorMessage;
StreamSubscription<void>? _refreshSubscription;
// Getters for subclasses
List<T> get items => _items;
bool get isLoading => _isLoading;
String? get errorMessage => _errorMessage;
@override
void initState() {
super.initState();
loadItems();
// Subscribe to refresh stream if provided
final refreshStream = getRefreshStream();
if (refreshStream != null) {
_refreshSubscription = refreshStream.listen((_) {
if (mounted) {
loadItems();
}
});
}
}
@override
void dispose() {
_refreshSubscription?.cancel();
super.dispose();
}
@override
void didUpdateWidget(W oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.globalKey != widget.library.globalKey) {
loadItems();
}
}
/// Load items from the API
/// This is the main data loading function that subclasses must implement
Future<List<T>> loadData();
/// Build the content widget given the loaded items
/// This is called by ContentStateBuilder when items are available
Widget buildContent(List<T> items);
/// Icon to display when there are no items (empty state)
IconData get emptyIcon;
/// Message to display when there are no items (empty state)
String get emptyMessage;
/// Context string for error messages (e.g., "playlists", "collections")
String get errorContext;
/// Optional refresh stream to listen for external refresh events
/// Return null if no refresh stream is needed
Stream<void>? getRefreshStream() => null;
/// Load items with error handling and state management
Future<void> loadItems() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final loadedItems = await loadData();
if (!mounted) return;
setState(() {
_items = loadedItems;
_isLoading = false;
});
} catch (e) {
if (!mounted) return;
appLogger.e('Error loading $errorContext', error: e);
setState(() {
_errorMessage = 'Failed to load $errorContext: ${e.toString()}';
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
return ContentStateBuilder<T>(
isLoading: _isLoading,
errorMessage: _errorMessage,
items: _items,
emptyIcon: emptyIcon,
emptyMessage: emptyMessage,
onRetry: loadItems,
builder: (items) =>
RefreshIndicator(onRefresh: loadItems, child: buildContent(items)),
);
}
}
@@ -6,18 +6,20 @@ import '../../models/plex_library.dart';
import '../../models/plex_metadata.dart';
import '../../models/plex_filter.dart';
import '../../models/plex_sort.dart';
import '../../providers/plex_client_provider.dart';
import '../../providers/settings_provider.dart';
import '../../utils/provider_extensions.dart';
import '../../utils/error_message_utils.dart';
import '../../utils/grid_size_calculator.dart';
import '../../utils/server_tagging_extensions.dart';
import '../../widgets/media_card.dart';
import '../../widgets/folder_tree_view.dart';
import '../../widgets/filters_bottom_sheet.dart';
import '../../widgets/sort_bottom_sheet.dart';
import '../../widgets/empty_state_widget.dart';
import '../../widgets/error_state_widget.dart';
import '../../services/storage_service.dart';
import '../../services/settings_service.dart' show ViewMode;
import '../../mixins/item_updatable.dart';
import '../../mixins/library_tab_state.dart';
import '../../mixins/refreshable.dart';
import '../../i18n/strings.g.dart';
@@ -40,12 +42,19 @@ class LibraryBrowseTab extends StatefulWidget {
}
class _LibraryBrowseTabState extends State<LibraryBrowseTab>
with AutomaticKeepAliveClientMixin, ItemUpdatable, Refreshable {
with
AutomaticKeepAliveClientMixin,
ItemUpdatable,
Refreshable,
LibraryTabStateMixin {
@override
bool get wantKeepAlive => true;
@override
PlexClient get client => context.clientSafe;
PlexLibrary get library => widget.library;
@override
PlexClient get client => getClientForLibrary();
@override
void refresh() {
@@ -89,7 +98,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
void didUpdateWidget(LibraryBrowseTab oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.key != widget.library.key) {
if (oldWidget.library.globalKey != widget.library.globalKey) {
_loadContent();
}
}
@@ -106,8 +115,8 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
_cancelToken = CancelToken();
final currentRequestId = ++_requestId;
// Extract context dependencies before async gap
final clientProvider = context.plexClient;
// Extract context dependencies before async gap - use server-specific client
final client = getClientForLibrary();
setState(() {
_isLoading = true;
@@ -118,11 +127,6 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
});
try {
final client = clientProvider.client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final storage = await StorageService.getInstance();
// Load filters and sorts for this library
@@ -131,10 +135,12 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
// Load saved preferences
final savedFilters = storage.getLibraryFilters(
sectionId: widget.library.key,
sectionId: widget.library.globalKey,
);
final savedSort = storage.getLibrarySort(widget.library.globalKey);
final savedGrouping = storage.getLibraryGrouping(
widget.library.globalKey,
);
final savedSort = storage.getLibrarySort(widget.library.key);
final savedGrouping = storage.getLibraryGrouping(widget.library.key);
// Check if request was cancelled
if (currentRequestId != _requestId) return;
@@ -192,10 +198,8 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
});
try {
final client = context.read<PlexClientProvider>().client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
// Use server-specific client for this library
final client = getClientForLibrary();
// Build filter params
final filterParams = Map<String, String>.from(_selectedFilters);
@@ -223,15 +227,18 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
cancelToken: _cancelToken,
);
// Tag items with server info for multi-server support
final taggedItems = items.tagWithLibrary(widget.library);
if (currentRequestId != _requestId) return;
setState(() {
if (loadMore) {
_items.addAll(items);
_items.addAll(taggedItems);
} else {
_items = items;
_items = taggedItems;
}
_hasMoreItems = items.length >= _pageSize;
_hasMoreItems = taggedItems.length >= _pageSize;
_currentPage++;
_isLoading = false;
});
@@ -325,9 +332,12 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
});
final storage = await StorageService.getInstance();
await storage.saveLibraryGrouping(widget.library.key, value);
await storage.saveLibraryGrouping(
widget.library.globalKey,
value,
);
if (!mounted) return;
if (!context.mounted) return;
Navigator.pop(context);
_loadItems();
@@ -357,7 +367,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
final storage = await StorageService.getInstance();
await storage.saveLibraryFilters(
filters,
sectionId: widget.library.key,
sectionId: widget.library.globalKey,
);
_loadItems();
@@ -382,7 +392,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
StorageService.getInstance().then((storage) {
storage.saveLibrarySort(
widget.library.key,
widget.library.globalKey,
sort.key,
descending: descending,
);
@@ -487,6 +497,7 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
if (_selectedGrouping == 'folders') {
return FolderTreeView(
libraryKey: widget.library.key,
serverId: widget.library.serverId,
onRefresh: updateItem,
);
}
@@ -496,33 +507,18 @@ class _LibraryBrowseTabState extends State<LibraryBrowseTab>
}
if (_errorMessage != null && _items.isEmpty) {
return 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: _loadContent,
child: Text(t.common.retry),
),
],
),
return ErrorStateWidget(
message: _errorMessage!,
icon: Icons.error_outline,
onRetry: _loadContent,
retryLabel: t.common.retry,
);
}
if (_items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.folder_open, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(t.libraries.thisLibraryIsEmpty),
],
),
return EmptyStateWidget(
message: t.libraries.thisLibraryIsEmpty,
icon: Icons.folder_open,
);
}
@@ -1,130 +1,53 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_library.dart';
import '../../models/plex_metadata.dart';
import '../../providers/plex_client_provider.dart';
import '../../utils/app_logger.dart';
import '../../utils/library_refresh_notifier.dart';
import '../../utils/server_tagging_extensions.dart';
import '../../i18n/strings.g.dart';
import '../../mixins/refreshable.dart';
import '../../widgets/content_state_builder.dart';
import '../../widgets/adaptive_media_grid.dart';
import 'base_library_tab.dart';
/// Collections tab for library screen
/// Shows collections for the current library
class LibraryCollectionsTab extends StatefulWidget {
final PlexLibrary library;
final String? viewMode;
final String? density;
class LibraryCollectionsTab extends BaseLibraryTab<PlexMetadata> {
const LibraryCollectionsTab({
super.key,
required this.library,
this.viewMode,
this.density,
required super.library,
super.viewMode,
super.density,
});
@override
State<LibraryCollectionsTab> createState() => _LibraryCollectionsTabState();
}
class _LibraryCollectionsTabState extends State<LibraryCollectionsTab>
with AutomaticKeepAliveClientMixin, Refreshable {
class _LibraryCollectionsTabState
extends BaseLibraryTabState<PlexMetadata, LibraryCollectionsTab> {
@override
bool get wantKeepAlive => true;
IconData get emptyIcon => Icons.collections;
@override
void refresh() {
_loadCollections();
}
List<PlexMetadata> _collections = [];
bool _isLoading = false;
String? _errorMessage;
StreamSubscription<void>? _refreshSubscription;
String get emptyMessage => t.libraries.noCollections;
@override
void initState() {
super.initState();
_loadCollections();
String get errorContext => t.collections.title;
// Listen for refresh notifications
_refreshSubscription = LibraryRefreshNotifier().collectionsStream.listen((
_,
) {
if (mounted) {
_loadCollections();
}
});
@override
Stream<void>? getRefreshStream() =>
LibraryRefreshNotifier().collectionsStream;
@override
Future<List<PlexMetadata>> loadData() async {
// Use server-specific client for this library
final client = getClientForLibrary();
final collections = await client.getLibraryCollections(widget.library.key);
// Tag collections with server info
return collections.tagWithLibrary(widget.library);
}
@override
void dispose() {
_refreshSubscription?.cancel();
super.dispose();
}
@override
void didUpdateWidget(LibraryCollectionsTab oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.key != widget.library.key) {
_loadCollections();
}
}
Future<void> _loadCollections() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final client = context.read<PlexClientProvider>().client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final collections = await client.getLibraryCollections(
widget.library.key,
);
if (!mounted) return;
setState(() {
_collections = collections;
_isLoading = false;
});
} catch (e) {
if (!mounted) return;
appLogger.e('Error loading collections', error: e);
setState(() {
_errorMessage = t.errors.failedToLoad(
context: t.collections.title,
error: e.toString(),
);
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
return ContentStateBuilder<PlexMetadata>(
isLoading: _isLoading,
errorMessage: _errorMessage,
items: _collections,
emptyIcon: Icons.collections,
emptyMessage: t.libraries.noCollections,
onRetry: _loadCollections,
builder: (items) => RefreshIndicator(
onRefresh: _loadCollections,
child: AdaptiveMediaGrid(items: items, onRefresh: _loadCollections),
),
);
Widget buildContent(List<PlexMetadata> items) {
return AdaptiveMediaGrid(items: items, onRefresh: loadItems);
}
}
@@ -1,172 +1,99 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_library.dart';
import '../../models/plex_playlist.dart';
import '../../providers/plex_client_provider.dart';
import '../../providers/settings_provider.dart';
import '../../utils/app_logger.dart';
import '../../utils/library_refresh_notifier.dart';
import '../../services/settings_service.dart' show ViewMode;
import '../../utils/grid_size_calculator.dart';
import '../../utils/server_tagging_extensions.dart';
import '../../widgets/media_card.dart';
import '../../i18n/strings.g.dart';
import '../../mixins/refreshable.dart';
import '../../widgets/content_state_builder.dart';
import 'base_library_tab.dart';
/// Playlists tab for library screen
/// Shows playlists that contain items from the current library
class LibraryPlaylistsTab extends StatefulWidget {
final PlexLibrary library;
final String? viewMode;
final String? density;
class LibraryPlaylistsTab extends BaseLibraryTab<PlexPlaylist> {
const LibraryPlaylistsTab({
super.key,
required this.library,
this.viewMode,
this.density,
required super.library,
super.viewMode,
super.density,
});
@override
State<LibraryPlaylistsTab> createState() => _LibraryPlaylistsTabState();
}
class _LibraryPlaylistsTabState extends State<LibraryPlaylistsTab>
with AutomaticKeepAliveClientMixin, Refreshable {
class _LibraryPlaylistsTabState
extends BaseLibraryTabState<PlexPlaylist, LibraryPlaylistsTab> {
@override
bool get wantKeepAlive => true;
IconData get emptyIcon => Icons.playlist_play;
@override
void refresh() {
_loadPlaylists();
}
List<PlexPlaylist> _playlists = [];
bool _isLoading = false;
String? _errorMessage;
StreamSubscription<void>? _refreshSubscription;
String get emptyMessage => t.playlists.noPlaylists;
@override
void initState() {
super.initState();
_loadPlaylists();
String get errorContext => t.playlists.title;
// Listen for refresh notifications
_refreshSubscription = LibraryRefreshNotifier().playlistsStream.listen((_) {
if (mounted) {
_loadPlaylists();
}
});
@override
Stream<void>? getRefreshStream() => LibraryRefreshNotifier().playlistsStream;
@override
Future<List<PlexPlaylist>> loadData() async {
// Use server-specific client for this library
final client = getClientForLibrary();
// Get playlists for this library
final playlists = await client.getLibraryPlaylists(
sectionId: widget.library.key,
playlistType: 'video',
);
// Tag playlists with server info
return playlists.tagWithLibrary(widget.library);
}
@override
void dispose() {
_refreshSubscription?.cancel();
super.dispose();
}
@override
void didUpdateWidget(LibraryPlaylistsTab oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.key != widget.library.key) {
_loadPlaylists();
}
}
Future<void> _loadPlaylists() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final client = context.read<PlexClientProvider>().client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
// Get playlists for this library
final playlists = await client.getLibraryPlaylists(
sectionId: widget.library.key,
playlistType: 'video',
);
if (!mounted) return;
setState(() {
_playlists = playlists;
_isLoading = false;
});
} catch (e) {
if (!mounted) return;
appLogger.e('Error loading playlists', error: e);
setState(() {
_errorMessage = t.errors.failedToLoad(
context: t.playlists.title,
error: e.toString(),
);
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
return ContentStateBuilder<PlexPlaylist>(
isLoading: _isLoading,
errorMessage: _errorMessage,
items: _playlists,
emptyIcon: Icons.playlist_play,
emptyMessage: t.playlists.noPlaylists,
onRetry: _loadPlaylists,
builder: (items) => RefreshIndicator(
onRefresh: _loadPlaylists,
child: Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
itemCount: items.length,
itemBuilder: (context, index) {
final playlist = items[index];
return MediaCard(
key: Key(playlist.ratingKey),
item: playlist,
onListRefresh: _loadPlaylists,
);
},
Widget buildContent(List<PlexPlaylist> items) {
return Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
if (settingsProvider.viewMode == ViewMode.list) {
return ListView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
itemCount: items.length,
itemBuilder: (context, index) {
final playlist = items[index];
return MediaCard(
key: Key(playlist.ratingKey),
item: playlist,
onListRefresh: loadItems,
);
} else {
return GridView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) {
final playlist = items[index];
return MediaCard(
key: Key(playlist.ratingKey),
item: playlist,
onListRefresh: _loadPlaylists,
);
},
},
);
} else {
return GridView.builder(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
settingsProvider.libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemCount: items.length,
itemBuilder: (context, index) {
final playlist = items[index];
return MediaCard(
key: Key(playlist.ratingKey),
item: playlist,
onListRefresh: loadItems,
);
}
},
),
),
},
);
}
},
);
}
}
@@ -1,86 +1,48 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../models/plex_library.dart';
import '../../models/plex_hub.dart';
import '../../providers/plex_client_provider.dart';
import '../../utils/app_logger.dart';
import '../../widgets/hub_section.dart';
import '../../i18n/strings.g.dart';
import '../../mixins/refreshable.dart';
import '../../widgets/content_state_builder.dart';
import 'base_library_tab.dart';
/// Recommended tab for library screen
/// Shows library-specific hubs and recommendations
class LibraryRecommendedTab extends StatefulWidget {
final PlexLibrary library;
const LibraryRecommendedTab({super.key, required this.library});
class LibraryRecommendedTab extends BaseLibraryTab<PlexHub> {
const LibraryRecommendedTab({super.key, required super.library});
@override
State<LibraryRecommendedTab> createState() => _LibraryRecommendedTabState();
}
class _LibraryRecommendedTabState extends State<LibraryRecommendedTab>
with AutomaticKeepAliveClientMixin, Refreshable {
class _LibraryRecommendedTabState
extends BaseLibraryTabState<PlexHub, LibraryRecommendedTab> {
@override
bool get wantKeepAlive => true;
IconData get emptyIcon => Icons.recommend;
@override
void refresh() {
_loadHubs();
}
List<PlexHub> _hubs = [];
bool _isLoading = false;
String? _errorMessage;
String get emptyMessage => t.libraries.noRecommendations;
@override
void initState() {
super.initState();
_loadHubs();
String get errorContext => t.libraries.tabs.recommended;
@override
Future<List<PlexHub>> loadData() async {
// Use server-specific client for this library
final client = getClientForLibrary();
// Hubs are now tagged with server info at the source
return await client.getLibraryHubs(widget.library.key, limit: 12);
}
@override
void didUpdateWidget(LibraryRecommendedTab oldWidget) {
super.didUpdateWidget(oldWidget);
// Reload if library changed
if (oldWidget.library.key != widget.library.key) {
_loadHubs();
}
}
Future<void> _loadHubs() async {
setState(() {
_isLoading = true;
_errorMessage = null;
});
try {
final client = context.read<PlexClientProvider>().client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final hubs = await client.getLibraryHubs(widget.library.key, limit: 12);
if (!mounted) return;
setState(() {
_hubs = hubs;
_isLoading = false;
});
} catch (e) {
if (!mounted) return;
appLogger.e('Error loading library hubs', error: e);
setState(() {
_errorMessage = t.errors.failedToLoad(
context: t.libraries.tabs.recommended,
error: e.toString(),
);
_isLoading = false;
});
}
Widget buildContent(List<PlexHub> items) {
return ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: items.length,
itemBuilder: (context, index) {
final hub = items[index];
return HubSection(hub: hub, icon: _getHubIcon(hub));
},
);
}
IconData _getHubIcon(PlexHub hub) {
@@ -102,29 +64,4 @@ class _LibraryRecommendedTabState extends State<LibraryRecommendedTab>
}
return Icons.movie;
}
@override
Widget build(BuildContext context) {
super.build(context); // Required for AutomaticKeepAliveClientMixin
return ContentStateBuilder<PlexHub>(
isLoading: _isLoading,
errorMessage: _errorMessage,
items: _hubs,
emptyIcon: Icons.recommend,
emptyMessage: t.libraries.noRecommendations,
onRetry: _loadHubs,
builder: (items) => RefreshIndicator(
onRefresh: _loadHubs,
child: ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 8),
itemCount: items.length,
itemBuilder: (context, index) {
final hub = items[index];
return HubSection(hub: hub, icon: _getHubIcon(hub));
},
),
),
);
}
}
+173 -87
View File
@@ -3,14 +3,14 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../i18n/strings.g.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../providers/plex_client_provider.dart';
import '../providers/playback_state_provider.dart';
import '../theme/theme_helper.dart';
import '../utils/app_logger.dart';
import '../utils/content_rating_formatter.dart';
import '../utils/duration_formatter.dart';
import '../utils/provider_extensions.dart';
import '../utils/shuffle_play_helper.dart';
import '../utils/video_player_navigation.dart';
import '../widgets/app_bar_back_button.dart';
import '../widgets/desktop_app_bar.dart';
@@ -49,17 +49,19 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
super.dispose();
}
/// Get the correct PlexClient for this metadata's server
PlexClient _getClientForMetadata(BuildContext context) {
return context.getClientForServer(widget.metadata.serverId);
}
Future<void> _loadFullMetadata() async {
setState(() {
_isLoadingMetadata = true;
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// Use server-specific client for this metadata
final client = _getClientForMetadata(context);
// Fetch full metadata with clearLogo and OnDeck episode
final result = await client.getMetadataWithImagesAndOnDeck(
@@ -69,9 +71,19 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
final onDeckEpisode = result['onDeckEpisode'] as PlexMetadata?;
if (metadata != null) {
// Preserve serverId from original metadata
final metadataWithServerId = metadata.copyWith(
serverId: widget.metadata.serverId,
serverName: widget.metadata.serverName,
);
final onDeckWithServerId = onDeckEpisode?.copyWith(
serverId: widget.metadata.serverId,
serverName: widget.metadata.serverName,
);
setState(() {
_fullMetadata = metadata;
_onDeckEpisode = onDeckEpisode;
_fullMetadata = metadataWithServerId;
_onDeckEpisode = onDeckWithServerId;
_isLoadingMetadata = false;
});
@@ -110,15 +122,21 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// Use server-specific client for this metadata
final client = _getClientForMetadata(context);
final seasons = await client.getChildren(widget.metadata.ratingKey);
// Preserve serverId for each season
final seasonsWithServerId = seasons
.map(
(season) => season.copyWith(
serverId: widget.metadata.serverId,
serverName: widget.metadata.serverName,
),
)
.toList();
setState(() {
_seasons = seasons;
_seasons = seasonsWithServerId;
_isLoadingSeasons = false;
});
} catch (e) {
@@ -132,26 +150,38 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
/// 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');
}
// Use server-specific client for this metadata
final client = _getClientForMetadata(context);
final metadata = await client.getMetadataWithImages(
widget.metadata.ratingKey,
);
if (metadata != null) {
// Preserve serverId from original metadata
final metadataWithServerId = metadata.copyWith(
serverId: widget.metadata.serverId,
serverName: widget.metadata.serverName,
);
// 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);
final seasons = await client.getChildren(widget.metadata.ratingKey);
// Preserve serverId for each season
updatedSeasons = seasons
.map(
(season) => season.copyWith(
serverId: widget.metadata.serverId,
serverName: widget.metadata.serverName,
),
)
.toList();
}
// Single setState to minimize rebuilds - scroll position is preserved by controller
setState(() {
_fullMetadata = metadata;
_fullMetadata = metadataWithServerId;
if (updatedSeasons != null) {
_seasons = updatedSeasons;
}
@@ -165,12 +195,8 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
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');
}
// Use server-specific client for this metadata
final client = _getClientForMetadata(context);
// If seasons aren't loaded yet, wait for them or load them
if (_seasons.isEmpty && !_isLoadingSeasons) {
@@ -208,13 +234,15 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
// Play the first episode
final firstEpisode = episodes.first;
// Preserve serverId for the episode
final episodeWithServerId = firstEpisode.copyWith(
serverId: widget.metadata.serverId,
serverName: widget.metadata.serverName,
);
if (mounted) {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Playing first episode: ${firstEpisode.title}');
await navigateToVideoPlayer(context, metadata: firstEpisode);
// Client already retrieved earlier in the method
appLogger.d('Playing first episode: ${episodeWithServerId.title}');
await navigateToVideoPlayer(context, metadata: episodeWithServerId);
appLogger.d('Returned from playback, refreshing metadata');
// Refresh metadata when returning from video player
_loadFullMetadata();
@@ -228,6 +256,100 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
}
}
/// Handle shuffle play using play queues
Future<void> _handleShufflePlayWithQueue(
BuildContext context,
PlexMetadata metadata,
) async {
final client = _getClientForMetadata(context);
final playbackState = context.read<PlaybackStateProvider>();
final itemType = metadata.type.toLowerCase();
try {
// Show loading indicator
if (context.mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) =>
const Center(child: CircularProgressIndicator()),
);
}
// Determine the rating key for the play queue
String showRatingKey;
if (itemType == 'show') {
showRatingKey = metadata.ratingKey;
} else if (itemType == 'season') {
// For seasons, we need the show's rating key
// The season's parentRatingKey should point to the show
if (metadata.parentRatingKey == null) {
throw Exception('Season is missing parentRatingKey');
}
showRatingKey = metadata.parentRatingKey!;
} else {
throw Exception('Shuffle play only works for shows and seasons');
}
// Create a shuffled play queue for the show
final playQueue = await client.createShowPlayQueue(
showRatingKey: showRatingKey,
shuffle: 1,
);
// Close loading indicator
if (context.mounted) {
Navigator.pop(context);
}
if (playQueue == null ||
playQueue.items == null ||
playQueue.items!.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(t.messages.noEpisodesFound)));
}
return;
}
// Initialize playback state with the play queue
await playbackState.setPlaybackFromPlayQueue(
playQueue,
showRatingKey,
serverId: metadata.serverId,
serverName: metadata.serverName,
);
// Set the client for the playback state provider
playbackState.setClient(client);
// Navigate to the first episode in the shuffled queue
final firstEpisode = playQueue.items!.first.copyWith(
serverId: metadata.serverId,
serverName: metadata.serverName,
);
if (context.mounted) {
await navigateToVideoPlayer(context, metadata: firstEpisode);
// Refresh metadata when returning from video player
_loadFullMetadata();
}
} 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(t.messages.errorLoading(error: e.toString()))),
);
}
}
}
@override
Widget build(BuildContext context) {
// Use full metadata if loaded, otherwise use passed metadata
@@ -265,16 +387,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
children: [
// Background Art
if (metadata.art != null)
Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
);
}
Builder(
builder: (context) {
final client = _getClientForMetadata(context);
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(metadata.art),
fit: BoxFit.cover,
@@ -331,21 +446,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
SizedBox(
height: 120,
width: 400,
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
),
);
}
child: Builder(
builder: (context) {
final client = _getClientForMetadata(
context,
);
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
metadata.clearLogo,
@@ -593,10 +698,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
// Otherwise, play the first episode of the first season
if (metadata.type.toLowerCase() == 'show') {
if (_onDeckEpisode != null) {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d(
'Playing on deck episode: ${_onDeckEpisode!.title}',
);
@@ -614,10 +715,6 @@ 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 navigateToVideoPlayer(
@@ -650,7 +747,10 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
metadata.type.toLowerCase() == 'season') ...[
IconButton.filledTonal(
onPressed: () async {
await handleShufflePlay(context, metadata);
await _handleShufflePlayWithQueue(
context,
metadata,
);
},
icon: const Icon(Icons.shuffle),
tooltip: t.tooltips.shufflePlay,
@@ -665,9 +765,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
IconButton.filledTonal(
onPressed: () async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final client = _getClientForMetadata(context);
await client.markAsWatched(metadata.ratingKey);
if (context.mounted) {
@@ -706,9 +804,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
IconButton.filledTonal(
onPressed: () async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final client = _getClientForMetadata(context);
await client.markAsUnwatched(metadata.ratingKey);
if (context.mounted) {
@@ -985,19 +1081,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
if (season.thumb != null)
ClipRRect(
borderRadius: BorderRadius.circular(6),
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),
);
}
child: Builder(
builder: (context) {
final client = _getClientForMetadata(context);
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(season.thumb),
width: 80,
+61 -138
View File
@@ -1,6 +1,8 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_playlist.dart';
import '../models/plex_metadata.dart';
import '../providers/settings_provider.dart';
import '../providers/playback_state_provider.dart';
import '../utils/app_logger.dart';
@@ -25,7 +27,8 @@ class PlaylistDetailScreen extends StatefulWidget {
}
class _PlaylistDetailScreenState
extends BaseMediaListDetailScreen<PlaylistDetailScreen> {
extends BaseMediaListDetailScreen<PlaylistDetailScreen>
with StandardItemLoader<PlaylistDetailScreen> {
@override
dynamic get mediaItem => widget.playlist;
@@ -36,37 +39,21 @@ class _PlaylistDetailScreenState
String get emptyMessage => t.playlists.emptyPlaylist;
@override
Future<void> loadItems() async {
if (mounted) {
setState(() {
isLoading = true;
errorMessage = null;
});
}
IconData get emptyIcon => Icons.playlist_play;
try {
final client = this.client;
final newItems = await client.getPlaylist(widget.playlist.ratingKey);
@override
Future<List<PlexMetadata>> fetchItems() async {
return await client.getPlaylist(widget.playlist.ratingKey);
}
if (mounted) {
setState(() {
items = newItems;
isLoading = false;
});
}
@override
String getLoadSuccessMessage(int itemCount) {
return 'Loaded $itemCount items for playlist: ${widget.playlist.title}';
}
appLogger.d(
'Loaded ${newItems.length} items for playlist: ${widget.playlist.title}',
);
} catch (e) {
appLogger.e('Failed to load playlist items', error: e);
if (mounted) {
setState(() {
errorMessage = 'Failed to load playlist items: ${e.toString()}';
isLoading = false;
});
}
}
/// Get the correct PlexClient for this playlist's server
PlexClient _getClientForPlaylist() {
return context.getClientForServer(widget.playlist.serverId);
}
Future<void> _deletePlaylist() async {
@@ -221,9 +208,7 @@ class _PlaylistDetailScreenState
if (items.isEmpty || index < 0 || index >= items.length) return;
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final client = _getClientForPlaylist();
final selectedItem = items[index];
@@ -312,113 +297,51 @@ class _PlaylistDetailScreenState
],
),
pinned: true,
actions: [
// Play button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.play_arrow),
tooltip: t.discover.play,
onPressed: playItems,
),
// Shuffle button
if (items.isNotEmpty)
IconButton(
icon: const Icon(Icons.shuffle),
tooltip: t.playlists.shuffle,
onPressed: shufflePlayItems,
),
// Delete button for non-smart playlists
if (!widget.playlist.smart)
IconButton(
icon: const Icon(Icons.delete),
tooltip: t.playlists.delete,
onPressed: _deletePlaylist,
color: Colors.red,
),
],
),
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: loadItems,
child: Text(t.common.retry),
),
],
),
),
)
else if (items.isEmpty && isLoading)
const SliverFillRemaining(
child: Center(child: CircularProgressIndicator()),
)
else if (items.isEmpty)
SliverFillRemaining(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.playlist_play,
size: 64,
color: Colors.grey,
),
const SizedBox(height: 16),
Text(
t.playlists.emptyPlaylist,
style: const TextStyle(fontSize: 16, color: Colors.grey),
),
],
),
),
)
else if (widget.playlist.smart)
// Smart playlists: Use grid view (cannot be reordered)
SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: GridSizeCalculator.getMaxCrossAxisExtent(
context,
context.watch<SettingsProvider>().libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
delegate: SliverChildBuilderDelegate((context, index) {
return MediaCard(item: items[index], onRefresh: updateItem);
}, childCount: items.length),
),
)
else
// Regular playlists: Use reorderable list view
SliverReorderableList(
itemBuilder: (context, index) {
final item = items[index];
return PlaylistItemCard(
key: ValueKey(item.playlistItemID ?? item.ratingKey),
item: item,
index: index,
onRemove: () => _removeItem(index),
onTap: () => _playFromItem(index),
canReorder: !widget.playlist.smart,
);
},
itemCount: items.length,
onReorder: _onReorder,
actions: buildAppBarActions(
onDelete: widget.playlist.smart ? null : _deletePlaylist,
deleteTooltip: t.playlists.delete,
showDelete: !widget.playlist.smart,
),
),
...buildStateSlivers(),
if (items.isNotEmpty)
if (widget.playlist.smart)
// Smart playlists: Use grid view (cannot be reordered)
SliverPadding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
sliver: SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
GridSizeCalculator.getMaxCrossAxisExtent(
context,
context.watch<SettingsProvider>().libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
delegate: SliverChildBuilderDelegate((context, index) {
return MediaCard(item: items[index], onRefresh: updateItem);
}, childCount: items.length),
),
)
else
// Regular playlists: Use reorderable list view
SliverReorderableList(
itemBuilder: (context, index) {
final item = items[index];
return PlaylistItemCard(
key: ValueKey(item.playlistItemID ?? item.ratingKey),
item: item,
index: index,
onRemove: () => _removeItem(index),
onTap: () => _playFromItem(index),
canReorder: !widget.playlist.smart,
);
},
itemCount: items.length,
onReorder: _onReorder,
),
],
),
);
+16 -20
View File
@@ -3,16 +3,14 @@ import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../i18n/strings.g.dart';
import '../mixins/item_updatable.dart';
import '../mixins/refreshable.dart';
import '../models/plex_metadata.dart';
import '../providers/multi_server_provider.dart';
import '../providers/settings_provider.dart';
import '../services/settings_service.dart';
import '../utils/app_logger.dart';
import '../utils/grid_cross_axis_extent.dart';
import '../utils/provider_extensions.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/media_card.dart';
@@ -23,11 +21,7 @@ class SearchScreen extends StatefulWidget {
State<SearchScreen> createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen>
with Refreshable, ItemUpdatable {
@override
PlexClient get client => context.clientSafe;
class _SearchScreenState extends State<SearchScreen> with Refreshable {
final _searchController = TextEditingController();
List<PlexMetadata> _searchResults = [];
bool _isSearching = false;
@@ -91,13 +85,18 @@ class _SearchScreenState extends State<SearchScreen>
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
final multiServerProvider = Provider.of<MultiServerProvider>(
context,
listen: false,
);
if (!multiServerProvider.hasConnectedServers) {
throw Exception('No servers available');
}
final results = await client.search(query);
// Search across all connected servers
final results = await multiServerProvider.aggregationService
.searchAcrossServers(query);
if (mounted) {
setState(() {
_searchResults = results;
@@ -140,13 +139,10 @@ class _SearchScreenState extends State<SearchScreen>
});
}
@override
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
final index = _searchResults.indexWhere(
(item) => item.ratingKey == ratingKey,
);
if (index != -1) {
_searchResults[index] = updatedMetadata;
void updateItem(String ratingKey) {
// Trigger a refresh of the search to get updated metadata
if (_searchController.text.isNotEmpty) {
_performSearch(_searchController.text);
}
}
+18 -25
View File
@@ -1,9 +1,7 @@
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 '../providers/plex_client_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/duration_formatter.dart';
@@ -24,17 +22,28 @@ class SeasonDetailScreen extends StatefulWidget {
class _SeasonDetailScreenState extends State<SeasonDetailScreen>
with ItemUpdatable {
late final PlexClient _client;
@override
PlexClient get client => context.clientSafe;
PlexClient get client => _client;
List<PlexMetadata> _episodes = [];
bool _isLoadingEpisodes = false;
bool _watchStateChanged = false;
/// Get the correct PlexClient for this season's server
PlexClient _getClientForSeason(BuildContext context) {
return context.getClientForServer(widget.season.serverId);
}
@override
void initState() {
super.initState();
_loadEpisodes();
// Initialize the client once in initState
WidgetsBinding.instance.addPostFrameCallback((_) {
_client = _getClientForSeason(context);
_loadEpisodes();
});
}
Future<void> _loadEpisodes() async {
@@ -43,13 +52,8 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final episodes = await client.getChildren(widget.season.ratingKey);
// Episodes are now tagged with server info at the source
final episodes = await _client.getChildren(widget.season.ratingKey);
setState(() {
_episodes = episodes;
_isLoadingEpisodes = false;
@@ -165,21 +169,10 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
child: AspectRatio(
aspectRatio: 16 / 9,
child: episode.thumb != null
? 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),
),
);
}
? Builder(
builder: (context) {
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
imageUrl: _client.getThumbnailUrl(
episode.thumb,
),
filterQuality: FilterQuality.medium,
-329
View File
@@ -1,329 +0,0 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import '../i18n/strings.g.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.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 '../utils/error_message_utils.dart';
import 'main_screen.dart';
class ServerSelectionScreen extends StatefulWidget {
final PlexAuthService authService;
final String plexToken;
const ServerSelectionScreen({
super.key,
required this.authService,
required this.plexToken,
});
@override
State<ServerSelectionScreen> createState() => _ServerSelectionScreenState();
}
class _ServerSelectionScreenState extends State<ServerSelectionScreen> {
List<PlexServer>? _servers;
bool _isLoading = true;
String? _errorMessage;
String? _currentServerUrl;
List<Map<String, dynamic>>? _debugServerData;
@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);
setState(() {
_servers = servers;
_isLoading = false;
_debugServerData = null; // Clear any previous debug data
});
} catch (e) {
setState(() {
_errorMessage = _getErrorMessage(e);
_isLoading = false;
// Store debug data if it's a parsing exception
if (e is ServerParsingException) {
_debugServerData = e.invalidServerData;
} else {
_debugServerData = null;
}
});
appLogger.e('Failed to load servers', error: e);
}
}
String _getErrorMessage(dynamic error) {
if (error is DioException) {
return mapDioErrorToMessage(
error,
context: t.serverSelection.noServersFound,
);
}
if (error is ServerParsingException) {
return t.serverSelection.malformedServerData(
count: error.invalidServerData.length,
);
} else if (error is FormatException) {
// Handle JSON parsing errors with more user-friendly messages
if (error.message.contains('Invalid server data')) {
return t.serverSelection.incompleteServerInfo;
} else if (error.message.contains('Invalid connection data')) {
return t.serverSelection.incompleteConnectionInfo;
}
return t.serverSelection.malformedServerInfo(message: error.message);
} else if (error.toString().contains('SocketException') ||
error.toString().contains('TimeoutException')) {
return t.serverSelection.networkConnectionFailed;
} else if (error.toString().contains('401') ||
error.toString().contains('Unauthorized')) {
return t.serverSelection.authenticationFailed;
} else if (error.toString().contains('404') ||
error.toString().contains('Not Found')) {
return t.serverSelection.plexServiceUnavailable;
}
return t.serverSelection.failedToLoadServers(error: error.toString());
}
Future<void> _copyDebugDataToClipboard() async {
if (_debugServerData == null) return;
final jsonString = const JsonEncoder.withIndent(
' ',
).convert(_debugServerData);
await Clipboard.setData(ClipboardData(text: jsonString));
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.serverSelection.serverDebugCopied)),
);
}
}
Future<void> _selectServer(PlexServer server) async {
// Show loading dialog
if (mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text(t.serverSelection.connectingToServer),
],
),
),
);
}
try {
// Get client identifier and storage
final storage = await StorageService.getInstance();
final clientId =
storage.getClientIdentifier() ?? widget.authService.clientIdentifier;
// Get current profile context to maintain profile across server switch
final currentUserUUID = storage.getCurrentUserUUID();
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 ?? t.errors.connectionFailedGeneric),
),
);
}
}
} catch (e) {
// Close loading dialog on error
if (mounted) {
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(t.messages.errorLoading(error: e.toString()))),
);
}
appLogger.e('Server selection failed', error: e);
}
}
bool _isCurrentServer(PlexServer server) {
if (_currentServerUrl == null) return false;
// 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(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(t.screens.selectServer)),
SliverFillRemaining(
child: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Text(
_errorMessage!,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
textAlign: TextAlign.center,
),
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _loadServers,
child: Text(t.common.retry),
),
if (_debugServerData != null) ...[
const SizedBox(width: 16),
OutlinedButton.icon(
onPressed: _copyDebugDataToClipboard,
icon: const Icon(Icons.copy),
label: Text(t.serverSelection.copyDebugData),
),
],
],
),
if (_debugServerData != null) ...[
const SizedBox(height: 12),
Text(
'Debug data available for ${_debugServerData!.length} server(s)',
style: Theme.of(context).textTheme.bodySmall,
),
],
],
),
)
: _servers == null || _servers!.isEmpty
? Center(child: Text(t.serverSelection.noServersFound))
: 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),
),
),
);
},
),
),
],
),
);
}
}
-60
View File
@@ -79,8 +79,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
const SizedBox(height: 24),
_buildVideoPlaybackSection(),
const SizedBox(height: 24),
_buildShufflePlaySection(),
const SizedBox(height: 24),
_buildKeyboardShortcutsSection(),
const SizedBox(height: 24),
_buildAdvancedSection(),
@@ -283,64 +281,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
}
Widget _buildShufflePlaySection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
t.settings.shufflePlay,
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.visibility_off),
title: Text(t.settings.unwatchedOnly),
subtitle: Text(t.settings.unwatchedOnlyDescription),
value: settingsProvider.shuffleUnwatchedOnly,
onChanged: (value) async {
await settingsProvider.setShuffleUnwatchedOnly(value);
},
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.shuffle),
title: Text(t.settings.shuffleOrderNavigation),
subtitle: Text(t.settings.shuffleOrderNavigationDescription),
value: settingsProvider.shuffleOrderNavigation,
onChanged: (value) async {
await settingsProvider.setShuffleOrderNavigation(value);
},
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.loop),
title: Text(t.settings.loopShuffleQueue),
subtitle: Text(t.settings.loopShuffleQueueDescription),
value: settingsProvider.shuffleLoopQueue,
onChanged: (value) async {
await settingsProvider.setShuffleLoopQueue(value);
},
);
},
),
],
),
);
}
Widget _buildKeyboardShortcutsSection() {
return Card(
child: Column(
+153 -175
View File
@@ -11,9 +11,105 @@ class SubtitleStylingScreen extends StatefulWidget {
State<SubtitleStylingScreen> createState() => _SubtitleStylingScreenState();
}
class _SubtitleStylingScreenState extends State<SubtitleStylingScreen> {
static const EdgeInsets _sliderPadding = EdgeInsets.fromLTRB(16, 16, 16, 8);
// Composable widget for slider sections
class _StylingSliderSection extends StatelessWidget {
final String label;
final int value;
final double min;
final double max;
final int divisions;
final ValueChanged<double> onChanged;
final ValueChanged<double>? onChangeEnd;
final String Function(int)? valueFormatter;
const _StylingSliderSection({
required this.label,
required this.value,
required this.min,
required this.max,
required this.divisions,
required this.onChanged,
this.onChangeEnd,
this.valueFormatter,
});
@override
Widget build(BuildContext context) {
final formattedValue = valueFormatter?.call(value) ?? value.toString();
return Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [Text(label), Text(formattedValue)],
),
const SizedBox(height: 8),
Row(
children: [
Text(
valueFormatter?.call(min.toInt()) ?? min.toInt().toString(),
style: const TextStyle(fontSize: 12, color: Colors.grey),
),
Expanded(
child: Slider(
value: value.toDouble(),
min: min,
max: max,
divisions: divisions,
label: formattedValue,
onChanged: onChanged,
onChangeEnd: onChangeEnd,
),
),
Text(
valueFormatter?.call(max.toInt()) ?? max.toInt().toString(),
style: const TextStyle(fontSize: 12, color: Colors.grey),
),
],
),
],
),
);
}
}
// Composable widget for color picker tiles
class _ColorSettingTile extends StatelessWidget {
final String label;
final String currentColor;
final VoidCallback onTap;
final Color Function(String) hexToColor;
const _ColorSettingTile({
required this.label,
required this.currentColor,
required this.onTap,
required this.hexToColor,
});
@override
Widget build(BuildContext context) {
return ListTile(
leading: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: hexToColor(currentColor),
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(4),
),
),
title: Text(label),
subtitle: Text(currentColor),
trailing: const Icon(Icons.chevron_right),
onTap: onTap,
);
}
}
class _SubtitleStylingScreenState extends State<SubtitleStylingScreen> {
late SettingsService _settingsService;
bool _isLoading = true;
@@ -134,66 +230,27 @@ class _SubtitleStylingScreenState extends State<SubtitleStylingScreen> {
),
),
// Font Size Slider
Padding(
padding: _sliderPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(t.subtitlingStyling.fontSize),
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),
),
],
),
],
),
_StylingSliderSection(
label: t.subtitlingStyling.fontSize,
value: _fontSize,
min: 30,
max: 80,
divisions: 50,
onChanged: (value) {
setState(() {
_fontSize = value.toInt();
});
},
onChangeEnd: (value) {
_settingsService.setSubtitleFontSize(_fontSize);
},
),
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: Text(t.subtitlingStyling.textColor),
subtitle: Text(_textColor),
trailing: const Icon(Icons.chevron_right),
_ColorSettingTile(
label: t.subtitlingStyling.textColor,
currentColor: _textColor,
hexToColor: _hexToColor,
onTap: () {
_showColorPicker(t.subtitlingStyling.textColor, _textColor, (
color,
@@ -207,66 +264,27 @@ class _SubtitleStylingScreenState extends State<SubtitleStylingScreen> {
),
const Divider(),
// Border Size Slider
Padding(
padding: _sliderPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(t.subtitlingStyling.borderSize),
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),
),
],
),
],
),
_StylingSliderSection(
label: t.subtitlingStyling.borderSize,
value: _borderSize,
min: 0,
max: 5,
divisions: 5,
onChanged: (value) {
setState(() {
_borderSize = value.toInt();
});
},
onChangeEnd: (value) {
_settingsService.setSubtitleBorderSize(_borderSize);
},
),
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: Text(t.subtitlingStyling.borderColor),
subtitle: Text(_borderColor),
trailing: const Icon(Icons.chevron_right),
_ColorSettingTile(
label: t.subtitlingStyling.borderColor,
currentColor: _borderColor,
hexToColor: _hexToColor,
onTap: () {
_showColorPicker(t.subtitlingStyling.borderColor, _borderColor, (
color,
@@ -280,68 +298,28 @@ class _SubtitleStylingScreenState extends State<SubtitleStylingScreen> {
),
const Divider(),
// Background Opacity Slider
Padding(
padding: _sliderPadding,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(t.subtitlingStyling.backgroundOpacity),
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),
),
],
),
],
),
_StylingSliderSection(
label: t.subtitlingStyling.backgroundOpacity,
value: _backgroundOpacity,
min: 0,
max: 100,
divisions: 20,
valueFormatter: (value) => '$value%',
onChanged: (value) {
setState(() {
_backgroundOpacity = value.toInt();
});
},
onChangeEnd: (value) {
_settingsService.setSubtitleBackgroundOpacity(_backgroundOpacity);
},
),
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: Text(t.subtitlingStyling.backgroundColor),
subtitle: Text(_backgroundColor),
trailing: const Icon(Icons.chevron_right),
_ColorSettingTile(
label: t.subtitlingStyling.backgroundColor,
currentColor: _backgroundColor,
hexToColor: _hexToColor,
onTap: () {
_showColorPicker(
t.subtitlingStyling.backgroundColor,
File diff suppressed because it is too large Load Diff
+303
View File
@@ -0,0 +1,303 @@
import 'dart:async';
import '../client/plex_client.dart';
import '../models/plex_hub.dart';
import '../models/plex_library.dart';
import '../models/plex_metadata.dart';
import '../utils/app_logger.dart';
import 'multi_server_manager.dart';
import 'plex_auth_service.dart';
/// Service for aggregating data from multiple Plex servers
class DataAggregationService {
final MultiServerManager _serverManager;
DataAggregationService(this._serverManager);
/// Fetch libraries from all online servers and tag them with server info
Future<List<PlexLibrary>> getLibrariesFromAllServers() async {
return _perServer<PlexLibrary>(
operationName: 'fetching libraries',
operation: (serverId, client, server) async {
final libraries = await client.getLibraries();
// Tag each library with server info
return libraries.map((lib) {
return PlexLibrary(
key: lib.key,
title: lib.title,
type: lib.type,
agent: lib.agent,
scanner: lib.scanner,
language: lib.language,
uuid: lib.uuid,
updatedAt: lib.updatedAt,
createdAt: lib.createdAt,
hidden: lib.hidden,
);
}).toList();
},
);
}
/// Fetch "On Deck" (Continue Watching) from all servers and merge by recency
Future<List<PlexMetadata>> getOnDeckFromAllServers({int? limit}) async {
final allOnDeck = await _perServer<PlexMetadata>(
operationName: 'fetching on deck',
operation: (serverId, client, server) async {
final items = await client.getOnDeck();
// Tag each item with server info
return items.map((item) {
return item.copyWith(serverId: serverId, serverName: server?.name);
}).toList();
},
);
// Sort by most recently viewed
// Use lastViewedAt (when item was last viewed), falling back to updatedAt/addedAt if not available
allOnDeck.sort((a, b) {
final aTime = a.lastViewedAt ?? a.updatedAt ?? a.addedAt ?? 0;
final bTime = b.lastViewedAt ?? b.updatedAt ?? b.addedAt ?? 0;
return bTime.compareTo(aTime); // Descending (most recent first)
});
// Apply limit if specified
final result = limit != null && limit < allOnDeck.length
? allOnDeck.sublist(0, limit)
: allOnDeck;
appLogger.i('Fetched ${result.length} on deck items from all servers');
return result;
}
/// Fetch recommendation hubs from all servers
Future<List<PlexHub>> getHubsFromAllServers({int? limit}) async {
final clients = _serverManager.onlineClients;
if (clients.isEmpty) {
appLogger.w('No online servers available for fetching hubs');
return [];
}
appLogger.d('Fetching hubs from ${clients.length} servers');
final allHubs = <PlexHub>[];
// Fetch from all servers in parallel
final hubFutures = clients.entries.map((entry) async {
final serverId = entry.key;
final client = entry.value;
try {
// Get libraries for this server
final libraries = await client.getLibraries();
// Filter to only visible movie/show libraries
final visibleLibraries = libraries.where((library) {
if (library.type != 'movie' && library.type != 'show') {
return false;
}
if (library.hidden != null && library.hidden != 0) {
return false;
}
return true;
}).toList();
// Fetch hubs from all libraries in parallel
final libraryHubFutures = visibleLibraries.map((library) async {
try {
// Hubs are now tagged with server info at the source
return await client.getLibraryHubs(library.key);
} catch (e) {
appLogger.w(
'Failed to fetch hubs for library ${library.title}: $e',
);
return <PlexHub>[];
}
});
final libraryHubResults = await Future.wait(libraryHubFutures);
// Flatten all library hubs
final serverHubs = <PlexHub>[];
for (final hubs in libraryHubResults) {
serverHubs.addAll(hubs);
}
return serverHubs;
} catch (e, stackTrace) {
appLogger.e(
'Failed to fetch hubs from server $serverId',
error: e,
stackTrace: stackTrace,
);
_serverManager.updateServerStatus(serverId, false);
return <PlexHub>[];
}
});
final results = await Future.wait(hubFutures);
// Flatten results
for (final hubs in results) {
allHubs.addAll(hubs);
}
// Apply limit if specified
final result = limit != null && limit < allHubs.length
? allHubs.sublist(0, limit)
: allHubs;
appLogger.i('Fetched ${result.length} hubs from all servers');
return result;
}
/// Search across all online servers
Future<List<PlexMetadata>> searchAcrossServers(
String query, {
int? limit,
}) async {
if (query.trim().isEmpty) {
return [];
}
final allResults = await _perServer<PlexMetadata>(
operationName: 'searching for "$query"',
operation: (serverId, client, server) async {
final results = await client.search(query);
// Tag each result with server info
return results.map((item) {
return item.copyWith(serverId: serverId, serverName: server?.name);
}).toList();
},
);
// Apply limit if specified
final result = limit != null && limit < allResults.length
? allResults.sublist(0, limit)
: allResults;
appLogger.i('Found ${result.length} search results across all servers');
return result;
}
/// Get libraries for a specific server
Future<List<PlexLibrary>> getLibrariesForServer(String serverId) async {
final client = _serverManager.getClient(serverId);
if (client == null) {
appLogger.w('No client found for server $serverId');
return [];
}
try {
final libraries = await client.getLibraries();
// Tag with server info
return libraries.map((lib) {
return PlexLibrary(
key: lib.key,
title: lib.title,
type: lib.type,
agent: lib.agent,
scanner: lib.scanner,
language: lib.language,
uuid: lib.uuid,
updatedAt: lib.updatedAt,
createdAt: lib.createdAt,
hidden: lib.hidden,
);
}).toList();
} catch (e, stackTrace) {
appLogger.e(
'Failed to fetch libraries for server $serverId',
error: e,
stackTrace: stackTrace,
);
_serverManager.updateServerStatus(serverId, false);
return [];
}
}
/// Group libraries by server
Map<String, List<PlexLibrary>> groupLibrariesByServer(
List<PlexLibrary> libraries,
) {
final grouped = <String, List<PlexLibrary>>{};
for (final library in libraries) {
final serverId = library.serverId;
if (serverId != null) {
grouped.putIfAbsent(serverId, () => []).add(library);
}
}
return grouped;
}
// Private helper methods
/// Higher-order helper for per-server fan-out operations
///
/// Iterates over all online clients, executes the operation for each server,
/// handles errors, updates server status, and aggregates results.
///
/// Type parameter `T` is the item type returned by the operation
/// [operationName] is used for logging (e.g., "fetching libraries")
/// [operation] is the async function to run per server, returning `List<T>`
Future<List<T>> _perServer<T>({
required String operationName,
required Future<List<T>> Function(
String serverId,
PlexClient client,
PlexServer? server,
)
operation,
}) async {
final clients = _serverManager.onlineClients;
if (clients.isEmpty) {
appLogger.w('No online servers available for $operationName');
return [];
}
appLogger.d('$operationName from ${clients.length} servers');
final allResults = <T>[];
// Execute operation on all servers in parallel
final Iterable<Future<List<T>>> futures = clients.entries.map((
entry,
) async {
final serverId = entry.key;
final client = entry.value;
final server = _serverManager.getServer(serverId);
try {
return await operation(serverId, client, server);
} catch (e, stackTrace) {
appLogger.e(
'Failed $operationName from server $serverId',
error: e,
stackTrace: stackTrace,
);
_serverManager.updateServerStatus(serverId, false);
return <T>[];
}
});
final List<List<T>> results = await Future.wait<List<T>>(futures);
// Flatten results
for (final items in results) {
allResults.addAll(items);
}
return allResults;
}
}
@@ -0,0 +1,112 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../providers/playback_state_provider.dart';
import '../utils/app_logger.dart';
import '../utils/video_player_navigation.dart';
/// Result of loading adjacent episodes
class AdjacentEpisodes {
final PlexMetadata? next;
final PlexMetadata? previous;
AdjacentEpisodes({this.next, this.previous});
bool get hasNext => next != null;
bool get hasPrevious => previous != null;
}
/// Manages episode navigation for TV show playback.
///
/// Handles:
/// - Loading next/previous episodes from play queues
/// - Navigating between episodes while preserving track selections
/// - Supporting both sequential and shuffle playback modes
///
/// All episode navigation uses Plex play queues for consistent behavior.
class EpisodeNavigationService {
/// Load the next and previous episodes for the current episode
///
/// Returns null for episodes if:
/// - Not applicable (e.g., movie content)
/// - Next episode doesn't exist (end of season/series)
/// - Previous episode doesn't exist (first episode)
Future<AdjacentEpisodes> loadAdjacentEpisodes({
required BuildContext context,
required PlexClient client,
required PlexMetadata metadata,
}) async {
try {
final playbackState = context.read<PlaybackStateProvider>();
// All episode navigation now uses play queues (sequential, shuffle, playlists)
// If no queue is active, navigation is not available
if (!playbackState.isQueueActive) {
return AdjacentEpisodes();
}
// Use the play queue for next/previous navigation
final next = await playbackState.getNextEpisode(
metadata.ratingKey,
loopQueue: false,
);
final previous = await playbackState.getPreviousEpisode(
metadata.ratingKey,
);
final mode = playbackState.isShuffleActive ? 'Shuffle' : 'Sequential';
appLogger.d(
'$mode mode - Next: ${next?.title}, Previous: ${previous?.title}',
);
return AdjacentEpisodes(next: next, previous: previous);
} catch (e) {
// Non-critical: Failed to load next/previous episode metadata
appLogger.d('Could not load adjacent episodes', error: e);
return AdjacentEpisodes();
}
}
/// Navigate to the next or previous episode
///
/// Preserves the current audio track, subtitle track, and playback rate
/// selections when transitioning between episodes.
Future<void> navigateToEpisode({
required BuildContext context,
required PlexMetadata episode,
required Player? player,
bool usePushReplacement = true,
}) async {
if (!context.mounted) return;
// Capture current player state before navigation
AudioTrack? currentAudioTrack;
SubtitleTrack? currentSubtitleTrack;
double? currentPlaybackRate;
if (player != null) {
currentAudioTrack = player.state.track.audio;
currentSubtitleTrack = player.state.track.subtitle;
currentPlaybackRate = player.state.rate;
appLogger.d(
'Navigating to episode with preserved settings - Audio: ${currentAudioTrack.id}, Subtitle: ${currentSubtitleTrack.id}, Rate: ${currentPlaybackRate}x',
);
}
// Navigate to the new episode
if (context.mounted) {
navigateToVideoPlayer(
context,
metadata: episode,
preferredAudioTrack: currentAudioTrack,
preferredSubtitleTrack: currentSubtitleTrack,
preferredPlaybackRate: currentPlaybackRate,
usePushReplacement: usePushReplacement,
);
}
}
}
+5 -19
View File
@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import 'settings_service.dart';
import '../utils/player_utils.dart';
class KeyboardShortcutsService {
static KeyboardShortcutsService? _instance;
@@ -230,21 +231,6 @@ class KeyboardShortcutsService {
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,
@@ -270,16 +256,16 @@ class KeyboardShortcutsService {
_settingsService.setVolume(newVolume);
break;
case 'seek_forward':
_seekWithClamping(player, Duration(seconds: _seekTimeSmall));
seekWithClamping(player, Duration(seconds: _seekTimeSmall));
break;
case 'seek_backward':
_seekWithClamping(player, Duration(seconds: -_seekTimeSmall));
seekWithClamping(player, Duration(seconds: -_seekTimeSmall));
break;
case 'seek_forward_large':
_seekWithClamping(player, Duration(seconds: _seekTimeLarge));
seekWithClamping(player, Duration(seconds: _seekTimeLarge));
break;
case 'seek_backward_large':
_seekWithClamping(player, Duration(seconds: -_seekTimeLarge));
seekWithClamping(player, Duration(seconds: -_seekTimeLarge));
break;
case 'fullscreen_toggle':
onToggleFullscreen?.call();
+193
View File
@@ -0,0 +1,193 @@
import 'dart:async';
import 'package:os_media_controls/os_media_controls.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../utils/app_logger.dart';
/// Manages OS media controls integration for video playback.
///
/// Handles:
/// - Metadata updates (title, artwork, etc.)
/// - Playback state updates (playing/paused, position, speed)
/// - Control event streaming (play, pause, next, previous, seek)
/// - Position update throttling to prevent excessive API calls
class MediaControlsManager {
/// Stream of control events from OS media controls
Stream<dynamic> get controlEvents => OsMediaControls.controlEvents;
/// Last time position was updated (for throttling)
DateTime? _lastPositionUpdate;
/// Throttle interval for position updates (default: 1 second)
final Duration throttleInterval;
MediaControlsManager({this.throttleInterval = const Duration(seconds: 1)});
/// Update media metadata displayed in OS media controls
///
/// This includes title, artist, artwork, and duration.
Future<void> updateMetadata({
required PlexMetadata metadata,
PlexClient? client,
Duration? duration,
}) async {
try {
// Build artwork URL if client is available
String? artworkUrl;
if (client != null && metadata.thumb != null) {
try {
artworkUrl = client.getThumbnailUrl(metadata.thumb!);
appLogger.d('Artwork URL for media controls: $artworkUrl');
} catch (e) {
appLogger.w('Failed to build artwork URL', error: e);
}
}
// Update OS media controls
await OsMediaControls.setMetadata(
MediaMetadata(
title: metadata.title,
artist: _buildArtist(metadata),
artworkUrl: artworkUrl,
duration: duration,
),
);
appLogger.d('Updated media controls metadata: ${metadata.title}');
} catch (e) {
appLogger.w('Failed to update media controls metadata', error: e);
}
}
/// Update playback state in OS media controls
///
/// Updates the current playing state, position, and playback speed.
/// Position updates are throttled to avoid excessive API calls.
Future<void> updatePlaybackState({
required bool isPlaying,
required Duration position,
required double speed,
bool force = false,
}) async {
try {
// Throttle position updates unless forced
if (!force) {
final now = DateTime.now();
if (_lastPositionUpdate != null) {
final timeSinceLastUpdate = now.difference(_lastPositionUpdate!);
if (timeSinceLastUpdate < throttleInterval) {
return; // Skip this update
}
}
_lastPositionUpdate = now;
}
// Only update if playing (avoid excessive updates when paused)
if (isPlaying) {
await OsMediaControls.setPlaybackState(
MediaPlaybackState(
state: PlaybackState.playing,
position: position,
speed: speed,
),
);
} else {
await OsMediaControls.setPlaybackState(
MediaPlaybackState(
state: PlaybackState.paused,
position: position,
speed: speed,
),
);
}
} catch (e) {
appLogger.w('Failed to update media controls playback state', error: e);
}
}
/// Enable or disable next/previous track controls
///
/// This should be called based on content type and playback mode.
/// For example:
/// - Episodes: Enable both if there are adjacent episodes
/// - Playlist items: Enable based on playlist position
/// - Movies: Usually disabled
Future<void> setControlsEnabled({
bool canGoNext = false,
bool canGoPrevious = false,
}) async {
try {
final controls = <MediaControl>[];
if (canGoPrevious) controls.add(MediaControl.previous);
if (canGoNext) controls.add(MediaControl.next);
if (controls.isNotEmpty) {
await OsMediaControls.enableControls(controls);
appLogger.d(
'Media controls enabled - Previous: $canGoPrevious, Next: $canGoNext',
);
} else {
await OsMediaControls.disableControls([
MediaControl.previous,
MediaControl.next,
]);
appLogger.d('Media controls disabled');
}
} catch (e) {
appLogger.w('Failed to set media controls enabled state', error: e);
}
}
/// Clear all media controls
///
/// Should be called when playback stops or screen is disposed.
Future<void> clear() async {
try {
await OsMediaControls.clear();
_lastPositionUpdate = null;
appLogger.d('Media controls cleared');
} catch (e) {
appLogger.w('Failed to clear media controls', error: e);
}
}
/// Dispose resources
void dispose() {
_lastPositionUpdate = null;
}
/// Build artist string from metadata
///
/// For episodes: "Show Name - Season X Episode Y"
/// For movies: Director or studio
/// For other content: Fallback to year or empty
String _buildArtist(PlexMetadata metadata) {
if (metadata.type.toLowerCase() == 'episode') {
final parts = <String>[];
// Add show name
if (metadata.grandparentTitle != null) {
parts.add(metadata.grandparentTitle!);
}
// Add season/episode info
if (metadata.parentIndex != null && metadata.index != null) {
parts.add('S${metadata.parentIndex} E${metadata.index}');
} else if (metadata.parentTitle != null) {
parts.add(metadata.parentTitle!);
}
return parts.join(' • ');
} else if (metadata.type.toLowerCase() == 'movie') {
// For movies, use director or studio
// Note: These fields may need to be added to PlexMetadata model
if (metadata.year != null) {
return metadata.year.toString();
}
}
return '';
}
}
+459
View File
@@ -0,0 +1,459 @@
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import '../client/plex_client.dart';
import '../config/plex_config.dart';
import '../utils/app_logger.dart';
import 'plex_auth_service.dart';
import 'storage_service.dart';
/// Manages multiple Plex server connections simultaneously
class MultiServerManager {
/// Map of serverId (clientIdentifier) to PlexClient instances
final Map<String, PlexClient> _clients = {};
/// Map of serverId to server info
final Map<String, PlexServer> _servers = {};
/// Map of serverId to online status
final Map<String, bool> _serverStatus = {};
/// Stream controller for server status changes
final _statusController = StreamController<Map<String, bool>>.broadcast();
/// Stream of server status changes
Stream<Map<String, bool>> get statusStream => _statusController.stream;
/// Connectivity subscription for network monitoring
StreamSubscription<List<ConnectivityResult>>? _connectivitySubscription;
/// Map of serverId to active optimization futures
final Map<String, Future<void>> _activeOptimizations = {};
/// Get all registered server IDs
List<String> get serverIds => _servers.keys.toList();
/// Get all online server IDs
List<String> get onlineServerIds =>
_serverStatus.entries.where((e) => e.value).map((e) => e.key).toList();
/// Get all offline server IDs
List<String> get offlineServerIds =>
_serverStatus.entries.where((e) => !e.value).map((e) => e.key).toList();
/// Get client for specific server
PlexClient? getClient(String serverId) => _clients[serverId];
/// Get server info for specific server
PlexServer? getServer(String serverId) => _servers[serverId];
/// Get all online clients
Map<String, PlexClient> get onlineClients {
final result = <String, PlexClient>{};
for (final serverId in onlineServerIds) {
final client = _clients[serverId];
if (client != null) {
result[serverId] = client;
}
}
return result;
}
/// Get all servers
Map<String, PlexServer> get servers => Map.unmodifiable(_servers);
/// Check if a server is online
bool isServerOnline(String serverId) => _serverStatus[serverId] ?? false;
/// Connect to all available servers in parallel
/// Returns the number of successfully connected servers
Future<int> connectToAllServers(
List<PlexServer> servers, {
String? clientIdentifier,
Duration timeout = const Duration(seconds: 10),
Function(String serverId, PlexClient client)? onServerConnected,
Function(String serverId, Object error)? onServerFailed,
}) async {
if (servers.isEmpty) {
appLogger.w('No servers to connect to');
return 0;
}
appLogger.i('Connecting to ${servers.length} servers...');
// Use provided client ID or generate a unique one for this app instance
final effectiveClientId =
clientIdentifier ?? DateTime.now().millisecondsSinceEpoch.toString();
// Create connection tasks for all servers
final connectionFutures = servers.map((server) async {
final serverId = server.clientIdentifier;
try {
appLogger.d('Attempting connection to server: ${server.name}');
// Find best working connection for this server
PlexConnection? workingConnection;
await for (final connection in server.findBestWorkingConnection()) {
workingConnection = connection;
// Use first working connection (could wait for optimal, but that's slower)
break;
}
if (workingConnection == null) {
throw Exception('No working connection found');
}
final baseUrl = workingConnection.uri;
appLogger.d('Connected to ${server.name} at $baseUrl');
// Get storage and load cached endpoint for this server
final storage = await StorageService.getInstance();
final cachedEndpoint = storage.getServerEndpoint(serverId);
// Create PlexClient with the working connection and failover support
final prioritizedEndpoints = server.prioritizedEndpointUrls(
preferredFirst: cachedEndpoint ?? baseUrl,
);
final config = await PlexConfig.create(
baseUrl: baseUrl,
token: server.accessToken,
clientIdentifier: effectiveClientId,
);
final client = PlexClient(
config,
serverId: serverId,
serverName: server.name,
prioritizedEndpoints: prioritizedEndpoints,
onEndpointChanged: (newUrl) async {
await storage.saveServerEndpoint(serverId, newUrl);
appLogger.i(
'Updated endpoint for ${server.name} after failover: $newUrl',
);
},
);
// Save the initial endpoint
await storage.saveServerEndpoint(serverId, baseUrl);
// Store the client and server info
_clients[serverId] = client;
_servers[serverId] = server;
_serverStatus[serverId] = true;
onServerConnected?.call(serverId, client);
appLogger.i('Successfully connected to ${server.name}');
return serverId;
} catch (e, stackTrace) {
appLogger.e(
'Failed to connect to ${server.name}',
error: e,
stackTrace: stackTrace,
);
// Mark as offline
_servers[serverId] = server;
_serverStatus[serverId] = false;
onServerFailed?.call(serverId, e);
return null;
}
});
// Wait for all connections with timeout
final results = await Future.wait(
connectionFutures.map(
(f) => f.timeout(
timeout,
onTimeout: () {
appLogger.w('Server connection timed out');
return null;
},
),
),
);
// Count successful connections
final successCount = results.where((id) => id != null).length;
// Notify listeners of status change
_statusController.add(Map.from(_serverStatus));
appLogger.i(
'Connected to $successCount/${servers.length} servers successfully',
);
// Start network monitoring if we have any connected servers
if (successCount > 0) {
startNetworkMonitoring();
}
return successCount;
}
/// Add a single server connection
Future<bool> addServer(PlexServer server, {String? clientIdentifier}) async {
final serverId = server.clientIdentifier;
final effectiveClientId =
clientIdentifier ?? DateTime.now().millisecondsSinceEpoch.toString();
try {
appLogger.d('Adding server: ${server.name}');
// Find best working connection
PlexConnection? workingConnection;
await for (final connection in server.findBestWorkingConnection()) {
workingConnection = connection;
break;
}
if (workingConnection == null) {
throw Exception('No working connection found');
}
final baseUrl = workingConnection.uri;
// Get storage and load cached endpoint for this server
final storage = await StorageService.getInstance();
final cachedEndpoint = storage.getServerEndpoint(serverId);
// Create PlexClient with failover support
final prioritizedEndpoints = server.prioritizedEndpointUrls(
preferredFirst: cachedEndpoint ?? baseUrl,
);
final config = await PlexConfig.create(
baseUrl: baseUrl,
token: server.accessToken,
clientIdentifier: effectiveClientId,
);
final client = PlexClient(
config,
serverId: serverId,
serverName: server.name,
prioritizedEndpoints: prioritizedEndpoints,
onEndpointChanged: (newUrl) async {
await storage.saveServerEndpoint(serverId, newUrl);
appLogger.i(
'Updated endpoint for ${server.name} after failover: $newUrl',
);
},
);
// Save the initial endpoint
await storage.saveServerEndpoint(serverId, baseUrl);
// Store
_clients[serverId] = client;
_servers[serverId] = server;
_serverStatus[serverId] = true;
// Notify
_statusController.add(Map.from(_serverStatus));
appLogger.i('Successfully added server: ${server.name}');
return true;
} catch (e, stackTrace) {
appLogger.e(
'Failed to add server ${server.name}',
error: e,
stackTrace: stackTrace,
);
_servers[serverId] = server;
_serverStatus[serverId] = false;
_statusController.add(Map.from(_serverStatus));
return false;
}
}
/// Remove a server connection
void removeServer(String serverId) {
_clients.remove(serverId);
_servers.remove(serverId);
_serverStatus.remove(serverId);
_statusController.add(Map.from(_serverStatus));
appLogger.i('Removed server: $serverId');
}
/// Update server status (used for health monitoring)
void updateServerStatus(String serverId, bool isOnline) {
if (_serverStatus[serverId] != isOnline) {
_serverStatus[serverId] = isOnline;
_statusController.add(Map.from(_serverStatus));
appLogger.d('Server $serverId status changed to: $isOnline');
}
}
/// Test connection health for all servers
Future<void> checkServerHealth() async {
appLogger.d('Checking health for ${_clients.length} servers');
final healthChecks = _clients.entries.map((entry) async {
final serverId = entry.key;
final client = entry.value;
try {
// Simple ping by fetching server identity
await client.getServerIdentity();
updateServerStatus(serverId, true);
} catch (e) {
appLogger.w('Server $serverId health check failed: $e');
updateServerStatus(serverId, false);
}
});
await Future.wait(healthChecks);
}
/// Start monitoring network connectivity for all servers
void startNetworkMonitoring() {
if (_connectivitySubscription != null) {
appLogger.d('Network monitoring already active');
return;
}
appLogger.i('Starting network monitoring for all servers');
final connectivity = Connectivity();
_connectivitySubscription = connectivity.onConnectivityChanged.listen(
(results) {
final status = results.isNotEmpty
? results.first
: ConnectivityResult.none;
if (status == ConnectivityResult.none) {
appLogger.w(
'Connectivity lost, pausing optimization until network returns',
);
return;
}
appLogger.d(
'Connectivity change detected, re-optimizing all servers',
error: {
'status': status.name,
'interfaces': results.map((r) => r.name).toList(),
'serverCount': _servers.length,
},
);
// Re-optimize all servers
_reoptimizeAllServers(reason: 'connectivity:${status.name}');
},
onError: (error, stackTrace) {
appLogger.w(
'Connectivity listener error',
error: error,
stackTrace: stackTrace,
);
},
);
}
/// Stop monitoring network connectivity
void stopNetworkMonitoring() {
_connectivitySubscription?.cancel();
_connectivitySubscription = null;
appLogger.i('Stopped network monitoring');
}
/// Re-optimize all connected servers
void _reoptimizeAllServers({required String reason}) {
for (final entry in _servers.entries) {
final serverId = entry.key;
final server = entry.value;
// Skip if server is offline
if (!isServerOnline(serverId)) {
continue;
}
// Skip if optimization already running for this server
if (_activeOptimizations.containsKey(serverId)) {
appLogger.d(
'Optimization already running for ${server.name}, skipping',
error: {'reason': reason},
);
continue;
}
// Run optimization
_activeOptimizations[serverId] =
_reoptimizeServer(
serverId: serverId,
server: server,
reason: reason,
).whenComplete(() {
_activeOptimizations.remove(serverId);
});
}
}
/// Re-optimize connection for a specific server
Future<void> _reoptimizeServer({
required String serverId,
required PlexServer server,
required String reason,
}) async {
final storage = await StorageService.getInstance();
final client = _clients[serverId];
try {
appLogger.d(
'Starting connection optimization for ${server.name}',
error: {'reason': reason},
);
await for (final connection in server.findBestWorkingConnection()) {
final newUrl = connection.uri;
// Check if this is actually a better connection than current
if (client != null && client.config.baseUrl == newUrl) {
appLogger.d(
'Already using optimal endpoint for ${server.name}: $newUrl',
);
continue;
}
// Save the new endpoint
await storage.saveServerEndpoint(serverId, newUrl);
// If client has endpoint failover, it will automatically switch
// Otherwise, we might need to recreate the client (but failover should handle it)
appLogger.i(
'Updated optimal endpoint for ${server.name}: $newUrl',
error: {'type': connection.displayType},
);
}
} catch (e, stackTrace) {
appLogger.w(
'Connection optimization failed for ${server.name}',
error: e,
stackTrace: stackTrace,
);
}
}
/// Disconnect all servers
void disconnectAll() {
appLogger.i('Disconnecting all servers');
stopNetworkMonitoring();
_clients.clear();
_servers.clear();
_serverStatus.clear();
_activeOptimizations.clear();
_statusController.add({});
}
/// Dispose resources
void dispose() {
disconnectAll();
_statusController.close();
}
}
@@ -0,0 +1,214 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../client/plex_client.dart';
import '../models/plex_media_info.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../utils/app_logger.dart';
import '../i18n/strings.g.dart';
import 'track_selection_service.dart';
/// Service responsible for initializing video playback
///
/// Handles the complex process of:
/// 1. Fetching video playback data from the Plex server
/// 2. Building external subtitle tracks
/// 3. Opening media in the player
/// 4. Adding external subtitles to the player
/// 5. Selecting and applying audio/subtitle tracks
/// 6. Seeking to resume position
/// 7. Starting playback
class PlaybackInitializationService {
final Player player;
final PlexClient client;
final BuildContext context;
PlaybackInitializationService({
required this.player,
required this.client,
required this.context,
});
/// Start playback for the given metadata
///
/// Returns a PlaybackInitializationResult with available versions and other data
Future<PlaybackInitializationResult> startPlayback({
required PlexMetadata metadata,
required int selectedMediaIndex,
required PlexUserProfile? profileSettings,
AudioTrack? preferredAudioTrack,
SubtitleTrack? preferredSubtitleTrack,
double? preferredPlaybackRate,
}) async {
try {
// Get consolidated playback data (URL, media info, and versions) in a single API call
final playbackData = await client.getVideoPlaybackData(
metadata.ratingKey,
mediaIndex: selectedMediaIndex,
);
if (!playbackData.hasValidVideoUrl) {
throw PlaybackException(t.messages.fileInfoNotAvailable);
}
final videoUrl = playbackData.videoUrl!;
final mediaInfo = playbackData.mediaInfo;
// Build list of external subtitle tracks for media_kit
final externalSubtitles = _buildExternalSubtitles(mediaInfo);
// Open video (without external subtitles in Media constructor)
await player.open(Media(videoUrl), play: false);
// Wait for media to be ready (duration > 0)
await _waitForMediaReady();
// Add external subtitle tracks without auto-selecting them
if (externalSubtitles.isNotEmpty) {
await _addExternalSubtitles(externalSubtitles);
}
// Select and apply tracks BEFORE seeking to resume position
// This prevents track changes from resetting the playback position on Android
final trackSelectionService = TrackSelectionService(
player: player,
profileSettings: profileSettings,
metadata: metadata,
);
await trackSelectionService.selectAndApplyTracks(
preferredAudioTrack: preferredAudioTrack,
preferredSubtitleTrack: preferredSubtitleTrack,
preferredPlaybackRate: preferredPlaybackRate,
);
// Set up playback position if resuming (AFTER track selection)
if (metadata.viewOffset != null && metadata.viewOffset! > 0) {
appLogger.d('Resuming playback at ${metadata.viewOffset} ms');
final resumePosition = Duration(milliseconds: metadata.viewOffset!);
await player.seek(resumePosition);
}
// Start playback after seeking
await player.play();
// Return result with available versions for UI updates
return PlaybackInitializationResult(
availableVersions: playbackData.availableVersions,
);
} catch (e) {
if (e is PlaybackException) {
rethrow;
}
throw PlaybackException(t.messages.errorLoading(error: e.toString()));
}
}
/// Build list of external subtitle tracks from media info
List<SubtitleTrack> _buildExternalSubtitles(PlexMediaInfo? mediaInfo) {
final externalSubtitles = <SubtitleTrack>[];
if (mediaInfo == null) {
return externalSubtitles;
}
final externalTracks = mediaInfo.subtitleTracks
.where((PlexSubtitleTrack track) => track.isExternal)
.toList();
if (externalTracks.isNotEmpty) {
appLogger.d('Found ${externalTracks.length} external subtitle track(s)');
}
for (final plexTrack in externalTracks) {
try {
// Skip if no auth token is available
final token = client.config.token;
if (token == null) {
appLogger.w('No auth token available for external subtitles');
continue;
}
final url = plexTrack.getSubtitleUrl(client.config.baseUrl, token);
// Skip if URL couldn't be constructed
if (url == null) continue;
externalSubtitles.add(
SubtitleTrack.uri(
url,
title:
plexTrack.displayTitle ??
plexTrack.language ??
'Track ${plexTrack.id}',
language: plexTrack.languageCode,
),
);
} catch (e) {
// Silent fallback - log error but continue with other subtitles
appLogger.w(
'Failed to add external subtitle track ${plexTrack.id}',
error: e,
);
}
}
return externalSubtitles;
}
/// Wait for media to be ready (duration > 0)
Future<void> _waitForMediaReady() async {
int attempts = 0;
while (player.state.duration.inMilliseconds == 0 && attempts < 100) {
await Future.delayed(const Duration(milliseconds: 100));
attempts++;
}
}
/// Add external subtitle tracks to the player without auto-selecting them
Future<void> _addExternalSubtitles(
List<SubtitleTrack> externalSubtitles,
) async {
appLogger.d(
'Adding ${externalSubtitles.length} external subtitle(s) to player',
);
final nativePlayer = player.platform as dynamic;
for (final subtitleTrack in externalSubtitles) {
try {
// Use mpv's sub-add with 'auto' flag to avoid auto-selection
await nativePlayer.command([
'sub-add',
subtitleTrack.id,
'auto',
subtitleTrack.title ?? 'external',
subtitleTrack.language ?? 'auto',
]);
} catch (e) {
appLogger.w(
'Failed to add external subtitle: ${subtitleTrack.title}',
error: e,
);
}
}
}
}
/// Result of playback initialization
class PlaybackInitializationResult {
final List<dynamic> availableVersions;
PlaybackInitializationResult({required this.availableVersions});
}
/// Exception thrown when playback initialization fails
class PlaybackException implements Exception {
final String message;
PlaybackException(this.message);
@override
String toString() => message;
}
+121
View File
@@ -0,0 +1,121 @@
import 'dart:async';
import 'package:media_kit/media_kit.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../utils/app_logger.dart';
/// Tracks playback progress and reports it to the Plex server.
///
/// Handles:
/// - Periodic timeline updates during playback
/// - Resume position tracking
/// - State change reporting (playing, paused, stopped)
class PlaybackProgressTracker {
final PlexClient client;
final PlexMetadata metadata;
final Player player;
/// Timer for periodic progress updates
Timer? _progressTimer;
/// Update interval (default: 10 seconds)
final Duration updateInterval;
PlaybackProgressTracker({
required this.client,
required this.metadata,
required this.player,
this.updateInterval = const Duration(seconds: 10),
});
/// Start tracking playback progress
///
/// Begins periodic timeline updates to the Plex server.
void startTracking() {
if (_progressTimer != null) {
appLogger.w('Progress tracking already started');
return;
}
_progressTimer = Timer.periodic(updateInterval, (timer) {
if (player.state.playing) {
_sendProgress('playing');
}
});
appLogger.d(
'Started progress tracking (interval: ${updateInterval.inSeconds}s)',
);
}
/// Stop tracking playback progress
///
/// Cancels the periodic timer.
void stopTracking() {
_progressTimer?.cancel();
_progressTimer = null;
appLogger.d('Stopped progress tracking');
}
/// Send progress update to Plex server
///
/// [state] can be 'playing', 'paused', or 'stopped'
Future<void> sendProgress(String state) async {
await _sendProgress(state);
}
Future<void> _sendProgress(String state) async {
try {
final position = player.state.position;
final duration = player.state.duration;
// Don't send progress if no duration (not ready)
if (duration.inMilliseconds == 0) {
return;
}
// Build timeline query parameters
final queryParams = {
'ratingKey': metadata.ratingKey,
'key': '/library/metadata/${metadata.ratingKey}',
'state': state,
'time': position.inMilliseconds.toString(),
'duration': duration.inMilliseconds.toString(),
};
// Add playQueueItemID if available (for playlist/shuffle playback)
if (metadata.playQueueItemID != null) {
queryParams['playQueueItemID'] = metadata.playQueueItemID.toString();
}
// Send timeline update
await client
.updateProgress(
metadata.ratingKey,
time: position.inMilliseconds,
state: state,
duration: duration.inMilliseconds,
)
.catchError((error) {
// Silent handling - don't interrupt playback for progress errors
appLogger.d(
'Failed to update progress (non-critical)',
error: error,
);
});
appLogger.d(
'Progress update sent: $state at ${position.inSeconds}s / ${duration.inSeconds}s',
);
} catch (e) {
appLogger.d('Failed to send progress update (non-critical)', error: e);
}
}
/// Dispose resources
void dispose() {
stopTracking();
}
}
+10 -1
View File
@@ -645,7 +645,16 @@ class PlexServer {
}
for (final connection in connections) {
addCandidate(connection, connection.httpDirectUrl, false, false);
// First, try the actual connection URI (may be HTTPS plex.direct)
final isPlexDirect = connection.uri.contains('.plex.direct');
final isHttps = connection.protocol == 'https';
addCandidate(connection, connection.uri, isPlexDirect, isHttps);
// For HTTPS connections, also add HTTP direct IP as fallback
// This provides backward compatibility and fallback for cert issues
if (isHttps) {
addCandidate(connection, connection.httpDirectUrl, false, false);
}
}
return [
-346
View File
@@ -1,346 +0,0 @@
import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
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 {
static StreamSubscription<List<ConnectivityResult>>?
_connectivitySubscription;
static Future<void>? _activeOptimization;
static PlexServer? _activeServer;
static PlexClient? _activeClient;
/// 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 {
final storage = await StorageService.getInstance();
final connectionStream = server
.findBestWorkingConnection()
.asBroadcastStream();
PlexClient? client;
final optimizationSubscription = connectionStream
.skip(1)
.listen(
(connection) async {
await _handleOptimizedConnection(
connection: connection,
storage: storage,
server: server,
client: client,
reason: 'initial_latency_sweep',
);
},
onError: (error, stackTrace) {
appLogger.w(
'Background connection optimization error',
error: error,
stackTrace: stackTrace,
);
},
);
try {
final connection = await connectionStream.first;
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 prioritizedEndpoints = server.prioritizedEndpointUrls(
preferredFirst: connection.uri,
);
final config = await PlexConfig.create(
baseUrl: connection.uri,
token: server.accessToken,
clientIdentifier: clientIdentifier,
);
client = PlexClient(
config,
prioritizedEndpoints: prioritizedEndpoints,
onEndpointChanged: (newUrl) async {
await storage.saveServerUrl(newUrl);
appLogger.i(
'Updated stored server URL after failover',
error: newUrl,
);
},
);
// Fetch machine identifier and cache it in config
try {
final machineId = await client.getMachineIdentifier();
if (machineId != null) {
client.config = config.copyWith(machineIdentifier: machineId);
appLogger.d('Cached machine identifier: $machineId');
}
} catch (e) {
appLogger.w('Failed to fetch machine identifier', error: e);
// Continue without it - buildMetadataUri will fallback to fetching it
}
// Verify server is accessible if requested
if (verifyServer) {
try {
await client.getServerIdentity();
} catch (e) {
await optimizationSubscription.cancel();
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 while optimization continues in background
_activeServer = server;
_activeClient = client;
_startConnectivityMonitoring(server);
return ServerConnectionResult(client: client, userProfile: userProfile);
} on StateError catch (e, stackTrace) {
await optimizationSubscription.cancel();
appLogger.e(
'No working connections found for this server',
error: e,
stackTrace: stackTrace,
);
return ServerConnectionResult(
error: 'No working connections found for this server',
);
} catch (e, stackTrace) {
await optimizationSubscription.cancel();
appLogger.e(
'Error connecting to server',
error: e,
stackTrace: stackTrace,
);
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;
}
}
static void _startConnectivityMonitoring(PlexServer server) {
_connectivitySubscription?.cancel();
final connectivity = Connectivity();
_connectivitySubscription = connectivity.onConnectivityChanged.listen(
(results) {
final status = results.isNotEmpty
? results.first
: ConnectivityResult.none;
if (status == ConnectivityResult.none) {
appLogger.w(
'Connectivity lost, pausing optimization until network returns',
);
return;
}
appLogger.d(
'Connectivity change detected, triggering endpoint optimization',
error: {
'status': status.name,
'interfaces': results.map((r) => r.name).toList(),
},
);
_activeServer = server;
_triggerReoptimization(reason: 'connectivity:${status.name}');
},
onError: (error, stackTrace) {
appLogger.w(
'Connectivity listener error',
error: error,
stackTrace: stackTrace,
);
},
);
}
static void _triggerReoptimization({required String reason}) {
if (_activeServer == null) {
appLogger.d(
'Optimization trigger ignored because there is no active server',
error: {'reason': reason},
);
return;
}
if (_activeOptimization != null) {
appLogger.d(
'Optimization already running, skipping new trigger',
error: {'reason': reason},
);
return;
}
_activeOptimization =
_runOptimization(
server: _activeServer!,
client: _activeClient,
reason: reason,
).whenComplete(() {
_activeOptimization = null;
});
}
static Future<void> _runOptimization({
required PlexServer server,
required PlexClient? client,
required String reason,
}) async {
final storage = await StorageService.getInstance();
try {
appLogger.d(
'Starting background connection optimization run',
error: {'reason': reason},
);
await for (final connection in server.findBestWorkingConnection()) {
await _handleOptimizedConnection(
connection: connection,
storage: storage,
server: server,
client: client,
reason: reason,
);
}
} catch (e, stackTrace) {
appLogger.w(
'Background connection optimization failed',
error: e,
stackTrace: stackTrace,
);
}
}
static Future<void> _handleOptimizedConnection({
required PlexConnection connection,
required StorageService storage,
required PlexServer server,
required PlexClient? client,
required String reason,
}) async {
final previousUrl = storage.getServerUrl();
final isNewEndpoint = previousUrl != connection.uri;
await storage.saveServerUrl(connection.uri);
appLogger.d(
'Evaluated optimized endpoint candidate',
error: {
'uri': connection.uri,
'displayType': connection.displayType,
'reason': reason,
'isNewEndpoint': isNewEndpoint,
},
);
if (client != null) {
final prioritizedEndpoints = server.prioritizedEndpointUrls(
preferredFirst: connection.uri,
);
await client.updateEndpointPreferences(
prioritizedEndpoints,
switchToFirst: isNewEndpoint,
);
if (isNewEndpoint) {
appLogger.i(
'Active client switched to optimized endpoint',
error: {'uri': connection.uri, 'reason': reason},
);
}
} else if (isNewEndpoint) {
appLogger.i(
'Stored optimized endpoint for future sessions',
error: {'uri': connection.uri, 'reason': reason},
);
}
if (isNewEndpoint && !connection.uri.startsWith('https://')) {
final upgraded = await server.upgradeConnectionToHttps(connection);
if (upgraded != null && upgraded.uri != connection.uri) {
await _handleOptimizedConnection(
connection: upgraded,
storage: storage,
server: server,
client: client,
reason: '$reason:https-upgrade',
);
}
}
}
}
+239
View File
@@ -0,0 +1,239 @@
import 'dart:convert';
import '../utils/app_logger.dart';
import 'plex_auth_service.dart';
import 'storage_service.dart';
/// Centralized server configuration registry
/// Manages which servers are available, enabled/disabled, and their configurations
class ServerRegistry {
final StorageService _storage;
ServerRegistry(this._storage);
/// Get all registered servers
Future<List<PlexServer>> getServers() async {
try {
final serversJson = _storage.getServersListJson();
if (serversJson == null || serversJson.isEmpty) {
return [];
}
final List<dynamic> serversList = jsonDecode(serversJson);
return serversList
.map((json) => PlexServer.fromJson(json as Map<String, dynamic>))
.toList();
} catch (e, stackTrace) {
appLogger.e(
'Failed to load servers from storage',
error: e,
stackTrace: stackTrace,
);
return [];
}
}
/// Save all servers to storage
Future<void> saveServers(List<PlexServer> servers) async {
try {
final serversJson = jsonEncode(servers.map((s) => s.toJson()).toList());
await _storage.saveServersListJson(serversJson);
appLogger.d('Saved ${servers.length} servers to storage');
} catch (e, stackTrace) {
appLogger.e(
'Failed to save servers to storage',
error: e,
stackTrace: stackTrace,
);
rethrow;
}
}
/// Get enabled server IDs
Future<Set<String>> getEnabledServerIds() async {
try {
final enabledJson = _storage.getEnabledServersJson();
if (enabledJson == null || enabledJson.isEmpty) {
// If no enabled servers are stored, all servers are enabled by default
final servers = await getServers();
return servers.map((s) => s.clientIdentifier).toSet();
}
final List<dynamic> enabledList = jsonDecode(enabledJson);
return enabledList.cast<String>().toSet();
} catch (e, stackTrace) {
appLogger.e(
'Failed to load enabled servers from storage',
error: e,
stackTrace: stackTrace,
);
return {};
}
}
/// Save enabled server IDs
Future<void> saveEnabledServerIds(Set<String> serverIds) async {
try {
final enabledJson = jsonEncode(serverIds.toList());
await _storage.saveEnabledServersJson(enabledJson);
appLogger.d('Saved ${serverIds.length} enabled servers to storage');
} catch (e, stackTrace) {
appLogger.e(
'Failed to save enabled servers to storage',
error: e,
stackTrace: stackTrace,
);
rethrow;
}
}
/// Get only enabled servers
Future<List<PlexServer>> getEnabledServers() async {
final servers = await getServers();
final enabledIds = await getEnabledServerIds();
if (enabledIds.isEmpty) {
// If no enabled list, all servers are enabled
return servers;
}
return servers
.where((s) => enabledIds.contains(s.clientIdentifier))
.toList();
}
/// Enable a server
Future<void> enableServer(String serverId) async {
final enabledIds = await getEnabledServerIds();
enabledIds.add(serverId);
await saveEnabledServerIds(enabledIds);
appLogger.i('Enabled server: $serverId');
}
/// Disable a server
Future<void> disableServer(String serverId) async {
final enabledIds = await getEnabledServerIds();
enabledIds.remove(serverId);
await saveEnabledServerIds(enabledIds);
appLogger.i('Disabled server: $serverId');
}
/// Check if a server is enabled
Future<bool> isServerEnabled(String serverId) async {
final enabledIds = await getEnabledServerIds();
return enabledIds.contains(serverId);
}
/// Get a specific server by ID
Future<PlexServer?> getServer(String serverId) async {
final servers = await getServers();
try {
return servers.firstWhere((s) => s.clientIdentifier == serverId);
} catch (e) {
return null;
}
}
/// Update server status (called when server connection status changes)
Future<void> updateServerStatus(
String serverId, {
bool? online,
DateTime? lastSeen,
}) async {
final servers = await getServers();
final serverIndex = servers.indexWhere(
(s) => s.clientIdentifier == serverId,
);
if (serverIndex == -1) {
appLogger.w('Server not found for status update: $serverId');
return;
}
// Note: PlexServer from auth service doesn't have mutable status fields
// Status tracking is handled by MultiServerManager
// This method is kept for future extension if we add status to PlexServer model
}
/// Add or update a single server
Future<void> upsertServer(PlexServer server) async {
final servers = await getServers();
final index = servers.indexWhere(
(s) => s.clientIdentifier == server.clientIdentifier,
);
if (index >= 0) {
servers[index] = server;
appLogger.d('Updated server: ${server.name}');
} else {
servers.add(server);
appLogger.d('Added new server: ${server.name}');
}
await saveServers(servers);
// Ensure new servers are enabled by default
if (index < 0) {
await enableServer(server.clientIdentifier);
}
}
/// Remove a server
Future<void> removeServer(String serverId) async {
final servers = await getServers();
servers.removeWhere((s) => s.clientIdentifier == serverId);
await saveServers(servers);
// Also remove from enabled list
final enabledIds = await getEnabledServerIds();
enabledIds.remove(serverId);
await saveEnabledServerIds(enabledIds);
appLogger.i('Removed server: $serverId');
}
/// Clear all servers
Future<void> clearAllServers() async {
await _storage.clearServersList();
await _storage.clearEnabledServers();
appLogger.i('Cleared all servers from registry');
}
/// Migrate from single server storage to multi-server
/// This is called during app startup to migrate existing users
Future<void> migrateFromSingleServer() async {
try {
// Check if we already have servers in the new format
final existingServers = await getServers();
if (existingServers.isNotEmpty) {
appLogger.d('Servers already migrated, skipping migration');
return;
}
// Try to load old single-server data
final oldServerData = _storage.getServerData();
if (oldServerData == null) {
appLogger.d('No old server data to migrate');
return;
}
// Parse and migrate
final server = PlexServer.fromJson(oldServerData);
appLogger.i('Migrating single server to multi-server: ${server.name}');
// Save as first server in new format
await saveServers([server]);
await enableServer(server.clientIdentifier);
appLogger.i('Migration complete');
} catch (e, stackTrace) {
appLogger.e(
'Failed to migrate from single server',
error: e,
stackTrace: stackTrace,
);
// Don't rethrow - migration failure shouldn't crash the app
}
}
}
+7 -37
View File
@@ -39,9 +39,6 @@ class SettingsService {
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 const String _keyAppLocale = 'app_locale';
static const String _keyRememberTrackSelections = 'remember_track_selections';
@@ -777,9 +774,14 @@ class SettingsService {
final jsonString = _prefs.getString(_keyMediaVersionPreferences);
if (jsonString == null) return {};
final decoded = _decodeJsonStringToMap(jsonString);
return decoded.map((key, value) => MapEntry(key, value as int));
}
/// Helper to decode JSON string to Map with error handling
Map<String, dynamic> _decodeJsonStringToMap(String jsonString) {
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
return decoded.map((key, value) => MapEntry(key, value as int));
return json.decode(jsonString) as Map<String, dynamic>;
} catch (e) {
return {};
}
@@ -800,35 +802,6 @@ class SettingsService {
);
}
// 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
}
// Track Selection Settings
/// Remember Track Selections - Save per-media audio/subtitle language preferences
@@ -868,9 +841,6 @@ class SettingsService {
_prefs.remove(_keySubtitleBorderColor),
_prefs.remove(_keySubtitleBackgroundColor),
_prefs.remove(_keySubtitleBackgroundOpacity),
_prefs.remove(_keyShuffleUnwatchedOnly),
_prefs.remove(_keyShuffleOrderNavigation),
_prefs.remove(_keyShuffleLoopQueue),
_prefs.remove(_keyAppLocale),
_prefs.remove(_keyRememberTrackSelections),
]);
+132 -44
View File
@@ -19,6 +19,9 @@ class StorageService {
static const String _keyHomeUsersCache = 'home_users_cache';
static const String _keyHomeUsersCacheExpiry = 'home_users_cache_expiry';
static const String _keyHiddenLibraries = 'hidden_libraries';
static const String _keyServersList = 'servers_list';
static const String _keyEnabledServers = 'enabled_servers';
static const String _keyServerOrder = 'server_order';
static StorageService? _instance;
late SharedPreferences _prefs;
@@ -51,6 +54,20 @@ class StorageService {
return _prefs.getString(_keyServerUrl);
}
// Per-Server Endpoint URL (for multi-server connection caching)
Future<void> saveServerEndpoint(String serverId, String url) async {
await _prefs.setString('server_endpoint_$serverId', url);
LogRedactionManager.registerServerUrl(url);
}
String? getServerEndpoint(String serverId) {
return _prefs.getString('server_endpoint_$serverId');
}
Future<void> clearServerEndpoint(String serverId) async {
await _prefs.remove('server_endpoint_$serverId');
}
// Server Access Token
Future<void> saveToken(String token) async {
await _prefs.setString(_keyToken, token);
@@ -87,14 +104,7 @@ class StorageService {
}
Map<String, dynamic>? getServerData() {
final jsonString = _prefs.getString(_keyServerData);
if (jsonString == null) return null;
try {
return json.decode(jsonString) as Map<String, dynamic>;
} catch (e) {
return null;
}
return _readJsonMap(_keyServerData);
}
// Client Identifier
@@ -136,6 +146,7 @@ class StorageService {
_prefs.remove(_keyCurrentUserUUID),
_prefs.remove(_keyHomeUsersCache),
_prefs.remove(_keyHomeUsersCacheExpiry),
clearMultiServerData(),
]);
LogRedactionManager.clearTrackedValues();
}
@@ -149,11 +160,6 @@ class StorageService {
};
}
// Selected Library Index (deprecated - use library key instead)
Future<void> saveSelectedLibraryIndex(int index) async {
await _prefs.setInt(_keySelectedLibraryIndex, index);
}
int? getSelectedLibraryIndex() {
return _prefs.getInt(_keySelectedLibraryIndex);
}
@@ -191,12 +197,8 @@ class StorageService {
_prefs.getString(_keyLibraryFilters);
if (jsonString == null) return {};
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
return decoded.map((key, value) => MapEntry(key, value.toString()));
} catch (e) {
return {};
}
final decoded = _decodeJsonStringToMap(jsonString);
return decoded.map((key, value) => MapEntry(key, value.toString()));
}
// Library Sort (per-library, stored individually with descending flag)
@@ -210,15 +212,7 @@ class StorageService {
}
Map<String, dynamic>? getLibrarySort(String sectionId) {
final jsonString = _prefs.getString('library_sort_$sectionId');
if (jsonString == null) return null;
try {
return json.decode(jsonString) as Map<String, dynamic>;
} catch (e) {
// Legacy support: if it's just a string, return it as the key
return {'key': jsonString, 'descending': false};
}
return _readJsonMap('library_sort_$sectionId', legacyStringOk: true);
}
// Library Grouping (per-library, e.g., 'movies', 'shows', 'seasons', 'episodes')
@@ -298,14 +292,7 @@ class StorageService {
}
Map<String, dynamic>? getUserProfile() {
final jsonString = _prefs.getString(_keyUserProfile);
if (jsonString == null) return null;
try {
return json.decode(jsonString) as Map<String, dynamic>;
} catch (e) {
return null;
}
return _readJsonMap(_keyUserProfile);
}
// Current User UUID
@@ -337,14 +324,7 @@ class StorageService {
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;
}
return _readJsonMap(_keyHomeUsersCache);
}
Future<void> clearHomeUsersCache() async {
@@ -371,4 +351,112 @@ class StorageService {
saveToken(authToken), // Update the main token
]);
}
// Multi-Server Support Methods
/// Get servers list as JSON string
String? getServersListJson() {
return _prefs.getString(_keyServersList);
}
/// Save servers list as JSON string
Future<void> saveServersListJson(String serversJson) async {
await _prefs.setString(_keyServersList, serversJson);
}
/// Get enabled servers as JSON string
String? getEnabledServersJson() {
return _prefs.getString(_keyEnabledServers);
}
/// Save enabled servers as JSON string
Future<void> saveEnabledServersJson(String enabledJson) async {
await _prefs.setString(_keyEnabledServers, enabledJson);
}
/// Clear servers list
Future<void> clearServersList() async {
await _prefs.remove(_keyServersList);
}
/// Clear enabled servers
Future<void> clearEnabledServers() async {
await _prefs.remove(_keyEnabledServers);
}
/// Clear all multi-server data
Future<void> clearMultiServerData() async {
// Clear all server endpoint caches
final keys = _prefs.getKeys();
final endpointKeys = keys.where(
(key) => key.startsWith('server_endpoint_'),
);
await Future.wait([
clearServersList(),
clearEnabledServers(),
clearServerOrder(),
...endpointKeys.map((key) => _prefs.remove(key)),
]);
}
/// Server Order (stored as JSON list of server IDs)
Future<void> saveServerOrder(List<String> serverIds) async {
final jsonString = json.encode(serverIds);
await _prefs.setString(_keyServerOrder, jsonString);
}
List<String>? getServerOrder() {
final jsonString = _prefs.getString(_keyServerOrder);
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;
}
}
/// Clear server order
Future<void> clearServerOrder() async {
await _prefs.remove(_keyServerOrder);
}
// Private helper methods
/// Helper to read and decode JSON Map from preferences
///
/// [key] - The preference key to read
/// [legacyStringOk] - If true, returns {'key': value, 'descending': false}
/// when value is a plain string (for legacy library sort)
Map<String, dynamic>? _readJsonMap(
String key, {
bool legacyStringOk = false,
}) {
final jsonString = _prefs.getString(key);
if (jsonString == null) return null;
return _decodeJsonStringToMap(jsonString, legacyStringOk: legacyStringOk);
}
/// Helper to decode JSON string to Map with error handling
///
/// [jsonString] - The JSON string to decode
/// [legacyStringOk] - If true, returns {'key': value, 'descending': false}
/// when value is a plain string (for legacy library sort)
Map<String, dynamic> _decodeJsonStringToMap(
String jsonString, {
bool legacyStringOk = false,
}) {
try {
return json.decode(jsonString) as Map<String, dynamic>;
} catch (e) {
if (legacyStringOk) {
// Legacy support: if it's just a string, return it as the key
return {'key': jsonString, 'descending': false};
}
return {};
}
}
}
+519 -157
View File
@@ -1,228 +1,313 @@
import '../models/plex_media_info.dart';
import 'package:media_kit/media_kit.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../utils/app_logger.dart';
import '../utils/language_codes.dart';
/// Service for selecting audio and subtitle tracks based on user preferences
/// Service for selecting and applying audio and subtitle tracks based on
/// preferences, user profiles, and per-media settings.
class TrackSelectionService {
/// Selects the best audio track based on user preferences
///
/// Priority order:
/// 1. Per-media preferred audio language (from metadata.audioLanguage)
/// 2. Profile-wide language preferences (if auto-select is enabled)
/// 3. Plex's selected track (if auto-select is disabled)
/// 4. First track
///
/// Returns the selected audio track, or null if no suitable track is found
static PlexAudioTrack? selectAudioTrack(
List<PlexAudioTrack> tracks,
PlexUserProfile profile, {
PlexMetadata? metadata,
}) {
if (tracks.isEmpty) return null;
final Player player;
final PlexUserProfile? profileSettings;
final PlexMetadata metadata;
// Priority 1: Check for per-media audio language preference
if (metadata?.audioLanguage != null) {
final perMediaTrack = tracks.firstWhere(
(track) =>
_matchesLanguage(track.languageCode, metadata!.audioLanguage),
orElse: () => tracks.first,
);
// Only use it if we actually found a matching track
if (_matchesLanguage(
perMediaTrack.languageCode,
metadata!.audioLanguage,
)) {
return perMediaTrack;
TrackSelectionService({
required this.player,
this.profileSettings,
required this.metadata,
});
/// Generic track matching for audio and subtitle tracks
/// Returns the best matching track based on hierarchical criteria:
/// 1. Exact match (id + title + language)
/// 2. Partial match (title + language)
/// 3. Language-only match
T? findBestTrackMatch<T>(
List<T> availableTracks,
T preferred,
String Function(T) getId,
String? Function(T) getTitle,
String? Function(T) getLanguage,
) {
if (availableTracks.isEmpty) return null;
// Filter out auto and no tracks
final validTracks = availableTracks
.where((t) => getId(t) != 'auto' && getId(t) != 'no')
.toList();
if (validTracks.isEmpty) return null;
final preferredId = getId(preferred);
final preferredTitle = getTitle(preferred);
final preferredLanguage = getLanguage(preferred);
// Try to match: id, title, and language
for (var track in validTracks) {
if (getId(track) == preferredId &&
getTitle(track) == preferredTitle &&
getLanguage(track) == preferredLanguage) {
return track;
}
}
// Priority 2: If auto-select is disabled, use Plex's selected track
if (!profile.autoSelectAudio) {
return tracks.firstWhere(
(track) => track.selected,
orElse: () => tracks.first,
);
// Try to match: title and language
for (var track in validTracks) {
if (getTitle(track) == preferredTitle &&
getLanguage(track) == preferredLanguage) {
return track;
}
}
// Priority 3: Use profile-wide language preferences
// Try to match: language only
for (var track in validTracks) {
if (getLanguage(track) == preferredLanguage) {
return track;
}
}
return null;
}
AudioTrack? findBestAudioMatch(
List<AudioTrack> availableTracks,
AudioTrack preferred,
) {
return findBestTrackMatch<AudioTrack>(
availableTracks,
preferred,
(t) => t.id,
(t) => t.title,
(t) => t.language,
);
}
AudioTrack? findAudioTrackByProfile(
List<AudioTrack> availableTracks,
PlexUserProfile profile,
) {
appLogger.d('Audio track selection using user profile');
appLogger.d(
'Profile settings - autoSelectAudio: ${profile.autoSelectAudio}, defaultAudioLanguage: ${profile.defaultAudioLanguage}, defaultAudioLanguages: ${profile.defaultAudioLanguages}',
);
if (availableTracks.isEmpty || !profile.autoSelectAudio) {
appLogger.d(
'Cannot use profile: ${availableTracks.isEmpty ? "No tracks available" : "autoSelectAudio is false"}',
);
return null;
}
// Build list of preferred languages
final preferredLanguages = <String>[];
if (profile.defaultAudioLanguage != null) {
if (profile.defaultAudioLanguage != null &&
profile.defaultAudioLanguage!.isNotEmpty) {
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;
appLogger.d('Cannot use profile: No defaultAudioLanguage(s) specified');
return null;
}
// 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,
appLogger.d('Preferred languages: ${preferredLanguages.join(", ")}');
// Try to find track matching any preferred language
for (final preferredLanguage in preferredLanguages) {
// Get all possible language code variations (e.g., "en" → ["en", "eng"])
final languageVariations = LanguageCodes.getVariations(preferredLanguage);
appLogger.d(
'Checking language variations for "$preferredLanguage": ${languageVariations.join(", ")}',
);
if (matchingTrack != tracks.first ||
_matchesLanguage(matchingTrack.languageCode, language)) {
return matchingTrack;
for (var track in availableTracks) {
final trackLang = track.language?.toLowerCase();
if (trackLang != null && languageVariations.contains(trackLang)) {
appLogger.d(
'Found audio track matching profile language "$preferredLanguage" (matched: "$trackLang"): ${track.title ?? "Track ${track.id}"}',
);
return track;
}
}
}
// Fallback to first track
return tracks.first;
appLogger.d(
'No audio track found matching profile languages or their variations',
);
return null;
}
/// Selects the best subtitle track based on user preferences
///
/// Priority order:
/// 1. Per-media preferred subtitle language (from metadata.subtitleLanguage)
/// 2. Profile-wide subtitle preferences (based on auto-select mode)
/// 3. Disabled (null)
///
/// Returns the selected subtitle track, or null if subtitles should be disabled
static PlexSubtitleTrack? selectSubtitleTrack(
List<PlexSubtitleTrack> tracks,
PlexUserProfile profile,
PlexAudioTrack? selectedAudioTrack, {
PlexMetadata? metadata,
}) {
if (tracks.isEmpty) return null;
// Priority 1: Check for per-media subtitle language preference
if (metadata?.subtitleLanguage != null &&
metadata!.subtitleLanguage!.isNotEmpty) {
// Check if subtitle should be disabled (empty string or "none")
if (metadata.subtitleLanguage == 'none' ||
metadata.subtitleLanguage == '') {
return null;
}
final perMediaTrack = tracks.firstWhere(
(track) =>
_matchesLanguage(track.languageCode, metadata.subtitleLanguage),
orElse: () => tracks.first,
);
// Only use it if we actually found a matching track
if (_matchesLanguage(
perMediaTrack.languageCode,
metadata.subtitleLanguage,
)) {
return perMediaTrack;
}
SubtitleTrack? findBestSubtitleMatch(
List<SubtitleTrack> availableTracks,
SubtitleTrack preferred,
) {
// Handle special "no subtitles" case
if (preferred.id == 'no') {
return SubtitleTrack.no();
}
// Priority 2: Use profile-wide subtitle preferences
// Mode 0: Manually selected - return null to disable subtitles
if (profile.autoSelectSubtitle == 0) {
return findBestTrackMatch<SubtitleTrack>(
availableTracks,
preferred,
(t) => t.id,
(t) => t.title,
(t) => t.language,
);
}
SubtitleTrack? findSubtitleTrackByProfile(
List<SubtitleTrack> availableTracks,
PlexUserProfile profile, {
AudioTrack? selectedAudioTrack,
}) {
appLogger.d('Subtitle track selection using user profile');
appLogger.d(
'Profile settings - autoSelectSubtitle: ${profile.autoSelectSubtitle}, defaultSubtitleLanguage: ${profile.defaultSubtitleLanguage}, defaultSubtitleLanguages: ${profile.defaultSubtitleLanguages}, defaultSubtitleForced: ${profile.defaultSubtitleForced}, defaultSubtitleAccessibility: ${profile.defaultSubtitleAccessibility}',
);
if (availableTracks.isEmpty) {
appLogger.d('Cannot use profile: No subtitle tracks available');
return null;
}
// Mode 0: Manually selected - return OFF
if (profile.autoSelectSubtitle == 0) {
appLogger.d(
'Profile specifies manual mode (autoSelectSubtitle=0) - Subtitles OFF',
);
return SubtitleTrack.no();
}
// Mode 1: Shown with foreign audio
if (profile.autoSelectSubtitle == 1) {
appLogger.d(
'Profile specifies foreign audio mode (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;
final audioLang = selectedAudioTrack.language?.toLowerCase();
final prefLang = profile.defaultSubtitleLanguage!.toLowerCase();
final languageVariations = LanguageCodes.getVariations(prefLang);
appLogger.d(
'Checking if audio is foreign - audio: $audioLang, preferred subtitle lang: $prefLang',
);
// If audio matches preferred language, no subtitles needed
if (_matchesLanguage(audioLang, prefLang)) {
return null;
if (audioLang != null && languageVariations.contains(audioLang)) {
appLogger.d('Audio matches preferred language - Subtitles OFF');
return SubtitleTrack.no();
}
appLogger.d('Foreign audio detected - enabling subtitles');
}
// Foreign audio detected, enable subtitles
return _findBestSubtitle(tracks, profile);
// Foreign audio detected or cannot determine, enable subtitles
}
// Mode 2: Always enabled
if (profile.autoSelectSubtitle == 2) {
return _findBestSubtitle(tracks, profile);
}
// Mode 2: Always enabled (or continuing from mode 1 with foreign audio)
appLogger.d('Selecting subtitle track based on preferences');
return null;
}
/// Finds the best subtitle track matching user preferences
static PlexSubtitleTrack? _findBestSubtitle(
List<PlexSubtitleTrack> tracks,
PlexUserProfile profile,
) {
// Build list of preferred language codes
// Build list of preferred languages
final preferredLanguages = <String>[];
if (profile.defaultSubtitleLanguage != null) {
if (profile.defaultSubtitleLanguage != null &&
profile.defaultSubtitleLanguage!.isNotEmpty) {
preferredLanguages.add(profile.defaultSubtitleLanguage!);
}
if (profile.defaultSubtitleLanguages != null) {
preferredLanguages.addAll(profile.defaultSubtitleLanguages!);
}
// Filter tracks based on preferences
var candidateTracks = tracks;
if (preferredLanguages.isEmpty) {
appLogger.d(
'Cannot use profile: No defaultSubtitleLanguage(s) specified',
);
return null;
}
// Apply SDH (hearing impaired) filtering
candidateTracks = _filterBySDH(
appLogger.d('Preferred languages: ${preferredLanguages.join(", ")}');
// Apply filtering based on preferences
var candidateTracks = availableTracks;
// Filter by SDH (defaultSubtitleAccessibility: 0-3)
candidateTracks = filterSubtitlesBySDH(
candidateTracks,
profile.defaultSubtitleAccessibility,
);
// Apply forced subtitle filtering
candidateTracks = _filterByForced(
// Filter by forced subtitle preference (defaultSubtitleForced: 0-3)
candidateTracks = filterSubtitlesByForced(
candidateTracks,
profile.defaultSubtitleForced,
);
// If no candidates after filtering, relax filters
if (candidateTracks.isEmpty) {
candidateTracks = tracks;
appLogger.d('No tracks match strict filters, relaxing filters');
candidateTracks = availableTracks;
}
// 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,
// Try to find track matching any preferred language
for (final preferredLanguage in preferredLanguages) {
final languageVariations = LanguageCodes.getVariations(preferredLanguage);
appLogger.d(
'Checking language variations for "$preferredLanguage": ${languageVariations.join(", ")}',
);
if (matchingTrack != candidateTracks.first ||
_matchesLanguage(matchingTrack.languageCode, language)) {
return matchingTrack;
for (var track in candidateTracks) {
final trackLang = track.language?.toLowerCase();
if (trackLang != null && languageVariations.contains(trackLang)) {
appLogger.d(
'Found subtitle matching profile language "$preferredLanguage" (matched: "$trackLang"): ${track.title ?? "Track ${track.id}"}',
);
return track;
}
}
}
// Fallback to first candidate
return candidateTracks.firstOrNull;
appLogger.d(
'No subtitle track found matching profile languages or their variations',
);
return null;
}
/// Filters subtitle tracks based on SDH (hearing impaired) preference
/// Filters subtitle tracks based on SDH (Subtitles for Deaf or Hard-of-Hearing) 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,
List<SubtitleTrack> filterSubtitlesBySDH(
List<SubtitleTrack> 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;
final preferred = tracks.where((t) => isSDH(t) == preferSDH).toList();
if (preferred.isNotEmpty) {
appLogger.d(
'Applying SDH preference: ${preferSDH ? "prefer SDH" : "prefer non-SDH"} (${preferred.length} tracks)',
);
return preferred;
}
appLogger.d('No tracks match SDH preference, using all tracks');
return tracks;
} else if (preference == 2) {
// Only SDH
return tracks.where(_isSDH).toList();
final filtered = tracks.where((t) => isSDH(t)).toList();
appLogger.d('Filtering to SDH only (${filtered.length} tracks)');
return filtered;
} else if (preference == 3) {
// Only non-SDH
return tracks.where((t) => !_isSDH(t)).toList();
final filtered = tracks.where((t) => !isSDH(t)).toList();
appLogger.d('Filtering to non-SDH only (${filtered.length} tracks)');
return filtered;
}
return tracks;
}
@@ -234,49 +319,62 @@ class TrackSelectionService {
/// - 1: Prefer forced subtitles
/// - 2: Only show forced subtitles
/// - 3: Only show non-forced subtitles
static List<PlexSubtitleTrack> _filterByForced(
List<PlexSubtitleTrack> tracks,
List<SubtitleTrack> filterSubtitlesByForced(
List<SubtitleTrack> 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;
final preferred = tracks
.where((t) => isForced(t) == preferForced)
.toList();
if (preferred.isNotEmpty) {
appLogger.d(
'Applying forced preference: ${preferForced ? "prefer forced" : "prefer non-forced"} (${preferred.length} tracks)',
);
return preferred;
}
appLogger.d('No tracks match forced preference, using all tracks');
return tracks;
} else if (preference == 2) {
// Only forced
return tracks.where((t) => t.forced).toList();
final filtered = tracks.where((t) => isForced(t)).toList();
appLogger.d('Filtering to forced only (${filtered.length} tracks)');
return filtered;
} else if (preference == 3) {
// Only non-forced
return tracks.where((t) => !t.forced).toList();
final filtered = tracks.where((t) => !isForced(t)).toList();
appLogger.d('Filtering to non-forced only (${filtered.length} tracks)');
return filtered;
}
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) {
/// Since media_kit may not expose this directly, we infer from the title
bool isSDH(SubtitleTrack 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');
title.contains('deaf');
}
/// Checks if a language code matches a preferred language
/// Checks if a subtitle track is forced
bool isForced(SubtitleTrack track) {
final title = track.title?.toLowerCase() ?? '';
return title.contains('forced');
}
/// Checks if a track language matches a preferred language
///
/// Handles both 2-letter (ISO 639-1) and 3-letter (ISO 639-2) codes
/// Also handles bibliographic variants and region codes (e.g., "en-US")
static bool _matchesLanguage(
String? trackLanguage,
String? preferredLanguage,
) {
bool languageMatches(String? trackLanguage, String? preferredLanguage) {
if (trackLanguage == null || preferredLanguage == null) {
return false;
}
@@ -299,4 +397,268 @@ class TrackSelectionService {
// Check if track's base code matches any variation
return variations.contains(trackBase);
}
/// Log available tracks for debugging
void logAvailableTracks(
List<AudioTrack> audioTracks,
List<SubtitleTrack> subtitleTracks,
) {
appLogger.d('Available audio tracks: ${audioTracks.length}');
for (var track in audioTracks) {
appLogger.d(
' - ${track.title ?? "Track ${track.id}"} (${track.language ?? "unknown"}) ${track.isDefault == true ? "[DEFAULT]" : ""}',
);
}
appLogger.d('Available subtitle tracks: ${subtitleTracks.length}');
for (var track in subtitleTracks) {
appLogger.d(
' - ${track.title ?? "Track ${track.id}"} (${track.language ?? "unknown"}) ${track.isDefault == true ? "[DEFAULT]" : ""}',
);
}
}
/// Select the best audio track based on priority:
/// Priority 1: Preferred track from navigation
/// Priority 2: Per-media language preference
/// Priority 3: User profile preferences
/// Priority 4: Default or first track
AudioTrack? selectAudioTrack(
List<AudioTrack> availableTracks,
AudioTrack? preferredAudioTrack,
) {
if (availableTracks.isEmpty) return null;
AudioTrack? trackToSelect;
// Priority 1: Try to match preferred track from navigation
if (preferredAudioTrack != null) {
appLogger.d('Priority 1: Checking preferred track from navigation');
appLogger.d(
' Preferred: ${preferredAudioTrack.title ?? "Track ${preferredAudioTrack.id}"} (${preferredAudioTrack.language ?? "unknown"})',
);
trackToSelect = findBestAudioMatch(availableTracks, preferredAudioTrack);
if (trackToSelect != null) {
appLogger.d(' Matched preferred track');
return trackToSelect;
}
appLogger.d(' No match found for preferred track');
} else {
appLogger.d('Priority 1: No preferred track from navigation');
}
// Priority 2: If no preferred track matched, try per-media language preference
if (metadata.audioLanguage != null) {
appLogger.d('Priority 2: Checking per-media audio language preference');
appLogger.d(' Per-media audio language: ${metadata.audioLanguage}');
final matchedTrack = availableTracks.firstWhere(
(track) => languageMatches(track.language, metadata.audioLanguage),
orElse: () => availableTracks.first,
);
if (languageMatches(matchedTrack.language, metadata.audioLanguage)) {
appLogger.d(' Matched per-media audio language preference');
return matchedTrack;
}
appLogger.d(' No match found for per-media audio language');
} else {
appLogger.d('Priority 2: No per-media audio language preference');
}
// Priority 3: If no preferred track matched, try user profile preferences
if (profileSettings != null) {
appLogger.d('Priority 3: Checking user profile preferences');
trackToSelect = findAudioTrackByProfile(
availableTracks,
profileSettings!,
);
if (trackToSelect != null) {
return trackToSelect;
}
} else {
appLogger.d('Priority 3: No user profile available');
}
// Priority 4: If no match, use default or first track
appLogger.d('Priority 4: Using default or first available track');
trackToSelect = availableTracks.firstWhere(
(t) => t.isDefault == true,
orElse: () => availableTracks.first,
);
final isDefault = trackToSelect.isDefault == true;
appLogger.d(
' Selected ${isDefault ? "default" : "first"} track: ${trackToSelect.title ?? "Track ${trackToSelect.id}"} (${trackToSelect.language ?? "unknown"})',
);
return trackToSelect;
}
/// Select the best subtitle track based on priority:
/// Priority 1: Preferred track from navigation
/// Priority 2: Per-media language preference
/// Priority 3: User profile preferences
/// Priority 4: Default track
/// Priority 5: Off
SubtitleTrack selectSubtitleTrack(
List<SubtitleTrack> availableTracks,
SubtitleTrack? preferredSubtitleTrack,
AudioTrack? selectedAudioTrack,
) {
SubtitleTrack? subtitleToSelect;
// Priority 1: Try preferred track from navigation (always wins)
if (preferredSubtitleTrack != null) {
appLogger.d('Priority 1: Checking preferred track from navigation');
if (preferredSubtitleTrack.id == 'no') {
appLogger.d(' Preferred: OFF');
return SubtitleTrack.no();
} else if (availableTracks.isNotEmpty) {
appLogger.d(
' Preferred: ${preferredSubtitleTrack.title ?? "Track ${preferredSubtitleTrack.id}"} (${preferredSubtitleTrack.language ?? "unknown"})',
);
subtitleToSelect = findBestSubtitleMatch(
availableTracks,
preferredSubtitleTrack,
);
if (subtitleToSelect != null) {
appLogger.d(' Matched preferred track');
return subtitleToSelect;
}
appLogger.d(' No match found for preferred track');
}
} else {
appLogger.d('Priority 1: No preferred track from navigation');
}
// Priority 2: If no preferred match, try per-media language preference
if (metadata.subtitleLanguage != null) {
appLogger.d(
'Priority 2: Checking per-media subtitle language preference',
);
appLogger.d(
' Per-media subtitle language: ${metadata.subtitleLanguage}',
);
// Check if subtitle should be disabled
if (metadata.subtitleLanguage == 'none' ||
metadata.subtitleLanguage!.isEmpty) {
appLogger.d(' Per-media preference: Subtitles OFF');
return SubtitleTrack.no();
} else if (availableTracks.isNotEmpty) {
final matchedTrack = availableTracks.firstWhere(
(track) => languageMatches(track.language, metadata.subtitleLanguage),
orElse: () => availableTracks.first,
);
if (languageMatches(matchedTrack.language, metadata.subtitleLanguage)) {
appLogger.d(' Matched per-media subtitle language preference');
return matchedTrack;
}
appLogger.d(' No match found for per-media subtitle language');
}
} else {
appLogger.d('Priority 2: No per-media subtitle language preference');
}
// Priority 3: If no preferred match, apply user profile preferences
if (profileSettings != null && availableTracks.isNotEmpty) {
appLogger.d('Priority 3: Checking user profile preferences');
subtitleToSelect = findSubtitleTrackByProfile(
availableTracks,
profileSettings!,
selectedAudioTrack: selectedAudioTrack,
);
if (subtitleToSelect != null) {
return subtitleToSelect;
}
} else if (availableTracks.isNotEmpty) {
appLogger.d('Priority 3: No user profile available');
}
// Priority 4: If no profile match, check for default subtitle
if (availableTracks.isNotEmpty) {
appLogger.d('Priority 4: Checking for default subtitle track');
final defaultTrack = availableTracks.firstWhere(
(t) => t.isDefault == true,
orElse: () => availableTracks.first,
);
if (defaultTrack.isDefault == true) {
appLogger.d(
' Found default track: ${defaultTrack.title ?? "Track ${defaultTrack.id}"} (${defaultTrack.language ?? "unknown"})',
);
return defaultTrack;
}
appLogger.d(' No default subtitle track found');
}
// Priority 5: If still no subtitle selected, turn off
appLogger.d('Priority 5: No subtitle selected - Subtitles OFF');
return SubtitleTrack.no();
}
/// Select and apply audio and subtitle tracks based on preferences
Future<void> selectAndApplyTracks({
AudioTrack? preferredAudioTrack,
SubtitleTrack? preferredSubtitleTrack,
double? preferredPlaybackRate,
Function(AudioTrack)? onAudioTrackChanged,
Function(SubtitleTrack)? onSubtitleTrackChanged,
}) async {
// Wait for tracks to be loaded
int attempts = 0;
while (player.state.tracks.audio.isEmpty &&
player.state.tracks.subtitle.isEmpty &&
attempts < 100) {
await Future.delayed(const Duration(milliseconds: 100));
attempts++;
}
appLogger.d('Starting track selection process');
// Get real tracks (excluding auto and no)
final realAudioTracks = player.state.tracks.audio
.where((t) => t.id != 'auto' && t.id != 'no')
.toList();
final realSubtitleTracks = player.state.tracks.subtitle
.where((t) => t.id != 'auto' && t.id != 'no')
.toList();
// Log available tracks
logAvailableTracks(realAudioTracks, realSubtitleTracks);
// Select and apply audio track
appLogger.d('Audio track selection');
final selectedAudioTrack = selectAudioTrack(
realAudioTracks,
preferredAudioTrack,
);
if (selectedAudioTrack != null) {
appLogger.i(
'Final audio selection: ${selectedAudioTrack.title ?? "Track ${selectedAudioTrack.id}"} (${selectedAudioTrack.language ?? "unknown"})',
);
player.setAudioTrack(selectedAudioTrack);
} else {
appLogger.d('No audio tracks available');
}
// Select and apply subtitle track
appLogger.d('Subtitle track selection');
final selectedSubtitleTrack = selectSubtitleTrack(
realSubtitleTracks,
preferredSubtitleTrack,
selectedAudioTrack,
);
final finalSubtitle = selectedSubtitleTrack.id == 'no'
? 'OFF'
: '${selectedSubtitleTrack.title ?? "Track ${selectedSubtitleTrack.id}"} (${selectedSubtitleTrack.language ?? "unknown"})';
appLogger.i('Final subtitle selection: $finalSubtitle');
player.setSubtitleTrack(selectedSubtitleTrack);
// Set playback rate if preferred rate was provided
if (preferredPlaybackRate != null) {
appLogger.d('Setting preferred playback rate: ${preferredPlaybackRate}x');
player.setRate(preferredPlaybackRate);
}
appLogger.d('Track selection complete');
}
}
+266
View File
@@ -0,0 +1,266 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../models/plex_media_version.dart';
import '../utils/app_logger.dart';
/// Manages video filtering, aspect ratio modes, and subtitle positioning for video playback.
///
/// This service handles:
/// - BoxFit mode cycling (contain → cover → fill)
/// - Video cropping calculations for fill screen mode
/// - Subtitle positioning adjustments based on crop parameters
/// - Debounced video filter updates on resize events
class VideoFilterManager {
final Player player;
final List<PlexMediaVersion> availableVersions;
final int selectedMediaIndex;
/// BoxFit mode state: 0=contain (letterbox), 1=cover (fill screen), 2=fill (stretch)
int _boxFitMode = 0;
/// Track if a pinch gesture is occurring (public for gesture tracking)
bool isPinching = false;
/// Current player viewport size
Size? _playerSize;
/// Current video dimensions
Size? _videoSize;
/// Debounce timer for resize events
Timer? _resizeDebounceTimer;
VideoFilterManager({
required this.player,
required this.availableVersions,
required this.selectedMediaIndex,
});
/// Current BoxFit mode (0=contain, 1=cover, 2=fill)
int get boxFitMode => _boxFitMode;
/// Current player size
Size? get playerSize => _playerSize;
/// Get current BoxFit based on mode
BoxFit get currentBoxFit {
switch (_boxFitMode) {
case 0:
return BoxFit.contain;
case 1:
return BoxFit.cover;
case 2:
return BoxFit.fill;
default:
return BoxFit.contain;
}
}
/// Cycle through BoxFit modes: contain → cover → fill → contain (for button)
void cycleBoxFitMode() {
_boxFitMode = (_boxFitMode + 1) % 3;
updateVideoFilter();
}
/// Toggle between contain and cover modes only (for pinch gesture)
void toggleContainCover() {
_boxFitMode = _boxFitMode == 0 ? 1 : 0;
updateVideoFilter();
}
/// Update player size when layout changes
void updatePlayerSize(Size size) {
// Check if size actually changed to avoid unnecessary updates
if (_playerSize == null ||
(_playerSize!.width - size.width).abs() > 0.1 ||
(_playerSize!.height - size.height).abs() > 0.1) {
_playerSize = size;
debouncedUpdateVideoFilter();
}
}
/// Calculates crop parameters for "fill screen" mode (BoxFit.cover) to eliminate letterboxing.
///
/// This method is only active when [_boxFitMode] == 1 (cover mode). It determines how to
/// crop the video to completely fill the player area while maintaining aspect ratio.
///
/// **How it works:**
/// 1. Compares video aspect ratio vs player aspect ratio
/// 2. Crops the dimension that would create letterboxing:
/// - Wide video (16:9) on tall player (4:3): crops left/right sides
/// - Tall video (4:3) on wide player (16:9): crops top/bottom
/// 3. Centers the crop within the video
/// 4. Calculates subtitle margin adjustments to keep subtitles visible
///
/// **Subtitle positioning:**
/// MPV uses a 720p reference coordinate system for subtitle positioning.
/// When cropping zooms the video, subtitles need larger margins to avoid
/// being cropped or appearing too close to edges.
///
/// Returns `null` if:
/// - Not in cover mode (_boxFitMode != 1)
/// - Player or video size is unknown
/// - Aspect ratios are too similar (< 0.01 difference) - no crop needed
///
/// Returns a map containing:
/// - `width`, `height`: Dimensions of the cropped area in video pixels
/// - `x`, `y`: Crop offset from video's top-left corner in pixels
/// - `subMarginX`, `subMarginY`: Subtitle margins in MPV coordinate space (720p reference)
/// - `subScale`: Subtitle scaling factor (currently always 1.0)
Map<String, dynamic>? _calculateCropParameters() {
// Only calculate for cover mode with known dimensions
if (_boxFitMode != 1 || _playerSize == null || _videoSize == null) {
return null;
}
final playerAspect = _playerSize!.width / _playerSize!.height;
final videoAspect = _videoSize!.width / _videoSize!.height;
// No cropping needed if aspect ratios are very similar
if ((playerAspect - videoAspect).abs() < 0.01) return null;
late final int cropW, cropH, cropX, cropY;
if (videoAspect > playerAspect) {
// Video is wider than player - crop left/right sides
// Example: 16:9 video in 4:3 player
final scale = _playerSize!.height / _videoSize!.height;
cropH = _videoSize!.height.toInt();
cropW = (_playerSize!.width / scale).toInt();
cropX = ((_videoSize!.width - cropW) ~/ 2); // Center horizontally
cropY = 0;
} else {
// Video is taller than player - crop top/bottom
// Example: 4:3 video in 16:9 player (most common case)
final scale = _playerSize!.width / _videoSize!.width;
cropW = _videoSize!.width.toInt();
cropH = (_playerSize!.height / scale).toInt();
cropX = 0;
cropY = ((_videoSize!.height - cropH) ~/ 2); // Center vertically
}
// Subtitle positioning constants
/// MPV's subtitle coordinate system height (720p reference)
const double kSubCoord = 720.0;
/// Base horizontal subtitle margin to prevent edge clipping
const double baseX = 20.0;
/// Base vertical subtitle margin, tuned to position subtitles
/// comfortably above the bottom while avoiding overscan areas
const double baseY = 45.0;
// Calculate additional margin needed due to cropping
// When we crop, the visible area is "zoomed in", so subtitles need
// proportionally larger margins to maintain the same visual distance from edges
double extraX = cropX > 0
? (cropX / _videoSize!.width) * kSubCoord * videoAspect
: 0.0;
double extraY = cropY > 0 ? (cropY / _videoSize!.height) * kSubCoord : 0.0;
// Apply additional margin (never reduce below base)
int marginX = (baseX + extraX).round();
int marginY = (baseY + extraY).round();
return {
'width': cropW,
'height': cropH,
'x': cropX,
'y': cropY,
'subMarginX': marginX,
'subMarginY': marginY,
'subScale': 1.0,
};
}
/// Get video dimensions from the currently selected media version
Size? _getCurrentVideoSize() {
if (availableVersions.isEmpty ||
selectedMediaIndex >= availableVersions.length) {
return null;
}
final currentVersion = availableVersions[selectedMediaIndex];
if (currentVersion.width != null && currentVersion.height != null) {
return Size(
currentVersion.width!.toDouble(),
currentVersion.height!.toDouble(),
);
}
return null;
}
/// Update the video filter based on current crop mode
void updateVideoFilter() async {
try {
final nativePlayer = player.platform as dynamic;
if (_boxFitMode == 1) {
// Fill screen mode - apply crop filter
_videoSize = _getCurrentVideoSize();
final cropParams = _calculateCropParameters();
if (cropParams != null) {
final cropFilter =
'crop=${cropParams['width']}:${cropParams['height']}:${cropParams['x']}:${cropParams['y']}';
appLogger.d(
'Applying video filter: $cropFilter (player: $_playerSize, video: $_videoSize)',
);
// Apply crop filter
await nativePlayer.setProperty('vf', cropFilter);
// Apply subtitle margins and scaling to compensate for crop zoom
final subMarginX = cropParams['subMarginX']!;
final subMarginY = cropParams['subMarginY']!;
final subScale = cropParams['subScale']!;
appLogger.d(
'Applying subtitle properties - margins: x=$subMarginX, y=$subMarginY, scale=$subScale',
);
await nativePlayer.setProperty('sub-margin-x', subMarginX.toString());
await nativePlayer.setProperty('sub-margin-y', subMarginY.toString());
await nativePlayer.setProperty('sub-scale', subScale.toString());
} else {
// Clear filter but apply base margins if no cropping needed
appLogger.d(
'Clearing video filter - aspect ratios similar, applying base margins (player: $_playerSize, video: $_videoSize)',
);
await nativePlayer.setProperty('vf', '');
await nativePlayer.setProperty('sub-margin-x', '20'); // Base margin
await nativePlayer.setProperty('sub-margin-y', '40'); // Base margin
await nativePlayer.setProperty('sub-scale', '1.0'); // Reset scale
}
} else {
// Other modes - clear video filter but apply base margins
appLogger.d(
'Clearing video filter, applying base margins - BoxFit mode $_boxFitMode',
);
await nativePlayer.setProperty('vf', '');
await nativePlayer.setProperty('sub-margin-x', '20'); // Base margin
await nativePlayer.setProperty('sub-margin-y', '40'); // Base margin
await nativePlayer.setProperty('sub-scale', '1.0'); // Reset scale
}
} catch (e) {
appLogger.w('Failed to update video filter', error: e);
}
}
/// Debounced version of updateVideoFilter for resize events
void debouncedUpdateVideoFilter() {
_resizeDebounceTimer?.cancel();
_resizeDebounceTimer = Timer(const Duration(milliseconds: 50), () {
updateVideoFilter();
});
}
/// Clean up resources
void dispose() {
_resizeDebounceTimer?.cancel();
}
}
+54 -7
View File
@@ -25,6 +25,8 @@ Future<void> playCollectionOrPlaylist({
}
String ratingKey = item.ratingKey;
String? serverId = item.serverId;
String? serverName = item.serverName;
final PlayQueueResponse? playQueue;
if (isCollection) {
@@ -59,18 +61,39 @@ Future<void> playCollectionOrPlaylist({
fetchedQueue.items!.isNotEmpty) {
if (!context.mounted) return;
// Preserve serverId for all items in the queue
final itemsWithServerId = fetchedQueue.items!.map((queueItem) {
return queueItem.copyWith(serverId: serverId, serverName: serverName);
}).toList();
final queueWithServerId = PlayQueueResponse(
playQueueID: fetchedQueue.playQueueID,
playQueueSelectedItemID: fetchedQueue.playQueueSelectedItemID,
playQueueSelectedItemOffset: fetchedQueue.playQueueSelectedItemOffset,
playQueueSelectedMetadataItemID:
fetchedQueue.playQueueSelectedMetadataItemID,
playQueueShuffled: fetchedQueue.playQueueShuffled,
playQueueSourceURI: fetchedQueue.playQueueSourceURI,
playQueueTotalCount: fetchedQueue.playQueueTotalCount,
playQueueVersion: fetchedQueue.playQueueVersion,
size: fetchedQueue.size,
items: itemsWithServerId,
);
// Set play queue in provider
final playbackState = context.read<PlaybackStateProvider>();
playbackState.setClient(client);
await playbackState.setPlaybackFromPlayQueue(fetchedQueue, ratingKey);
await playbackState.setPlaybackFromPlayQueue(
queueWithServerId,
ratingKey,
serverId: serverId,
serverName: serverName,
);
if (!context.mounted) return;
// Navigate to first item
await navigateToVideoPlayer(
context,
metadata: fetchedQueue.items!.first,
);
await navigateToVideoPlayer(context, metadata: itemsWithServerId.first);
return;
}
}
@@ -88,15 +111,39 @@ Future<void> playCollectionOrPlaylist({
if (!context.mounted) return;
// Preserve serverId for all items in the queue
final itemsWithServerId = playQueue.items!.map((queueItem) {
return queueItem.copyWith(serverId: serverId, serverName: serverName);
}).toList();
final queueWithServerId = PlayQueueResponse(
playQueueID: playQueue.playQueueID,
playQueueSelectedItemID: playQueue.playQueueSelectedItemID,
playQueueSelectedItemOffset: playQueue.playQueueSelectedItemOffset,
playQueueSelectedMetadataItemID:
playQueue.playQueueSelectedMetadataItemID,
playQueueShuffled: playQueue.playQueueShuffled,
playQueueSourceURI: playQueue.playQueueSourceURI,
playQueueTotalCount: playQueue.playQueueTotalCount,
playQueueVersion: playQueue.playQueueVersion,
size: playQueue.size,
items: itemsWithServerId,
);
// Set play queue in provider
final playbackState = context.read<PlaybackStateProvider>();
playbackState.setClient(client);
await playbackState.setPlaybackFromPlayQueue(playQueue, ratingKey);
await playbackState.setPlaybackFromPlayQueue(
queueWithServerId,
ratingKey,
serverId: serverId,
serverName: serverName,
);
if (!context.mounted) return;
// Navigate to first item
await navigateToVideoPlayer(context, metadata: playQueue.items!.first);
await navigateToVideoPlayer(context, metadata: itemsWithServerId.first);
} catch (e) {
appLogger.e('Failed to ${shuffle ? "shuffle play" : "play"}', error: e);
if (context.mounted) {
+16
View File
@@ -0,0 +1,16 @@
import 'package:media_kit/media_kit.dart';
/// 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);
}
+49 -9
View File
@@ -1,10 +1,14 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../i18n/strings.g.dart';
import '../models/plex_library.dart';
import '../models/plex_user_profile.dart';
import '../providers/hidden_libraries_provider.dart';
import '../providers/multi_server_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';
import 'app_logger.dart';
extension ProviderExtensions on BuildContext {
PlexClientProvider get plexClient =>
@@ -25,12 +29,48 @@ extension ProviderExtensions on BuildContext {
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;
/// Get PlexClient for a specific server ID
/// If serverId is null, returns the first available online client
/// Throws an exception if no client is available
PlexClient getClientForServer(String? serverId) {
final multiServerProvider = Provider.of<MultiServerProvider>(
this,
listen: false,
);
if (serverId == null) {
// No serverId specified - try to get first online server
appLogger.w('No serverId provided, using first available online server');
if (!multiServerProvider.hasConnectedServers) {
throw Exception(t.errors.noClientAvailable);
}
final firstServerId = multiServerProvider.onlineServerIds.first;
final client = multiServerProvider.getClientForServer(firstServerId);
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
return client;
}
final serverClient = multiServerProvider.getClientForServer(serverId);
if (serverClient == null) {
appLogger.e('No client found for server $serverId');
throw Exception(t.errors.noClientAvailable);
}
return serverClient;
}
/// Get PlexClient for a library
/// Throws an exception if no client is available
PlexClient getClientForLibrary(PlexLibrary library) {
return getClientForServer(library.serverId);
}
}
+39
View File
@@ -0,0 +1,39 @@
import '../models/plex_metadata.dart';
import '../models/plex_playlist.dart';
import '../models/plex_library.dart';
/// Extension methods for tagging items with server information
/// Used for multi-server support to track which server each item belongs to
extension PlexMetadataServerTagging on Iterable<PlexMetadata> {
/// Tags all items in the collection with the given server ID and name
/// Returns a new list with all items updated
List<PlexMetadata> tagWithServer(String? serverId, String? serverName) {
return map(
(item) => item.copyWith(serverId: serverId, serverName: serverName),
).toList();
}
/// Tags all items in the collection with server info from a library
/// Returns a new list with all items updated
List<PlexMetadata> tagWithLibrary(PlexLibrary library) {
return tagWithServer(library.serverId, library.serverName);
}
}
extension PlexPlaylistServerTagging on Iterable<PlexPlaylist> {
/// Tags all playlists in the collection with the given server ID and name
/// Returns a new list with all playlists updated
List<PlexPlaylist> tagWithServer(String? serverId, String? serverName) {
return map(
(playlist) =>
playlist.copyWith(serverId: serverId, serverName: serverName),
).toList();
}
/// Tags all playlists in the collection with server info from a library
/// Returns a new list with all playlists updated
List<PlexPlaylist> tagWithLibrary(PlexLibrary library) {
return tagWithServer(library.serverId, library.serverName);
}
}
-112
View File
@@ -1,112 +0,0 @@
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';
import '../i18n/strings.g.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(SnackBar(content: Text(t.messages.noEpisodesFound)));
}
return;
}
// Shuffle the episodes
episodes.shuffle();
// Store shuffle queue in provider
// ignore: deprecated_member_use_from_same_package
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(t.messages.errorLoading(error: e.toString()))),
);
}
}
}
-31
View File
@@ -1,31 +0,0 @@
import 'package:flutter/material.dart';
import '../models/plex_home_user.dart';
import '../i18n/strings.g.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(
t.messages.failedToSwitchProfile(displayName: user.displayName),
),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
return success;
}
}
+33
View File
@@ -0,0 +1,33 @@
import 'package:flutter/material.dart';
/// Get the replay icon based on the duration
/// Returns numbered icons (replay_5, replay_10, replay_30) when available,
/// otherwise returns generic replay icon
IconData getReplayIcon(int seconds) {
switch (seconds) {
case 5:
return Icons.replay_5;
case 10:
return Icons.replay_10;
case 30:
return Icons.replay_30;
default:
return Icons.replay; // Generic icon for custom durations
}
}
/// Get the forward icon based on the duration
/// Returns numbered icons (forward_5, forward_10, forward_30) when available,
/// otherwise returns generic forward icon
IconData getForwardIcon(int seconds) {
switch (seconds) {
case 5:
return Icons.forward_5;
case 10:
return Icons.forward_10;
case 30:
return Icons.forward_30;
default:
return Icons.forward; // Generic icon for custom durations
}
}
+15 -1
View File
@@ -29,11 +29,13 @@ class AppBarBackButton extends StatefulWidget {
/// [style] determines the visual appearance of the back button.
/// [onPressed] is called when the button is tapped. If null, defaults to Navigator.pop.
/// [color] overrides the default icon color. If null, uses white for circular/video, theme default for plain.
/// [semanticLabel] provides accessibility label for screen readers.
const AppBarBackButton({
super.key,
this.style = BackButtonStyle.circular,
this.onPressed,
this.color,
this.semanticLabel,
});
/// The visual style of the back button
@@ -45,6 +47,9 @@ class AppBarBackButton extends StatefulWidget {
/// The color of the back arrow icon. If null, uses style-appropriate default.
final Color? color;
/// Semantic label for screen readers
final String? semanticLabel;
@override
State<AppBarBackButton> createState() => _AppBarBackButtonState();
}
@@ -124,7 +129,7 @@ class _AppBarBackButtonState extends State<AppBarBackButton>
break;
}
final button = MouseRegion(
final buttonWidget = MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) => _onHoverChange(true),
onExit: (_) => _onHoverChange(false),
@@ -154,6 +159,15 @@ class _AppBarBackButtonState extends State<AppBarBackButton>
),
);
final button = widget.semanticLabel != null
? Semantics(
label: widget.semanticLabel,
button: true,
excludeSemantics: true,
child: buttonWidget,
)
: buttonWidget;
return widget.style == BackButtonStyle.circular
? SafeArea(child: button)
: button;
+54
View File
@@ -0,0 +1,54 @@
import 'package:flutter/material.dart';
/// A reusable header widget for bottom sheets
/// Provides consistent styling with title, optional leading widget, optional action, and close button
class BottomSheetHeader extends StatelessWidget {
/// The title text to display
final String title;
/// Optional leading widget (e.g., icon or back button)
final Widget? leading;
/// Optional action widget (e.g., clear button)
final Widget? action;
/// Optional callback when close button is pressed
/// Defaults to Navigator.pop(context)
final VoidCallback? onClose;
const BottomSheetHeader({
super.key,
required this.title,
this.leading,
this.action,
this.onClose,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Theme.of(context).dividerColor),
),
),
child: Row(
children: [
if (leading != null) ...[leading!, const SizedBox(width: 8)],
Expanded(
child: Text(
title,
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
if (action != null) action!,
IconButton(
icon: const Icon(Icons.close),
onPressed: onClose ?? () => Navigator.pop(context),
),
],
),
);
}
}
+8 -25
View File
@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
import '../i18n/strings.g.dart';
import 'empty_state_widget.dart';
import 'error_state_widget.dart';
/// A widget that handles loading, error, empty, and content states
/// Provides a consistent UI pattern across the app for data-driven screens
@@ -45,36 +47,17 @@ class ContentStateBuilder<T> extends StatelessWidget {
// Error state (only show error if items list is empty)
if (errorMessage != null && items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.error_outline, size: 48, color: Colors.red),
const SizedBox(height: 16),
Text(
errorMessage!,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white70),
),
const SizedBox(height: 16),
ElevatedButton(onPressed: onRetry, child: Text(t.common.retry)),
],
),
return ErrorStateWidget(
message: errorMessage!,
icon: Icons.error_outline,
onRetry: onRetry,
retryLabel: t.common.retry,
);
}
// Empty state
if (items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(emptyIcon, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(emptyMessage, style: const TextStyle(color: Colors.white70)),
],
),
);
return EmptyStateWidget(message: emptyMessage, icon: emptyIcon);
}
// Content state - delegate to builder
-170
View File
@@ -1,6 +1,4 @@
import 'package:flutter/material.dart';
import '../utils/platform_detector.dart';
import '../i18n/strings.g.dart';
/// A menu action item for context menus
class ContextMenuItem {
@@ -22,171 +20,3 @@ class ContextMenuItem {
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: Text(t.common.cancel),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
style: isDestructive
? TextButton.styleFrom(foregroundColor: Colors.red)
: null,
child: Text(t.common.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 ?? t.dialog.confirmAction,
message: selectedItem.confirmationMessage ?? t.dialog.areYouSure,
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,
);
}
}
-112
View File
@@ -3,58 +3,6 @@ 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.
class DesktopAppBar extends StatelessWidget implements PreferredSizeWidget {
final Widget? title;
final List<Widget>? actions;
final Widget? leading;
final bool automaticallyImplyLeading;
final double? elevation;
final Color? backgroundColor;
final Color? surfaceTintColor;
final Color? shadowColor;
final double? scrolledUnderElevation;
const DesktopAppBar({
super.key,
this.title,
this.actions,
this.leading,
this.automaticallyImplyLeading = true,
this.elevation,
this.backgroundColor,
this.surfaceTintColor,
this.shadowColor,
this.scrolledUnderElevation,
});
@override
Widget build(BuildContext context) {
final appBar = AppBar(
title: title != null
? DesktopTitleBarPadding(
leftPadding: leading != null ? 0 : null,
child: title!,
)
: null,
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
leading: DesktopAppBarHelper.buildAdjustedLeading(leading),
automaticallyImplyLeading: automaticallyImplyLeading,
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
scrolledUnderElevation: scrolledUnderElevation,
);
return DesktopAppBarHelper.wrapWithGestureDetector(appBar);
}
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
/// A custom sliver app bar that automatically handles desktop window controls spacing.
/// Use this instead of SliverAppBar for consistent desktop platform behavior.
class DesktopSliverAppBar extends StatelessWidget {
@@ -142,66 +90,6 @@ class DesktopSliverAppBar extends StatelessWidget {
}
}
/// 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;
+7 -36
View File
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'state_message_widget.dart';
/// A reusable widget for displaying empty states throughout the app
class EmptyStateWidget extends StatelessWidget {
@@ -24,42 +25,12 @@ class EmptyStateWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (icon != null) ...[
Icon(
icon,
size: 64,
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.4),
),
const SizedBox(height: 16),
],
Text(
message,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.6),
),
),
if (onAction != null && actionLabel != null) ...[
const SizedBox(height: 24),
FilledButton.icon(
onPressed: onAction,
icon: const Icon(Icons.add),
label: Text(actionLabel!),
),
],
],
),
),
return StateMessageWidget(
message: message,
icon: icon,
onAction: onAction,
actionLabel: actionLabel,
actionIcon: Icons.add,
);
}
}
+9 -28
View File
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'state_message_widget.dart';
/// A reusable widget for displaying error states throughout the app
class ErrorStateWidget extends StatelessWidget {
@@ -24,34 +25,14 @@ class ErrorStateWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (icon != null) ...[
Icon(icon, size: 64, color: Theme.of(context).colorScheme.error),
const SizedBox(height: 16),
],
Text(
message,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color: Theme.of(context).colorScheme.error,
),
),
if (onRetry != null) ...[
const SizedBox(height: 24),
FilledButton.icon(
onPressed: onRetry,
icon: const Icon(Icons.refresh),
label: Text(retryLabel ?? 'Retry'),
),
],
],
),
),
return StateMessageWidget(
message: message,
icon: icon,
iconColor: Theme.of(context).colorScheme.error,
textColor: Theme.of(context).colorScheme.error,
onAction: onRetry,
actionLabel: retryLabel ?? 'Retry',
actionIcon: Icons.refresh,
);
}
}
+14 -60
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import '../models/plex_filter.dart';
import '../widgets/app_bar_back_button.dart';
import '../widgets/bottom_sheet_header.dart';
import '../utils/provider_extensions.dart';
import '../i18n/strings.g.dart';
@@ -59,10 +60,7 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
});
try {
final client = context.client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final client = context.getClientForServer(null);
final values = await client.getFilterValues(filter.key);
setState(() {
@@ -114,34 +112,11 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
return Column(
children: [
// Header with back button
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Theme.of(context).dividerColor),
),
),
child: Row(
children: [
AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: _goBack,
),
const SizedBox(width: 8),
Expanded(
child: Text(
_currentFilter!.title,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(context),
),
],
BottomSheetHeader(
title: _currentFilter!.title,
leading: AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: _goBack,
),
),
@@ -209,27 +184,11 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
return Column(
children: [
// Header
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Theme.of(context).dividerColor),
),
),
child: Row(
children: [
const Icon(Icons.filter_alt),
const SizedBox(width: 12),
Text(
t.libraries.filters,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
if (_tempSelectedFilters.isNotEmpty)
TextButton.icon(
BottomSheetHeader(
title: t.libraries.filters,
leading: const Icon(Icons.filter_alt),
action: _tempSelectedFilters.isNotEmpty
? TextButton.icon(
onPressed: () {
setState(() {
_tempSelectedFilters.clear();
@@ -238,13 +197,8 @@ class _FiltersBottomSheetState extends State<FiltersBottomSheet> {
},
icon: const Icon(Icons.clear_all),
label: Text(t.libraries.clearAll),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(context),
),
],
),
)
: null,
),
// All Filters (boolean toggles first, then regular filters)
+41 -41
View File
@@ -1,21 +1,28 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../providers/plex_client_provider.dart';
import '../utils/app_logger.dart';
import '../utils/video_player_navigation.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
import 'folder_tree_item.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../i18n/strings.g.dart';
import 'folder_tree_item.dart';
import 'empty_state_widget.dart';
import 'error_state_widget.dart';
/// Expandable tree view for browsing library folders
/// Shows a hierarchical file/folder structure
class FolderTreeView extends StatefulWidget {
final String libraryKey;
final String? serverId; // Server this library belongs to
final void Function(String)? onRefresh;
const FolderTreeView({super.key, required this.libraryKey, this.onRefresh});
const FolderTreeView({
super.key,
required this.libraryKey,
this.serverId,
this.onRefresh,
});
@override
State<FolderTreeView> createState() => _FolderTreeViewState();
@@ -42,18 +49,23 @@ class _FolderTreeViewState extends State<FolderTreeView> {
});
try {
final clientProvider = context.read<PlexClientProvider>();
final client = clientProvider.client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final client = context.getClientForServer(widget.serverId);
final folders = await client.getLibraryFolders(widget.libraryKey);
if (!mounted) return;
final taggedFolders = folders
.map(
(folder) => folder.copyWith(
serverId: widget.serverId,
serverName: null, // server name not required for folders listing
),
)
.toList();
setState(() {
_rootFolders = folders;
_rootFolders = taggedFolders;
_isLoadingRoot = false;
});
@@ -89,18 +101,21 @@ class _FolderTreeViewState extends State<FolderTreeView> {
});
try {
final clientProvider = context.read<PlexClientProvider>();
final client = clientProvider.client;
if (client == null) {
throw Exception(t.errors.noClientAvailable);
}
final client = context.getClientForServer(widget.serverId);
final children = await client.getFolderChildren(folder.key);
if (!mounted) return;
final taggedChildren = children
.map(
(child) =>
child.copyWith(serverId: widget.serverId, serverName: null),
)
.toList();
setState(() {
_childrenCache[folder.key] = children;
_childrenCache[folder.key] = taggedChildren;
_expandedFolders.add(folder.key);
_loadingFolders.remove(folder.key);
});
@@ -227,33 +242,18 @@ class _FolderTreeViewState extends State<FolderTreeView> {
}
if (_errorMessage != null) {
return 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: _loadRootFolders,
child: Text(t.common.retry),
),
],
),
return ErrorStateWidget(
message: _errorMessage!,
icon: Icons.error_outline,
onRetry: _loadRootFolders,
retryLabel: t.common.retry,
);
}
if (_rootFolders.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.folder_open, size: 64, color: Colors.grey),
const SizedBox(height: 16),
Text(t.libraries.noFoldersFound),
],
),
return EmptyStateWidget(
message: t.libraries.noFoldersFound,
icon: Icons.folder_open,
);
}
+71 -18
View File
@@ -1,9 +1,9 @@
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_playlist.dart';
import '../providers/plex_client_provider.dart';
import '../providers/settings_provider.dart';
import '../services/settings_service.dart';
import '../utils/provider_extensions.dart';
@@ -49,10 +49,51 @@ class MediaCard extends StatefulWidget {
}
class _MediaCardState extends State<MediaCard> {
void _handleTap(BuildContext context) async {
final client = context.client;
if (client == null) return;
String _buildSemanticLabel() {
final item = widget.item;
final itemType = item.type.toLowerCase();
// Build base label based on type
String baseLabel;
if (itemType == 'episode') {
final episodeInfo = item.parentIndex != null && item.index != null
? 'S${item.parentIndex} E${item.index}'
: '';
baseLabel = t.accessibility.mediaCardEpisode(
title: item.displayTitle,
episodeInfo: episodeInfo,
);
} else if (itemType == 'season') {
final seasonInfo = item.parentIndex != null
? 'Season ${item.parentIndex}'
: '';
baseLabel = t.accessibility.mediaCardSeason(
title: item.displayTitle,
seasonInfo: seasonInfo,
);
} else if (itemType == 'movie') {
baseLabel = t.accessibility.mediaCardMovie(title: item.displayTitle);
} else {
baseLabel = t.accessibility.mediaCardShow(title: item.displayTitle);
}
// Add watched status
if (item.isWatched) {
baseLabel = '$baseLabel, ${t.accessibility.mediaCardWatched}';
} else if (item.viewOffset != null &&
item.duration != null &&
item.viewOffset! > 0) {
final percent = ((item.viewOffset! / item.duration!) * 100).round();
baseLabel =
'$baseLabel, ${t.accessibility.mediaCardPartiallyWatched(percent: percent)}';
} else {
baseLabel = '$baseLabel, ${t.accessibility.mediaCardUnwatched}';
}
return baseLabel;
}
void _handleTap(BuildContext context) async {
// Handle playlists
if (widget.item is PlexPlaylist) {
await Navigator.push(
@@ -138,15 +179,19 @@ class _MediaCardState extends State<MediaCard> {
? ViewMode.grid
: settingsProvider.viewMode;
final semanticLabel = _buildSemanticLabel();
final cardWidget = viewMode == ViewMode.grid
? _MediaCardGrid(
item: widget.item,
width: widget.width,
height: widget.height,
semanticLabel: semanticLabel,
onTap: () => _handleTap(context),
)
: _MediaCardList(
item: widget.item,
semanticLabel: semanticLabel,
onTap: () => _handleTap(context),
density: settingsProvider.libraryDensity,
);
@@ -170,12 +215,14 @@ class _MediaCardGrid extends StatelessWidget {
final dynamic item; // Can be PlexMetadata or PlexPlaylist
final double? width;
final double? height;
final String semanticLabel;
final VoidCallback onTap;
const _MediaCardGrid({
required this.item,
this.width,
this.height,
required this.semanticLabel,
required this.onTap,
});
@@ -184,8 +231,7 @@ class _MediaCardGrid extends StatelessWidget {
return SizedBox(
width: width,
child: Semantics(
label: "media-card-${item.ratingKey}",
identifier: "media-card-${item.ratingKey}",
label: semanticLabel,
button: true,
child: InkWell(
onTap: onTap,
@@ -334,11 +380,13 @@ class _MediaCardGrid extends StatelessWidget {
/// List layout for media cards
class _MediaCardList extends StatelessWidget {
final dynamic item; // Can be PlexMetadata or PlexPlaylist
final String semanticLabel;
final VoidCallback onTap;
final LibraryDensity density;
const _MediaCardList({
required this.item,
required this.semanticLabel,
required this.onTap,
required this.density,
});
@@ -501,8 +549,7 @@ class _MediaCardList extends StatelessWidget {
final subtitle = _buildSubtitleText();
return Semantics(
label: "media-card-${item.ratingKey}",
identifier: "media-card-${item.ratingKey}",
label: semanticLabel,
button: true,
child: InkWell(
onTap: onTap,
@@ -602,6 +649,19 @@ class _MediaCardList extends StatelessWidget {
}
}
/// Helper to get the correct PlexClient for an item's server
PlexClient _getClientForItem(BuildContext context, dynamic item) {
String? serverId;
if (item is PlexMetadata) {
serverId = item.serverId;
} else if (item is PlexPlaylist) {
serverId = item.serverId;
}
return context.getClientForServer(serverId);
}
Widget _buildPosterImage(BuildContext context, dynamic item) {
String? posterUrl;
IconData fallbackIcon = Icons.movie;
@@ -615,16 +675,9 @@ Widget _buildPosterImage(BuildContext context, dynamic item) {
}
if (posterUrl != null) {
return Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return SkeletonLoader(
child: Center(
child: Icon(fallbackIcon, size: 40, color: Colors.white54),
),
);
}
return Builder(
builder: (context) {
final client = _getClientForItem(context, item);
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(posterUrl!),
+120 -21
View File
@@ -1,15 +1,18 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_playlist.dart';
import '../providers/playback_state_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/app_logger.dart';
import '../utils/collection_playlist_play_helper.dart';
import '../utils/library_refresh_notifier.dart';
import '../utils/video_player_navigation.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
import '../widgets/file_info_bottom_sheet.dart';
import '../utils/shuffle_play_helper.dart';
import '../i18n/strings.g.dart';
/// Helper class to store menu action data
@@ -57,9 +60,22 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
_tapPosition = details.globalPosition;
}
/// Get the correct PlexClient for this item's server
PlexClient _getClientForItem() {
String? serverId;
// Get serverId from the item (could be PlexMetadata or PlexPlaylist)
if (widget.item is PlexMetadata) {
serverId = (widget.item as PlexMetadata).serverId;
} else if (widget.item is PlexPlaylist) {
serverId = (widget.item as PlexPlaylist).serverId;
}
return context.getClientForServer(serverId);
}
void _showContextMenu(BuildContext context) async {
final client = context.client;
if (client == null) return;
final client = _getClientForItem();
final isPlaylist = widget.item is PlexPlaylist;
final metadata = isPlaylist ? null : widget.item as PlexMetadata;
@@ -374,7 +390,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
break;
case 'shuffle_play':
await handleShufflePlay(context, metadata!);
await _handleShufflePlayWithQueue(context);
break;
case 'play':
@@ -423,9 +439,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
) async {
if (ratingKey == null) return;
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final client = _getClientForItem();
try {
final metadata = await client.getMetadata(ratingKey);
@@ -447,8 +461,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
/// Show file info bottom sheet
Future<void> _showFileInfo(BuildContext context) async {
final client = context.client;
if (client == null) return;
final client = _getClientForItem();
try {
// Show loading indicator
@@ -500,6 +513,96 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
}
}
/// Handle shuffle play using play queues
Future<void> _handleShufflePlayWithQueue(BuildContext context) async {
final client = _getClientForItem();
final metadata = widget.item as PlexMetadata;
final playbackState = context.read<PlaybackStateProvider>();
final itemType = metadata.type.toLowerCase();
try {
// Show loading indicator
if (context.mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) =>
const Center(child: CircularProgressIndicator()),
);
}
// Determine the rating key for the play queue
String showRatingKey;
if (itemType == 'show') {
showRatingKey = metadata.ratingKey;
} else if (itemType == 'season') {
// For seasons, we need the show's rating key
// The season's parentRatingKey should point to the show
if (metadata.parentRatingKey == null) {
throw Exception('Season is missing parentRatingKey');
}
showRatingKey = metadata.parentRatingKey!;
} else {
throw Exception('Shuffle play only works for shows and seasons');
}
// Create a shuffled play queue for the show
final playQueue = await client.createShowPlayQueue(
showRatingKey: showRatingKey,
shuffle: 1,
);
// Close loading indicator
if (context.mounted) {
Navigator.pop(context);
}
if (playQueue == null ||
playQueue.items == null ||
playQueue.items!.isEmpty) {
if (context.mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(t.messages.noEpisodesFound)));
}
return;
}
// Initialize playback state with the play queue
await playbackState.setPlaybackFromPlayQueue(
playQueue,
showRatingKey,
serverId: metadata.serverId,
serverName: metadata.serverName,
);
// Set the client for the playback state provider
playbackState.setClient(client);
// Navigate to the first episode in the shuffled queue
final firstEpisode = playQueue.items!.first.copyWith(
serverId: metadata.serverId,
serverName: metadata.serverName,
);
if (context.mounted) {
await navigateToVideoPlayer(context, metadata: firstEpisode);
}
} 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(t.messages.errorLoading(error: e.toString()))),
);
}
}
}
/// Show submenu for Add to... (Playlist or Collection)
Future<void> _showAddToSubmenu(BuildContext context) async {
final useBottomSheet = Platform.isIOS || Platform.isAndroid;
@@ -583,8 +686,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
/// Show dialog to select playlist and add item
Future<void> _showAddToPlaylistDialog(BuildContext context) async {
final client = context.client;
if (client == null) return;
final client = _getClientForItem();
try {
final metadata = widget.item as PlexMetadata;
@@ -694,8 +796,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
/// Show dialog to select collection and add item
Future<void> _showAddToCollectionDialog(BuildContext context) async {
final client = context.client;
if (client == null) return;
final client = _getClientForItem();
try {
final metadata = widget.item as PlexMetadata;
@@ -784,6 +885,8 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
final itemUri = await client.buildMetadataUri(metadata.ratingKey);
appLogger.d('Built URI for $itemType: $itemUri');
if (!context.mounted) return;
if (result == '_create_new') {
// Create new collection flow
final collectionName = await showDialog<String>(
@@ -916,8 +1019,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
BuildContext context,
PlexMetadata metadata,
) async {
final client = context.client;
if (client == null) return;
final client = _getClientForItem();
if (widget.collectionId == null) {
appLogger.e('Cannot remove from collection: collectionId is null');
@@ -992,8 +1094,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
bool isCollection,
bool isPlaylist,
) async {
final client = context.client;
if (client == null) return;
final client = _getClientForItem();
await playCollectionOrPlaylist(
context: context,
@@ -1009,8 +1110,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
bool isCollection,
bool isPlaylist,
) async {
final client = context.client;
if (client == null) return;
final client = _getClientForItem();
await playCollectionOrPlaylist(
context: context,
@@ -1026,8 +1126,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
bool isCollection,
bool isPlaylist,
) async {
final client = context.client;
if (client == null) return;
final client = _getClientForItem();
final itemTitle = widget.item.title;
final itemTypeLabel = isCollection
+10 -8
View File
@@ -1,9 +1,9 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../providers/plex_client_provider.dart';
import '../utils/duration_formatter.dart';
import '../utils/provider_extensions.dart';
import '../i18n/strings.g.dart';
/// Custom list item widget for playlist items
@@ -118,15 +118,17 @@ class PlaylistItemCard extends StatelessWidget {
);
}
/// Get the correct PlexClient for this item's server
PlexClient _getClientForItem(BuildContext context) {
return context.getClientForServer(item.serverId);
}
Widget _buildPosterImage(BuildContext context) {
final posterUrl = item.posterThumb();
if (posterUrl != null) {
return Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return _buildPlaceholder();
}
return Builder(
builder: (context) {
final client = _getClientForItem(context);
return ClipRRect(
borderRadius: BorderRadius.circular(6),
-88
View File
@@ -1,88 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/user_switching_utils.dart';
import 'user_avatar_widget.dart';
import '../screens/profile_switch_screen.dart';
class ProfileSelector extends StatelessWidget {
final double avatarSize;
final bool showCurrentUserOnly;
const ProfileSelector({
super.key,
this.avatarSize = 32,
this.showCurrentUserOnly = false,
});
@override
Widget build(BuildContext context) {
return Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
if (userProvider.currentUser == null) {
return const SizedBox.shrink();
}
if (showCurrentUserOnly || !userProvider.hasMultipleUsers) {
// Show only current user avatar
return UserAvatarWidget(
user: userProvider.currentUser!,
size: avatarSize,
onTap: userProvider.hasMultipleUsers
? () => _showProfileSwitchDialog(context)
: null,
);
}
// Show horizontal list of users
return SizedBox(
height: avatarSize + 8,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: userProvider.home?.users.length ?? 0,
separatorBuilder: (context, index) => const SizedBox(width: 8),
itemBuilder: (context, index) {
final users = userProvider.home!.users;
final user = users[index];
final isCurrentUser = user.uuid == userProvider.currentUser?.uuid;
return Container(
decoration: isCurrentUser
? BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Theme.of(context).colorScheme.primary,
width: 2,
),
)
: null,
child: Padding(
padding: EdgeInsets.all(isCurrentUser ? 2 : 0),
child: UserAvatarWidget(
user: user,
size: avatarSize - (isCurrentUser ? 4 : 0),
onTap: isCurrentUser
? () => _showProfileSwitchDialog(context)
: () => _switchToUser(context, user),
),
),
);
},
),
);
},
);
}
void _showProfileSwitchDialog(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ProfileSwitchScreen()),
);
}
void _switchToUser(BuildContext context, PlexHomeUser user) async {
await UserSwitchingUtils.switchToUser(context, user);
}
}
-88
View File
@@ -1,88 +0,0 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/user_switching_utils.dart';
import 'profile_list_tile.dart';
import '../i18n/strings.g.dart';
class ProfileSwitchDialog extends StatelessWidget {
const ProfileSwitchDialog({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
final users = userProvider.home?.users ?? [];
return AlertDialog(
content: SizedBox(
width: double.maxFinite,
height: users.isEmpty ? 100 : (users.length * 72.0).clamp(100, 400),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (userProvider.isLoading)
const Expanded(
child: Center(child: CircularProgressIndicator()),
)
else if (users.isEmpty)
Expanded(
child: Center(child: Text(t.profile.noUsersAvailable)),
)
else
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: users.length,
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),
),
),
);
},
),
),
if (userProvider.error != null)
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text(
userProvider.error!,
style: TextStyle(
color: theme.colorScheme.error,
fontSize: 12,
),
textAlign: TextAlign.center,
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(t.common.cancel),
),
],
);
},
);
}
void _switchToUser(BuildContext context, PlexHomeUser user) async {
await UserSwitchingUtils.switchToUser(context, user, popOnSuccess: true);
}
}
+65
View File
@@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
/// A small badge widget that indicates which server content is from
/// Shows server name or first letter with optional tooltip
class ServerBadge extends StatelessWidget {
final String? serverName;
final Color? backgroundColor;
final Color? textColor;
final double size;
final bool showFullName;
const ServerBadge({
super.key,
required this.serverName,
this.backgroundColor,
this.textColor,
this.size = 20,
this.showFullName = false,
});
@override
Widget build(BuildContext context) {
if (serverName == null || serverName!.isEmpty) {
return const SizedBox.shrink();
}
final theme = Theme.of(context);
final bgColor =
backgroundColor ??
theme.colorScheme.primaryContainer.withValues(alpha: 0.8);
final fgColor = textColor ?? theme.colorScheme.onPrimaryContainer;
final displayText = showFullName
? serverName!
: serverName!.substring(0, 1).toUpperCase();
final badge = Container(
padding: EdgeInsets.symmetric(
horizontal: showFullName ? 6 : 4,
vertical: 2,
),
decoration: BoxDecoration(
color: bgColor,
borderRadius: BorderRadius.circular(4),
),
child: Text(
displayText,
style: TextStyle(
color: fgColor,
fontSize: showFullName ? 10 : 11,
fontWeight: FontWeight.w600,
height: 1.2,
),
),
);
// If showing full name, no need for tooltip
if (showFullName) {
return badge;
}
// Show tooltip with full server name on hover/long press
return Tooltip(message: serverName!, child: badge);
}
}
-103
View File
@@ -1,103 +0,0 @@
import 'package:flutter/material.dart';
import '../services/plex_auth_service.dart';
import '../i18n/strings.g.dart';
class ServerListTile extends StatelessWidget {
final PlexServer server;
final VoidCallback onTap;
final bool showTrailingIcon;
final bool isCurrentServer;
const ServerListTile({
super.key,
required this.server,
required this.onTap,
this.showTrailingIcon = true,
this.isCurrentServer = false,
});
@override
Widget build(BuildContext context) {
final isOnline = server.isOnline;
return Semantics(
selected: isCurrentServer,
identifier: server.name,
label: server.name,
child: ListTile(
key: ValueKey(server.name),
leading: Icon(
Icons.dns,
color: isOnline
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.5),
semanticLabel: t.common.server,
),
title: Text(server.name),
subtitle: Semantics(
label:
'${isOnline ? t.common.online : t.common.offline}, ${server.owned ? t.common.owned : t.common.shared}',
excludeSemantics: true,
child: Row(
children: [
Semantics(
excludeSemantics: true,
child: Icon(
isOnline ? Icons.circle : Icons.circle_outlined,
size: 10,
color: isOnline ? Colors.green : Colors.grey,
),
),
const SizedBox(width: 4),
Text(
isOnline ? t.common.online : t.common.offline,
style: TextStyle(
fontSize: 12,
color: isOnline ? Colors.green : Colors.grey,
),
),
const SizedBox(width: 8),
Semantics(
excludeSemantics: true,
child: Text(
'•',
style: TextStyle(
fontSize: 12,
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.5),
),
),
),
const SizedBox(width: 8),
Text(
server.owned ? t.common.owned : t.common.shared,
style: const TextStyle(fontSize: 12),
),
],
),
),
trailing: isCurrentServer
? Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(12),
),
child: Text(
t.common.current,
style: TextStyle(
fontSize: 10,
color: Theme.of(context).colorScheme.onPrimary,
fontWeight: FontWeight.bold,
letterSpacing: 0.5,
),
),
)
: (showTrailingIcon ? const Icon(Icons.chevron_right) : null),
onTap: isCurrentServer ? null : onTap,
enabled: !isCurrentServer,
),
);
}
}
+7 -27
View File
@@ -1,5 +1,6 @@
import 'package:flutter/material.dart';
import '../models/plex_sort.dart';
import '../widgets/bottom_sheet_header.dart';
import '../i18n/strings.g.dart';
class SortBottomSheet extends StatefulWidget {
@@ -61,35 +62,14 @@ class _SortBottomSheetState extends State<SortBottomSheet> {
builder: (context, scrollController) {
return Column(
children: [
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Theme.of(context).dividerColor),
),
),
child: Row(
children: [
Expanded(
child: Text(
t.libraries.sortBy,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
if (widget.onClear != null)
TextButton(
BottomSheetHeader(
title: t.libraries.sortBy,
action: widget.onClear != null
? TextButton(
onPressed: _handleClear,
child: Text(t.common.clear),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () => Navigator.pop(context),
),
],
),
)
: null,
),
Expanded(
child: RadioGroup<PlexSort>(
+82
View File
@@ -0,0 +1,82 @@
import 'package:flutter/material.dart';
/// Base widget for displaying state messages (empty, error, etc.)
/// Provides a consistent UI pattern for showing icons, messages, and actions
class StateMessageWidget extends StatelessWidget {
/// The message to display
final String message;
/// Optional icon to display above the message
final IconData? icon;
/// Optional color for the icon
final Color? iconColor;
/// Optional color for the message text
final Color? textColor;
/// Optional callback for action button
final VoidCallback? onAction;
/// Optional label for the action button
final String? actionLabel;
/// Optional icon for the action button
final IconData? actionIcon;
const StateMessageWidget({
super.key,
required this.message,
this.icon,
this.iconColor,
this.textColor,
this.onAction,
this.actionLabel,
this.actionIcon,
});
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (icon != null) ...[
Icon(
icon,
size: 64,
color:
iconColor ??
Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.4),
),
const SizedBox(height: 16),
],
Text(
message,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
color:
textColor ??
Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.6),
),
),
if (onAction != null && actionLabel != null) ...[
const SizedBox(height: 24),
FilledButton.icon(
onPressed: onAction,
icon: Icon(actionIcon ?? Icons.refresh),
label: Text(actionLabel!),
),
],
],
),
),
);
}
}
@@ -0,0 +1,320 @@
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../../models/plex_media_info.dart';
import '../../models/plex_metadata.dart';
import '../../services/fullscreen_state_manager.dart';
import '../../utils/desktop_window_padding.dart';
import '../../utils/duration_formatter.dart';
import '../../i18n/strings.g.dart';
import '../app_bar_back_button.dart';
import 'widgets/timeline_slider.dart';
/// Desktop-specific video controls layout with top bar and bottom controls
class DesktopVideoControls extends StatelessWidget {
final Player player;
final PlexMetadata metadata;
final VoidCallback? onNext;
final VoidCallback? onPrevious;
final List<PlexChapter> chapters;
final bool chaptersLoaded;
final int seekTimeSmall;
final VoidCallback onSeekToPreviousChapter;
final VoidCallback onSeekToNextChapter;
final ValueChanged<Duration> onSeek;
final ValueChanged<Duration> onSeekEnd;
final Widget volumeControl;
final Widget trackChapterControls;
final IconData Function(int) getReplayIcon;
final IconData Function(int) getForwardIcon;
const DesktopVideoControls({
super.key,
required this.player,
required this.metadata,
this.onNext,
this.onPrevious,
required this.chapters,
required this.chaptersLoaded,
required this.seekTimeSmall,
required this.onSeekToPreviousChapter,
required this.onSeekToNextChapter,
required this.onSeek,
required this.onSeekEnd,
required this.volumeControl,
required this.trackChapterControls,
required this.getReplayIcon,
required this.getForwardIcon,
});
@override
Widget build(BuildContext context) {
return Column(
children: [
// Top bar with back button and title
_buildTopBar(context),
const Spacer(),
// Bottom controls
_buildBottomControls(context),
],
);
}
Widget _buildTopBar(BuildContext context) {
// Use global fullscreen state for padding
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
// In fullscreen on macOS, use less left padding since traffic lights auto-hide
// In normal mode on macOS, need more padding to avoid traffic lights
final leftPadding = Platform.isMacOS
? (isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
: DesktopWindowPadding.macOSLeft)
: DesktopWindowPadding.macOSLeftFullscreen;
return _buildTopBarContent(context, leftPadding);
},
);
}
Widget _buildTopBarContent(BuildContext context, double leftPadding) {
final topBar = Padding(
padding: EdgeInsets.only(left: leftPadding, right: 16),
child: Row(
children: [
AppBarBackButton(
style: BackButtonStyle.video,
semanticLabel: t.videoControls.backButton,
onPressed: () => Navigator.of(context).pop(true),
),
const SizedBox(width: 16),
Expanded(
child: Platform.isMacOS
? _buildMacOSSingleLineTitle()
: _buildMultiLineTitle(),
),
],
),
);
// On macOS, wrap with GestureDetector to prevent window dragging
if (Platform.isMacOS) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) {}, // Consume pan gestures to prevent window dragging
child: topBar,
);
}
return topBar;
}
Widget _buildMacOSSingleLineTitle() {
// Build single-line title combining series and episode info
final seriesName = metadata.grandparentTitle ?? metadata.title;
final hasEpisodeInfo =
metadata.parentIndex != null && metadata.index != null;
final titleText = hasEpisodeInfo
? '$seriesName · S${metadata.parentIndex} E${metadata.index} · ${metadata.title}'
: seriesName;
return Text(
titleText,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
fontWeight: FontWeight.w500,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
Widget _buildMultiLineTitle() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
metadata.grandparentTitle ?? metadata.title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (metadata.parentIndex != null && metadata.index != null)
Text(
'S${metadata.parentIndex} · E${metadata.index} · ${metadata.title}',
style: const TextStyle(color: Colors.white70, fontSize: 14),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
);
}
Widget _buildBottomControls(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Column(
children: [
// Row 1: Timeline with time indicators
StreamBuilder<Duration>(
stream: player.stream.position,
initialData: player.state.position,
builder: (context, positionSnapshot) {
return StreamBuilder<Duration>(
stream: player.stream.duration,
initialData: player.state.duration,
builder: (context, durationSnapshot) {
final position = positionSnapshot.data ?? Duration.zero;
final duration = durationSnapshot.data ?? Duration.zero;
return Row(
children: [
Text(
formatDurationTimestamp(position),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
const SizedBox(width: 12),
Expanded(
child: TimelineSlider(
position: position,
duration: duration,
chapters: chapters,
chaptersLoaded: chaptersLoaded,
onSeek: onSeek,
onSeekEnd: onSeekEnd,
),
),
const SizedBox(width: 12),
Text(
formatDurationTimestamp(duration),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
],
);
},
);
},
),
const SizedBox(height: 4),
// Row 2: Playback controls and options
Row(
children: [
// Previous item
Semantics(
label: t.videoControls.previousButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
Icons.skip_previous,
color: onPrevious != null ? Colors.white : Colors.white54,
),
onPressed: onPrevious,
),
),
// Previous chapter (or skip backward if no chapters)
Semantics(
label: chapters.isEmpty
? t.videoControls.seekBackwardButton(seconds: seekTimeSmall)
: t.videoControls.previousChapterButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
chapters.isEmpty
? getReplayIcon(seekTimeSmall)
: Icons.fast_rewind,
color: Colors.white,
),
onPressed: onSeekToPreviousChapter,
),
),
// Play/Pause
StreamBuilder<bool>(
stream: player.stream.playing,
initialData: player.state.playing,
builder: (context, snapshot) {
final isPlaying = snapshot.data ?? false;
return Semantics(
label: isPlaying
? t.videoControls.pauseButton
: t.videoControls.playButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
isPlaying ? Icons.pause : Icons.play_arrow,
color: Colors.white,
size: 32,
),
iconSize: 32,
onPressed: () {
if (isPlaying) {
player.pause();
} else {
player.play();
}
},
),
);
},
),
// Next chapter (or skip forward if no chapters)
Semantics(
label: chapters.isEmpty
? t.videoControls.seekForwardButton(seconds: seekTimeSmall)
: t.videoControls.nextChapterButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
chapters.isEmpty
? getForwardIcon(seekTimeSmall)
: Icons.fast_forward,
color: Colors.white,
),
onPressed: onSeekToNextChapter,
),
),
// Next item
Semantics(
label: t.videoControls.nextButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
Icons.skip_next,
color: onNext != null ? Colors.white : Colors.white54,
),
onPressed: onNext,
),
),
const Spacer(),
// Volume control
volumeControl,
const SizedBox(width: 16),
// Audio track, subtitle, and chapter controls
trackChapterControls,
],
),
],
),
);
}
}
@@ -0,0 +1,297 @@
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../../models/plex_media_info.dart';
import '../../models/plex_metadata.dart';
import '../../utils/duration_formatter.dart';
import '../../utils/player_utils.dart';
import '../../utils/video_control_icons.dart';
import '../../i18n/strings.g.dart';
import '../app_bar_back_button.dart';
import 'widgets/timeline_slider.dart';
/// Mobile video controls layout for Plex video player
///
/// Displays a full-screen overlay with:
/// - Top bar: Back button, title, and track/chapter controls
/// - Center: Large playback controls (seek backward, play/pause, seek forward)
/// - Bottom bar: Timeline slider with chapter markers and timestamps
class MobileVideoControls extends StatelessWidget {
final Player player;
final PlexMetadata metadata;
final List<PlexChapter> chapters;
final bool chaptersLoaded;
final int seekTimeSmall;
final Widget trackChapterControls;
final Function(Duration) onSeek;
final Function(Duration) onSeekEnd;
final VoidCallback onPlayPause;
final VoidCallback? onCancelAutoHide;
final VoidCallback? onStartAutoHide;
const MobileVideoControls({
super.key,
required this.player,
required this.metadata,
required this.chapters,
required this.chaptersLoaded,
required this.seekTimeSmall,
required this.trackChapterControls,
required this.onSeek,
required this.onSeekEnd,
required this.onPlayPause,
this.onCancelAutoHide,
this.onStartAutoHide,
});
@override
Widget build(BuildContext context) {
return Column(
children: [
// Top bar with back button and track/chapter controls
_buildTopBar(context),
const Spacer(),
// Centered large playback controls
_buildPlaybackControls(context),
const Spacer(),
// Progress bar at bottom
_buildBottomBar(context),
],
);
}
Widget _buildTopBar(BuildContext context) {
final topBar = _conditionalSafeArea(
context: context,
bottom: false, // Only respect top safe area when in portrait
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
AppBarBackButton(
style: BackButtonStyle.video,
semanticLabel: t.videoControls.backButton,
onPressed: () => Navigator.of(context).pop(true),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
metadata.grandparentTitle ?? metadata.title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (metadata.parentIndex != null && metadata.index != null)
Text(
'S${metadata.parentIndex} · E${metadata.index} · ${metadata.title}',
style: const TextStyle(
color: Colors.white70,
fontSize: 14,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
// Track and chapter controls in top right
trackChapterControls,
],
),
),
);
// On macOS, wrap with GestureDetector to prevent window dragging
if (Platform.isMacOS) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) {}, // Consume pan gestures to prevent window dragging
child: topBar,
);
}
return topBar;
}
Widget _buildPlaybackControls(BuildContext context) {
return StreamBuilder<bool>(
stream: player.stream.playing,
initialData: player.state.playing,
builder: (context, snapshot) {
final isPlaying = snapshot.data ?? false;
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: Semantics(
label: t.videoControls.seekBackwardButton(
seconds: seekTimeSmall,
),
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
getReplayIcon(seekTimeSmall),
color: Colors.white,
size: 48,
),
iconSize: 48,
onPressed: () {
seekWithClamping(player, Duration(seconds: -seekTimeSmall));
},
),
),
),
const SizedBox(width: 48),
Container(
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: Semantics(
label: isPlaying
? t.videoControls.pauseButton
: t.videoControls.playButton,
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
isPlaying ? Icons.pause : Icons.play_arrow,
color: Colors.white,
size: 72,
),
iconSize: 72,
onPressed: () {
if (isPlaying) {
player.pause();
onCancelAutoHide?.call(); // Cancel auto-hide when paused
} else {
player.play();
onStartAutoHide?.call(); // Start auto-hide when playing
}
},
),
),
),
const SizedBox(width: 48),
Container(
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: Semantics(
label: t.videoControls.seekForwardButton(
seconds: seekTimeSmall,
),
button: true,
excludeSemantics: true,
child: IconButton(
icon: Icon(
getForwardIcon(seekTimeSmall),
color: Colors.white,
size: 48,
),
iconSize: 48,
onPressed: () {
seekWithClamping(player, Duration(seconds: seekTimeSmall));
},
),
),
),
],
);
},
);
}
Widget _buildBottomBar(BuildContext context) {
return _conditionalSafeArea(
context: context,
top: false, // Only respect bottom safe area when in portrait
child: Padding(
padding: const EdgeInsets.all(16),
child: StreamBuilder<Duration>(
stream: player.stream.position,
initialData: player.state.position,
builder: (context, positionSnapshot) {
return StreamBuilder<Duration>(
stream: player.stream.duration,
initialData: player.state.duration,
builder: (context, durationSnapshot) {
final position = positionSnapshot.data ?? Duration.zero;
final duration = durationSnapshot.data ?? Duration.zero;
return Column(
children: [
TimelineSlider(
position: position,
duration: duration,
chapters: chapters,
chaptersLoaded: chaptersLoaded,
onSeek: onSeek,
onSeekEnd: onSeekEnd,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
formatDurationTimestamp(position),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
Text(
formatDurationTimestamp(duration),
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
],
),
),
],
);
},
);
},
),
),
);
}
/// Conditionally wraps child with SafeArea only in portrait mode
Widget _conditionalSafeArea({
required BuildContext context,
required Widget child,
bool top = true,
bool bottom = true,
}) {
final orientation = MediaQuery.of(context).orientation;
final isPortrait = orientation == Orientation.portrait;
// Only apply SafeArea in portrait mode
if (isPortrait) {
return SafeArea(top: top, bottom: bottom, child: child);
}
// In landscape, return child without SafeArea
return child;
}
}
@@ -1,180 +0,0 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:plezy/services/settings_service.dart';
import '../../../i18n/strings.g.dart';
import '../../../utils/duration_formatter.dart';
import 'base_video_control_sheet.dart';
/// Bottom sheet for adjusting audio sync offset
class AudioSyncSheet extends StatefulWidget {
final Player player;
final int initialOffset;
const AudioSyncSheet({
super.key,
required this.player,
required this.initialOffset,
});
static void show(BuildContext context, Player player, int initialOffset) {
showModalBottomSheet(
context: context,
backgroundColor: Colors.grey[900],
isScrollControlled: true,
constraints: BaseVideoControlSheet.getBottomSheetConstraints(context),
builder: (context) =>
AudioSyncSheet(player: player, initialOffset: initialOffset),
);
}
@override
State<AudioSyncSheet> createState() => _AudioSyncSheetState();
}
class _AudioSyncSheetState extends State<AudioSyncSheet> {
late double _currentOffset;
@override
void initState() {
super.initState();
_currentOffset = widget.initialOffset.toDouble();
}
void _applyOffset(double offsetMs) async {
// Convert milliseconds to seconds for media_kit
final offsetSeconds = offsetMs / 1000.0;
// Apply to player using setProperty
await (widget.player.platform as dynamic).setProperty(
'audio-delay',
offsetSeconds.toString(),
);
// Save to settings
final settings = await SettingsService.getInstance();
await settings.setAudioSyncOffset(offsetMs.round());
}
void _resetOffset() {
setState(() {
_currentOffset = 0;
});
_applyOffset(0);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(Icons.sync, color: Colors.white),
const SizedBox(width: 12),
const Text(
'Audio Sync',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.white24, height: 1),
Expanded(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Current offset display
Text(
formatSyncOffset(_currentOffset),
style: const TextStyle(
color: Colors.white,
fontSize: 48,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
_currentOffset > 0
? 'Audio plays later'
: _currentOffset < 0
? 'Audio plays earlier'
: 'No offset',
style: const TextStyle(
color: Colors.white70,
fontSize: 16,
),
),
const SizedBox(height: 48),
// Slider
Row(
children: [
Text(
t.videoControls.minusTime(amount: "2", unit: "s"),
style: const TextStyle(color: Colors.white70),
),
Expanded(
child: Slider(
value: _currentOffset,
min: -2000,
max: 2000,
divisions: 80, // 50ms steps
activeColor: Colors.blue,
inactiveColor: Colors.white24,
onChanged: (value) {
setState(() {
_currentOffset = value;
});
},
onChangeEnd: (value) {
_applyOffset(value);
},
),
),
Text(
t.videoControls.addTime(amount: "2", unit: "s"),
style: const TextStyle(color: Colors.white70),
),
],
),
const SizedBox(height: 24),
// Reset button
ElevatedButton.icon(
onPressed: _currentOffset != 0 ? _resetOffset : null,
icon: const Icon(Icons.restart_alt),
label: Text(t.videoControls.resetToZero),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.grey[800],
foregroundColor: Colors.white,
disabledBackgroundColor: Colors.grey[850],
disabledForegroundColor: Colors.white38,
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
),
),
],
),
),
),
],
),
),
);
}
}
@@ -1,107 +1,40 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../../../i18n/strings.g.dart';
import 'base_video_control_sheet.dart';
import 'track_selection_sheet.dart';
/// Bottom sheet for selecting audio tracks
class AudioTrackSheet extends StatelessWidget {
final Player player;
final Function(AudioTrack)? onTrackChanged;
const AudioTrackSheet({super.key, required this.player, this.onTrackChanged});
class AudioTrackSheet {
static void show(
BuildContext context,
Player player, {
Function(AudioTrack)? onTrackChanged,
}) {
BaseVideoControlSheet.showSheet(
TrackSelectionSheet.show<AudioTrack>(
context: context,
builder: (context) =>
AudioTrackSheet(player: player, onTrackChanged: onTrackChanged),
);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Tracks>(
stream: player.stream.tracks,
initialData: player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final audioTracks = (tracks?.audio ?? [])
.where((track) => track.id != 'auto' && track.id != 'no')
.toList();
return BaseVideoControlSheet(
title: t.videoControls.audioLabel,
icon: Icons.audiotrack,
child: audioTracks.isEmpty
? const Center(
child: Text(
'No audio tracks available',
style: TextStyle(color: Colors.white70),
),
)
: StreamBuilder<Track>(
stream: player.stream.track,
initialData: player.state.track,
builder: (context, selectedSnapshot) {
// Use snapshot data or fall back to current state
final currentTrack =
selectedSnapshot.data ?? player.state.track;
final selectedTrack = currentTrack.audio;
final selectedId = selectedTrack.id;
return ListView.builder(
itemCount: audioTracks.length,
itemBuilder: (context, index) {
final audioTrack = audioTracks[index];
final isSelected = audioTrack.id == selectedId;
final parts = <String>[];
if (audioTrack.title != null &&
audioTrack.title!.isNotEmpty) {
parts.add(audioTrack.title!);
}
if (audioTrack.language != null &&
audioTrack.language!.isNotEmpty) {
parts.add(audioTrack.language!.toUpperCase());
}
if (audioTrack.codec != null &&
audioTrack.codec!.isNotEmpty) {
parts.add(audioTrack.codec!.toUpperCase());
}
if (audioTrack.channelscount != null) {
parts.add('${audioTrack.channelscount}ch');
}
final label = parts.isEmpty
? 'Audio Track ${index + 1}'
: parts.join(' · ');
return ListTile(
title: Text(
label,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
player.setAudioTrack(audioTrack);
onTrackChanged?.call(audioTrack);
Navigator.pop(context);
},
);
},
);
},
),
);
player: player,
title: t.videoControls.audioLabel,
icon: Icons.audiotrack,
extractTracks: (tracks) => tracks?.audio ?? [],
getCurrentTrack: (track) => track.audio,
buildLabel: (audioTrack, index) {
final parts = <String>[];
if (audioTrack.title != null && audioTrack.title!.isNotEmpty) {
parts.add(audioTrack.title!);
}
if (audioTrack.language != null && audioTrack.language!.isNotEmpty) {
parts.add(audioTrack.language!.toUpperCase());
}
if (audioTrack.codec != null && audioTrack.codec!.isNotEmpty) {
parts.add(audioTrack.codec!.toUpperCase());
}
if (audioTrack.channelscount != null) {
parts.add('${audioTrack.channelscount}ch');
}
return parts.isEmpty ? 'Audio Track ${index + 1}' : parts.join(' · ');
},
setTrack: (track) => player.setAudioTrack(track),
onTrackChanged: onTrackChanged,
);
}
}
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'video_sheet_header.dart';
/// Base class for video control bottom sheets providing common UI structure
class BaseVideoControlSheet extends StatelessWidget {
@@ -6,6 +7,7 @@ class BaseVideoControlSheet extends StatelessWidget {
final IconData icon;
final Widget child;
final Color? iconColor;
final VoidCallback? onBack;
const BaseVideoControlSheet({
super.key,
@@ -13,6 +15,7 @@ class BaseVideoControlSheet extends StatelessWidget {
required this.icon,
required this.child,
this.iconColor,
this.onBack,
});
/// Get consistent bottom sheet constraints across all video control sheets
@@ -48,7 +51,12 @@ class BaseVideoControlSheet extends StatelessWidget {
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
_buildHeader(context),
VideoSheetHeader(
title: title,
icon: icon,
iconColor: iconColor,
onBack: onBack,
),
const Divider(color: Colors.white24, height: 1),
Expanded(child: child),
],
@@ -56,29 +64,4 @@ class BaseVideoControlSheet extends StatelessWidget {
),
);
}
Widget _buildHeader(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Icon(icon, color: iconColor ?? Colors.white),
const SizedBox(width: 12),
Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
);
}
}
@@ -1,9 +1,9 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:provider/provider.dart';
import '../../../client/plex_client.dart';
import '../../../models/plex_media_info.dart';
import '../../../providers/plex_client_provider.dart';
import '../../../utils/duration_formatter.dart';
import '../../../utils/provider_extensions.dart';
import 'base_video_control_sheet.dart';
/// Bottom sheet for selecting chapters
@@ -11,30 +11,39 @@ class ChapterSheet extends StatelessWidget {
final Player player;
final List<PlexChapter> chapters;
final bool chaptersLoaded;
final String? serverId; // Server ID for the metadata these chapters belong to
const ChapterSheet({
super.key,
required this.player,
required this.chapters,
required this.chaptersLoaded,
this.serverId,
});
static void show(
BuildContext context,
Player player,
List<PlexChapter> chapters,
bool chaptersLoaded,
) {
bool chaptersLoaded, {
String? serverId,
}) {
BaseVideoControlSheet.showSheet(
context: context,
builder: (context) => ChapterSheet(
player: player,
chapters: chapters,
chaptersLoaded: chaptersLoaded,
serverId: serverId,
),
);
}
/// Get the correct PlexClient for the metadata's server
PlexClient _getClientForChapters(BuildContext context) {
return context.getClientForServer(serverId);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Duration>(
@@ -84,16 +93,9 @@ class ChapterSheet extends StatelessWidget {
children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return const Icon(
Icons.image,
color: Colors.white54,
size: 34,
);
}
child: Builder(
builder: (context) {
final client = _getClientForChapters(context);
return Image.network(
client.getThumbnailUrl(chapter.thumb),
width: 60,
@@ -1,64 +0,0 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'base_video_control_sheet.dart';
/// Bottom sheet for selecting playback speed
class PlaybackSpeedSheet extends StatelessWidget {
final Player player;
const PlaybackSpeedSheet({super.key, required this.player});
static void show(BuildContext context, Player player) {
BaseVideoControlSheet.showSheet(
context: context,
builder: (context) => PlaybackSpeedSheet(player: player),
);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<double>(
stream: player.stream.rate,
initialData: player.state.rate,
builder: (context, snapshot) {
final currentRate = snapshot.data ?? 1.0;
// Define available playback speeds
final speeds = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0];
return BaseVideoControlSheet(
title: 'Playback Speed',
icon: Icons.speed,
child: ListView.builder(
itemCount: speeds.length,
itemBuilder: (context, index) {
final speed = speeds[index];
final isSelected = (currentRate - speed).abs() < 0.01;
// Format speed label
final label = speed == 1.0
? 'Normal'
: '${speed.toStringAsFixed(2)}x';
return ListTile(
title: Text(
label,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
player.setRate(speed);
Navigator.pop(context);
},
);
},
),
);
},
);
}
}
@@ -1,54 +0,0 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../../../i18n/strings.g.dart';
import '../../../services/settings_service.dart';
import '../../../services/sleep_timer_service.dart';
import 'base_video_control_sheet.dart';
import '../widgets/sleep_timer_content.dart';
/// Bottom sheet for sleep timer configuration
class SleepTimerSheet extends StatelessWidget {
final Player player;
final int defaultDuration;
const SleepTimerSheet({
super.key,
required this.player,
required this.defaultDuration,
});
static void show(BuildContext context, Player player) async {
final settingsService = await SettingsService.getInstance();
final defaultDuration = settingsService.getSleepTimerDuration();
if (!context.mounted) return;
BaseVideoControlSheet.showSheet(
context: context,
builder: (context) =>
SleepTimerSheet(player: player, defaultDuration: defaultDuration),
);
}
@override
Widget build(BuildContext context) {
final sleepTimer = SleepTimerService();
return ListenableBuilder(
listenable: sleepTimer,
builder: (context, _) {
return BaseVideoControlSheet(
title: t.videoControls.sleepTimer,
icon: sleepTimer.isActive ? Icons.bedtime : Icons.bedtime_outlined,
iconColor: sleepTimer.isActive ? Colors.amber : null,
child: SleepTimerContent(
player: player,
sleepTimer: sleepTimer,
defaultDuration: defaultDuration,
onCancel: () => Navigator.pop(context),
),
);
},
);
}
}
@@ -1,144 +1,51 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../../../i18n/strings.g.dart';
import 'base_video_control_sheet.dart';
import 'track_selection_sheet.dart';
/// Bottom sheet for selecting subtitle tracks
class SubtitleTrackSheet extends StatelessWidget {
final Player player;
final Function(SubtitleTrack)? onTrackChanged;
const SubtitleTrackSheet({
super.key,
required this.player,
this.onTrackChanged,
});
class SubtitleTrackSheet {
static void show(
BuildContext context,
Player player, {
Function(SubtitleTrack)? onTrackChanged,
}) {
BaseVideoControlSheet.showSheet(
TrackSelectionSheet.show<SubtitleTrack>(
context: context,
builder: (context) =>
SubtitleTrackSheet(player: player, onTrackChanged: onTrackChanged),
);
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Tracks>(
stream: player.stream.tracks,
initialData: player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final subtitles = (tracks?.subtitle ?? [])
.where((track) => track.id != 'auto' && track.id != 'no')
.toList();
return BaseVideoControlSheet(
title: t.videoControls.subtitlesLabel,
icon: Icons.subtitles,
child: subtitles.isEmpty
? const Center(
child: Text(
'No subtitles available',
style: TextStyle(color: Colors.white70),
),
)
: StreamBuilder<Track>(
stream: player.stream.track,
initialData: player.state.track,
builder: (context, selectedSnapshot) {
// Use snapshot data or fall back to current state
final currentTrack =
selectedSnapshot.data ?? player.state.track;
final selectedTrack = currentTrack.subtitle;
final selectedId = selectedTrack.id;
final isOffSelected = selectedId == 'no';
return ListView.builder(
itemCount: subtitles.length + 1, // +1 for "Off" option
itemBuilder: (context, index) {
// First item is "Off"
if (index == 0) {
return ListTile(
title: Text(
'Off',
style: TextStyle(
color: isOffSelected
? Colors.blue
: Colors.white,
),
),
trailing: isOffSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
player.setSubtitleTrack(SubtitleTrack.no());
onTrackChanged?.call(SubtitleTrack.no());
Navigator.pop(context);
},
);
}
// Subsequent items are subtitle tracks
final subtitle = subtitles[index - 1];
final isSelected = subtitle.id == selectedId;
// Build label with available info
final parts = <String>[];
if (subtitle.title != null &&
subtitle.title!.isNotEmpty) {
parts.add(subtitle.title!);
}
if (subtitle.language != null &&
subtitle.language!.isNotEmpty) {
parts.add(subtitle.language!.toUpperCase());
}
if (subtitle.codec != null &&
subtitle.codec!.isNotEmpty) {
// Format codec names nicely
String codecName = subtitle.codec!.toUpperCase();
if (codecName == 'SUBRIP') {
codecName = 'SRT';
} else if (codecName == 'DVD_SUBTITLE') {
codecName = 'DVD';
} else if (codecName == 'ASS' || codecName == 'SSA') {
codecName = codecName; // Keep as-is
} else if (codecName == 'WEBVTT') {
codecName = 'VTT';
}
parts.add(codecName);
}
final label = parts.isEmpty
? 'Track $index'
: parts.join(' · ');
return ListTile(
title: Text(
label,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
player.setSubtitleTrack(subtitle);
onTrackChanged?.call(subtitle);
Navigator.pop(context);
},
);
},
);
},
),
);
player: player,
title: t.videoControls.subtitlesLabel,
icon: Icons.subtitles,
extractTracks: (tracks) => tracks?.subtitle ?? [],
getCurrentTrack: (track) => track.subtitle,
buildLabel: (subtitle, index) {
final parts = <String>[];
if (subtitle.title != null && subtitle.title!.isNotEmpty) {
parts.add(subtitle.title!);
}
if (subtitle.language != null && subtitle.language!.isNotEmpty) {
parts.add(subtitle.language!.toUpperCase());
}
if (subtitle.codec != null && subtitle.codec!.isNotEmpty) {
// Format codec names nicely
String codecName = subtitle.codec!.toUpperCase();
if (codecName == 'SUBRIP') {
codecName = 'SRT';
} else if (codecName == 'DVD_SUBTITLE') {
codecName = 'DVD';
} else if (codecName == 'ASS' || codecName == 'SSA') {
codecName = codecName; // Keep as-is
} else if (codecName == 'WEBVTT') {
codecName = 'VTT';
}
parts.add(codecName);
}
return parts.isEmpty ? 'Track ${index + 1}' : parts.join(' · ');
},
setTrack: (track) => player.setSubtitleTrack(track),
onTrackChanged: onTrackChanged,
showOffOption: true,
createOffTrack: () => SubtitleTrack.no(),
isOffTrack: (track) => track.id == 'no',
);
}
}
@@ -0,0 +1,197 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'base_video_control_sheet.dart';
/// Generic track selection sheet for audio and subtitle tracks
///
/// Type parameter [T] should be either [AudioTrack] or [SubtitleTrack]
class TrackSelectionSheet<T> extends StatelessWidget {
final Player player;
final String title;
final IconData icon;
final List<T> Function(Tracks?) extractTracks;
final T Function(Track) getCurrentTrack;
final String Function(T track, int index) buildLabel;
final void Function(T track) setTrack;
final Function(T)? onTrackChanged;
final bool showOffOption;
final T Function()? createOffTrack;
final bool Function(T track)? isOffTrack;
const TrackSelectionSheet({
super.key,
required this.player,
required this.title,
required this.icon,
required this.extractTracks,
required this.getCurrentTrack,
required this.buildLabel,
required this.setTrack,
this.onTrackChanged,
this.showOffOption = false,
this.createOffTrack,
this.isOffTrack,
});
static void show<T>({
required BuildContext context,
required Player player,
required String title,
required IconData icon,
required List<T> Function(Tracks?) extractTracks,
required T Function(Track) getCurrentTrack,
required String Function(T track, int index) buildLabel,
required void Function(T track) setTrack,
Function(T)? onTrackChanged,
bool showOffOption = false,
T Function()? createOffTrack,
bool Function(T track)? isOffTrack,
}) {
BaseVideoControlSheet.showSheet(
context: context,
builder: (context) => TrackSelectionSheet<T>(
player: player,
title: title,
icon: icon,
extractTracks: extractTracks,
getCurrentTrack: getCurrentTrack,
buildLabel: buildLabel,
setTrack: setTrack,
onTrackChanged: onTrackChanged,
showOffOption: showOffOption,
createOffTrack: createOffTrack,
isOffTrack: isOffTrack,
),
);
}
String _getEmptyMessage() {
if (T == SubtitleTrack) {
return 'No subtitles available';
} else if (T == AudioTrack) {
return 'No audio tracks available';
}
return 'No tracks available';
}
@override
Widget build(BuildContext context) {
return StreamBuilder<Tracks>(
stream: player.stream.tracks,
initialData: player.state.tracks,
builder: (context, snapshot) {
final tracks = snapshot.data;
final availableTracks = extractTracks(tracks).where((track) {
// Filter out 'auto' and 'no' tracks from the list
if (track is AudioTrack) {
return track.id != 'auto' && track.id != 'no';
} else if (track is SubtitleTrack) {
return track.id != 'auto' && track.id != 'no';
}
return true;
}).toList();
return BaseVideoControlSheet(
title: title,
icon: icon,
child: availableTracks.isEmpty
? Center(
child: Text(
_getEmptyMessage(),
style: const TextStyle(color: Colors.white70),
),
)
: StreamBuilder<Track>(
stream: player.stream.track,
initialData: player.state.track,
builder: (context, selectedSnapshot) {
final currentTrack =
selectedSnapshot.data ?? player.state.track;
final selectedTrack = getCurrentTrack(currentTrack);
// Determine if "Off" is selected
final isOffSelected =
isOffTrack?.call(selectedTrack) ?? false;
final itemCount =
availableTracks.length + (showOffOption ? 1 : 0);
return ListView.builder(
itemCount: itemCount,
itemBuilder: (context, index) {
// First item is "Off" if enabled
if (showOffOption && index == 0) {
return ListTile(
title: Text(
'Off',
style: TextStyle(
color: isOffSelected
? Colors.blue
: Colors.white,
),
),
trailing: isOffSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
if (createOffTrack != null) {
final offTrack = createOffTrack!();
setTrack(offTrack);
onTrackChanged?.call(offTrack);
}
Navigator.pop(context);
},
);
}
// Subsequent items are tracks
final trackIndex = showOffOption ? index - 1 : index;
final track = availableTracks[trackIndex];
// Check if this track is selected
String trackId;
if (track is AudioTrack) {
trackId = track.id;
} else if (track is SubtitleTrack) {
trackId = track.id;
} else {
trackId = '';
}
String selectedId;
if (selectedTrack is AudioTrack) {
selectedId = selectedTrack.id;
} else if (selectedTrack is SubtitleTrack) {
selectedId = selectedTrack.id;
} else {
selectedId = '';
}
final isSelected = trackId == selectedId;
final label = buildLabel(track, trackIndex);
return ListTile(
title: Text(
label,
style: TextStyle(
color: isSelected ? Colors.blue : Colors.white,
),
),
trailing: isSelected
? const Icon(Icons.check, color: Colors.blue)
: null,
onTap: () {
setTrack(track);
onTrackChanged?.call(track);
Navigator.pop(context);
},
);
},
);
},
),
);
},
);
}
}
@@ -7,6 +7,7 @@ import '../widgets/sync_offset_control.dart';
import '../widgets/sleep_timer_content.dart';
import '../../../i18n/strings.g.dart';
import 'base_video_control_sheet.dart';
import 'video_sheet_header.dart';
enum _SettingsView { menu, speed, sleep, audioSync, subtitleSync, audioDevice }
@@ -183,34 +184,11 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
_audioSyncOffset != 0 ||
_subtitleSyncOffset != 0);
return Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
// Back button or icon
if (_currentView != _SettingsView.menu)
IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: _navigateBack,
)
else
Icon(_getIcon(), color: isIconActive ? Colors.amber : Colors.white),
const SizedBox(width: 12),
Text(
_getTitle(),
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
return VideoSheetHeader(
title: _getTitle(),
icon: _getIcon(),
iconColor: isIconActive ? Colors.amber : Colors.white,
onBack: _currentView != _SettingsView.menu ? _navigateBack : null,
);
}
@@ -278,7 +256,7 @@ class _VideoSettingsSheetState extends State<VideoSettingsSheet> {
snapshot.data ?? widget.player.state.audioDevice;
final deviceLabel = currentDevice.description.isEmpty
? currentDevice.name
: currentDevice.description;
: '${currentDevice.name} · ${currentDevice.description}';
return _SettingsMenuItem(
icon: Icons.speaker,
@@ -0,0 +1,54 @@
import 'package:flutter/material.dart';
/// Shared header widget for video control sheets
///
/// Provides a consistent header with an icon/back button, title, and close button
class VideoSheetHeader extends StatelessWidget {
final String title;
final IconData? icon;
final Color? iconColor;
final VoidCallback? onBack;
final VoidCallback? onClose;
const VideoSheetHeader({
super.key,
required this.title,
this.icon,
this.iconColor,
this.onBack,
this.onClose,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
// Back button or icon
if (onBack != null)
IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: onBack,
)
else if (icon != null)
Icon(icon, color: iconColor ?? Colors.white),
const SizedBox(width: 12),
Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: onClose ?? () => Navigator.pop(context),
),
],
),
);
}
}

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