Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf509ee57c | ||
|
|
823ba0beab | ||
|
|
b310d1f169 | ||
|
|
bdd39c252e | ||
|
|
1d29281143 | ||
|
|
12ee134191 | ||
|
|
9248fb4ddb | ||
|
|
b3696035b5 | ||
|
|
b8a5afc08f | ||
|
|
0796f9c30d | ||
|
|
cebe90d39b | ||
|
|
abd5900290 | ||
|
|
67934c1f1a |
@@ -1,7 +1,16 @@
|
||||
# Plezy
|
||||
<h1>
|
||||
<img src="assets/plezy.png" alt="Plezy Logo" height="24" style="vertical-align: middle;" />
|
||||
Plezy
|
||||
</h1>
|
||||
|
||||
Plezy is a modern Plex media client that provides a seamless streaming experience across desktop and mobile platforms. Built with Flutter, it offers native performance and a clean, intuitive interface for browsing and playing your Plex media library.
|
||||
|
||||
<p align="center">
|
||||
<img src="screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
|
||||
</p>
|
||||
|
||||
*See more screenshots in the [screenshots folder](screenshots/#readme)*
|
||||
|
||||
## Download
|
||||
|
||||
### Mobile
|
||||
@@ -34,14 +43,6 @@ Coming soon
|
||||
- Playback progress sync and resume functionality
|
||||
- Auto-play next episode
|
||||
|
||||
## Platform Support
|
||||
|
||||
- ✅ macOS
|
||||
- ✅ Windows
|
||||
- ✅ Linux
|
||||
- ✅ Android
|
||||
- ✅ iOS
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Flutter SDK 3.8.1 or higher
|
||||
@@ -71,15 +72,6 @@ dart run build_runner build
|
||||
flutter run
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
On first launch, Plezy will guide you through:
|
||||
1. Authenticating with your Plex account
|
||||
2. Selecting your Plex Media Server
|
||||
3. Testing connections to find the optimal one
|
||||
|
||||
Your credentials and preferences are securely stored locally for automatic sign-in on subsequent launches.
|
||||
|
||||
## Development
|
||||
|
||||
### Code Generation
|
||||
|
||||
+289
-295
@@ -6,6 +6,14 @@ import '../models/plex_media_info.dart';
|
||||
import '../models/plex_filter.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
/// Result of testing a connection, including success status and latency
|
||||
class ConnectionTestResult {
|
||||
final bool success;
|
||||
final int latencyMs;
|
||||
|
||||
ConnectionTestResult({required this.success, required this.latencyMs});
|
||||
}
|
||||
|
||||
class PlexClient {
|
||||
final PlexConfig config;
|
||||
late final Dio _dio;
|
||||
@@ -43,12 +51,28 @@ class PlexClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Test connection to a specific URL with token
|
||||
/// Test connection to a specific URL with token (legacy method)
|
||||
static Future<bool> testConnectionUrl(
|
||||
String baseUrl,
|
||||
String token, {
|
||||
Duration timeout = const Duration(seconds: 5),
|
||||
}) async {
|
||||
final result = await testConnectionWithLatency(
|
||||
baseUrl,
|
||||
token,
|
||||
timeout: timeout,
|
||||
);
|
||||
return result.success;
|
||||
}
|
||||
|
||||
/// Test connection to a specific URL with token and measure latency
|
||||
static Future<ConnectionTestResult> testConnectionWithLatency(
|
||||
String baseUrl,
|
||||
String token, {
|
||||
Duration timeout = const Duration(seconds: 5),
|
||||
}) async {
|
||||
final stopwatch = Stopwatch()..start();
|
||||
|
||||
try {
|
||||
final dio = Dio(
|
||||
BaseOptions(
|
||||
@@ -64,12 +88,115 @@ class PlexClient {
|
||||
options: Options(headers: {'X-Plex-Token': token}),
|
||||
);
|
||||
|
||||
return response.statusCode == 200 || response.statusCode == 401;
|
||||
stopwatch.stop();
|
||||
final success = response.statusCode == 200 || response.statusCode == 401;
|
||||
|
||||
return ConnectionTestResult(
|
||||
success: success,
|
||||
latencyMs: stopwatch.elapsedMilliseconds,
|
||||
);
|
||||
} catch (e) {
|
||||
return false;
|
||||
stopwatch.stop();
|
||||
return ConnectionTestResult(
|
||||
success: false,
|
||||
latencyMs: stopwatch.elapsedMilliseconds,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Test connection multiple times and return average latency
|
||||
static Future<ConnectionTestResult> testConnectionWithAverageLatency(
|
||||
String baseUrl,
|
||||
String token, {
|
||||
int attempts = 3,
|
||||
Duration timeout = const Duration(seconds: 5),
|
||||
}) async {
|
||||
final results = <ConnectionTestResult>[];
|
||||
|
||||
for (int i = 0; i < attempts; i++) {
|
||||
final result = await testConnectionWithLatency(
|
||||
baseUrl,
|
||||
token,
|
||||
timeout: timeout,
|
||||
);
|
||||
|
||||
// If any attempt fails, return failed result immediately
|
||||
if (!result.success) {
|
||||
return ConnectionTestResult(
|
||||
success: false,
|
||||
latencyMs: result.latencyMs,
|
||||
);
|
||||
}
|
||||
|
||||
results.add(result);
|
||||
}
|
||||
|
||||
// Calculate average latency from successful attempts
|
||||
final avgLatency =
|
||||
results.fold<int>(0, (sum, result) => sum + result.latencyMs) ~/
|
||||
results.length;
|
||||
|
||||
return ConnectionTestResult(success: true, latencyMs: avgLatency);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API Response Parsing Helpers
|
||||
// ============================================================================
|
||||
|
||||
/// Extract MediaContainer from API response
|
||||
Map<String, dynamic>? _getMediaContainer(Response response) {
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
return response.data['MediaContainer'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Extract list of PlexMetadata from response
|
||||
List<PlexMetadata> _extractMetadataList(Response response) {
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null && container['Metadata'] != null) {
|
||||
return (container['Metadata'] as List)
|
||||
.map((json) => PlexMetadata.fromJson(json))
|
||||
.toList();
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Extract first metadata JSON from response (returns raw Map or null)
|
||||
Map<String, dynamic>? _getFirstMetadataJson(Response response) {
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null &&
|
||||
container['Metadata'] != null &&
|
||||
(container['Metadata'] as List).isNotEmpty) {
|
||||
return container['Metadata'][0] as Map<String, dynamic>;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Extract single PlexMetadata from response (returns first item or null)
|
||||
PlexMetadata? _extractSingleMetadata(Response response) {
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
return metadataJson != null ? PlexMetadata.fromJson(metadataJson) : null;
|
||||
}
|
||||
|
||||
/// Generic helper to extract and map Directory list from response
|
||||
List<T> _extractDirectoryList<T>(
|
||||
Response response,
|
||||
T Function(Map<String, dynamic>) fromJson,
|
||||
) {
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null && container['Directory'] != null) {
|
||||
return (container['Directory'] as List)
|
||||
.map((json) => fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API Methods
|
||||
// ============================================================================
|
||||
|
||||
/// Get server identity
|
||||
Future<Map<String, dynamic>> getServerIdentity() async {
|
||||
final response = await _dio.get('/identity');
|
||||
@@ -79,17 +206,7 @@ class PlexClient {
|
||||
/// Get library sections
|
||||
Future<List<PlexLibrary>> getLibraries() async {
|
||||
final response = await _dio.get('/library/sections');
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Directory'] != null) {
|
||||
return (container['Directory'] as List)
|
||||
.map((json) => PlexLibrary.fromJson(json))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
return _extractDirectoryList(response, PlexLibrary.fromJson);
|
||||
}
|
||||
|
||||
/// Get library content by section ID
|
||||
@@ -113,31 +230,13 @@ class PlexClient {
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null) {
|
||||
return (container['Metadata'] as List)
|
||||
.map((json) => PlexMetadata.fromJson(json))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
return _extractMetadataList(response);
|
||||
}
|
||||
|
||||
/// Get metadata by rating key
|
||||
Future<PlexMetadata?> getMetadata(String ratingKey) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey');
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null &&
|
||||
(container['Metadata'] as List).isNotEmpty) {
|
||||
return PlexMetadata.fromJson(container['Metadata'][0]);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return _extractSingleMetadata(response);
|
||||
}
|
||||
|
||||
/// Get metadata by rating key with images (includes clearLogo and OnDeck)
|
||||
@@ -152,26 +251,20 @@ class PlexClient {
|
||||
PlexMetadata? metadata;
|
||||
PlexMetadata? onDeckEpisode;
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
if (metadataJson != null) {
|
||||
metadata = PlexMetadata.fromJsonWithImages(metadataJson);
|
||||
|
||||
// Get main metadata
|
||||
if (container['Metadata'] != null &&
|
||||
(container['Metadata'] as List).isNotEmpty) {
|
||||
final metadataJson = container['Metadata'][0];
|
||||
metadata = PlexMetadata.fromJsonWithImages(metadataJson);
|
||||
// Check if OnDeck is nested inside Metadata
|
||||
if (metadataJson.containsKey('OnDeck') &&
|
||||
metadataJson['OnDeck'] != null) {
|
||||
final onDeckData = metadataJson['OnDeck'];
|
||||
|
||||
// Check if OnDeck is nested inside Metadata
|
||||
if (metadataJson.containsKey('OnDeck') &&
|
||||
metadataJson['OnDeck'] != null) {
|
||||
final onDeckData = metadataJson['OnDeck'];
|
||||
|
||||
// OnDeck can be either a Map with 'Metadata' key or direct metadata
|
||||
if (onDeckData is Map && onDeckData.containsKey('Metadata')) {
|
||||
final onDeckMetadata = onDeckData['Metadata'];
|
||||
if (onDeckMetadata != null) {
|
||||
onDeckEpisode = PlexMetadata.fromJson(onDeckMetadata);
|
||||
}
|
||||
// OnDeck can be either a Map with 'Metadata' key or direct metadata
|
||||
if (onDeckData is Map && onDeckData.containsKey('Metadata')) {
|
||||
final onDeckMetadata = onDeckData['Metadata'];
|
||||
if (onDeckMetadata != null) {
|
||||
onDeckEpisode = PlexMetadata.fromJson(onDeckMetadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -183,16 +276,10 @@ class PlexClient {
|
||||
/// Get metadata by rating key with images (includes clearLogo)
|
||||
Future<PlexMetadata?> getMetadataWithImages(String ratingKey) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey');
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null &&
|
||||
(container['Metadata'] as List).isNotEmpty) {
|
||||
return PlexMetadata.fromJsonWithImages(container['Metadata'][0]);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
return metadataJson != null
|
||||
? PlexMetadata.fromJsonWithImages(metadataJson)
|
||||
: null;
|
||||
}
|
||||
|
||||
/// Search across all libraries using the hub search endpoint
|
||||
@@ -257,49 +344,25 @@ class PlexClient {
|
||||
'/library/recentlyAdded',
|
||||
queryParameters: {'X-Plex-Container-Size': limit, 'includeGuids': 1},
|
||||
);
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null) {
|
||||
return (container['Metadata'] as List)
|
||||
.map((json) => PlexMetadata.fromJson(json))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
return _extractMetadataList(response);
|
||||
}
|
||||
|
||||
/// Get on deck items (continue watching)
|
||||
Future<List<PlexMetadata>> getOnDeck() async {
|
||||
final response = await _dio.get('/library/onDeck');
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null) {
|
||||
return (container['Metadata'] as List)
|
||||
.map((json) => PlexMetadata.fromJsonWithImages(json))
|
||||
.toList();
|
||||
}
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null && container['Metadata'] != null) {
|
||||
return (container['Metadata'] as List)
|
||||
.map((json) => PlexMetadata.fromJsonWithImages(json))
|
||||
.toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get children of a metadata item (e.g., seasons for a show, episodes for a season)
|
||||
Future<List<PlexMetadata>> getChildren(String ratingKey) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey/children');
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null) {
|
||||
return (container['Metadata'] as List)
|
||||
.map((json) => PlexMetadata.fromJson(json))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
return _extractMetadataList(response);
|
||||
}
|
||||
|
||||
/// Get thumbnail URL
|
||||
@@ -315,26 +378,19 @@ class PlexClient {
|
||||
/// Get video URL for direct playback
|
||||
Future<String?> getVideoUrl(String ratingKey) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey');
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null &&
|
||||
(container['Metadata'] as List).isNotEmpty) {
|
||||
final metadata = container['Metadata'][0];
|
||||
if (metadataJson != null &&
|
||||
metadataJson['Media'] != null &&
|
||||
(metadataJson['Media'] as List).isNotEmpty) {
|
||||
final media = metadataJson['Media'][0];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
|
||||
// Get the first Media item and its Part
|
||||
if (metadata['Media'] != null &&
|
||||
(metadata['Media'] as List).isNotEmpty) {
|
||||
final media = metadata['Media'][0];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
|
||||
if (partKey != null) {
|
||||
// Return direct play URL
|
||||
return '${config.baseUrl}$partKey?X-Plex-Token=${config.token}';
|
||||
}
|
||||
}
|
||||
if (partKey != null) {
|
||||
// Return direct play URL
|
||||
return '${config.baseUrl}$partKey?X-Plex-Token=${config.token}';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -349,26 +405,19 @@ class PlexClient {
|
||||
queryParameters: {'includeChapters': 1},
|
||||
);
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null &&
|
||||
(container['Metadata'] as List).isNotEmpty) {
|
||||
final metadata = container['Metadata'][0];
|
||||
|
||||
if (metadata['Chapter'] != null) {
|
||||
final chapterList = metadata['Chapter'] as List<dynamic>;
|
||||
return chapterList.map((chapter) {
|
||||
return PlexChapter(
|
||||
id: chapter['id'] as int,
|
||||
index: chapter['index'] as int?,
|
||||
startTimeOffset: chapter['startTimeOffset'] as int?,
|
||||
endTimeOffset: chapter['endTimeOffset'] as int?,
|
||||
title: chapter['tag'] as String?,
|
||||
thumb: chapter['thumb'] as String?,
|
||||
);
|
||||
}).toList();
|
||||
}
|
||||
}
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
if (metadataJson != null && metadataJson['Chapter'] != null) {
|
||||
final chapterList = metadataJson['Chapter'] as List<dynamic>;
|
||||
return chapterList.map((chapter) {
|
||||
return PlexChapter(
|
||||
id: chapter['id'] as int,
|
||||
index: chapter['index'] as int?,
|
||||
startTimeOffset: chapter['startTimeOffset'] as int?,
|
||||
endTimeOffset: chapter['endTimeOffset'] as int?,
|
||||
title: chapter['tag'] as String?,
|
||||
thumb: chapter['thumb'] as String?,
|
||||
);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
@@ -377,91 +426,83 @@ class PlexClient {
|
||||
/// Get detailed media info including chapters and tracks
|
||||
Future<PlexMediaInfo?> getMediaInfo(String ratingKey) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey');
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null &&
|
||||
(container['Metadata'] as List).isNotEmpty) {
|
||||
final metadata = container['Metadata'][0];
|
||||
if (metadataJson != null &&
|
||||
metadataJson['Media'] != null &&
|
||||
(metadataJson['Media'] as List).isNotEmpty) {
|
||||
final media = metadataJson['Media'][0];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
|
||||
// Get the first Media item and its Part
|
||||
if (metadata['Media'] != null &&
|
||||
(metadata['Media'] as List).isNotEmpty) {
|
||||
final media = metadata['Media'][0];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
if (partKey != null) {
|
||||
// Parse streams (audio and subtitle tracks)
|
||||
final streams = part['Stream'] as List<dynamic>? ?? [];
|
||||
final audioTracks = <PlexAudioTrack>[];
|
||||
final subtitleTracks = <PlexSubtitleTrack>[];
|
||||
|
||||
if (partKey != null) {
|
||||
// Parse streams (audio and subtitle tracks)
|
||||
final streams = part['Stream'] as List<dynamic>? ?? [];
|
||||
final audioTracks = <PlexAudioTrack>[];
|
||||
final subtitleTracks = <PlexSubtitleTrack>[];
|
||||
for (var stream in streams) {
|
||||
final streamType = stream['streamType'] as int?;
|
||||
|
||||
for (var stream in streams) {
|
||||
final streamType = stream['streamType'] as int?;
|
||||
|
||||
if (streamType == 2) {
|
||||
// Audio track
|
||||
audioTracks.add(
|
||||
PlexAudioTrack(
|
||||
id: stream['id'] as int,
|
||||
index: stream['index'] as int?,
|
||||
codec: stream['codec'] as String?,
|
||||
language: stream['language'] as String?,
|
||||
languageCode: stream['languageCode'] as String?,
|
||||
title: stream['title'] as String?,
|
||||
displayTitle: stream['displayTitle'] as String?,
|
||||
channels: stream['channels'] as int?,
|
||||
selected: stream['selected'] == 1,
|
||||
),
|
||||
);
|
||||
} else if (streamType == 3) {
|
||||
// Subtitle track
|
||||
subtitleTracks.add(
|
||||
PlexSubtitleTrack(
|
||||
id: stream['id'] as int,
|
||||
index: stream['index'] as int?,
|
||||
codec: stream['codec'] as String?,
|
||||
language: stream['language'] as String?,
|
||||
languageCode: stream['languageCode'] as String?,
|
||||
title: stream['title'] as String?,
|
||||
displayTitle: stream['displayTitle'] as String?,
|
||||
selected: stream['selected'] == 1,
|
||||
forced: stream['forced'] == 1,
|
||||
key: stream['key'] as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse chapters
|
||||
final chapters = <PlexChapter>[];
|
||||
if (metadata['Chapter'] != null) {
|
||||
final chapterList = metadata['Chapter'] as List<dynamic>;
|
||||
for (var chapter in chapterList) {
|
||||
chapters.add(
|
||||
PlexChapter(
|
||||
id: chapter['id'] as int,
|
||||
index: chapter['index'] as int?,
|
||||
startTimeOffset: chapter['startTimeOffset'] as int?,
|
||||
endTimeOffset: chapter['endTimeOffset'] as int?,
|
||||
title: chapter['title'] as String?,
|
||||
thumb: chapter['thumb'] as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return PlexMediaInfo(
|
||||
videoUrl:
|
||||
'${config.baseUrl}$partKey?X-Plex-Token=${config.token}',
|
||||
audioTracks: audioTracks,
|
||||
subtitleTracks: subtitleTracks,
|
||||
chapters: chapters,
|
||||
if (streamType == 2) {
|
||||
// Audio track
|
||||
audioTracks.add(
|
||||
PlexAudioTrack(
|
||||
id: stream['id'] as int,
|
||||
index: stream['index'] as int?,
|
||||
codec: stream['codec'] as String?,
|
||||
language: stream['language'] as String?,
|
||||
languageCode: stream['languageCode'] as String?,
|
||||
title: stream['title'] as String?,
|
||||
displayTitle: stream['displayTitle'] as String?,
|
||||
channels: stream['channels'] as int?,
|
||||
selected: stream['selected'] == 1,
|
||||
),
|
||||
);
|
||||
} else if (streamType == 3) {
|
||||
// Subtitle track
|
||||
subtitleTracks.add(
|
||||
PlexSubtitleTrack(
|
||||
id: stream['id'] as int,
|
||||
index: stream['index'] as int?,
|
||||
codec: stream['codec'] as String?,
|
||||
language: stream['language'] as String?,
|
||||
languageCode: stream['languageCode'] as String?,
|
||||
title: stream['title'] as String?,
|
||||
displayTitle: stream['displayTitle'] as String?,
|
||||
selected: stream['selected'] == 1,
|
||||
forced: stream['forced'] == 1,
|
||||
key: stream['key'] as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse chapters
|
||||
final chapters = <PlexChapter>[];
|
||||
if (metadataJson['Chapter'] != null) {
|
||||
final chapterList = metadataJson['Chapter'] as List<dynamic>;
|
||||
for (var chapter in chapterList) {
|
||||
chapters.add(
|
||||
PlexChapter(
|
||||
id: chapter['id'] as int,
|
||||
index: chapter['index'] as int?,
|
||||
startTimeOffset: chapter['startTimeOffset'] as int?,
|
||||
endTimeOffset: chapter['endTimeOffset'] as int?,
|
||||
title: chapter['title'] as String?,
|
||||
thumb: chapter['thumb'] as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return PlexMediaInfo(
|
||||
videoUrl: '${config.baseUrl}$partKey?X-Plex-Token=${config.token}',
|
||||
audioTracks: audioTracks,
|
||||
subtitleTracks: subtitleTracks,
|
||||
chapters: chapters,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -519,51 +560,34 @@ class PlexClient {
|
||||
/// Get sessions (currently playing)
|
||||
Future<List<dynamic>> getSessions() async {
|
||||
final response = await _dio.get('/status/sessions');
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Metadata'] != null) {
|
||||
return container['Metadata'] as List;
|
||||
}
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null && container['Metadata'] != null) {
|
||||
return container['Metadata'] as List;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get available filters for a library section
|
||||
Future<List<PlexFilter>> getLibraryFilters(String sectionId) async {
|
||||
final response = await _dio.get('/library/sections/$sectionId/filters');
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Directory'] != null) {
|
||||
return (container['Directory'] as List)
|
||||
.map((json) => PlexFilter.fromJson(json))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
return _extractDirectoryList(response, PlexFilter.fromJson);
|
||||
}
|
||||
|
||||
/// Get filter values (e.g., list of genres, years, etc.)
|
||||
Future<List<PlexFilterValue>> getFilterValues(String filterKey) async {
|
||||
final response = await _dio.get(filterKey);
|
||||
|
||||
if (response.data is Map && response.data.containsKey('MediaContainer')) {
|
||||
final container = response.data['MediaContainer'];
|
||||
if (container['Directory'] != null) {
|
||||
return (container['Directory'] as List)
|
||||
.map((json) => PlexFilterValue.fromJson(json))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
return _extractDirectoryList(response, PlexFilterValue.fromJson);
|
||||
}
|
||||
|
||||
/// Get next episode for a TV show episode
|
||||
Future<PlexMetadata?> getNextEpisode(PlexMetadata currentEpisode) async {
|
||||
/// 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;
|
||||
}
|
||||
@@ -584,73 +608,43 @@ class PlexClient {
|
||||
(e) => e.ratingKey == currentEpisode.ratingKey,
|
||||
);
|
||||
|
||||
if (currentIndex != -1 && currentIndex < episodes.length - 1) {
|
||||
// Return next episode in the same season
|
||||
return episodes[currentIndex + 1];
|
||||
} else if (currentIndex == episodes.length - 1) {
|
||||
// Last episode of the season, try to get first episode of next season
|
||||
final seasons = await getChildren(grandparentKey);
|
||||
final currentSeasonIndex = seasons.indexWhere(
|
||||
(s) => s.ratingKey == parentKey,
|
||||
);
|
||||
if (currentIndex == -1) return null;
|
||||
|
||||
if (currentSeasonIndex != -1 &&
|
||||
currentSeasonIndex < seasons.length - 1) {
|
||||
final nextSeason = seasons[currentSeasonIndex + 1];
|
||||
final nextSeasonEpisodes = await getChildren(nextSeason.ratingKey);
|
||||
final targetIndex = currentIndex + direction;
|
||||
|
||||
if (nextSeasonEpisodes.isNotEmpty) {
|
||||
return nextSeasonEpisodes.first;
|
||||
}
|
||||
}
|
||||
// Check if target episode is within current season
|
||||
if (targetIndex >= 0 && targetIndex < episodes.length) {
|
||||
return episodes[targetIndex];
|
||||
}
|
||||
} catch (e) {
|
||||
// Silently handle errors
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
// Need to move to adjacent season
|
||||
final isAtBoundary = direction > 0
|
||||
? currentIndex == episodes.length - 1
|
||||
: currentIndex == 0;
|
||||
|
||||
/// Get previous episode for a TV show episode
|
||||
Future<PlexMetadata?> getPreviousEpisode(PlexMetadata currentEpisode) 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 > 0) {
|
||||
// Return previous episode in the same season
|
||||
return episodes[currentIndex - 1];
|
||||
} else if (currentIndex == 0) {
|
||||
// First episode of the season, try to get last episode of previous season
|
||||
if (isAtBoundary) {
|
||||
// Get all seasons
|
||||
final seasons = await getChildren(grandparentKey);
|
||||
final currentSeasonIndex = seasons.indexWhere(
|
||||
(s) => s.ratingKey == parentKey,
|
||||
);
|
||||
|
||||
if (currentSeasonIndex > 0) {
|
||||
final previousSeason = seasons[currentSeasonIndex - 1];
|
||||
final previousSeasonEpisodes = await getChildren(
|
||||
previousSeason.ratingKey,
|
||||
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 (previousSeasonEpisodes.isNotEmpty) {
|
||||
return previousSeasonEpisodes.last;
|
||||
if (targetSeasonEpisodes.isNotEmpty) {
|
||||
// Return first episode for next season, last for previous
|
||||
return direction > 0
|
||||
? targetSeasonEpisodes.first
|
||||
: targetSeasonEpisodes.last;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+27
-102
@@ -3,17 +3,16 @@ import 'package:flutter/services.dart';
|
||||
import 'dart:io' show Platform;
|
||||
import 'package:media_kit/media_kit.dart';
|
||||
import 'package:window_manager/window_manager.dart';
|
||||
import 'client/plex_client.dart';
|
||||
import 'config/plex_config.dart';
|
||||
import 'screens/main_screen.dart';
|
||||
import 'screens/auth_screen.dart';
|
||||
import 'services/storage_service.dart';
|
||||
import 'services/plex_auth_service.dart';
|
||||
import 'services/server_connection_service.dart';
|
||||
import 'services/macos_titlebar_service.dart';
|
||||
import 'services/fullscreen_state_manager.dart';
|
||||
import 'models/plex_user_profile.dart';
|
||||
import 'utils/language_codes.dart';
|
||||
import 'utils/app_logger.dart';
|
||||
import 'theme/mono_theme.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
@@ -59,11 +58,8 @@ class MainApp extends StatelessWidget {
|
||||
return MaterialApp(
|
||||
title: 'Plezy',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
|
||||
useMaterial3: true,
|
||||
),
|
||||
darkTheme: ThemeData.dark(useMaterial3: true),
|
||||
theme: monoTheme(dark: false),
|
||||
darkTheme: monoTheme(dark: true),
|
||||
navigatorObservers: [routeObserver],
|
||||
home: const SetupScreen(),
|
||||
);
|
||||
@@ -97,52 +93,37 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
// Recreate PlexServer from stored data
|
||||
final server = PlexServer.fromJson(serverData);
|
||||
|
||||
// Test connections to find best working one
|
||||
final connection = await server.findBestWorkingConnection();
|
||||
// Connect using the optimized service
|
||||
final result = await ServerConnectionService.connectToServer(
|
||||
server,
|
||||
clientIdentifier: clientId,
|
||||
verifyServer: true,
|
||||
fetchUserProfile: plexToken != null,
|
||||
plexToken: plexToken,
|
||||
);
|
||||
|
||||
if (connection != null) {
|
||||
// Update stored server URL with working connection
|
||||
await storage.saveServerUrl(connection.uri);
|
||||
|
||||
// Create client with working connection
|
||||
final config = await PlexConfig.create(
|
||||
baseUrl: connection.uri,
|
||||
token: server.accessToken,
|
||||
clientIdentifier: clientId,
|
||||
);
|
||||
final client = PlexClient(config);
|
||||
|
||||
// Verify server is accessible
|
||||
try {
|
||||
await client.getServerIdentity();
|
||||
|
||||
// Fetch and cache user profile if we have a plex token
|
||||
PlexUserProfile? userProfile;
|
||||
if (plexToken != null) {
|
||||
userProfile = await _fetchAndCacheUserProfile(plexToken);
|
||||
}
|
||||
|
||||
// Success! Navigate to main screen
|
||||
if (mounted) {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) =>
|
||||
MainScreen(client: client, userProfile: userProfile),
|
||||
// Handle result
|
||||
if (result.isSuccess) {
|
||||
// Success! Navigate to main screen
|
||||
if (mounted) {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MainScreen(
|
||||
client: result.client!,
|
||||
userProfile: result.userProfile,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
// Server identity check failed
|
||||
await storage.clearCredentials();
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
// No working connections found
|
||||
// Connection failed, clear credentials
|
||||
await storage.clearCredentials();
|
||||
}
|
||||
} catch (e) {
|
||||
// Error loading or testing server
|
||||
appLogger.e('Error during auto-login', error: e);
|
||||
await storage.clearCredentials();
|
||||
}
|
||||
}
|
||||
@@ -156,62 +137,6 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<PlexUserProfile?> _fetchAndCacheUserProfile(String plexToken) async {
|
||||
appLogger.d('Fetching user profile from Plex API');
|
||||
try {
|
||||
final authService = await PlexAuthService.create();
|
||||
final profile = await authService.getUserProfile(plexToken);
|
||||
|
||||
appLogger.i(
|
||||
'Successfully fetched user profile',
|
||||
error: {
|
||||
'autoSelectAudio': profile.autoSelectAudio,
|
||||
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
|
||||
'autoSelectSubtitle': profile.autoSelectSubtitle,
|
||||
'defaultSubtitleLanguage':
|
||||
profile.defaultSubtitleLanguage ?? 'not set',
|
||||
'defaultSubtitleForced': profile.defaultSubtitleForced,
|
||||
},
|
||||
);
|
||||
|
||||
// Cache the profile
|
||||
final storage = await StorageService.getInstance();
|
||||
await storage.saveUserProfile(profile.toJson());
|
||||
appLogger.d('User profile cached locally');
|
||||
|
||||
return profile;
|
||||
} catch (e) {
|
||||
appLogger.w(
|
||||
'Failed to fetch user profile from API, attempting to load from cache',
|
||||
error: e,
|
||||
);
|
||||
|
||||
// Failed to fetch profile, try to load from cache
|
||||
final storage = await StorageService.getInstance();
|
||||
final cachedProfile = storage.getUserProfile();
|
||||
if (cachedProfile != null) {
|
||||
final profile = PlexUserProfile.fromJson(cachedProfile);
|
||||
appLogger.i(
|
||||
'Loaded user profile from cache',
|
||||
error: {
|
||||
'autoSelectAudio': profile.autoSelectAudio,
|
||||
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
|
||||
'autoSelectSubtitle': profile.autoSelectSubtitle,
|
||||
'defaultSubtitleLanguage':
|
||||
profile.defaultSubtitleLanguage ?? 'not set',
|
||||
'defaultSubtitleForced': profile.defaultSubtitleForced,
|
||||
},
|
||||
);
|
||||
return profile;
|
||||
}
|
||||
|
||||
appLogger.w(
|
||||
'No cached user profile available, track selection will use defaults',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Scaffold(
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../client/plex_client.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
|
||||
/// Mixin for screens that need to update individual items after watch state changes
|
||||
///
|
||||
/// This provides a standard implementation for fetching updated metadata
|
||||
/// and replacing items in lists, while allowing each screen to customize
|
||||
/// which lists should be updated.
|
||||
mixin ItemUpdatable<T extends StatefulWidget> on State<T> {
|
||||
/// The Plex client to use for fetching updated metadata
|
||||
/// Each screen must provide access to their client
|
||||
PlexClient get client;
|
||||
|
||||
/// Updates a single item in the screen's list(s) after watch state changes
|
||||
///
|
||||
/// Fetches the latest metadata with images (including clearLogo) and
|
||||
/// calls [updateItemInLists] to update the appropriate list(s).
|
||||
///
|
||||
/// If the fetch fails, the error is silently caught and the item will
|
||||
/// be updated on the next full refresh.
|
||||
Future<void> updateItem(String ratingKey) async {
|
||||
try {
|
||||
final updatedMetadata = await client.getMetadataWithImages(ratingKey);
|
||||
if (updatedMetadata != null) {
|
||||
setState(() {
|
||||
updateItemInLists(ratingKey, updatedMetadata);
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// Silently fail - the item will update on next full refresh
|
||||
}
|
||||
}
|
||||
|
||||
/// Override this method to specify which list(s) should be updated
|
||||
///
|
||||
/// This method is called within [setState], so you should directly
|
||||
/// modify your list(s) without calling setState again.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @override
|
||||
/// void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
|
||||
/// final index = _items.indexWhere((item) => item.ratingKey == ratingKey);
|
||||
/// if (index != -1) {
|
||||
/// _items[index] = updatedMetadata;
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata);
|
||||
}
|
||||
@@ -39,110 +39,110 @@ class _AboutScreenState extends State<AboutScreen> {
|
||||
DesktopSliverAppBar(
|
||||
title: const Text('About'),
|
||||
pinned: true,
|
||||
leading: const AppBarBackButton(
|
||||
style: BackButtonStyle.circular,
|
||||
),
|
||||
leading: const AppBarBackButton(style: BackButtonStyle.circular),
|
||||
),
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildListDelegate([
|
||||
// App Icon and Name
|
||||
Center(
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 24),
|
||||
Image.asset(
|
||||
'assets/plezy.png',
|
||||
width: 80,
|
||||
height: 80,
|
||||
// App Icon and Name
|
||||
Center(
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 24),
|
||||
Image.asset('assets/plezy.png', width: 80, height: 80),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
appName,
|
||||
style: Theme.of(context).textTheme.headlineMedium
|
||||
?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Version $appVersion',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
'A beautiful Plex client for Flutter',
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// Open Source Licenses
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.description),
|
||||
title: const Text('Open Source Licenses'),
|
||||
subtitle: const Text(
|
||||
'View licenses of third-party libraries',
|
||||
),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
showLicensePage(
|
||||
context: context,
|
||||
applicationName: appName,
|
||||
applicationVersion: appVersion,
|
||||
applicationIcon: Image.asset(
|
||||
'assets/plezy.png',
|
||||
width: 48,
|
||||
height: 48,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
appName,
|
||||
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Version $appVersion',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
'A beautiful Plex client for Flutter',
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// Open Source Licenses
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.description),
|
||||
title: const Text('Open Source Licenses'),
|
||||
subtitle: const Text('View licenses of third-party libraries'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
showLicensePage(
|
||||
context: context,
|
||||
applicationName: appName,
|
||||
applicationVersion: appVersion,
|
||||
applicationIcon: Image.asset(
|
||||
'assets/plezy.png',
|
||||
width: 48,
|
||||
height: 48,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Key Dependencies
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Key Dependencies',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
// Key Dependencies
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Key Dependencies',
|
||||
style: Theme.of(context).textTheme.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildDependencyItem('http', 'HTTP networking'),
|
||||
_buildDependencyItem('dio', 'Advanced HTTP client'),
|
||||
_buildDependencyItem(
|
||||
'cached_network_image',
|
||||
'Image caching',
|
||||
),
|
||||
_buildDependencyItem('media_kit', 'Video playback'),
|
||||
_buildDependencyItem(
|
||||
'shared_preferences',
|
||||
'Local storage',
|
||||
),
|
||||
_buildDependencyItem('xml', 'XML parsing'),
|
||||
_buildDependencyItem('url_launcher', 'External links'),
|
||||
_buildDependencyItem(
|
||||
'window_manager',
|
||||
'Desktop window management',
|
||||
),
|
||||
_buildDependencyItem(
|
||||
'macos_window_utils',
|
||||
'macOS window controls',
|
||||
),
|
||||
_buildDependencyItem('logger', 'Logging'),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_buildDependencyItem('http', 'HTTP networking'),
|
||||
_buildDependencyItem('dio', 'Advanced HTTP client'),
|
||||
_buildDependencyItem('cached_network_image', 'Image caching'),
|
||||
_buildDependencyItem('media_kit', 'Video playback'),
|
||||
_buildDependencyItem('shared_preferences', 'Local storage'),
|
||||
_buildDependencyItem('xml', 'XML parsing'),
|
||||
_buildDependencyItem('url_launcher', 'External links'),
|
||||
_buildDependencyItem(
|
||||
'window_manager',
|
||||
'Desktop window management',
|
||||
),
|
||||
_buildDependencyItem(
|
||||
'macos_window_utils',
|
||||
'macOS window controls',
|
||||
),
|
||||
_buildDependencyItem('logger', 'Logging'),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
const SizedBox(height: 24),
|
||||
]),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -121,11 +121,7 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Image.asset(
|
||||
'assets/plezy.png',
|
||||
width: 120,
|
||||
height: 120,
|
||||
),
|
||||
Image.asset('assets/plezy.png', width: 120, height: 120),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
'Plezy',
|
||||
@@ -147,7 +143,10 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
OutlinedButton(
|
||||
onPressed: _retryAuthentication,
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 24),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 12,
|
||||
horizontal: 24,
|
||||
),
|
||||
),
|
||||
child: const Text('Retry'),
|
||||
),
|
||||
|
||||
+296
-129
@@ -2,16 +2,18 @@ import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import '../client/plex_client.dart';
|
||||
import '../config/plex_config.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_user_profile.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../services/plex_auth_service.dart';
|
||||
import '../services/server_connection_service.dart';
|
||||
import '../widgets/media_card.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/server_list_tile.dart';
|
||||
import '../mixins/refreshable.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../utils/platform_detector.dart';
|
||||
import 'video_player_screen.dart';
|
||||
import 'main_screen.dart';
|
||||
import 'about_screen.dart';
|
||||
@@ -32,18 +34,28 @@ class DiscoverScreen extends StatefulWidget {
|
||||
State<DiscoverScreen> createState() => _DiscoverScreenState();
|
||||
}
|
||||
|
||||
class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
with Refreshable, ItemUpdatable, SingleTickerProviderStateMixin {
|
||||
@override
|
||||
PlexClient get client => widget.client;
|
||||
|
||||
List<PlexMetadata> _onDeck = [];
|
||||
List<PlexMetadata> _recentlyAdded = [];
|
||||
bool _isLoading = true;
|
||||
String? _errorMessage;
|
||||
final PageController _heroController = PageController();
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
int _currentHeroIndex = 0;
|
||||
Timer? _autoScrollTimer;
|
||||
late AnimationController _indicatorAnimationController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_indicatorAnimationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(seconds: 5),
|
||||
);
|
||||
_loadContent();
|
||||
_startAutoScroll();
|
||||
}
|
||||
@@ -52,10 +64,13 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
void dispose() {
|
||||
_autoScrollTimer?.cancel();
|
||||
_heroController.dispose();
|
||||
_scrollController.dispose();
|
||||
_indicatorAnimationController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _startAutoScroll() {
|
||||
_indicatorAnimationController.forward(from: 0.0);
|
||||
_autoScrollTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
|
||||
if (_onDeck.isEmpty || !_heroController.hasClients) return;
|
||||
|
||||
@@ -65,6 +80,10 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
duration: const Duration(milliseconds: 500),
|
||||
curve: Curves.easeInOut,
|
||||
);
|
||||
// Wait for page transition to complete before resetting progress
|
||||
Future.delayed(const Duration(milliseconds: 500), () {
|
||||
_indicatorAnimationController.forward(from: 0.0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -110,6 +129,25 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
_loadContent();
|
||||
}
|
||||
|
||||
@override
|
||||
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
|
||||
// Check and update in _onDeck list
|
||||
final onDeckIndex = _onDeck.indexWhere(
|
||||
(item) => item.ratingKey == ratingKey,
|
||||
);
|
||||
if (onDeckIndex != -1) {
|
||||
_onDeck[onDeckIndex] = updatedMetadata;
|
||||
}
|
||||
|
||||
// Check and update in _recentlyAdded list
|
||||
final recentlyAddedIndex = _recentlyAdded.indexWhere(
|
||||
(item) => item.ratingKey == ratingKey,
|
||||
);
|
||||
if (recentlyAddedIndex != -1) {
|
||||
_recentlyAdded[recentlyAddedIndex] = updatedMetadata;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _handleSwitchServer() async {
|
||||
final storage = await StorageService.getInstance();
|
||||
final plexToken = storage.getPlexToken();
|
||||
@@ -229,34 +267,16 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
);
|
||||
}
|
||||
|
||||
// Test connections to find best working one
|
||||
final connection = await server.findBestWorkingConnection();
|
||||
|
||||
// Close loading dialog
|
||||
if (mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
if (connection == null) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('No working connections found for this server'),
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Store server information
|
||||
final storage = await StorageService.getInstance();
|
||||
await storage.saveServerData(server.toJson());
|
||||
await storage.saveServerUrl(connection.uri);
|
||||
await storage.saveServerAccessToken(server.accessToken);
|
||||
|
||||
// Get client identifier
|
||||
final storage = await StorageService.getInstance();
|
||||
final clientId = storage.getClientIdentifier();
|
||||
|
||||
if (clientId == null) {
|
||||
// Close loading dialog
|
||||
if (mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Client identifier not found')),
|
||||
@@ -265,20 +285,35 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create new client
|
||||
final config = await PlexConfig.create(
|
||||
baseUrl: connection.uri,
|
||||
token: server.accessToken,
|
||||
// Connect using the optimized service
|
||||
final result = await ServerConnectionService.connectToServer(
|
||||
server,
|
||||
clientIdentifier: clientId,
|
||||
);
|
||||
final client = PlexClient(config);
|
||||
|
||||
// Replace current screen with main screen (includes bottom nav)
|
||||
// Close loading dialog
|
||||
if (mounted) {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => MainScreen(client: client)),
|
||||
);
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
// Handle result
|
||||
if (result.isSuccess) {
|
||||
// Replace current screen with main screen (includes bottom nav)
|
||||
if (mounted) {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MainScreen(client: result.client!),
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Show error
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(result.error ?? 'Connection failed')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,6 +351,7 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: CustomScrollView(
|
||||
controller: _scrollController,
|
||||
slivers: [
|
||||
DesktopSliverAppBar(
|
||||
title: const Text('Discover'),
|
||||
@@ -501,27 +537,62 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
return _buildHeroItem(_onDeck[index]);
|
||||
},
|
||||
),
|
||||
// Page indicators
|
||||
// Page indicators with animated progress
|
||||
Positioned(
|
||||
bottom: 16,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: List.generate(
|
||||
_onDeck.length,
|
||||
(index) => Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||
width: _currentHeroIndex == index ? 24 : 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: _currentHeroIndex == index
|
||||
? Colors.white
|
||||
: Colors.white.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
),
|
||||
),
|
||||
children: List.generate(_onDeck.length, (index) {
|
||||
final isActive = _currentHeroIndex == index;
|
||||
if (isActive) {
|
||||
// Animated progress indicator for active page
|
||||
return AnimatedBuilder(
|
||||
animation: _indicatorAnimationController,
|
||||
builder: (context, child) {
|
||||
// Fill width animates from 8px to 24px
|
||||
final fillWidth =
|
||||
8.0 + (16.0 * _indicatorAnimationController.value);
|
||||
return AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeInOut,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||
width: 24,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Container(
|
||||
width: fillWidth,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
} else {
|
||||
// Static indicator for inactive pages
|
||||
return AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeInOut,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
);
|
||||
}
|
||||
}),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -533,10 +604,6 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
Widget _buildHeroItem(PlexMetadata heroItem) {
|
||||
final isEpisode = heroItem.type.toLowerCase() == 'episode';
|
||||
final showName = heroItem.grandparentTitle ?? heroItem.title;
|
||||
final episodeInfo =
|
||||
isEpisode && heroItem.parentIndex != null && heroItem.index != null
|
||||
? 'S${heroItem.parentIndex} · E${heroItem.index} · ${heroItem.title}'
|
||||
: null;
|
||||
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
@@ -569,22 +636,45 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
// Background Image - use episode art or grandparent art
|
||||
// Background Image with fade/zoom animation and parallax
|
||||
if (heroItem.art != null || heroItem.grandparentArt != null)
|
||||
CachedNetworkImage(
|
||||
imageUrl: widget.client.getThumbnailUrl(
|
||||
heroItem.art ?? heroItem.grandparentArt,
|
||||
),
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => Container(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
errorWidget: (context, url, error) => Container(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
AnimatedBuilder(
|
||||
animation: _scrollController,
|
||||
builder: (context, child) {
|
||||
final scrollOffset = _scrollController.hasClients
|
||||
? _scrollController.offset
|
||||
: 0.0;
|
||||
return Transform.translate(
|
||||
offset: Offset(0, scrollOffset * 0.3),
|
||||
child: child,
|
||||
);
|
||||
},
|
||||
child: TweenAnimationBuilder<double>(
|
||||
tween: Tween(begin: 0.0, end: 1.0),
|
||||
duration: const Duration(milliseconds: 800),
|
||||
curve: Curves.easeOut,
|
||||
builder: (context, value, child) {
|
||||
return Transform.scale(
|
||||
scale: 1.0 + (0.1 * (1 - value)),
|
||||
child: Opacity(opacity: value, child: child),
|
||||
);
|
||||
},
|
||||
child: CachedNetworkImage(
|
||||
imageUrl: widget.client.getThumbnailUrl(
|
||||
heroItem.art ?? heroItem.grandparentArt,
|
||||
),
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => Container(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
errorWidget: (context, url, error) => Container(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
@@ -608,13 +698,15 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
),
|
||||
),
|
||||
|
||||
// Content
|
||||
// Content with responsive alignment
|
||||
Positioned(
|
||||
bottom: 70,
|
||||
bottom: PlatformDetector.isDesktop(context) ? 80 : 70,
|
||||
left: 0,
|
||||
right: 0,
|
||||
right: PlatformDetector.isDesktop(context) ? 200 : 0,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 32),
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: PlatformDetector.isDesktop(context) ? 40 : 16,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@@ -700,72 +792,61 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
|
||||
// Episode info
|
||||
if (episodeInfo != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 6,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
episodeInfo,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
// Metadata as dot-separated text
|
||||
if (heroItem.year != null ||
|
||||
heroItem.contentRating != null ||
|
||||
heroItem.rating != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
[
|
||||
if (heroItem.rating != null)
|
||||
'★ ${(heroItem.rating! / 10).toStringAsFixed(1)}',
|
||||
if (heroItem.contentRating != null)
|
||||
heroItem.contentRating!,
|
||||
if (heroItem.year != null) heroItem.year.toString(),
|
||||
].join(' • '),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
// Summary
|
||||
// Summary with episode info (Apple TV style)
|
||||
if (heroItem.summary != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
heroItem.summary!,
|
||||
style: const TextStyle(
|
||||
color: Colors.white70,
|
||||
fontSize: 14,
|
||||
height: 1.4,
|
||||
),
|
||||
RichText(
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
text: TextSpan(
|
||||
style: const TextStyle(
|
||||
color: Colors.white70,
|
||||
fontSize: 14,
|
||||
height: 1.4,
|
||||
),
|
||||
children: [
|
||||
if (isEpisode &&
|
||||
heroItem.parentIndex != null &&
|
||||
heroItem.index != null)
|
||||
TextSpan(
|
||||
text:
|
||||
'S${heroItem.parentIndex}, E${heroItem.index}: ',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
TextSpan(text: heroItem.summary!),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// Play Button
|
||||
FilledButton.icon(
|
||||
onPressed: () {
|
||||
appLogger.d('Playing: ${heroItem.title}');
|
||||
Navigator.push<bool>(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
client: widget.client,
|
||||
metadata: heroItem,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
icon: const Icon(Icons.play_arrow, size: 20),
|
||||
label: const Text('Play'),
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.white,
|
||||
foregroundColor: Colors.black,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 24,
|
||||
vertical: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Smart Play Button with progress
|
||||
_buildSmartPlayButton(heroItem),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -777,6 +858,91 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSmartPlayButton(PlexMetadata heroItem) {
|
||||
final hasProgress =
|
||||
heroItem.viewOffset != null &&
|
||||
heroItem.duration != null &&
|
||||
heroItem.viewOffset! > 0 &&
|
||||
heroItem.duration! > 0;
|
||||
|
||||
final minutesLeft = hasProgress
|
||||
? ((heroItem.duration! - heroItem.viewOffset!) / 60000).round()
|
||||
: 0;
|
||||
|
||||
final progress = hasProgress
|
||||
? heroItem.viewOffset! / heroItem.duration!
|
||||
: 0.0;
|
||||
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
appLogger.d('Playing: ${heroItem.title}');
|
||||
Navigator.push<bool>(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
client: widget.client,
|
||||
metadata: heroItem,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.play_arrow, size: 20, color: Colors.black),
|
||||
const SizedBox(width: 8),
|
||||
if (hasProgress) ...[
|
||||
// Progress bar
|
||||
Container(
|
||||
width: 40,
|
||||
height: 6,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black26,
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
),
|
||||
child: FractionallySizedBox(
|
||||
alignment: Alignment.centerLeft,
|
||||
widthFactor: progress,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black,
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'$minutesLeft min left',
|
||||
style: const TextStyle(
|
||||
color: Colors.black,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
] else
|
||||
const Text(
|
||||
'Play',
|
||||
style: TextStyle(
|
||||
color: Colors.black,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHorizontalList(
|
||||
List<PlexMetadata> items, {
|
||||
bool isLarge = false,
|
||||
@@ -811,11 +977,12 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 2),
|
||||
child: MediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
client: widget.client,
|
||||
item: item,
|
||||
width: cardWidth,
|
||||
height: cardHeight,
|
||||
onRefresh: _loadContent,
|
||||
onRefresh: updateItem,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -9,6 +9,8 @@ import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/app_bar_back_button.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../mixins/refreshable.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
import '../theme/theme_helper.dart';
|
||||
|
||||
class LibrariesScreen extends StatefulWidget {
|
||||
final PlexClient client;
|
||||
@@ -20,7 +22,11 @@ class LibrariesScreen extends StatefulWidget {
|
||||
State<LibrariesScreen> createState() => _LibrariesScreenState();
|
||||
}
|
||||
|
||||
class _LibrariesScreenState extends State<LibrariesScreen> with Refreshable {
|
||||
class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
with Refreshable, ItemUpdatable {
|
||||
@override
|
||||
PlexClient get client => widget.client;
|
||||
|
||||
List<PlexLibrary> _libraries = [];
|
||||
List<PlexMetadata> _items = [];
|
||||
List<PlexFilter> _filters = [];
|
||||
@@ -167,6 +173,14 @@ class _LibrariesScreenState extends State<LibrariesScreen> with Refreshable {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
|
||||
final index = _items.indexWhere((item) => item.ratingKey == ratingKey);
|
||||
if (index != -1) {
|
||||
_items[index] = updatedMetadata;
|
||||
}
|
||||
}
|
||||
|
||||
// Public method to refresh content
|
||||
@override
|
||||
void refresh() {
|
||||
@@ -285,6 +299,7 @@ class _LibrariesScreenState extends State<LibrariesScreen> with Refreshable {
|
||||
children: List.generate(_libraries.length, (index) {
|
||||
final library = _libraries[index];
|
||||
final isSelected = index == _selectedLibraryIndex;
|
||||
final t = tokens(context);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: ChoiceChip(
|
||||
@@ -294,13 +309,7 @@ class _LibrariesScreenState extends State<LibrariesScreen> with Refreshable {
|
||||
Icon(
|
||||
_getLibraryIcon(library.type),
|
||||
size: 16,
|
||||
color: isSelected
|
||||
? Theme.of(
|
||||
context,
|
||||
).colorScheme.onSecondaryContainer
|
||||
: Theme.of(
|
||||
context,
|
||||
).colorScheme.onSurfaceVariant,
|
||||
color: isSelected ? t.bg : t.text,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(library.title),
|
||||
@@ -312,6 +321,16 @@ class _LibrariesScreenState extends State<LibrariesScreen> with Refreshable {
|
||||
_loadLibraryContent(index);
|
||||
}
|
||||
},
|
||||
backgroundColor: t.surface,
|
||||
selectedColor: t.text,
|
||||
side: BorderSide(color: t.outline),
|
||||
labelStyle: TextStyle(
|
||||
color: isSelected ? t.bg : t.text,
|
||||
fontWeight: isSelected
|
||||
? FontWeight.w600
|
||||
: FontWeight.w400,
|
||||
),
|
||||
showCheckmark: false,
|
||||
),
|
||||
);
|
||||
}),
|
||||
@@ -374,9 +393,10 @@ class _LibrariesScreenState extends State<LibrariesScreen> with Refreshable {
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
final item = _items[index];
|
||||
return MediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
client: widget.client,
|
||||
item: item,
|
||||
onRefresh: _applyFilters,
|
||||
onRefresh: updateItem,
|
||||
userProfile: widget.userProfile,
|
||||
);
|
||||
}, childCount: _items.length),
|
||||
|
||||
@@ -7,6 +7,7 @@ import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/app_bar_back_button.dart';
|
||||
import '../widgets/media_context_menu.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../theme/theme_helper.dart';
|
||||
import 'season_detail_screen.dart';
|
||||
import 'video_player_screen.dart';
|
||||
|
||||
@@ -32,13 +33,22 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
PlexMetadata? _fullMetadata;
|
||||
PlexMetadata? _onDeckEpisode;
|
||||
bool _isLoadingMetadata = true;
|
||||
late final ScrollController _scrollController;
|
||||
bool _watchStateChanged = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_scrollController = ScrollController();
|
||||
_loadFullMetadata();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadFullMetadata() async {
|
||||
setState(() {
|
||||
_isLoadingMetadata = true;
|
||||
@@ -108,6 +118,37 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update watch state without full screen rebuild
|
||||
/// This preserves scroll position and only updates watch-related data
|
||||
Future<void> _updateWatchState() async {
|
||||
try {
|
||||
final metadata = await widget.client.getMetadataWithImages(
|
||||
widget.metadata.ratingKey,
|
||||
);
|
||||
|
||||
if (metadata != null) {
|
||||
// For shows, also refetch seasons to update their watch counts
|
||||
List<PlexMetadata>? updatedSeasons;
|
||||
if (metadata.type.toLowerCase() == 'show') {
|
||||
updatedSeasons = await widget.client.getChildren(
|
||||
widget.metadata.ratingKey,
|
||||
);
|
||||
}
|
||||
|
||||
// Single setState to minimize rebuilds - scroll position is preserved by controller
|
||||
setState(() {
|
||||
_fullMetadata = metadata;
|
||||
if (updatedSeasons != null) {
|
||||
_seasons = updatedSeasons;
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to update watch state', error: e);
|
||||
// Silently fail - user can manually refresh if needed
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _playFirstEpisode() async {
|
||||
try {
|
||||
// If seasons aren't loaded yet, wait for them or load them
|
||||
@@ -192,13 +233,15 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
controller: _scrollController,
|
||||
slivers: [
|
||||
// Hero header with background art
|
||||
DesktopSliverAppBar(
|
||||
expandedHeight: headerHeight,
|
||||
pinned: true,
|
||||
leading: const AppBarBackButton(
|
||||
leading: AppBarBackButton(
|
||||
style: BackButtonStyle.circular,
|
||||
onPressed: () => Navigator.pop(context, _watchStateChanged),
|
||||
),
|
||||
flexibleSpace: FlexibleSpaceBar(
|
||||
background: Stack(
|
||||
@@ -438,7 +481,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
// Otherwise, play the first episode of the first season
|
||||
if (metadata.type.toLowerCase() == 'show') {
|
||||
if (_onDeckEpisode != null) {
|
||||
appLogger.d('Playing on deck episode: ${_onDeckEpisode!.title}');
|
||||
appLogger.d(
|
||||
'Playing on deck episode: ${_onDeckEpisode!.title}',
|
||||
);
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
@@ -449,7 +494,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
),
|
||||
),
|
||||
);
|
||||
appLogger.d('Returned from playback, refreshing metadata');
|
||||
appLogger.d(
|
||||
'Returned from playback, refreshing metadata',
|
||||
);
|
||||
// Refresh metadata when returning from video player
|
||||
_loadFullMetadata();
|
||||
} else {
|
||||
@@ -469,7 +516,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
),
|
||||
),
|
||||
);
|
||||
appLogger.d('Returned from playback, refreshing metadata');
|
||||
appLogger.d(
|
||||
'Returned from playback, refreshing metadata',
|
||||
);
|
||||
// Refresh metadata when returning from video player
|
||||
_loadFullMetadata();
|
||||
}
|
||||
@@ -495,13 +544,14 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
metadata.ratingKey,
|
||||
);
|
||||
if (context.mounted) {
|
||||
_watchStateChanged = true;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Marked as watched'),
|
||||
),
|
||||
);
|
||||
// Refresh metadata to update UI
|
||||
_loadFullMetadata();
|
||||
// Update watch state without full rebuild
|
||||
_updateWatchState();
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
@@ -527,13 +577,14 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
metadata.ratingKey,
|
||||
);
|
||||
if (context.mounted) {
|
||||
_watchStateChanged = true;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Marked as unwatched'),
|
||||
),
|
||||
);
|
||||
// Refresh metadata to update UI
|
||||
_loadFullMetadata();
|
||||
// Update watch state without full rebuild
|
||||
_updateWatchState();
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
@@ -642,15 +693,22 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
child: MediaContextMenu(
|
||||
client: widget.client,
|
||||
metadata: season,
|
||||
onRefresh: _loadFullMetadata,
|
||||
onTap: () {
|
||||
Navigator.push(
|
||||
onRefresh: (ratingKey) {
|
||||
_watchStateChanged = true;
|
||||
_updateWatchState();
|
||||
},
|
||||
onTap: () async {
|
||||
final watchStateChanged = await Navigator.push<bool>(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) =>
|
||||
SeasonDetailScreen(client: widget.client, season: season),
|
||||
),
|
||||
);
|
||||
if (watchStateChanged == true) {
|
||||
_watchStateChanged = true;
|
||||
_updateWatchState();
|
||||
}
|
||||
},
|
||||
child: InkWell(
|
||||
child: Padding(
|
||||
@@ -721,12 +779,20 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
LinearProgressIndicator(
|
||||
value:
|
||||
season.viewedLeafCount! / season.leafCount!,
|
||||
backgroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
SizedBox(
|
||||
width: 200,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: LinearProgressIndicator(
|
||||
value:
|
||||
season.viewedLeafCount! / season.leafCount!,
|
||||
backgroundColor: tokens(context).outline,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
minHeight: 6,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
|
||||
@@ -6,6 +6,7 @@ import '../models/plex_user_profile.dart';
|
||||
import '../widgets/media_card.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../mixins/refreshable.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
|
||||
class SearchScreen extends StatefulWidget {
|
||||
final PlexClient client;
|
||||
@@ -17,7 +18,11 @@ class SearchScreen extends StatefulWidget {
|
||||
State<SearchScreen> createState() => _SearchScreenState();
|
||||
}
|
||||
|
||||
class _SearchScreenState extends State<SearchScreen> with Refreshable {
|
||||
class _SearchScreenState extends State<SearchScreen>
|
||||
with Refreshable, ItemUpdatable {
|
||||
@override
|
||||
PlexClient get client => widget.client;
|
||||
|
||||
final _searchController = TextEditingController();
|
||||
List<PlexMetadata> _searchResults = [];
|
||||
bool _isSearching = false;
|
||||
@@ -101,6 +106,16 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
|
||||
final index = _searchResults.indexWhere(
|
||||
(item) => item.ratingKey == ratingKey,
|
||||
);
|
||||
if (index != -1) {
|
||||
_searchResults[index] = updatedMetadata;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
@@ -196,9 +211,10 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
final item = _searchResults[index];
|
||||
return MediaCard(
|
||||
key: Key(item.ratingKey),
|
||||
client: widget.client,
|
||||
item: item,
|
||||
onRefresh: refresh,
|
||||
onRefresh: updateItem,
|
||||
userProfile: widget.userProfile,
|
||||
);
|
||||
}, childCount: _searchResults.length),
|
||||
|
||||
@@ -5,6 +5,9 @@ import '../models/plex_metadata.dart';
|
||||
import '../models/plex_user_profile.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/app_bar_back_button.dart';
|
||||
import '../widgets/media_context_menu.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
import '../theme/theme_helper.dart';
|
||||
import 'video_player_screen.dart';
|
||||
|
||||
class SeasonDetailScreen extends StatefulWidget {
|
||||
@@ -23,9 +26,14 @@ class SeasonDetailScreen extends StatefulWidget {
|
||||
State<SeasonDetailScreen> createState() => _SeasonDetailScreenState();
|
||||
}
|
||||
|
||||
class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
|
||||
class _SeasonDetailScreenState extends State<SeasonDetailScreen>
|
||||
with ItemUpdatable {
|
||||
@override
|
||||
PlexClient get client => widget.client;
|
||||
|
||||
List<PlexMetadata> _episodes = [];
|
||||
bool _isLoadingEpisodes = false;
|
||||
bool _watchStateChanged = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -51,6 +59,20 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> updateItem(String ratingKey) async {
|
||||
_watchStateChanged = true;
|
||||
await super.updateItem(ratingKey);
|
||||
}
|
||||
|
||||
@override
|
||||
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
|
||||
final index = _episodes.indexWhere((item) => item.ratingKey == ratingKey);
|
||||
if (index != -1) {
|
||||
_episodes[index] = updatedMetadata;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
@@ -59,8 +81,9 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
|
||||
DesktopSliverAppBar(
|
||||
title: Text(widget.season.title),
|
||||
pinned: true,
|
||||
leading: const AppBarBackButton(
|
||||
leading: AppBarBackButton(
|
||||
style: BackButtonStyle.circular,
|
||||
onPressed: () => Navigator.pop(context, _watchStateChanged),
|
||||
),
|
||||
),
|
||||
if (_isLoadingEpisodes)
|
||||
@@ -73,35 +96,30 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icon(
|
||||
Icons.movie_outlined,
|
||||
size: 64,
|
||||
color: Colors.grey,
|
||||
color: tokens(context).textMuted,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No episodes found',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleLarge?.copyWith(color: Colors.grey),
|
||||
).textTheme.titleLarge?.copyWith(
|
||||
color: tokens(context).textMuted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
if (index.isOdd) {
|
||||
return const SizedBox(height: 12);
|
||||
}
|
||||
final episodeIndex = index ~/ 2;
|
||||
final episode = _episodes[episodeIndex];
|
||||
return _buildEpisodeCard(episode);
|
||||
}, childCount: _episodes.length * 2 - 1),
|
||||
),
|
||||
SliverList(
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
final episode = _episodes[index];
|
||||
return _buildEpisodeCard(episode);
|
||||
}, childCount: _episodes.length),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -117,25 +135,37 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
|
||||
? episode.viewOffset! / episode.duration!
|
||||
: 0.0;
|
||||
|
||||
return Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
return MediaContextMenu(
|
||||
client: widget.client,
|
||||
metadata: episode,
|
||||
onRefresh: updateItem,
|
||||
onTap: () async {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
client: widget.client,
|
||||
metadata: episode,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
),
|
||||
);
|
||||
// Refresh episodes when returning from video player
|
||||
_loadEpisodes();
|
||||
},
|
||||
child: InkWell(
|
||||
onTap: () async {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
client: widget.client,
|
||||
metadata: episode,
|
||||
userProfile: widget.userProfile,
|
||||
key: Key(episode.ratingKey),
|
||||
hoverColor: Theme.of(context).colorScheme.surface.withValues(alpha: 0.05),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border(
|
||||
bottom: BorderSide(
|
||||
color: tokens(context).outline,
|
||||
width: 0.5,
|
||||
),
|
||||
),
|
||||
);
|
||||
// Refresh episodes when returning from video player
|
||||
_loadEpisodes();
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
@@ -153,6 +183,7 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
|
||||
imageUrl: widget.client.getThumbnailUrl(
|
||||
episode.thumb,
|
||||
),
|
||||
filterQuality: FilterQuality.medium,
|
||||
fit: BoxFit.cover,
|
||||
placeholder: (context, url) => Container(
|
||||
color: Theme.of(
|
||||
@@ -206,31 +237,6 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
|
||||
),
|
||||
),
|
||||
|
||||
// Watched indicator
|
||||
if (episode.isWatched)
|
||||
Positioned(
|
||||
top: 4,
|
||||
right: 4,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.3),
|
||||
blurRadius: 4,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.check,
|
||||
color: Colors.white,
|
||||
size: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Progress bar at bottom
|
||||
if (hasProgress && !episode.isWatched)
|
||||
Positioned(
|
||||
@@ -244,36 +250,11 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
|
||||
),
|
||||
child: LinearProgressIndicator(
|
||||
value: progress,
|
||||
backgroundColor: Colors.grey.withValues(alpha: 0.3),
|
||||
backgroundColor: tokens(context).outline,
|
||||
minHeight: 3,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Duration badge
|
||||
if (episode.duration != null)
|
||||
Positioned(
|
||||
bottom: 4,
|
||||
right: 4,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 4,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.7),
|
||||
borderRadius: BorderRadius.circular(3),
|
||||
),
|
||||
child: Text(
|
||||
_formatDuration(episode.duration!),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -331,13 +312,47 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
|
||||
Text(
|
||||
episode.summary!,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.grey,
|
||||
color: tokens(context).textMuted,
|
||||
height: 1.3,
|
||||
),
|
||||
maxLines: 3,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
|
||||
// Metadata row (duration, watched status)
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
if (episode.duration != null)
|
||||
Text(
|
||||
_formatDuration(episode.duration!),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
if (episode.duration != null && episode.isWatched) ...[
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6),
|
||||
child: Text(
|
||||
'•',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'Watched ✓',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../services/plex_auth_service.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../client/plex_client.dart';
|
||||
import '../config/plex_config.dart';
|
||||
import '../services/server_connection_service.dart';
|
||||
import '../widgets/server_list_tile.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import 'main_screen.dart';
|
||||
@@ -66,49 +65,41 @@ class _ServerSelectionScreenState extends State<ServerSelectionScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
// Test connections to find best working one
|
||||
final connection = await server.findBestWorkingConnection();
|
||||
// Get client identifier
|
||||
final storage = await StorageService.getInstance();
|
||||
final clientId =
|
||||
storage.getClientIdentifier() ?? widget.authService.clientIdentifier;
|
||||
|
||||
// Connect using the optimized service
|
||||
final result = await ServerConnectionService.connectToServer(
|
||||
server,
|
||||
clientIdentifier: clientId,
|
||||
plexToken: widget.plexToken,
|
||||
);
|
||||
|
||||
// Close loading dialog
|
||||
if (mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
if (connection == null) {
|
||||
// Handle result
|
||||
if (result.isSuccess) {
|
||||
// Navigate to main app
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('No working connections found for this server'),
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MainScreen(client: result.client!),
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Store server information
|
||||
final storage = await StorageService.getInstance();
|
||||
await storage.saveServerData(server.toJson());
|
||||
await storage.saveServerUrl(connection.uri);
|
||||
await storage.saveServerAccessToken(server.accessToken);
|
||||
await storage.savePlexToken(widget.plexToken);
|
||||
|
||||
// Get client identifier
|
||||
final clientId =
|
||||
storage.getClientIdentifier() ?? widget.authService.clientIdentifier;
|
||||
|
||||
// Create client and navigate to main app
|
||||
final config = await PlexConfig.create(
|
||||
baseUrl: connection.uri,
|
||||
token: server.accessToken,
|
||||
clientIdentifier: clientId,
|
||||
);
|
||||
final client = PlexClient(config);
|
||||
|
||||
if (mounted) {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => MainScreen(client: client)),
|
||||
);
|
||||
} else {
|
||||
// Show error
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(result.error ?? 'Connection failed')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ class VideoPlayerScreen extends StatefulWidget {
|
||||
final PlexMetadata metadata;
|
||||
final AudioTrack? preferredAudioTrack;
|
||||
final SubtitleTrack? preferredSubtitleTrack;
|
||||
final double? preferredPlaybackRate;
|
||||
final PlexUserProfile? userProfile;
|
||||
|
||||
const VideoPlayerScreen({
|
||||
@@ -23,6 +24,7 @@ class VideoPlayerScreen extends StatefulWidget {
|
||||
required this.metadata,
|
||||
this.preferredAudioTrack,
|
||||
this.preferredSubtitleTrack,
|
||||
this.preferredPlaybackRate,
|
||||
this.userProfile,
|
||||
});
|
||||
|
||||
@@ -103,8 +105,11 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
}
|
||||
|
||||
try {
|
||||
final next = await widget.client.getNextEpisode(widget.metadata);
|
||||
final previous = await widget.client.getPreviousEpisode(widget.metadata);
|
||||
final next = await widget.client.findAdjacentEpisode(widget.metadata, 1);
|
||||
final previous = await widget.client.findAdjacentEpisode(
|
||||
widget.metadata,
|
||||
-1,
|
||||
);
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
@@ -194,38 +199,50 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
});
|
||||
}
|
||||
|
||||
AudioTrack? _findBestAudioMatch(
|
||||
List<AudioTrack> availableTracks,
|
||||
AudioTrack preferred,
|
||||
/// 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) => t.id != 'auto' && t.id != 'no')
|
||||
.where((t) => getId(t) != 'auto' && getId(t) != 'no')
|
||||
.toList();
|
||||
if (validTracks.isEmpty) return null;
|
||||
|
||||
// Try to match: index, title, and language
|
||||
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 (track.id == preferred.id &&
|
||||
track.title == preferred.title &&
|
||||
track.language == preferred.language) {
|
||||
if (getId(track) == preferredId &&
|
||||
getTitle(track) == preferredTitle &&
|
||||
getLanguage(track) == preferredLanguage) {
|
||||
return track;
|
||||
}
|
||||
}
|
||||
|
||||
// Try to match: title and language
|
||||
for (var track in validTracks) {
|
||||
if (track.title == preferred.title &&
|
||||
track.language == preferred.language) {
|
||||
if (getTitle(track) == preferredTitle &&
|
||||
getLanguage(track) == preferredLanguage) {
|
||||
return track;
|
||||
}
|
||||
}
|
||||
|
||||
// Try to match: language only
|
||||
for (var track in validTracks) {
|
||||
if (track.language == preferred.language) {
|
||||
if (getLanguage(track) == preferredLanguage) {
|
||||
return track;
|
||||
}
|
||||
}
|
||||
@@ -233,6 +250,19 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
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,
|
||||
@@ -282,44 +312,18 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
List<SubtitleTrack> availableTracks,
|
||||
SubtitleTrack preferred,
|
||||
) {
|
||||
// If preferred is "no", return no subtitles
|
||||
// Handle special "no subtitles" case
|
||||
if (preferred.id == 'no') {
|
||||
return SubtitleTrack.no();
|
||||
}
|
||||
|
||||
if (availableTracks.isEmpty) return null;
|
||||
|
||||
// Filter out auto and no tracks
|
||||
final validTracks = availableTracks
|
||||
.where((t) => t.id != 'auto' && t.id != 'no')
|
||||
.toList();
|
||||
if (validTracks.isEmpty) return null;
|
||||
|
||||
// Try to match: index, title, and language
|
||||
for (var track in validTracks) {
|
||||
if (track.id == preferred.id &&
|
||||
track.title == preferred.title &&
|
||||
track.language == preferred.language) {
|
||||
return track;
|
||||
}
|
||||
}
|
||||
|
||||
// Try to match: title and language
|
||||
for (var track in validTracks) {
|
||||
if (track.title == preferred.title &&
|
||||
track.language == preferred.language) {
|
||||
return track;
|
||||
}
|
||||
}
|
||||
|
||||
// Try to match: language only
|
||||
for (var track in validTracks) {
|
||||
if (track.language == preferred.language) {
|
||||
return track;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
return _findBestTrackMatch<SubtitleTrack>(
|
||||
availableTracks,
|
||||
preferred,
|
||||
(t) => t.id,
|
||||
(t) => t.title,
|
||||
(t) => t.language,
|
||||
);
|
||||
}
|
||||
|
||||
SubtitleTrack? _findSubtitleTrackByProfile(
|
||||
@@ -545,6 +549,14 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
appLogger.i('Final subtitle selection: $finalSubtitle');
|
||||
player.setSubtitleTrack(subtitleToSelect);
|
||||
|
||||
// Set playback rate if preferred rate was provided
|
||||
if (widget.preferredPlaybackRate != null) {
|
||||
appLogger.d(
|
||||
'Setting preferred playback rate: ${widget.preferredPlaybackRate}x',
|
||||
);
|
||||
player.setRate(widget.preferredPlaybackRate!);
|
||||
}
|
||||
|
||||
appLogger.d('Track selection complete');
|
||||
}
|
||||
|
||||
@@ -610,34 +622,16 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
_showPlayNextDialog = false;
|
||||
});
|
||||
|
||||
// Capture current track selection BEFORE pausing
|
||||
final currentAudioTrack = player.state.track.audio;
|
||||
final currentSubtitleTrack = player.state.track.subtitle;
|
||||
|
||||
// Pause and stop current playback
|
||||
player.pause();
|
||||
_progressTimer?.cancel();
|
||||
_sendProgress('stopped');
|
||||
|
||||
// Navigate to the next episode using pushReplacement to destroy current player
|
||||
if (mounted) {
|
||||
Navigator.of(context).pushReplacement(
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
client: widget.client,
|
||||
metadata: _nextEpisode!,
|
||||
preferredAudioTrack: currentAudioTrack,
|
||||
preferredSubtitleTrack: currentSubtitleTrack,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
await _navigateToEpisode(_nextEpisode!);
|
||||
}
|
||||
|
||||
Future<void> _playPrevious() async {
|
||||
if (_previousEpisode == null) return;
|
||||
await _navigateToEpisode(_previousEpisode!);
|
||||
}
|
||||
|
||||
/// Navigates to a new episode, preserving playback state and track selections
|
||||
Future<void> _navigateToEpisode(PlexMetadata episodeMetadata) async {
|
||||
// Capture current track selection BEFORE pausing
|
||||
final currentAudioTrack = player.state.track.audio;
|
||||
final currentSubtitleTrack = player.state.track.subtitle;
|
||||
@@ -647,17 +641,22 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
_progressTimer?.cancel();
|
||||
_sendProgress('stopped');
|
||||
|
||||
// Navigate to the previous episode using pushReplacement to destroy current player
|
||||
// Navigate to the episode using pushReplacement to destroy current player
|
||||
if (mounted) {
|
||||
final currentRate = player.state.rate;
|
||||
Navigator.of(context).pushReplacement(
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
client: widget.client,
|
||||
metadata: _previousEpisode!,
|
||||
preferredAudioTrack: currentAudioTrack,
|
||||
preferredSubtitleTrack: currentSubtitleTrack,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
PageRouteBuilder(
|
||||
pageBuilder: (context, animation, secondaryAnimation) =>
|
||||
VideoPlayerScreen(
|
||||
client: widget.client,
|
||||
metadata: episodeMetadata,
|
||||
preferredAudioTrack: currentAudioTrack,
|
||||
preferredSubtitleTrack: currentSubtitleTrack,
|
||||
preferredPlaybackRate: currentRate,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
transitionDuration: Duration.zero,
|
||||
reverseTransitionDuration: Duration.zero,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
+156
-104
@@ -11,7 +11,7 @@ class PlexAuthService {
|
||||
static const String _clientsApi = 'https://clients.plex.tv/api/v2';
|
||||
|
||||
final Dio _dio;
|
||||
late final String _clientIdentifier;
|
||||
final String _clientIdentifier;
|
||||
|
||||
PlexAuthService._(this._dio, this._clientIdentifier);
|
||||
|
||||
@@ -20,33 +20,43 @@ class PlexAuthService {
|
||||
final dio = Dio();
|
||||
|
||||
// Get or create client identifier
|
||||
String? clientId = storage.getClientIdentifier();
|
||||
if (clientId == null) {
|
||||
clientId = const Uuid().v4();
|
||||
await storage.saveClientIdentifier(clientId);
|
||||
String? clientIdentifier = storage.getClientIdentifier();
|
||||
if (clientIdentifier == null) {
|
||||
clientIdentifier = const Uuid().v4();
|
||||
await storage.saveClientIdentifier(clientIdentifier);
|
||||
}
|
||||
|
||||
return PlexAuthService._(dio, clientId);
|
||||
return PlexAuthService._(dio, clientIdentifier);
|
||||
}
|
||||
|
||||
String get clientIdentifier => _clientIdentifier;
|
||||
|
||||
Options _getCommonOptions({String? authToken}) {
|
||||
final headers = {
|
||||
'Accept': 'application/json',
|
||||
'X-Plex-Product': _appName,
|
||||
'X-Plex-Client-Identifier': _clientIdentifier,
|
||||
};
|
||||
|
||||
if (authToken != null) {
|
||||
headers['X-Plex-Token'] = authToken;
|
||||
}
|
||||
|
||||
return Options(headers: headers);
|
||||
}
|
||||
|
||||
Future<Response> _getUser(String authToken) {
|
||||
return _dio.get(
|
||||
'$_plexApiBase/user',
|
||||
options: _getCommonOptions(authToken: authToken),
|
||||
);
|
||||
}
|
||||
|
||||
/// Verify if a plex.tv token is valid
|
||||
Future<bool> verifyToken(String token) async {
|
||||
Future<bool> verifyToken(String authToken) async {
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
'$_plexApiBase/user',
|
||||
options: Options(
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-Plex-Product': _appName,
|
||||
'X-Plex-Client-Identifier': _clientIdentifier,
|
||||
'X-Plex-Token': token,
|
||||
},
|
||||
validateStatus: (status) => status != null && status < 500,
|
||||
),
|
||||
);
|
||||
return response.statusCode == 200;
|
||||
await _getUser(authToken);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
@@ -56,13 +66,7 @@ class PlexAuthService {
|
||||
Future<Map<String, dynamic>> createPin() async {
|
||||
final response = await _dio.post(
|
||||
'$_plexApiBase/pins?strong=true',
|
||||
options: Options(
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-Plex-Product': _appName,
|
||||
'X-Plex-Client-Identifier': _clientIdentifier,
|
||||
},
|
||||
),
|
||||
options: _getCommonOptions(),
|
||||
);
|
||||
|
||||
return response.data as Map<String, dynamic>;
|
||||
@@ -91,12 +95,7 @@ class PlexAuthService {
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
'$_plexApiBase/pins/$pinId',
|
||||
options: Options(
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-Plex-Client-Identifier': _clientIdentifier,
|
||||
},
|
||||
),
|
||||
options: _getCommonOptions(),
|
||||
);
|
||||
|
||||
final data = response.data as Map<String, dynamic>;
|
||||
@@ -133,17 +132,10 @@ class PlexAuthService {
|
||||
}
|
||||
|
||||
/// Fetch available Plex servers for the authenticated user
|
||||
Future<List<PlexServer>> fetchServers(String plexToken) async {
|
||||
Future<List<PlexServer>> fetchServers(String authToken) async {
|
||||
final response = await _dio.get(
|
||||
'$_clientsApi/resources?includeHttps=1&includeRelay=1&includeIPv6=1',
|
||||
options: Options(
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-Plex-Product': _appName,
|
||||
'X-Plex-Client-Identifier': _clientIdentifier,
|
||||
'X-Plex-Token': plexToken,
|
||||
},
|
||||
),
|
||||
options: _getCommonOptions(authToken: authToken),
|
||||
);
|
||||
|
||||
final List<dynamic> resources = response.data as List<dynamic>;
|
||||
@@ -156,34 +148,17 @@ class PlexAuthService {
|
||||
}
|
||||
|
||||
/// Get user information
|
||||
Future<Map<String, dynamic>> getUserInfo(String token) async {
|
||||
final response = await _dio.get(
|
||||
'$_plexApiBase/user',
|
||||
options: Options(
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-Plex-Product': _appName,
|
||||
'X-Plex-Client-Identifier': _clientIdentifier,
|
||||
'X-Plex-Token': token,
|
||||
},
|
||||
),
|
||||
);
|
||||
Future<Map<String, dynamic>> getUserInfo(String authToken) async {
|
||||
final response = await _getUser(authToken);
|
||||
|
||||
return response.data as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
/// Get user profile with preferences (audio/subtitle settings)
|
||||
Future<PlexUserProfile> getUserProfile(String token) async {
|
||||
Future<PlexUserProfile> getUserProfile(String authToken) async {
|
||||
final response = await _dio.get(
|
||||
'$_clientsApi/user',
|
||||
options: Options(
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'X-Plex-Product': _appName,
|
||||
'X-Plex-Client-Identifier': _clientIdentifier,
|
||||
'X-Plex-Token': token,
|
||||
},
|
||||
),
|
||||
options: _getCommonOptions(authToken: authToken),
|
||||
);
|
||||
|
||||
return PlexUserProfile.fromJson(response.data as Map<String, dynamic>);
|
||||
@@ -259,68 +234,145 @@ class PlexServer {
|
||||
/// Check if server is online using the presence field
|
||||
bool get isOnline => presence;
|
||||
|
||||
PlexConnection? _selectBest(Iterable<PlexConnection> candidates) {
|
||||
final local = candidates.where((c) => c.local && !c.relay).toList();
|
||||
if (local.isNotEmpty) return local.first;
|
||||
|
||||
final remote = candidates.where((c) => !c.local && !c.relay).toList();
|
||||
if (remote.isNotEmpty) return remote.first;
|
||||
|
||||
final relay = candidates.where((c) => c.relay).toList();
|
||||
if (relay.isNotEmpty) return relay.first;
|
||||
|
||||
if (candidates.isNotEmpty) return candidates.first;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Get the best connection URL
|
||||
/// Priority: local > remote > relay
|
||||
PlexConnection? getBestConnection() {
|
||||
if (connections.isEmpty) return null;
|
||||
return _selectBest(connections);
|
||||
}
|
||||
|
||||
// Try to find local connection first
|
||||
final local = connections.where((c) => c.local && !c.relay).toList();
|
||||
if (local.isNotEmpty) return local.first;
|
||||
PlexConnection? _findLowestLatency(
|
||||
List<MapEntry<PlexConnection, ConnectionTestResult>> entries,
|
||||
) {
|
||||
if (entries.isEmpty) return null;
|
||||
final bestEntry = entries.reduce(
|
||||
(a, b) => a.value.latencyMs < b.value.latencyMs ? a : b,
|
||||
);
|
||||
return bestEntry.key;
|
||||
}
|
||||
|
||||
// Try remote (non-relay) connection
|
||||
final remote = connections.where((c) => !c.local && !c.relay).toList();
|
||||
if (remote.isNotEmpty) return remote.first;
|
||||
PlexConnection? _selectBestWithLatency(
|
||||
Map<PlexConnection, ConnectionTestResult> results,
|
||||
) {
|
||||
final localEntries = results.entries
|
||||
.where((e) => e.key.local && !e.key.relay)
|
||||
.toList();
|
||||
final remoteEntries = results.entries
|
||||
.where((e) => !e.key.local && !e.key.relay)
|
||||
.toList();
|
||||
final relayEntries = results.entries.where((e) => e.key.relay).toList();
|
||||
|
||||
// Fall back to relay as last resort
|
||||
final relay = connections.where((c) => c.relay).toList();
|
||||
if (relay.isNotEmpty) return relay.first;
|
||||
|
||||
// Return any connection
|
||||
return connections.first;
|
||||
return _findLowestLatency(localEntries) ??
|
||||
_findLowestLatency(remoteEntries) ??
|
||||
_findLowestLatency(relayEntries);
|
||||
}
|
||||
|
||||
/// Find the best working connection by testing them
|
||||
/// Tests ALL connections simultaneously and returns the best working one
|
||||
/// Returns a Stream that emits connections progressively:
|
||||
/// 1. First emission: The first connection that responds successfully
|
||||
/// 2. Second emission (optional): The best connection after latency testing
|
||||
/// Priority: local > remote > relay (from successful connections)
|
||||
Future<PlexConnection?> findBestWorkingConnection() async {
|
||||
Stream<PlexConnection> findBestWorkingConnection() async* {
|
||||
if (connections.isEmpty) return;
|
||||
|
||||
// Phase 1: Race to find first working connection
|
||||
final completer = Completer<PlexConnection?>();
|
||||
PlexConnection? firstConnection;
|
||||
int completedTests = 0;
|
||||
|
||||
// Start testing all connections simultaneously
|
||||
for (final connection in connections) {
|
||||
PlexClient.testConnectionWithLatency(connection.uri, accessToken).then((
|
||||
result,
|
||||
) {
|
||||
completedTests++;
|
||||
|
||||
// If this is the first successful connection, emit it immediately
|
||||
if (result.success && !completer.isCompleted) {
|
||||
completer.complete(connection);
|
||||
}
|
||||
|
||||
// If all tests complete without success, complete with null
|
||||
if (completedTests == connections.length && !completer.isCompleted) {
|
||||
completer.complete(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Wait for and emit the first successful connection
|
||||
firstConnection = await completer.future;
|
||||
if (firstConnection == null) {
|
||||
return; // No working connections found
|
||||
}
|
||||
|
||||
yield firstConnection;
|
||||
|
||||
// Phase 2: Continue testing in background to find best connection
|
||||
// Test each connection 2-3 times and average the latency
|
||||
final connectionResults = <PlexConnection, ConnectionTestResult>{};
|
||||
|
||||
await Future.wait(
|
||||
connections.map((connection) async {
|
||||
final result = await PlexClient.testConnectionWithAverageLatency(
|
||||
connection.uri,
|
||||
accessToken,
|
||||
attempts: 2,
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
connectionResults[connection] = result;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// If no connections succeeded, we're done
|
||||
if (connectionResults.isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the best connection considering both priority and latency
|
||||
final bestConnection = _selectBestWithLatency(connectionResults);
|
||||
|
||||
// Emit the best connection if it's different from the first one
|
||||
if (bestConnection != null && bestConnection.uri != firstConnection.uri) {
|
||||
yield bestConnection;
|
||||
}
|
||||
}
|
||||
|
||||
/// Legacy method for backward compatibility - returns first working connection
|
||||
/// For optimal performance, use findBestWorkingConnection() stream instead
|
||||
@Deprecated('Use findBestWorkingConnection() stream for optimized connection')
|
||||
Future<PlexConnection?> findBestWorkingConnectionLegacy() async {
|
||||
if (connections.isEmpty) return null;
|
||||
|
||||
// Test all connections simultaneously
|
||||
final results = await Future.wait(
|
||||
final working = <PlexConnection>[];
|
||||
await Future.wait(
|
||||
connections.map((connection) async {
|
||||
final works = await PlexClient.testConnectionUrl(
|
||||
connection.uri,
|
||||
accessToken,
|
||||
);
|
||||
return works ? connection : null;
|
||||
if (works) {
|
||||
working.add(connection);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Filter out failed connections
|
||||
final workingConnections = results
|
||||
.where((c) => c != null)
|
||||
.cast<PlexConnection>()
|
||||
.toList();
|
||||
|
||||
if (workingConnections.isEmpty) return null;
|
||||
|
||||
// From working connections, prefer local > remote > relay
|
||||
final localWorking = workingConnections
|
||||
.where((c) => c.local && !c.relay)
|
||||
.toList();
|
||||
if (localWorking.isNotEmpty) return localWorking.first;
|
||||
|
||||
final remoteWorking = workingConnections
|
||||
.where((c) => !c.local && !c.relay)
|
||||
.toList();
|
||||
if (remoteWorking.isNotEmpty) return remoteWorking.first;
|
||||
|
||||
final relayWorking = workingConnections.where((c) => c.relay).toList();
|
||||
if (relayWorking.isNotEmpty) return relayWorking.first;
|
||||
|
||||
// Fallback to any working connection
|
||||
return workingConnections.first;
|
||||
return _selectBest(working);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'plex_auth_service.dart';
|
||||
import 'storage_service.dart';
|
||||
import '../client/plex_client.dart';
|
||||
import '../config/plex_config.dart';
|
||||
import '../models/plex_user_profile.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
/// Result of a server connection attempt
|
||||
class ServerConnectionResult {
|
||||
final PlexClient? client;
|
||||
final PlexUserProfile? userProfile;
|
||||
final String? error;
|
||||
|
||||
ServerConnectionResult({this.client, this.userProfile, this.error});
|
||||
|
||||
bool get isSuccess => client != null;
|
||||
}
|
||||
|
||||
/// Service for handling optimized server connections
|
||||
/// Implements fast-first connection with background optimization
|
||||
class ServerConnectionService {
|
||||
/// Connect to a Plex server with optimized connection testing
|
||||
///
|
||||
/// Returns immediately with first working connection, then continues
|
||||
/// testing in background to find the optimal connection.
|
||||
///
|
||||
/// Parameters:
|
||||
/// - [server]: The PlexServer to connect to
|
||||
/// - [clientIdentifier]: Client identifier for the PlexClient
|
||||
/// - [plexToken]: Optional plex.tv token to save to storage
|
||||
/// - [verifyServer]: Whether to verify server is accessible before returning
|
||||
/// - [fetchUserProfile]: Whether to fetch and cache user profile
|
||||
/// - [onProgress]: Callback for progress updates (e.g., show/hide loading)
|
||||
static Future<ServerConnectionResult> connectToServer(
|
||||
PlexServer server, {
|
||||
required String clientIdentifier,
|
||||
String? plexToken,
|
||||
bool verifyServer = false,
|
||||
bool fetchUserProfile = false,
|
||||
void Function(String message)? onProgress,
|
||||
}) async {
|
||||
PlexConnection? firstConnection;
|
||||
final storage = await StorageService.getInstance();
|
||||
|
||||
try {
|
||||
// Listen to the connection stream for progressive connection testing
|
||||
await for (final connection in server.findBestWorkingConnection()) {
|
||||
if (firstConnection == null) {
|
||||
// First emission - use this connection immediately
|
||||
firstConnection = connection;
|
||||
|
||||
if (onProgress != null) {
|
||||
onProgress('Connected to ${connection.displayType} endpoint');
|
||||
}
|
||||
|
||||
// Save server information to storage
|
||||
await storage.saveServerData(server.toJson());
|
||||
await storage.saveServerUrl(connection.uri);
|
||||
await storage.saveServerAccessToken(server.accessToken);
|
||||
|
||||
// Save plex token if provided
|
||||
if (plexToken != null) {
|
||||
await storage.savePlexToken(plexToken);
|
||||
}
|
||||
|
||||
// Create client with working connection
|
||||
final config = await PlexConfig.create(
|
||||
baseUrl: connection.uri,
|
||||
token: server.accessToken,
|
||||
clientIdentifier: clientIdentifier,
|
||||
);
|
||||
final client = PlexClient(config);
|
||||
|
||||
// Verify server is accessible if requested
|
||||
if (verifyServer) {
|
||||
try {
|
||||
await client.getServerIdentity();
|
||||
} catch (e) {
|
||||
appLogger.w('Server identity verification failed', error: e);
|
||||
await storage.clearCredentials();
|
||||
return ServerConnectionResult(
|
||||
error: 'Server is not accessible: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch user profile if requested
|
||||
PlexUserProfile? userProfile;
|
||||
if (fetchUserProfile && plexToken != null) {
|
||||
userProfile = await _fetchAndCacheUserProfile(plexToken);
|
||||
}
|
||||
|
||||
// Return success result
|
||||
// Note: Stream continues in background to find better connection
|
||||
return ServerConnectionResult(
|
||||
client: client,
|
||||
userProfile: userProfile,
|
||||
);
|
||||
} else {
|
||||
// Second emission - better connection found
|
||||
// Update stored connection seamlessly for future app launches
|
||||
await storage.saveServerUrl(connection.uri);
|
||||
appLogger.d(
|
||||
'Switched to better connection: ${connection.displayType} (${connection.uri})',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle case where no connections were found
|
||||
if (firstConnection == null) {
|
||||
return ServerConnectionResult(
|
||||
error: 'No working connections found for this server',
|
||||
);
|
||||
}
|
||||
|
||||
// Should never reach here due to return in the stream loop
|
||||
return ServerConnectionResult(
|
||||
error: 'Unexpected error in connection flow',
|
||||
);
|
||||
} catch (e) {
|
||||
appLogger.e('Error connecting to server', error: e);
|
||||
return ServerConnectionResult(error: 'Connection failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch user profile from Plex API and cache it locally
|
||||
static Future<PlexUserProfile?> _fetchAndCacheUserProfile(
|
||||
String plexToken,
|
||||
) async {
|
||||
appLogger.d('Fetching user profile from Plex API');
|
||||
try {
|
||||
final authService = await PlexAuthService.create();
|
||||
final profile = await authService.getUserProfile(plexToken);
|
||||
|
||||
appLogger.i(
|
||||
'Successfully fetched user profile',
|
||||
error: {
|
||||
'autoSelectAudio': profile.autoSelectAudio,
|
||||
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
|
||||
'autoSelectSubtitle': profile.autoSelectSubtitle,
|
||||
'defaultSubtitleLanguage':
|
||||
profile.defaultSubtitleLanguage ?? 'not set',
|
||||
'defaultSubtitleForced': profile.defaultSubtitleForced,
|
||||
},
|
||||
);
|
||||
|
||||
// Cache the profile
|
||||
final storage = await StorageService.getInstance();
|
||||
await storage.saveUserProfile(profile.toJson());
|
||||
appLogger.d('User profile cached locally');
|
||||
|
||||
return profile;
|
||||
} catch (e) {
|
||||
appLogger.w(
|
||||
'Failed to fetch user profile from API, attempting to load from cache',
|
||||
error: e,
|
||||
);
|
||||
|
||||
// Failed to fetch profile, try to load from cache
|
||||
final storage = await StorageService.getInstance();
|
||||
final cachedProfile = storage.getUserProfile();
|
||||
if (cachedProfile != null) {
|
||||
final profile = PlexUserProfile.fromJson(cachedProfile);
|
||||
appLogger.i(
|
||||
'Loaded user profile from cache',
|
||||
error: {
|
||||
'autoSelectAudio': profile.autoSelectAudio,
|
||||
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
|
||||
'autoSelectSubtitle': profile.autoSelectSubtitle,
|
||||
'defaultSubtitleLanguage':
|
||||
profile.defaultSubtitleLanguage ?? 'not set',
|
||||
'defaultSubtitleForced': profile.defaultSubtitleForced,
|
||||
},
|
||||
);
|
||||
return profile;
|
||||
}
|
||||
|
||||
appLogger.w(
|
||||
'No cached user profile available, track selection will use defaults',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'mono_tokens.dart';
|
||||
|
||||
ThemeData monoTheme({required bool dark}) {
|
||||
// neutral greys tuned for crisp contrast
|
||||
final c = dark
|
||||
? (
|
||||
bg: const Color(0xFF0E0F12),
|
||||
surface: const Color(0xFF15171C),
|
||||
outline: const Color(0x1FFFFFFF),
|
||||
text: const Color(0xFFEDEDED),
|
||||
textMuted: const Color(0x99EDEDED),
|
||||
)
|
||||
: (
|
||||
bg: const Color(0xFFF7F7F8),
|
||||
surface: const Color(0xFFFFFFFF),
|
||||
outline: const Color(0x19000000),
|
||||
text: const Color(0xFF111111),
|
||||
textMuted: const Color(0x99111111),
|
||||
);
|
||||
|
||||
final base = ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: dark ? Brightness.dark : Brightness.light,
|
||||
colorScheme: ColorScheme(
|
||||
brightness: dark ? Brightness.dark : Brightness.light,
|
||||
primary: c.text,
|
||||
onPrimary: dark ? const Color(0xFF0E0F12) : Colors.white,
|
||||
secondary: c.text,
|
||||
onSecondary: c.bg,
|
||||
surface: c.surface,
|
||||
onSurface: c.text,
|
||||
error: const Color(0xFFB00020),
|
||||
onError: Colors.white,
|
||||
tertiary: c.text,
|
||||
onTertiary: c.bg,
|
||||
primaryContainer: c.surface,
|
||||
onPrimaryContainer: c.text,
|
||||
secondaryContainer: c.surface,
|
||||
onSecondaryContainer: c.text,
|
||||
surfaceContainerHighest: c.surface,
|
||||
surfaceContainerLow: c.bg,
|
||||
surfaceDim: c.bg,
|
||||
surfaceBright: c.surface,
|
||||
outline: c.outline,
|
||||
shadow: Colors.transparent,
|
||||
scrim: Colors.black,
|
||||
inverseSurface: c.text,
|
||||
onInverseSurface: c.bg,
|
||||
inversePrimary: c.bg,
|
||||
),
|
||||
// remove "Material feel"
|
||||
splashFactory: NoSplash.splashFactory,
|
||||
highlightColor: Colors.transparent,
|
||||
dividerColor: c.outline,
|
||||
scaffoldBackgroundColor: c.bg,
|
||||
appBarTheme: AppBarTheme(
|
||||
backgroundColor: c.bg,
|
||||
elevation: 0,
|
||||
scrolledUnderElevation: 0,
|
||||
centerTitle: false,
|
||||
foregroundColor: c.text,
|
||||
titleTextStyle: TextStyle(
|
||||
color: c.text,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: -0.2,
|
||||
),
|
||||
),
|
||||
textTheme: Typography.englishLike2021
|
||||
.apply(bodyColor: c.text, displayColor: c.text)
|
||||
.copyWith(
|
||||
displayLarge: const TextStyle(
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: -0.5,
|
||||
),
|
||||
titleMedium: const TextStyle(fontWeight: FontWeight.w600),
|
||||
bodyMedium: TextStyle(color: c.text),
|
||||
bodySmall: TextStyle(color: c.textMuted),
|
||||
),
|
||||
cardTheme: CardThemeData(
|
||||
color: c.surface,
|
||||
elevation: 0,
|
||||
margin: EdgeInsets.zero,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
filled: true,
|
||||
fillColor: c.surface,
|
||||
isDense: true,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: c.outline),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: c.outline),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: c.text.withValues(alpha: 0.5)),
|
||||
),
|
||||
hintStyle: TextStyle(color: c.textMuted),
|
||||
),
|
||||
elevatedButtonTheme: ElevatedButtonThemeData(
|
||||
style: ButtonStyle(
|
||||
padding: const WidgetStatePropertyAll(
|
||||
EdgeInsets.symmetric(horizontal: 18, vertical: 14),
|
||||
),
|
||||
elevation: const WidgetStatePropertyAll(0),
|
||||
backgroundColor: WidgetStatePropertyAll(c.text),
|
||||
foregroundColor: WidgetStatePropertyAll(dark ? c.bg : Colors.white),
|
||||
shape: WidgetStatePropertyAll(
|
||||
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
),
|
||||
),
|
||||
dividerTheme: DividerThemeData(space: 0, thickness: 1, color: c.outline),
|
||||
listTileTheme: ListTileThemeData(
|
||||
dense: true,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
|
||||
iconColor: c.text,
|
||||
textColor: c.text,
|
||||
),
|
||||
// minimal bottom bar
|
||||
navigationBarTheme: NavigationBarThemeData(
|
||||
backgroundColor: c.bg,
|
||||
elevation: 0,
|
||||
indicatorColor: Colors.transparent,
|
||||
labelTextStyle: WidgetStatePropertyAll(
|
||||
TextStyle(color: c.textMuted, fontSize: 11),
|
||||
),
|
||||
iconTheme: WidgetStateProperty.resolveWith((states) {
|
||||
final active = states.contains(WidgetState.selected);
|
||||
return IconThemeData(opacity: active ? 1 : .6, size: 22, color: c.text);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return base.copyWith(
|
||||
extensions: [
|
||||
MonoTokens(
|
||||
radiusSm: 8,
|
||||
radiusMd: 12,
|
||||
space: 12,
|
||||
fast: const Duration(milliseconds: 120),
|
||||
normal: const Duration(milliseconds: 200),
|
||||
bg: c.bg,
|
||||
surface: c.surface,
|
||||
outline: c.outline,
|
||||
text: c.text,
|
||||
textMuted: c.textMuted,
|
||||
splashFactory: NoSplash.splashFactory,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import 'dart:ui';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@immutable
|
||||
class MonoTokens extends ThemeExtension<MonoTokens> {
|
||||
final double radiusSm;
|
||||
final double radiusMd;
|
||||
final double space;
|
||||
final Duration fast;
|
||||
final Duration normal;
|
||||
final Color bg;
|
||||
final Color surface;
|
||||
final Color outline;
|
||||
final Color text;
|
||||
final Color textMuted;
|
||||
final InteractiveInkFeatureFactory? splashFactory;
|
||||
|
||||
const MonoTokens({
|
||||
required this.radiusSm,
|
||||
required this.radiusMd,
|
||||
required this.space,
|
||||
required this.fast,
|
||||
required this.normal,
|
||||
required this.bg,
|
||||
required this.surface,
|
||||
required this.outline,
|
||||
required this.text,
|
||||
required this.textMuted,
|
||||
required this.splashFactory,
|
||||
});
|
||||
|
||||
@override
|
||||
MonoTokens copyWith({
|
||||
double? radiusSm,
|
||||
double? radiusMd,
|
||||
double? space,
|
||||
Duration? fast,
|
||||
Duration? normal,
|
||||
Color? bg,
|
||||
Color? surface,
|
||||
Color? outline,
|
||||
Color? text,
|
||||
Color? textMuted,
|
||||
InteractiveInkFeatureFactory? splashFactory,
|
||||
}) => MonoTokens(
|
||||
radiusSm: radiusSm ?? this.radiusSm,
|
||||
radiusMd: radiusMd ?? this.radiusMd,
|
||||
space: space ?? this.space,
|
||||
fast: fast ?? this.fast,
|
||||
normal: normal ?? this.normal,
|
||||
bg: bg ?? this.bg,
|
||||
surface: surface ?? this.surface,
|
||||
outline: outline ?? this.outline,
|
||||
text: text ?? this.text,
|
||||
textMuted: textMuted ?? this.textMuted,
|
||||
splashFactory: splashFactory ?? this.splashFactory,
|
||||
);
|
||||
|
||||
@override
|
||||
ThemeExtension<MonoTokens> lerp(covariant MonoTokens? other, double t) {
|
||||
if (other == null) return this;
|
||||
Color lerpC(Color a, Color b) => Color.lerp(a, b, t)!;
|
||||
return MonoTokens(
|
||||
radiusSm: lerpDouble(radiusSm, other.radiusSm, t)!,
|
||||
radiusMd: lerpDouble(radiusMd, other.radiusMd, t)!,
|
||||
space: lerpDouble(space, other.space, t)!,
|
||||
fast: Duration(
|
||||
milliseconds: lerpDouble(
|
||||
fast.inMilliseconds.toDouble(),
|
||||
other.fast.inMilliseconds.toDouble(),
|
||||
t,
|
||||
)!.round(),
|
||||
),
|
||||
normal: Duration(
|
||||
milliseconds: lerpDouble(
|
||||
normal.inMilliseconds.toDouble(),
|
||||
other.normal.inMilliseconds.toDouble(),
|
||||
t,
|
||||
)!.round(),
|
||||
),
|
||||
bg: lerpC(bg, other.bg),
|
||||
surface: lerpC(surface, other.surface),
|
||||
outline: lerpC(outline, other.outline),
|
||||
text: lerpC(text, other.text),
|
||||
textMuted: lerpC(textMuted, other.textMuted),
|
||||
splashFactory: other.splashFactory,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'mono_tokens.dart';
|
||||
|
||||
/// Helper function to access MonoTokens from context
|
||||
MonoTokens tokens(BuildContext context) =>
|
||||
Theme.of(context).extension<MonoTokens>()!;
|
||||
@@ -24,10 +24,7 @@ class DesktopAppBarHelper {
|
||||
|
||||
// macOS: Add padding to keep actions away from edge
|
||||
if (actions != null) {
|
||||
return [
|
||||
...actions,
|
||||
SizedBox(width: DesktopWindowPadding.macOSRight),
|
||||
];
|
||||
return [...actions, SizedBox(width: DesktopWindowPadding.macOSRight)];
|
||||
} else {
|
||||
return [SizedBox(width: DesktopWindowPadding.macOSRight)];
|
||||
}
|
||||
@@ -60,7 +57,8 @@ class DesktopAppBarHelper {
|
||||
if (includeGestureDetector) {
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onPanDown: (_) {}, // Consume pan gestures to prevent window dragging
|
||||
onPanDown:
|
||||
(_) {}, // Consume pan gestures to prevent window dragging
|
||||
child: paddedWidget,
|
||||
);
|
||||
}
|
||||
@@ -135,7 +133,8 @@ class DesktopTitleBarPadding extends StatelessWidget {
|
||||
builder: (context, _) {
|
||||
final isFullscreen = FullscreenStateManager().isFullscreen;
|
||||
// In fullscreen, use minimal padding since traffic lights auto-hide
|
||||
final left = leftPadding ??
|
||||
final left =
|
||||
leftPadding ??
|
||||
(isFullscreen
|
||||
? DesktopWindowPadding.macOSLeftFullscreen
|
||||
: DesktopWindowPadding.macOSLeft);
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Utility class for platform detection
|
||||
class PlatformDetector {
|
||||
/// Detects if running on a mobile platform (iOS or Android)
|
||||
/// Uses Theme for consistent platform detection across the app
|
||||
static bool isMobile(BuildContext context) {
|
||||
final platform = Theme.of(context).platform;
|
||||
return platform == TargetPlatform.iOS || platform == TargetPlatform.android;
|
||||
}
|
||||
|
||||
/// Detects if running on a desktop platform (Windows, macOS, or Linux)
|
||||
static bool isDesktop(BuildContext context) {
|
||||
return !isMobile(context);
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,12 @@ class DesktopAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final appBar = AppBar(
|
||||
title: title != null ? DesktopTitleBarPadding(child: title!) : null,
|
||||
title: title != null
|
||||
? DesktopTitleBarPadding(
|
||||
leftPadding: leading != null ? 0 : null,
|
||||
child: title!,
|
||||
)
|
||||
: null,
|
||||
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
|
||||
leading: DesktopAppBarHelper.buildAdjustedLeading(leading),
|
||||
automaticallyImplyLeading: automaticallyImplyLeading,
|
||||
@@ -87,7 +92,12 @@ class DesktopSliverAppBar extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SliverAppBar(
|
||||
title: title != null ? DesktopTitleBarPadding(child: title!) : null,
|
||||
title: title != null
|
||||
? DesktopTitleBarPadding(
|
||||
leftPadding: leading != null ? 0 : null,
|
||||
child: title!,
|
||||
)
|
||||
: null,
|
||||
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
|
||||
leading: DesktopAppBarHelper.buildAdjustedLeading(
|
||||
leading,
|
||||
@@ -103,7 +113,9 @@ class DesktopSliverAppBar extends StatelessWidget {
|
||||
floating: floating,
|
||||
pinned: pinned,
|
||||
expandedHeight: expandedHeight,
|
||||
flexibleSpace: DesktopAppBarHelper.buildAdjustedFlexibleSpace(flexibleSpace),
|
||||
flexibleSpace: DesktopAppBarHelper.buildAdjustedFlexibleSpace(
|
||||
flexibleSpace,
|
||||
),
|
||||
bottom: bottom,
|
||||
);
|
||||
}
|
||||
|
||||
+88
-132
@@ -6,6 +6,7 @@ import '../models/plex_user_profile.dart';
|
||||
import '../screens/media_detail_screen.dart';
|
||||
import '../screens/season_detail_screen.dart';
|
||||
import '../screens/video_player_screen.dart';
|
||||
import '../theme/theme_helper.dart';
|
||||
import 'media_context_menu.dart';
|
||||
|
||||
class MediaCard extends StatefulWidget {
|
||||
@@ -13,7 +14,7 @@ class MediaCard extends StatefulWidget {
|
||||
final PlexMetadata item;
|
||||
final double? width;
|
||||
final double? height;
|
||||
final VoidCallback? onRefresh;
|
||||
final void Function(String ratingKey)? onRefresh;
|
||||
final PlexUserProfile? userProfile;
|
||||
|
||||
const MediaCard({
|
||||
@@ -30,7 +31,11 @@ class MediaCard extends StatefulWidget {
|
||||
State<MediaCard> createState() => _MediaCardState();
|
||||
}
|
||||
|
||||
class _MediaCardState extends State<MediaCard> {
|
||||
class _MediaCardState extends State<MediaCard>
|
||||
with AutomaticKeepAliveClientMixin {
|
||||
@override
|
||||
bool get wantKeepAlive => true;
|
||||
|
||||
void _handleTap(BuildContext context) async {
|
||||
final itemType = widget.item.type.toLowerCase();
|
||||
|
||||
@@ -48,7 +53,7 @@ class _MediaCardState extends State<MediaCard> {
|
||||
);
|
||||
// Refresh parent screen if result indicates it's needed
|
||||
if (result == true) {
|
||||
widget.onRefresh?.call();
|
||||
widget.onRefresh?.call(widget.item.ratingKey);
|
||||
}
|
||||
} else if (itemType == 'season') {
|
||||
// For seasons, show season detail screen
|
||||
@@ -63,7 +68,7 @@ class _MediaCardState extends State<MediaCard> {
|
||||
),
|
||||
);
|
||||
// Season screen doesn't return a refresh flag, but we can refresh anyway
|
||||
widget.onRefresh?.call();
|
||||
widget.onRefresh?.call(widget.item.ratingKey);
|
||||
} else {
|
||||
// For all other types (shows, movies), show detail screen
|
||||
final result = await Navigator.push<bool>(
|
||||
@@ -78,13 +83,14 @@ class _MediaCardState extends State<MediaCard> {
|
||||
);
|
||||
// Refresh parent screen if result indicates it's needed
|
||||
if (result == true) {
|
||||
widget.onRefresh?.call();
|
||||
widget.onRefresh?.call(widget.item.ratingKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
super.build(context); // Required for AutomaticKeepAliveClientMixin
|
||||
return SizedBox(
|
||||
width: widget.width,
|
||||
child: MediaContextMenu(
|
||||
@@ -104,132 +110,10 @@ class _MediaCardState extends State<MediaCard> {
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: widget.height,
|
||||
child: Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
height: widget.height,
|
||||
child: _buildPosterImage(context),
|
||||
),
|
||||
),
|
||||
if (widget.item.isWatched)
|
||||
Positioned(
|
||||
top: 4,
|
||||
right: 4,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.3),
|
||||
blurRadius: 4,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.check,
|
||||
color: Colors.white,
|
||||
size: 16,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Progress bar for partially watched episodes
|
||||
if (widget.item.viewOffset != null &&
|
||||
widget.item.duration != null &&
|
||||
widget.item.viewOffset! > 0 &&
|
||||
!widget.item.isWatched)
|
||||
Positioned(
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: ClipRRect(
|
||||
borderRadius: const BorderRadius.only(
|
||||
bottomLeft: Radius.circular(8),
|
||||
bottomRight: Radius.circular(8),
|
||||
),
|
||||
child: LinearProgressIndicator(
|
||||
value:
|
||||
widget.item.viewOffset! /
|
||||
widget.item.duration!,
|
||||
backgroundColor: Colors.black.withValues(
|
||||
alpha: 0.5,
|
||||
),
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(
|
||||
Colors.red,
|
||||
),
|
||||
minHeight: 4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: _buildPosterWithOverlay(context),
|
||||
)
|
||||
else
|
||||
Expanded(
|
||||
child: Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: _buildPosterImage(context),
|
||||
),
|
||||
if (widget.item.isWatched)
|
||||
Positioned(
|
||||
top: 4,
|
||||
right: 4,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.green,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.3),
|
||||
blurRadius: 4,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.check,
|
||||
color: Colors.white,
|
||||
size: 16,
|
||||
),
|
||||
),
|
||||
),
|
||||
// Progress bar for partially watched episodes
|
||||
if (widget.item.viewOffset != null &&
|
||||
widget.item.duration != null &&
|
||||
widget.item.viewOffset! > 0 &&
|
||||
!widget.item.isWatched)
|
||||
Positioned(
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: ClipRRect(
|
||||
borderRadius: const BorderRadius.only(
|
||||
bottomLeft: Radius.circular(8),
|
||||
bottomRight: Radius.circular(8),
|
||||
),
|
||||
child: LinearProgressIndicator(
|
||||
value:
|
||||
widget.item.viewOffset! /
|
||||
widget.item.duration!,
|
||||
backgroundColor: Colors.black.withValues(
|
||||
alpha: 0.5,
|
||||
),
|
||||
valueColor: const AlwaysStoppedAnimation<Color>(
|
||||
Colors.red,
|
||||
),
|
||||
minHeight: 4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(child: _buildPosterWithOverlay(context)),
|
||||
const SizedBox(height: 4),
|
||||
// Text content
|
||||
Column(
|
||||
@@ -252,7 +136,7 @@ class _MediaCardState extends State<MediaCard> {
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.grey,
|
||||
color: tokens(context).textMuted,
|
||||
fontSize: 11,
|
||||
height: 1.1,
|
||||
),
|
||||
@@ -263,7 +147,7 @@ class _MediaCardState extends State<MediaCard> {
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.grey,
|
||||
color: tokens(context).textMuted,
|
||||
fontSize: 11,
|
||||
height: 1.1,
|
||||
),
|
||||
@@ -272,7 +156,7 @@ class _MediaCardState extends State<MediaCard> {
|
||||
Text(
|
||||
'${widget.item.year}',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.grey,
|
||||
color: tokens(context).textMuted,
|
||||
fontSize: 11,
|
||||
height: 1.1,
|
||||
),
|
||||
@@ -287,6 +171,18 @@ class _MediaCardState extends State<MediaCard> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPosterWithOverlay(BuildContext context) {
|
||||
return Stack(
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: _buildPosterImage(context),
|
||||
),
|
||||
_PosterOverlay(item: widget.item),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPosterImage(BuildContext context) {
|
||||
if (widget.item.posterThumb != null) {
|
||||
return CachedNetworkImage(
|
||||
@@ -295,6 +191,7 @@ class _MediaCardState extends State<MediaCard> {
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
filterQuality: FilterQuality.medium,
|
||||
fadeInDuration: const Duration(milliseconds: 300),
|
||||
placeholder: (context, url) => Container(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
@@ -311,3 +208,62 @@ class _MediaCardState extends State<MediaCard> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Overlay widget for poster showing watched indicator and progress bar
|
||||
class _PosterOverlay extends StatelessWidget {
|
||||
final PlexMetadata item;
|
||||
|
||||
const _PosterOverlay({required this.item});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Stack(
|
||||
children: [
|
||||
// Watched indicator (checkmark)
|
||||
if (item.isWatched)
|
||||
Positioned(
|
||||
top: 4,
|
||||
right: 4,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(4),
|
||||
decoration: BoxDecoration(
|
||||
color: tokens(context).text,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.3),
|
||||
blurRadius: 4,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(Icons.check, color: tokens(context).bg, size: 16),
|
||||
),
|
||||
),
|
||||
// Progress bar for partially watched content
|
||||
if (item.viewOffset != null &&
|
||||
item.duration != null &&
|
||||
item.viewOffset! > 0 &&
|
||||
!item.isWatched)
|
||||
Positioned(
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: ClipRRect(
|
||||
borderRadius: const BorderRadius.only(
|
||||
bottomLeft: Radius.circular(8),
|
||||
bottomRight: Radius.circular(8),
|
||||
),
|
||||
child: LinearProgressIndicator(
|
||||
value: item.viewOffset! / item.duration!,
|
||||
backgroundColor: tokens(context).outline,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
minHeight: 4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+120
-118
@@ -11,11 +11,7 @@ class _MenuAction {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
|
||||
_MenuAction({
|
||||
required this.value,
|
||||
required this.icon,
|
||||
required this.label,
|
||||
});
|
||||
_MenuAction({required this.value, required this.icon, required this.label});
|
||||
}
|
||||
|
||||
/// A reusable wrapper widget that adds a context menu (long press / right click)
|
||||
@@ -23,7 +19,7 @@ class _MenuAction {
|
||||
class MediaContextMenu extends StatefulWidget {
|
||||
final PlexClient client;
|
||||
final PlexMetadata metadata;
|
||||
final VoidCallback? onRefresh;
|
||||
final void Function(String ratingKey)? onRefresh;
|
||||
final VoidCallback? onTap;
|
||||
final Widget child;
|
||||
|
||||
@@ -87,11 +83,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
if ((itemType == 'episode' || itemType == 'season') &&
|
||||
widget.metadata.grandparentTitle != null) {
|
||||
menuActions.add(
|
||||
_MenuAction(
|
||||
value: 'series',
|
||||
icon: Icons.tv,
|
||||
label: 'Go to series',
|
||||
),
|
||||
_MenuAction(value: 'series', icon: Icons.tv, label: 'Go to series'),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -125,27 +117,33 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
...menuActions.map((action) => ListTile(
|
||||
leading: Icon(action.icon),
|
||||
title: Text(action.label),
|
||||
onTap: () => Navigator.pop(context, action.value),
|
||||
)),
|
||||
...menuActions.map(
|
||||
(action) => ListTile(
|
||||
leading: Icon(action.icon),
|
||||
title: Text(action.label),
|
||||
onTap: () => Navigator.pop(context, action.value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Show popup menu on larger screens
|
||||
final menuItems = menuActions.map((action) => PopupMenuItem(
|
||||
value: action.value,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(action.icon),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(action.label)),
|
||||
],
|
||||
),
|
||||
)).toList();
|
||||
final menuItems = menuActions
|
||||
.map(
|
||||
(action) => PopupMenuItem(
|
||||
value: action.value,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(action.icon),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(action.label)),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
|
||||
// Use stored tap position or fallback to widget position
|
||||
final RenderBox? overlay =
|
||||
@@ -159,15 +157,28 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
position = renderBox.localToGlobal(Offset.zero, ancestor: overlay);
|
||||
}
|
||||
|
||||
// Calculate position for menu using RelativeRect
|
||||
final overlayRect = RelativeRect.fromLTRB(
|
||||
position.dx,
|
||||
position.dy,
|
||||
position.dx + 1,
|
||||
position.dy + 1,
|
||||
);
|
||||
|
||||
// Use showMenu with fast animations via PopupMenuTheme
|
||||
selected = await showMenu<String>(
|
||||
context: context,
|
||||
position: RelativeRect.fromLTRB(
|
||||
position.dx,
|
||||
position.dy,
|
||||
position.dx,
|
||||
position.dy,
|
||||
),
|
||||
position: overlayRect,
|
||||
items: menuItems,
|
||||
elevation: 8,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
menuPadding: EdgeInsets.zero,
|
||||
// Override animation duration for faster animations
|
||||
popUpAnimationStyle: AnimationStyle(
|
||||
duration: const Duration(milliseconds: 150),
|
||||
curve: Curves.easeOutCubic,
|
||||
reverseCurve: Curves.easeIn,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -175,102 +186,93 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
|
||||
switch (selected) {
|
||||
case 'watch':
|
||||
try {
|
||||
await widget.client.markAsWatched(widget.metadata.ratingKey);
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('Marked as watched')));
|
||||
// Refresh parent screen to update UI
|
||||
widget.onRefresh?.call();
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Error: $e')));
|
||||
}
|
||||
}
|
||||
await _executeAction(
|
||||
context,
|
||||
() => widget.client.markAsWatched(widget.metadata.ratingKey),
|
||||
'Marked as watched',
|
||||
);
|
||||
break;
|
||||
|
||||
case 'unwatch':
|
||||
try {
|
||||
await widget.client.markAsUnwatched(widget.metadata.ratingKey);
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Marked as unwatched')),
|
||||
);
|
||||
// Refresh parent screen to update UI
|
||||
widget.onRefresh?.call();
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Error: $e')));
|
||||
}
|
||||
}
|
||||
await _executeAction(
|
||||
context,
|
||||
() => widget.client.markAsUnwatched(widget.metadata.ratingKey),
|
||||
'Marked as unwatched',
|
||||
);
|
||||
break;
|
||||
|
||||
case 'series':
|
||||
// Navigate to series detail screen
|
||||
if (widget.metadata.grandparentRatingKey != null) {
|
||||
try {
|
||||
final seriesMetadata = await widget.client.getMetadata(
|
||||
widget.metadata.grandparentRatingKey!,
|
||||
);
|
||||
if (seriesMetadata != null && context.mounted) {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MediaDetailScreen(
|
||||
client: widget.client,
|
||||
metadata: seriesMetadata,
|
||||
),
|
||||
),
|
||||
);
|
||||
// Refresh parent screen after returning
|
||||
widget.onRefresh?.call();
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Error loading series: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
await _navigateToRelated(
|
||||
context,
|
||||
widget.metadata.grandparentRatingKey,
|
||||
(metadata) =>
|
||||
MediaDetailScreen(client: widget.client, metadata: metadata),
|
||||
'Error loading series',
|
||||
);
|
||||
break;
|
||||
|
||||
case 'season':
|
||||
// Navigate to season detail screen
|
||||
if (widget.metadata.parentRatingKey != null) {
|
||||
try {
|
||||
final seasonMetadata = await widget.client.getMetadata(
|
||||
widget.metadata.parentRatingKey!,
|
||||
);
|
||||
if (seasonMetadata != null && context.mounted) {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => SeasonDetailScreen(
|
||||
client: widget.client,
|
||||
season: seasonMetadata,
|
||||
),
|
||||
),
|
||||
);
|
||||
// Refresh parent screen after returning
|
||||
widget.onRefresh?.call();
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Error loading season: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
await _navigateToRelated(
|
||||
context,
|
||||
widget.metadata.parentRatingKey,
|
||||
(metadata) =>
|
||||
SeasonDetailScreen(client: widget.client, season: metadata),
|
||||
'Error loading season',
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute an action with error handling and refresh
|
||||
Future<void> _executeAction(
|
||||
BuildContext context,
|
||||
Future<void> Function() action,
|
||||
String successMessage,
|
||||
) async {
|
||||
try {
|
||||
await action();
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(successMessage)));
|
||||
widget.onRefresh?.call(widget.metadata.ratingKey);
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Error: $e')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigate to a related item (series or season)
|
||||
Future<void> _navigateToRelated(
|
||||
BuildContext context,
|
||||
String? ratingKey,
|
||||
Widget Function(PlexMetadata) screenBuilder,
|
||||
String errorPrefix,
|
||||
) async {
|
||||
if (ratingKey == null) return;
|
||||
|
||||
try {
|
||||
final metadata = await widget.client.getMetadata(ratingKey);
|
||||
if (metadata != null && context.mounted) {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (context) => screenBuilder(metadata)),
|
||||
);
|
||||
widget.onRefresh?.call(widget.metadata.ratingKey);
|
||||
}
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('$errorPrefix: $e')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
|
||||
@@ -10,6 +10,7 @@ import '../models/plex_metadata.dart';
|
||||
import '../models/plex_media_info.dart';
|
||||
import '../services/fullscreen_state_manager.dart';
|
||||
import '../utils/desktop_window_padding.dart';
|
||||
import '../utils/platform_detector.dart';
|
||||
import 'app_bar_back_button.dart';
|
||||
|
||||
/// Custom video controls builder for Plex with chapter, audio, and subtitle support
|
||||
@@ -175,9 +176,54 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
}
|
||||
}
|
||||
|
||||
bool _isMobile(BuildContext context) {
|
||||
final platform = Theme.of(context).platform;
|
||||
return platform == TargetPlatform.iOS || platform == TargetPlatform.android;
|
||||
bool _hasMultipleAudioTracks(Tracks? tracks) {
|
||||
if (tracks == null) return false;
|
||||
final audioTracks = tracks.audio
|
||||
.where((track) => track.id != 'auto' && track.id != 'no')
|
||||
.toList();
|
||||
return audioTracks.length > 1;
|
||||
}
|
||||
|
||||
bool _hasSubtitles(Tracks? tracks) {
|
||||
if (tracks == null) return false;
|
||||
final subtitles = tracks.subtitle
|
||||
.where((track) => track.id != 'auto' && track.id != 'no')
|
||||
.toList();
|
||||
return subtitles.isNotEmpty;
|
||||
}
|
||||
|
||||
Widget _buildTrackAndChapterControls() {
|
||||
return StreamBuilder<Tracks>(
|
||||
stream: widget.player.stream.tracks,
|
||||
initialData: widget.player.state.tracks,
|
||||
builder: (context, snapshot) {
|
||||
final tracks = snapshot.data;
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.speed, color: Colors.white),
|
||||
onPressed: _showPlaybackSpeedBottomSheet,
|
||||
),
|
||||
if (_hasMultipleAudioTracks(tracks))
|
||||
IconButton(
|
||||
icon: const Icon(Icons.audiotrack, color: Colors.white),
|
||||
onPressed: _showAudioBottomSheet,
|
||||
),
|
||||
if (_hasSubtitles(tracks))
|
||||
IconButton(
|
||||
icon: const Icon(Icons.subtitles, color: Colors.white),
|
||||
onPressed: _showSubtitleBottomSheet,
|
||||
),
|
||||
if (_chapters.isNotEmpty)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.video_library, color: Colors.white),
|
||||
onPressed: _showChapterBottomSheet,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _seekToPreviousChapter() {
|
||||
@@ -225,7 +271,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
}
|
||||
|
||||
Future<void> _toggleFullscreen() async {
|
||||
if (!_isMobile(context)) {
|
||||
if (!PlatformDetector.isMobile(context)) {
|
||||
// Query actual window state to determine what action to take
|
||||
// This ensures we always toggle correctly regardless of local state
|
||||
final isCurrentlyFullscreen = await windowManager.isFullScreen();
|
||||
@@ -261,9 +307,40 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
}
|
||||
}
|
||||
|
||||
void _adjustVolume(double delta) {
|
||||
final currentVolume = widget.player.state.volume;
|
||||
final newVolume = (currentVolume + delta).clamp(0.0, 100.0);
|
||||
widget.player.setVolume(newVolume);
|
||||
}
|
||||
|
||||
void _toggleMute() {
|
||||
final currentVolume = widget.player.state.volume;
|
||||
if (currentVolume == 0) {
|
||||
// Unmute to 100%
|
||||
widget.player.setVolume(100.0);
|
||||
} else {
|
||||
// Mute
|
||||
widget.player.setVolume(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
void _seek(Duration offset) {
|
||||
final currentPosition = widget.player.state.position;
|
||||
final newPosition = currentPosition + offset;
|
||||
// Clamp to valid range
|
||||
final duration = widget.player.state.duration;
|
||||
if (newPosition < Duration.zero) {
|
||||
widget.player.seek(Duration.zero);
|
||||
} else if (newPosition > duration) {
|
||||
widget.player.seek(duration);
|
||||
} else {
|
||||
widget.player.seek(newPosition);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isMobile = _isMobile(context);
|
||||
final isMobile = PlatformDetector.isMobile(context);
|
||||
|
||||
return Focus(
|
||||
focusNode: _focusNode,
|
||||
@@ -271,16 +348,113 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
onKeyEvent: (node, event) {
|
||||
// Only respond to key down events (not key up)
|
||||
if (event is KeyDownEvent) {
|
||||
// Handle spacebar for play/pause
|
||||
if (event.logicalKey == LogicalKeyboardKey.space) {
|
||||
final isShiftPressed = HardwareKeyboard.instance.isShiftPressed;
|
||||
final isCtrlPressed = HardwareKeyboard.instance.isControlPressed;
|
||||
|
||||
// Play/Pause shortcuts
|
||||
if (event.logicalKey == LogicalKeyboardKey.space ||
|
||||
event.logicalKey == LogicalKeyboardKey.keyK) {
|
||||
_togglePlayPause();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// Arrow key handling - check for modifiers first
|
||||
if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
|
||||
if (isCtrlPressed) {
|
||||
// Ctrl+Left: Seek backward 1 minute
|
||||
_seek(const Duration(minutes: -1));
|
||||
} else if (isShiftPressed) {
|
||||
// Shift+Left: Seek backward 5 seconds
|
||||
_seek(const Duration(seconds: -5));
|
||||
} else {
|
||||
// Left: Seek backward 10 seconds
|
||||
_seek(const Duration(seconds: -10));
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
|
||||
if (isCtrlPressed) {
|
||||
// Ctrl+Right: Seek forward 1 minute
|
||||
_seek(const Duration(minutes: 1));
|
||||
} else if (isShiftPressed) {
|
||||
// Shift+Right: Seek forward 5 seconds
|
||||
_seek(const Duration(seconds: 5));
|
||||
} else {
|
||||
// Right: Seek forward 10 seconds
|
||||
_seek(const Duration(seconds: 10));
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
|
||||
// Up: Volume up 5%
|
||||
_adjustVolume(5.0);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
|
||||
// Down: Volume down 5%
|
||||
_adjustVolume(-5.0);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// J/L keys for seeking (alternative to arrows)
|
||||
if (event.logicalKey == LogicalKeyboardKey.keyJ) {
|
||||
// J: Seek backward 10 seconds
|
||||
_seek(const Duration(seconds: -10));
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (event.logicalKey == LogicalKeyboardKey.keyL) {
|
||||
// L: Seek forward 10 seconds
|
||||
_seek(const Duration(seconds: 10));
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// Fullscreen shortcuts
|
||||
if (event.logicalKey == LogicalKeyboardKey.keyF) {
|
||||
_toggleFullscreen();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
if (event.logicalKey == LogicalKeyboardKey.escape) {
|
||||
// Escape: Exit fullscreen (only if currently fullscreen)
|
||||
if (_isFullscreen) {
|
||||
_toggleFullscreen();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
|
||||
// Mute shortcut
|
||||
if (event.logicalKey == LogicalKeyboardKey.keyM) {
|
||||
_toggleMute();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
// Episode navigation shortcuts
|
||||
if (event.logicalKey == LogicalKeyboardKey.keyN) {
|
||||
// N: Next episode
|
||||
if (widget.onNext != null) {
|
||||
widget.onNext!();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
|
||||
if (event.logicalKey == LogicalKeyboardKey.keyP) {
|
||||
// P: Previous episode
|
||||
if (widget.onPrevious != null) {
|
||||
widget.onPrevious!();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
},
|
||||
child: MouseRegion(
|
||||
cursor: _showControls ? SystemMouseCursors.basic : SystemMouseCursors.none,
|
||||
cursor: _showControls
|
||||
? SystemMouseCursors.basic
|
||||
: SystemMouseCursors.none,
|
||||
onHover: (_) {
|
||||
// Show controls when mouse moves
|
||||
if (!_showControls) {
|
||||
@@ -295,50 +469,81 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
}
|
||||
},
|
||||
child: Stack(
|
||||
children: [
|
||||
// Invisible tap detector that always covers the full area
|
||||
Positioned.fill(
|
||||
child: GestureDetector(
|
||||
onTap: _toggleControls,
|
||||
onDoubleTap: _toggleFullscreen,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
child: Container(color: Colors.transparent),
|
||||
children: [
|
||||
// Invisible tap detector that always covers the full area
|
||||
Positioned.fill(
|
||||
child: GestureDetector(
|
||||
onTap: _toggleControls,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
child: Container(color: Colors.transparent),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Custom controls overlay - use AnimatedOpacity to keep widget tree alive
|
||||
Positioned.fill(
|
||||
child: IgnorePointer(
|
||||
ignoring: !_showControls,
|
||||
child: AnimatedOpacity(
|
||||
opacity: _showControls ? 1.0 : 0.0,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
child: GestureDetector(
|
||||
onTap: _toggleControls,
|
||||
onDoubleTap: _toggleFullscreen,
|
||||
behavior: HitTestBehavior.deferToChild,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [
|
||||
Colors.black.withValues(alpha: 0.7),
|
||||
Colors.transparent,
|
||||
Colors.transparent,
|
||||
Colors.black.withValues(alpha: 0.7),
|
||||
],
|
||||
stops: const [0.0, 0.2, 0.8, 1.0],
|
||||
// Custom controls overlay - use AnimatedOpacity to keep widget tree alive
|
||||
Positioned.fill(
|
||||
child: IgnorePointer(
|
||||
ignoring: !_showControls,
|
||||
child: AnimatedOpacity(
|
||||
opacity: _showControls ? 1.0 : 0.0,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
child: GestureDetector(
|
||||
onTap: _toggleControls,
|
||||
behavior: HitTestBehavior.deferToChild,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [
|
||||
Colors.black.withValues(alpha: 0.7),
|
||||
Colors.transparent,
|
||||
Colors.transparent,
|
||||
Colors.black.withValues(alpha: 0.7),
|
||||
],
|
||||
stops: const [0.0, 0.2, 0.8, 1.0],
|
||||
),
|
||||
),
|
||||
child: isMobile
|
||||
? _buildMobileLayout()
|
||||
: _buildDesktopLayout(),
|
||||
),
|
||||
child: isMobile
|
||||
? _buildMobileLayout()
|
||||
: _buildDesktopLayout(),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
// Middle area double-tap detector for fullscreen (desktop only)
|
||||
// Only covers the clear video area (20% to 80% vertically)
|
||||
if (!isMobile)
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final height = constraints.maxHeight;
|
||||
final topExclude = height * 0.20; // Top 20%
|
||||
final bottomExclude = height * 0.20; // Bottom 20%
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
Positioned(
|
||||
top: topExclude,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: bottomExclude,
|
||||
child: GestureDetector(
|
||||
onTap: _toggleControls,
|
||||
onDoubleTap: _toggleFullscreen,
|
||||
behavior: HitTestBehavior.translucent,
|
||||
child: Container(color: Colors.transparent),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -408,18 +613,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
),
|
||||
),
|
||||
// Track and chapter controls in top right
|
||||
IconButton(
|
||||
icon: const Icon(Icons.audiotrack, color: Colors.white),
|
||||
onPressed: _showAudioBottomSheet,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.subtitles, color: Colors.white),
|
||||
onPressed: _showSubtitleBottomSheet,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.video_library, color: Colors.white),
|
||||
onPressed: _showChapterBottomSheet,
|
||||
),
|
||||
_buildTrackAndChapterControls(),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -784,21 +978,8 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
// Volume control
|
||||
_buildVolumeControl(),
|
||||
const SizedBox(width: 16),
|
||||
// Audio track
|
||||
IconButton(
|
||||
icon: const Icon(Icons.audiotrack, color: Colors.white),
|
||||
onPressed: _showAudioBottomSheet,
|
||||
),
|
||||
// Subtitle track
|
||||
IconButton(
|
||||
icon: const Icon(Icons.subtitles, color: Colors.white),
|
||||
onPressed: _showSubtitleBottomSheet,
|
||||
),
|
||||
// Chapters
|
||||
IconButton(
|
||||
icon: const Icon(Icons.video_library, color: Colors.white),
|
||||
onPressed: _showChapterBottomSheet,
|
||||
),
|
||||
// Audio track, subtitle, and chapter controls
|
||||
_buildTrackAndChapterControls(),
|
||||
// Fullscreen
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
@@ -1399,6 +1580,88 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
);
|
||||
}
|
||||
|
||||
void _showPlaybackSpeedBottomSheet() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
backgroundColor: Colors.grey[900],
|
||||
isScrollControlled: true,
|
||||
constraints: _getBottomSheetConstraints(),
|
||||
builder: (context) => StreamBuilder<double>(
|
||||
stream: widget.player.stream.rate,
|
||||
initialData: widget.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];
|
||||
|
||||
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.speed, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
const Text(
|
||||
'Playback Speed',
|
||||
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: 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: () {
|
||||
widget.player.setRate(speed);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _formatDuration(Duration duration) {
|
||||
final hours = duration.inHours;
|
||||
final minutes = duration.inMinutes.remainder(60);
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
name: plezy
|
||||
description: "A beautiful Plex client for Flutter"
|
||||
publish_to: "none"
|
||||
version: 1.0.1+3
|
||||
version: 1.1.0+5
|
||||
|
||||
environment:
|
||||
sdk: ^3.8.1
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
## iOS
|
||||
|
||||
| Home | Library | Media Card |
|
||||
|------|---------|------------|
|
||||
|  |  |  |
|
||||
|
||||
## macOS
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||

|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.8 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.0 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.7 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.3 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.1 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.4 MiB |
Reference in New Issue
Block a user