Compare commits

..
24 Commits
Author SHA1 Message Date
edde746 bf509ee57c chore: bump version 2025-10-29 10:51:22 +01:00
edde746 823ba0beab fix: context menu overflowing 2025-10-29 10:50:08 +01:00
edde746 b310d1f169 fix: macos app bar padding issue 2025-10-29 10:49:52 +01:00
edde746 bdd39c252e feat: design improvements 2025-10-29 10:33:16 +01:00
edde746 1d29281143 fix: update watch state properly 2025-10-29 02:35:00 +01:00
edde746 12ee134191 refactor: deduplicate 2025-10-28 10:06:29 +01:00
edde746 9248fb4ddb refactor: episode navigation 2025-10-28 08:10:32 +01:00
edde746 b3696035b5 feat: playback speed controls 2025-10-28 07:59:17 +01:00
edde746 b8a5afc08f feat: keyboard video controls 2025-10-28 07:59:17 +01:00
edde746 0796f9c30d feat: screenshots 2025-10-28 07:59:17 +01:00
edde746 cebe90d39b refactor: deduplicate track controls
also fixes double click to fullscreen issues
2025-10-28 07:59:17 +01:00
edde746 abd5900290 perf(auth): better connection choice 2025-10-28 07:59:16 +01:00
edde746 67934c1f1a chore: bump version 2025-10-25 16:32:30 +02:00
edde746 3ad3876474 feat: auto close login browser 2025-10-25 16:31:36 +02:00
edde746 127b3ba2e4 feat(controls): better desktop gestures 2025-10-25 03:17:13 +02:00
edde746 1000032db0 refactor: simplify macos titlebar logic 2025-10-25 03:06:45 +02:00
edde746 dea2bc35ea fix: image quality 2025-10-22 22:27:17 +02:00
edde746 276af6c4e8 fix(actions): incorrect macos file 2025-10-22 20:12:18 +02:00
edde746 f3e91ba789 fix(actions): android build 2025-10-22 20:01:56 +02:00
edde746 7f9cee4222 fix: unify version source 2025-10-22 18:30:25 +02:00
edde746 9fe91f9c1d feat: privacy policy 2025-10-22 16:29:13 +02:00
edde746 6d7de29db1 feat: about screen 2025-10-22 16:28:57 +02:00
edde746 24981977c0 fix: image quality issue 2025-10-22 14:45:20 +02:00
edde746 c0ab7a524e fix(readme): download links 2025-10-22 14:12:57 +02:00
40 changed files with 2991 additions and 1436 deletions
+1 -1
View File
@@ -312,7 +312,7 @@ jobs:
files: |
artifacts/android-apk/plezy-android.apk
artifacts/ios-ipa/plezy-ios.ipa
artifacts/macos-dmg/plezy-macos.dmg
artifacts/macos-zip/plezy-macos.zip
artifacts/windows-portable/plezy-windows-portable.zip
artifacts/windows-installer/plezy-windows-installer.exe
artifacts/linux-app/plezy-linux.tar.gz
+98
View File
@@ -0,0 +1,98 @@
# Privacy Policy for Plezy
**Last Updated: October 22, 2025**
## Introduction
Plezy ("we", "our", or "the app") is a third-party Plex client that allows you to access and stream content from your Plex Media Server. This privacy policy explains how we handle your information when you use our app.
## Information We Collect
### Authentication Information
When you sign in to Plezy using your Plex account, we collect and process:
- Plex authentication tokens
- Plex account username
- Plex server connection information
### Local Network Information
To connect to your Plex Media Server on your local network, we may access:
- Local network device discovery information
- IP addresses of Plex servers on your network
### Usage Information
The app stores locally on your device:
- Your authentication session
- App preferences and settings
- Recently accessed content history
## How We Use Your Information
We use the collected information solely to:
- Authenticate you with your Plex account
- Connect to and communicate with your Plex Media Server
- Display your media library and stream content
- Maintain your session and app preferences
## Data Storage and Security
- **Authentication tokens** are stored securely on your device using platform-specific secure storage mechanisms
- **App preferences** are stored locally on your device
- **No data** is transmitted to our servers - all communication is directly between your device and your Plex Media Server or Plex's authentication services
## Third-Party Services
### Plex
Plezy uses Plex's authentication and media services. When you use this app:
- You authenticate directly with Plex's servers
- Your media streaming occurs between your device and your Plex Media Server
- Plex's own privacy policy applies to their services: https://www.plex.tv/about/privacy-legal/
We do not control and are not responsible for Plex's data practices.
## Data Sharing
We do not:
- Sell your personal information
- Share your information with third parties for marketing purposes
- Transmit your data to our own servers
- Track your viewing habits outside of local app functionality
Your data is only shared with:
- **Plex services** for authentication and media server communication (as required for the app to function)
## Your Rights and Choices
You can:
- **Sign out** at any time to remove your authentication session from the device
- **Uninstall the app** to remove all locally stored data
- **Manage your Plex account** directly through Plex's services
## Children's Privacy
Plezy does not knowingly collect personal information from children under 13. The app relies on Plex account authentication, and users must comply with Plex's terms of service and age requirements.
## Changes to This Privacy Policy
We may update this privacy policy from time to time. We will notify users of any material changes by updating the "Last Updated" date at the top of this policy.
## Data Retention
- Authentication tokens are retained on your device until you sign out or uninstall the app
- Local preferences and settings are retained until you uninstall the app
- No data is retained on our servers as we do not operate any backend services
## International Data Transfers
As we do not operate backend servers, there are no international data transfers from our side. Any data transfers occur directly between your device and Plex's services, subject to Plex's privacy policy.
## Legal Compliance
This app complies with:
- General Data Protection Regulation (GDPR)
- California Consumer Privacy Act (CCPA)
- Children's Online Privacy Protection Act (COPPA)
- Other applicable privacy laws
## Your Consent
By using Plezy, you consent to this privacy policy and the processing of your information as described herein.
+15 -29
View File
@@ -1,23 +1,32 @@
# 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
Coming soon
### Desktop
- [Windows (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-x64.zip)
- [macOS (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg)
- [Linux (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.tar.gz)
- [Windows (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
- [macOS (Universal)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.zip)
- [Linux (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-linux.tar.gz)
> Download the latest release from the [Releases page](https://github.com/edde746/plezy/releases)
## Features
### 🔐 Authentication & Server Management
- OAuth PIN-based authentication
- Sign in with Plex
- Automatic server discovery with smart connection selection
- Persistent sessions with auto-login
@@ -27,27 +36,13 @@ Coming soon
- Advanced search across all media
- Season and episode navigation
### 🎬 Video Playback (MediaKit/mpv)
### 🎬 Video Playback
- Wide codec support including HEVC, AV1, VP9, and more
- Advanced subtitle rendering with full ASS/SSA support
- Audio and subtitle track selection with user profile preferences
- Playback progress sync and resume functionality
- Auto-play next episode
### 🎨 User Experience
- Material Design 3 with dark theme
- Custom controls and context menus
- Desktop window management with custom macOS titlebar
- Fullscreen support with adaptive orientation
## Platform Support
- ✅ macOS
- ✅ Windows
- ✅ Linux
- ✅ Android
- ✅ iOS
## Prerequisites
- Flutter SDK 3.8.1 or higher
@@ -77,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
+24 -3
View File
@@ -1,3 +1,6 @@
import java.util.Properties
import java.io.FileInputStream
plugins {
id("com.android.application")
id("kotlin-android")
@@ -29,11 +32,29 @@ android {
versionName = flutter.versionName
}
signingConfigs {
create("release") {
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
val keystoreProperties = Properties()
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
keyAlias = keystoreProperties["keyAlias"] as String
keyPassword = keystoreProperties["keyPassword"] as String
storeFile = file(keystoreProperties["storeFile"] as String)
storePassword = keystoreProperties["storePassword"] as String
}
}
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug")
// Only use release signing if key.properties exists (not in CI/CD)
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
signingConfig = signingConfigs.getByName("release")
}
// If key.properties doesn't exist, it will use debug signing for CI builds
}
}
}
+7 -8
View File
@@ -1,14 +1,13 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- Internet access permissions -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- Media access permissions (Android 13 or higher) -->
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<!-- Storage access permissions (Android 12 or lower) -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Explicitly remove media permissions that media_kit may add -->
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" tools:node="remove" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" tools:node="remove" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
<application
android:label="Plezy"
+6
View File
@@ -473,11 +473,13 @@
DEVELOPMENT_TEAM = G88U5B5783;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = Plezy;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.entertainment";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0.0;
PRODUCT_BUNDLE_IDENTIFIER = com.edde746.plezy;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
@@ -657,11 +659,13 @@
DEVELOPMENT_TEAM = G88U5B5783;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = Plezy;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.entertainment";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0.0;
PRODUCT_BUNDLE_IDENTIFIER = com.edde746.plezy;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
@@ -681,11 +685,13 @@
DEVELOPMENT_TEAM = G88U5B5783;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = Plezy;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.entertainment";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0.0;
PRODUCT_BUNDLE_IDENTIFIER = com.edde746.plezy;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
+289 -295
View File
@@ -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;
}
}
}
+26 -2
View File
@@ -1,3 +1,5 @@
import 'package:package_info_plus/package_info_plus.dart';
class PlexConfig {
final String baseUrl;
final String? token;
@@ -12,13 +14,35 @@ class PlexConfig {
required this.baseUrl,
this.token,
required this.clientIdentifier,
this.product = 'Plezy',
this.version = '1.0.0',
required this.product,
required this.version,
this.platform = 'Flutter',
this.device,
this.acceptJson = true,
});
static Future<PlexConfig> create({
required String baseUrl,
String? token,
required String clientIdentifier,
String? product,
String? platform,
String? device,
bool acceptJson = true,
}) async {
final packageInfo = await PackageInfo.fromPlatform();
return PlexConfig(
baseUrl: baseUrl,
token: token,
clientIdentifier: clientIdentifier,
product: product ?? 'Plezy',
version: packageInfo.version,
platform: platform ?? 'Flutter',
device: device,
acceptJson: acceptJson,
);
}
Map<String, String> get headers {
final headers = {
'X-Plex-Client-Identifier': clientIdentifier,
+27 -102
View File
@@ -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 = PlexConfig(
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(
+51
View File
@@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
/// Mixin for screens that need to update individual items after watch state changes
///
/// This provides a standard implementation for fetching updated metadata
/// and replacing items in lists, while allowing each screen to customize
/// which lists should be updated.
mixin ItemUpdatable<T extends StatefulWidget> on State<T> {
/// The Plex client to use for fetching updated metadata
/// Each screen must provide access to their client
PlexClient get client;
/// Updates a single item in the screen's list(s) after watch state changes
///
/// Fetches the latest metadata with images (including clearLogo) and
/// calls [updateItemInLists] to update the appropriate list(s).
///
/// If the fetch fails, the error is silently caught and the item will
/// be updated on the next full refresh.
Future<void> updateItem(String ratingKey) async {
try {
final updatedMetadata = await client.getMetadataWithImages(ratingKey);
if (updatedMetadata != null) {
setState(() {
updateItemInLists(ratingKey, updatedMetadata);
});
}
} catch (e) {
// Silently fail - the item will update on next full refresh
}
}
/// Override this method to specify which list(s) should be updated
///
/// This method is called within [setState], so you should directly
/// modify your list(s) without calling setState again.
///
/// Example:
/// ```dart
/// @override
/// void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
/// final index = _items.indexWhere((item) => item.ratingKey == ratingKey);
/// if (index != -1) {
/// _items[index] = updatedMetadata;
/// }
/// }
/// ```
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata);
}
+182
View File
@@ -0,0 +1,182 @@
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
class AboutScreen extends StatefulWidget {
const AboutScreen({super.key});
@override
State<AboutScreen> createState() => _AboutScreenState();
}
class _AboutScreenState extends State<AboutScreen> {
String _appName = '';
String _appVersion = '';
@override
void initState() {
super.initState();
_loadPackageInfo();
}
Future<void> _loadPackageInfo() async {
final packageInfo = await PackageInfo.fromPlatform();
setState(() {
_appName = 'Plezy';
_appVersion = packageInfo.version;
});
}
@override
Widget build(BuildContext context) {
final appName = _appName;
final appVersion = _appVersion;
return Scaffold(
body: CustomScrollView(
slivers: [
DesktopSliverAppBar(
title: const Text('About'),
pinned: true,
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),
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),
),
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),
]),
),
),
],
),
);
}
Widget _buildDependencyItem(String name, String description) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
const Icon(Icons.circle, size: 6),
const SizedBox(width: 8),
Expanded(
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: name,
style: const TextStyle(fontWeight: FontWeight.w600),
),
TextSpan(
text: ' - $description',
style: const TextStyle(color: Colors.grey),
),
],
style: const TextStyle(fontSize: 13, color: Colors.white),
),
),
),
],
),
);
}
}
+40 -7
View File
@@ -15,6 +15,7 @@ class _AuthScreenState extends State<AuthScreen> {
bool _isAuthenticating = false;
String? _errorMessage;
late PlexAuthService _authService;
bool _shouldCancelPolling = false;
@override
void initState() {
@@ -30,6 +31,7 @@ class _AuthScreenState extends State<AuthScreen> {
setState(() {
_isAuthenticating = true;
_errorMessage = null;
_shouldCancelPolling = false;
});
try {
@@ -49,8 +51,16 @@ class _AuthScreenState extends State<AuthScreen> {
throw Exception('Could not launch auth URL');
}
// Poll for authentication
final token = await _authService.pollPinUntilClaimed(pinId);
// Poll for authentication with cancellation support
final token = await _authService.pollPinUntilClaimed(
pinId,
shouldCancel: () => _shouldCancelPolling,
);
// If polling was cancelled, don't show error
if (_shouldCancelPolling) {
return;
}
if (token == null) {
setState(() {
@@ -60,6 +70,13 @@ class _AuthScreenState extends State<AuthScreen> {
return;
}
// Auto-close the in-app browser on mobile (no-op on desktop)
try {
await closeInAppWebView();
} catch (e) {
// Ignore errors - browser might already be closed or on desktop
}
// Store the token
final storage = await StorageService.getInstance();
await storage.savePlexToken(token);
@@ -84,6 +101,15 @@ class _AuthScreenState extends State<AuthScreen> {
}
}
void _retryAuthentication() {
setState(() {
_shouldCancelPolling = true;
_isAuthenticating = false;
});
// Start new authentication after a brief delay to ensure cleanup
Future.delayed(const Duration(milliseconds: 100), _startAuthentication);
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -95,11 +121,7 @@ class _AuthScreenState extends State<AuthScreen> {
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Icon(
Icons.video_library,
size: 80,
color: Theme.of(context).colorScheme.primary,
),
Image.asset('assets/plezy.png', width: 120, height: 120),
const SizedBox(height: 24),
Text(
'Plezy',
@@ -117,6 +139,17 @@ class _AuthScreenState extends State<AuthScreen> {
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: _retryAuthentication,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(
vertical: 12,
horizontal: 24,
),
),
child: const Text('Retry'),
),
] else ...[
ElevatedButton(
onPressed: _startAuthentication,
+315 -129
View File
@@ -2,18 +2,21 @@ 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';
class DiscoverScreen extends StatefulWidget {
final PlexClient client;
@@ -31,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();
}
@@ -51,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;
@@ -64,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);
});
});
}
@@ -109,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();
@@ -228,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')),
@@ -264,20 +285,35 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
return;
}
// Create new client
final config = PlexConfig(
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')),
);
}
}
}
@@ -315,6 +351,7 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
return Scaffold(
body: SafeArea(
child: CustomScrollView(
controller: _scrollController,
slivers: [
DesktopSliverAppBar(
title: const Text('Discover'),
@@ -336,6 +373,13 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
_handleSwitchServer();
} else if (value == 'logout') {
_handleLogout();
} else if (value == 'about') {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const AboutScreen(),
),
);
}
},
itemBuilder: (context) => [
@@ -349,6 +393,16 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
],
),
),
const PopupMenuItem(
value: 'about',
child: Row(
children: [
Icon(Icons.info_outline),
SizedBox(width: 8),
Text('About'),
],
),
),
const PopupMenuItem(
value: 'logout',
child: Row(
@@ -483,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),
),
);
}
}),
),
),
],
@@ -515,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: () {
@@ -551,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
@@ -590,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,
@@ -610,6 +720,7 @@ class _DiscoverScreenState extends State<DiscoverScreen> with Refreshable {
imageUrl: widget.client.getThumbnailUrl(
heroItem.clearLogo,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
placeholder: (context, url) => Align(
@@ -681,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),
],
),
),
@@ -758,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,
@@ -792,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,
),
);
+32 -11
View File
@@ -6,8 +6,11 @@ import '../models/plex_filter.dart';
import '../models/plex_user_profile.dart';
import '../widgets/media_card.dart';
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;
@@ -19,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 = [];
@@ -166,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() {
@@ -284,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(
@@ -293,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),
@@ -311,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,
),
);
}),
@@ -373,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),
@@ -518,8 +539,8 @@ class _FiltersBottomSheetState extends State<_FiltersBottomSheet> {
),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back),
AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: _goBack,
),
const SizedBox(width: 8),
+86 -29
View File
@@ -4,8 +4,10 @@ import '../client/plex_client.dart';
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 '../utils/app_logger.dart';
import '../theme/theme_helper.dart';
import 'season_detail_screen.dart';
import 'video_player_screen.dart';
@@ -31,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;
@@ -107,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
@@ -191,24 +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: SafeArea(
child: Container(
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.of(context).pop(),
padding: EdgeInsets.zero,
),
),
leading: AppBarBackButton(
style: BackButtonStyle.circular,
onPressed: () => Navigator.pop(context, _watchStateChanged),
),
flexibleSpace: FlexibleSpaceBar(
background: Stack(
@@ -274,6 +307,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
imageUrl: widget.client.getThumbnailUrl(
metadata.clearLogo,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
placeholder: (context, url) => Align(
@@ -447,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(
@@ -458,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 {
@@ -478,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();
}
@@ -504,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) {
@@ -536,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) {
@@ -651,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(
@@ -730,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(
+18 -2
View File
@@ -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),
+104 -97
View File
@@ -4,6 +4,10 @@ import '../client/plex_client.dart';
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 {
@@ -22,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() {
@@ -50,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(
@@ -58,17 +81,9 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
DesktopSliverAppBar(
title: Text(widget.season.title),
pinned: true,
leading: Container(
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => Navigator.of(context).pop(),
padding: EdgeInsets.zero,
),
leading: AppBarBackButton(
style: BackButtonStyle.circular,
onPressed: () => Navigator.pop(context, _watchStateChanged),
),
),
if (_isLoadingEpisodes)
@@ -81,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),
),
],
),
@@ -125,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: [
@@ -161,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(
@@ -214,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(
@@ -252,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,
),
),
),
),
],
),
),
@@ -339,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,
),
),
],
],
),
],
),
),
@@ -363,9 +370,9 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
final seconds = duration.inSeconds.remainder(60);
if (hours > 0) {
return '${hours}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
return '$hours:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
} else {
return '${minutes}:${seconds.toString().padLeft(2, '0')}';
return '$minutes:${seconds.toString().padLeft(2, '0')}';
}
}
}
+28 -36
View File
@@ -1,9 +1,9 @@
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';
class ServerSelectionScreen extends StatefulWidget {
@@ -65,56 +65,48 @@ 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 = PlexConfig(
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')),
);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Select Server')),
appBar: const DesktopAppBar(title: Text('Select Server')),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
+78 -79
View File
@@ -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,
),
);
}
+163 -105
View File
@@ -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>;
@@ -109,11 +108,17 @@ class PlexAuthService {
/// Poll the PIN until it's claimed or timeout
Future<String?> pollPinUntilClaimed(
int pinId, {
Duration timeout = const Duration(minutes: 5),
Duration timeout = const Duration(minutes: 2),
bool Function()? shouldCancel,
}) async {
final endTime = DateTime.now().add(timeout);
while (DateTime.now().isBefore(endTime)) {
// Check if polling should be cancelled
if (shouldCancel != null && shouldCancel()) {
return null;
}
final token = await checkPin(pinId);
if (token != null) {
return token;
@@ -127,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>;
@@ -150,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>);
@@ -253,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);
}
}
+184
View File
@@ -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;
}
}
}
+158
View File
@@ -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,
),
],
);
}
+89
View File
@@ -0,0 +1,89 @@
import 'dart:ui';
import 'package:flutter/material.dart';
@immutable
class MonoTokens extends ThemeExtension<MonoTokens> {
final double radiusSm;
final double radiusMd;
final double space;
final Duration fast;
final Duration normal;
final Color bg;
final Color surface;
final Color outline;
final Color text;
final Color textMuted;
final InteractiveInkFeatureFactory? splashFactory;
const MonoTokens({
required this.radiusSm,
required this.radiusMd,
required this.space,
required this.fast,
required this.normal,
required this.bg,
required this.surface,
required this.outline,
required this.text,
required this.textMuted,
required this.splashFactory,
});
@override
MonoTokens copyWith({
double? radiusSm,
double? radiusMd,
double? space,
Duration? fast,
Duration? normal,
Color? bg,
Color? surface,
Color? outline,
Color? text,
Color? textMuted,
InteractiveInkFeatureFactory? splashFactory,
}) => MonoTokens(
radiusSm: radiusSm ?? this.radiusSm,
radiusMd: radiusMd ?? this.radiusMd,
space: space ?? this.space,
fast: fast ?? this.fast,
normal: normal ?? this.normal,
bg: bg ?? this.bg,
surface: surface ?? this.surface,
outline: outline ?? this.outline,
text: text ?? this.text,
textMuted: textMuted ?? this.textMuted,
splashFactory: splashFactory ?? this.splashFactory,
);
@override
ThemeExtension<MonoTokens> lerp(covariant MonoTokens? other, double t) {
if (other == null) return this;
Color lerpC(Color a, Color b) => Color.lerp(a, b, t)!;
return MonoTokens(
radiusSm: lerpDouble(radiusSm, other.radiusSm, t)!,
radiusMd: lerpDouble(radiusMd, other.radiusMd, t)!,
space: lerpDouble(space, other.space, t)!,
fast: Duration(
milliseconds: lerpDouble(
fast.inMilliseconds.toDouble(),
other.fast.inMilliseconds.toDouble(),
t,
)!.round(),
),
normal: Duration(
milliseconds: lerpDouble(
normal.inMilliseconds.toDouble(),
other.normal.inMilliseconds.toDouble(),
t,
)!.round(),
),
bg: lerpC(bg, other.bg),
surface: lerpC(surface, other.surface),
outline: lerpC(outline, other.outline),
text: lerpC(text, other.text),
textMuted: lerpC(textMuted, other.textMuted),
splashFactory: other.splashFactory,
);
}
}
+6
View File
@@ -0,0 +1,6 @@
import 'package:flutter/material.dart';
import 'mono_tokens.dart';
/// Helper function to access MonoTokens from context
MonoTokens tokens(BuildContext context) =>
Theme.of(context).extension<MonoTokens>()!;
+154
View File
@@ -0,0 +1,154 @@
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import '../services/fullscreen_state_manager.dart';
/// Padding values for desktop window controls
class DesktopWindowPadding {
/// Left padding for macOS traffic lights (normal window mode)
static const double macOSLeft = 80.0;
/// Left padding for macOS in fullscreen (reduced since traffic lights auto-hide)
static const double macOSLeftFullscreen = 0.0;
/// Right padding for macOS to prevent actions from being too close to edge
static const double macOSRight = 16.0;
}
/// Helper class for adjusting app bar widgets to account for desktop window controls
class DesktopAppBarHelper {
/// Builds actions list with appropriate right padding for macOS
static List<Widget>? buildAdjustedActions(List<Widget>? actions) {
if (!Platform.isMacOS) {
return actions;
}
// macOS: Add padding to keep actions away from edge
if (actions != null) {
return [...actions, SizedBox(width: DesktopWindowPadding.macOSRight)];
} else {
return [SizedBox(width: DesktopWindowPadding.macOSRight)];
}
}
/// Builds leading widget with appropriate left padding for macOS traffic lights
///
/// [includeGestureDetector] - If true, wraps in GestureDetector to prevent window dragging
static Widget? buildAdjustedLeading(
Widget? leading, {
bool includeGestureDetector = false,
}) {
if (!Platform.isMacOS || leading == null) {
return leading;
}
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
final leftPadding = isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
: DesktopWindowPadding.macOSLeft;
final paddedWidget = Padding(
padding: EdgeInsets.only(left: leftPadding),
child: leading,
);
if (includeGestureDetector) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown:
(_) {}, // Consume pan gestures to prevent window dragging
child: paddedWidget,
);
}
return paddedWidget;
},
);
}
/// Builds flexible space with gesture detector on macOS to prevent window dragging
static Widget? buildAdjustedFlexibleSpace(Widget? flexibleSpace) {
if (!Platform.isMacOS || flexibleSpace == null) {
return flexibleSpace;
}
return GestureDetector(
behavior: HitTestBehavior.translucent,
onPanDown: (_) {}, // Consume pan gestures to prevent window dragging
child: flexibleSpace,
);
}
/// Calculates the leading width for SliverAppBar to account for macOS traffic lights
static double? calculateLeadingWidth(Widget? leading) {
if (!Platform.isMacOS || leading == null) {
return null;
}
final isFullscreen = FullscreenStateManager().isFullscreen;
final leftPadding = isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
: DesktopWindowPadding.macOSLeft;
return leftPadding + kToolbarHeight;
}
/// Wraps a widget with GestureDetector on macOS to prevent window dragging
static Widget wrapWithGestureDetector(Widget child) {
if (!Platform.isMacOS) {
return child;
}
return GestureDetector(
behavior: HitTestBehavior.translucent,
onPanDown: (_) {}, // Consume pan gestures to prevent window dragging
child: child,
);
}
}
/// A widget that adds padding to account for desktop window controls.
/// On macOS, adds left padding for traffic lights (reduced in fullscreen).
class DesktopTitleBarPadding extends StatelessWidget {
final Widget child;
final double? leftPadding;
final double? rightPadding;
const DesktopTitleBarPadding({
super.key,
required this.child,
this.leftPadding,
this.rightPadding,
});
@override
Widget build(BuildContext context) {
if (!Platform.isMacOS) {
return child;
}
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
// In fullscreen, use minimal padding since traffic lights auto-hide
final left =
leftPadding ??
(isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
: DesktopWindowPadding.macOSLeft);
final right = rightPadding ?? 0.0;
if (left == 0.0 && right == 0.0) {
return child;
}
return Padding(
padding: EdgeInsets.only(left: left, right: right),
child: child,
);
},
);
}
}
+16
View File
@@ -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);
}
}
+107
View File
@@ -0,0 +1,107 @@
import 'package:flutter/material.dart';
/// Defines the visual style of the back button
enum BackButtonStyle {
/// Back button with circular semi-transparent background (used in detail screens)
circular,
/// Plain back button without background (used in sheets and simple contexts)
plain,
/// Back button styled for video player overlay
video,
}
/// A reusable back button widget that provides consistent styling across the app.
///
/// This widget supports different visual styles through [BackButtonStyle] enum:
/// - [BackButtonStyle.circular]: Semi-transparent circular background for detail screens
/// - [BackButtonStyle.plain]: Simple IconButton for sheets and simple contexts
/// - [BackButtonStyle.video]: Styled for video player overlay
///
/// Example usage:
/// ```dart
/// AppBarBackButton(style: BackButtonStyle.circular)
/// ```
class AppBarBackButton extends StatelessWidget {
/// Creates a back button with the specified style.
///
/// [style] determines the visual appearance of the back button.
/// [onPressed] is called when the button is tapped. If null, defaults to Navigator.pop.
/// [color] overrides the default icon color. If null, uses white for circular/video, theme default for plain.
const AppBarBackButton({
super.key,
this.style = BackButtonStyle.circular,
this.onPressed,
this.color,
});
/// The visual style of the back button
final BackButtonStyle style;
/// Callback when the button is pressed. Defaults to Navigator.of(context).pop()
final VoidCallback? onPressed;
/// The color of the back arrow icon. If null, uses style-appropriate default.
final Color? color;
void _handlePressed(BuildContext context) {
if (onPressed != null) {
onPressed!();
} else {
Navigator.of(context).pop();
}
}
@override
Widget build(BuildContext context) {
switch (style) {
case BackButtonStyle.circular:
return _buildCircularBackButton(context);
case BackButtonStyle.plain:
return _buildPlainBackButton(context);
case BackButtonStyle.video:
return _buildVideoBackButton(context);
}
}
/// Builds a back button with circular semi-transparent background
Widget _buildCircularBackButton(BuildContext context) {
return SafeArea(
child: Container(
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: IconButton(
icon: Icon(Icons.arrow_back, color: color ?? Colors.white),
onPressed: () => _handlePressed(context),
padding: EdgeInsets.zero,
tooltip: 'Back',
),
),
);
}
/// Builds a plain back button without background
Widget _buildPlainBackButton(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back, color: color),
onPressed: () => _handlePressed(context),
tooltip: 'Back',
);
}
/// Builds a back button styled for video player overlay
Widget _buildVideoBackButton(BuildContext context) {
return Container(
margin: const EdgeInsets.only(left: 8),
child: IconButton(
icon: Icon(Icons.arrow_back, color: color ?? Colors.white),
onPressed: () => _handlePressed(context),
tooltip: 'Back',
),
);
}
}
+25 -168
View File
@@ -1,62 +1,5 @@
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import '../services/fullscreen_state_manager.dart';
class DesktopWindowPadding {
/// Left padding for macOS traffic lights (normal window mode)
static const double macOSLeft = 80.0;
/// Left padding for macOS in fullscreen (reduced since traffic lights auto-hide)
static const double macOSLeftFullscreen = 0.0;
/// Right padding for macOS to prevent actions from being too close to edge
static const double macOSRight = 16.0;
}
/// A widget that adds padding to account for desktop window controls.
/// On macOS, adds left padding for traffic lights (reduced in fullscreen).
class DesktopTitleBarPadding extends StatelessWidget {
final Widget child;
final double? leftPadding;
final double? rightPadding;
const DesktopTitleBarPadding({
super.key,
required this.child,
this.leftPadding,
this.rightPadding,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
double left = 0.0;
double right = 0.0;
if (Platform.isMacOS) {
final isFullscreen = FullscreenStateManager().isFullscreen;
// In fullscreen, use minimal padding since traffic lights auto-hide
left =
leftPadding ??
(isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
: DesktopWindowPadding.macOSLeft);
}
if (left == 0.0 && right == 0.0) {
return child;
}
return Padding(
padding: EdgeInsets.only(left: left, right: right),
child: child,
);
},
);
}
}
import '../utils/desktop_window_padding.dart';
/// A custom app bar that automatically handles desktop window controls spacing.
/// Use this instead of AppBar for consistent desktop platform behavior.
@@ -86,43 +29,15 @@ class DesktopAppBar extends StatelessWidget implements PreferredSizeWidget {
@override
Widget build(BuildContext context) {
// Add right padding for desktop platforms
List<Widget>? adjustedActions = actions;
if (Platform.isMacOS) {
// macOS: Add padding to keep actions away from edge
if (actions != null) {
adjustedActions = [
...actions!,
SizedBox(width: DesktopWindowPadding.macOSRight),
];
} else {
adjustedActions = [SizedBox(width: DesktopWindowPadding.macOSRight)];
}
}
// Wrap leading widget with padding on macOS to avoid traffic lights
Widget? adjustedLeading = leading;
if (Platform.isMacOS && leading != null) {
adjustedLeading = ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
final leftPadding = isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
: DesktopWindowPadding.macOSLeft;
return Padding(
padding: EdgeInsets.only(left: leftPadding),
child: leading,
);
},
);
}
final appBar = AppBar(
title: title != null ? DesktopTitleBarPadding(child: title!) : null,
actions: adjustedActions,
leading: adjustedLeading,
title: title != null
? DesktopTitleBarPadding(
leftPadding: leading != null ? 0 : null,
child: title!,
)
: null,
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
leading: DesktopAppBarHelper.buildAdjustedLeading(leading),
automaticallyImplyLeading: automaticallyImplyLeading,
elevation: elevation,
backgroundColor: backgroundColor,
@@ -131,17 +46,7 @@ class DesktopAppBar extends StatelessWidget implements PreferredSizeWidget {
scrolledUnderElevation: scrolledUnderElevation,
);
// On macOS with transparent titlebar, wrap in GestureDetector to prevent
// window dragging and allow buttons to be clickable
if (Platform.isMacOS) {
return GestureDetector(
behavior: HitTestBehavior.translucent,
onPanDown: (_) {}, // Consume pan gestures to prevent window dragging
child: appBar,
);
}
return appBar;
return DesktopAppBarHelper.wrapWithGestureDetector(appBar);
}
@override
@@ -186,69 +91,19 @@ class DesktopSliverAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Add right padding for desktop platforms
List<Widget>? adjustedActions = actions;
if (Platform.isMacOS) {
// macOS: Add padding to keep actions away from edge
if (actions != null) {
adjustedActions = [
...actions!,
SizedBox(width: DesktopWindowPadding.macOSRight),
];
} else {
adjustedActions = [SizedBox(width: DesktopWindowPadding.macOSRight)];
}
}
// Wrap leading widget with gesture detector and padding on macOS
Widget? adjustedLeading = leading;
if (Platform.isMacOS && leading != null) {
adjustedLeading = ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
final leftPadding = isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
: DesktopWindowPadding.macOSLeft;
return GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown:
(_) {}, // Consume pan gestures to prevent window dragging
child: Padding(
padding: EdgeInsets.only(left: leftPadding),
child: leading,
),
);
},
);
}
// Wrap flexible space with gesture detector on macOS to prevent window dragging
Widget? adjustedFlexibleSpace = flexibleSpace;
if (Platform.isMacOS && flexibleSpace != null) {
adjustedFlexibleSpace = GestureDetector(
behavior: HitTestBehavior.translucent,
onPanDown: (_) {}, // Consume pan gestures to prevent window dragging
child: flexibleSpace,
);
}
// On macOS, increase leading width to account for traffic light spacing
double? leadingWidth;
if (Platform.isMacOS && leading != null) {
final isFullscreen = FullscreenStateManager().isFullscreen;
final leftPadding = isFullscreen
? DesktopWindowPadding.macOSLeftFullscreen
: DesktopWindowPadding.macOSLeft;
leadingWidth = leftPadding + kToolbarHeight;
}
return SliverAppBar(
title: title != null ? DesktopTitleBarPadding(child: title!) : null,
actions: adjustedActions,
leading: adjustedLeading,
leadingWidth: leadingWidth,
title: title != null
? DesktopTitleBarPadding(
leftPadding: leading != null ? 0 : null,
child: title!,
)
: null,
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
leading: DesktopAppBarHelper.buildAdjustedLeading(
leading,
includeGestureDetector: true,
),
leadingWidth: DesktopAppBarHelper.calculateLeadingWidth(leading),
automaticallyImplyLeading: automaticallyImplyLeading,
elevation: elevation,
backgroundColor: backgroundColor,
@@ -258,7 +113,9 @@ class DesktopSliverAppBar extends StatelessWidget {
floating: floating,
pinned: pinned,
expandedHeight: expandedHeight,
flexibleSpace: adjustedFlexibleSpace,
flexibleSpace: DesktopAppBarHelper.buildAdjustedFlexibleSpace(
flexibleSpace,
),
bottom: bottom,
);
}
+89 -132
View File
@@ -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(
@@ -294,6 +190,8 @@ class _MediaCardState extends State<MediaCard> {
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
filterQuality: FilterQuality.medium,
fadeInDuration: const Duration(milliseconds: 300),
placeholder: (context, url) => Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
),
@@ -310,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
View File
@@ -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(
+395 -81
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:window_manager/window_manager.dart';
import 'package:macos_window_utils/macos_window_utils.dart';
@@ -8,7 +9,9 @@ import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_media_info.dart';
import '../services/fullscreen_state_manager.dart';
import 'desktop_app_bar.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
Widget plexVideoControlsBuilder(
@@ -54,10 +57,12 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
bool _chaptersLoaded = false;
Timer? _hideTimer;
bool _isFullscreen = false;
late final FocusNode _focusNode;
@override
void initState() {
super.initState();
_focusNode = FocusNode();
_loadChapters();
_startHideTimer();
// Add window listener for tracking fullscreen state (for button icon)
@@ -69,6 +74,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
@override
void dispose() {
_hideTimer?.cancel();
_focusNode.dispose();
// Remove window listener
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
windowManager.removeListener(this);
@@ -170,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() {
@@ -220,76 +271,281 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
}
Future<void> _toggleFullscreen() async {
if (!_isMobile(context)) {
setState(() {
_isFullscreen = !_isFullscreen;
});
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();
if (Platform.isMacOS) {
// Use native macOS fullscreen - titlebar is handled automatically
if (_isFullscreen) {
await WindowManipulator.enterFullscreen();
} else {
// Window listener will update _isFullscreen for UI
if (isCurrentlyFullscreen) {
await WindowManipulator.exitFullscreen();
} else {
await WindowManipulator.enterFullscreen();
}
} else {
// For Windows/Linux, use window_manager
if (_isFullscreen) {
await windowManager.setFullScreen(true);
} else {
// Window listener will update _isFullscreen for UI
if (isCurrentlyFullscreen) {
await windowManager.setFullScreen(false);
} else {
await windowManager.setFullScreen(true);
}
}
}
}
void _togglePlayPause() {
final isPlaying = widget.player.state.playing;
if (isPlaying) {
widget.player.pause();
_hideTimer?.cancel(); // Cancel auto-hide when paused
} else {
widget.player.play();
_startHideTimer(); // Start auto-hide when playing
}
}
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 Stack(
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),
return Focus(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (node, event) {
// Only respond to key down events (not key up)
if (event is KeyDownEvent) {
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,
onHover: (_) {
// Show controls when mouse moves
if (!_showControls) {
setState(() {
_showControls = true;
});
_startHideTimer();
// On macOS, show traffic lights when controls appear
if (Platform.isMacOS) {
_updateTrafficLightVisibility();
}
}
},
child: Stack(
children: [
// Invisible tap detector that always covers the full area
Positioned.fill(
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],
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,
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),
),
),
],
);
},
),
),
],
),
],
),
);
}
@@ -326,8 +582,8 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
padding: const EdgeInsets.all(16),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
AppBarBackButton(
style: BackButtonStyle.video,
onPressed: () => Navigator.of(context).pop(true),
),
const SizedBox(width: 16),
@@ -357,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(),
],
),
);
@@ -547,8 +792,8 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
AppBarBackButton(
style: BackButtonStyle.video,
onPressed: () => Navigator.of(context).pop(true),
),
const SizedBox(width: 16),
@@ -733,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(
@@ -1348,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);
+41 -1
View File
@@ -294,6 +294,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.0"
flutter_svg:
dependency: "direct main"
description:
name: flutter_svg
sha256: b9c2ad5872518a27507ab432d1fb97e8813b05f0fc693f9d40fad06d073e0678
url: "https://pub.dev"
source: hosted
version: "2.2.1"
flutter_test:
dependency: "direct dev"
description: flutter
@@ -554,7 +562,7 @@ packages:
source: hosted
version: "2.2.0"
package_info_plus:
dependency: transitive
dependency: "direct main"
description:
name: package_info_plus
sha256: f69da0d3189a4b4ceaeb1a3defb0f329b3b352517f52bed4290f83d4f06bc08d
@@ -577,6 +585,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_parsing:
dependency: transitive
description:
name: path_parsing
sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
path_provider:
dependency: transitive
description:
@@ -1062,6 +1078,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.5.1"
vector_graphics:
dependency: transitive
description:
name: vector_graphics
sha256: a4f059dc26fc8295b5921376600a194c4ec7d55e72f2fe4c7d2831e103d461e6
url: "https://pub.dev"
source: hosted
version: "1.1.19"
vector_graphics_codec:
dependency: transitive
description:
name: vector_graphics_codec
sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146"
url: "https://pub.dev"
source: hosted
version: "1.1.13"
vector_graphics_compiler:
dependency: transitive
description:
name: vector_graphics_compiler
sha256: d354a7ec6931e6047785f4db12a1f61ec3d43b207fc0790f863818543f8ff0dc
url: "https://pub.dev"
source: hosted
version: "1.1.19"
vector_math:
dependency: transitive
description:
+4 -1
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 0.1.0
version: 1.1.0+5
environment:
sdk: ^3.8.1
@@ -24,6 +24,8 @@ dependencies:
uuid: ^4.4.0
window_manager: ^0.4.3
logger: ^2.0.2
flutter_svg: ^2.0.10
package_info_plus: ^9.0.0
dependency_overrides:
media_kit:
@@ -43,6 +45,7 @@ flutter:
uses-material-design: true
assets:
- lib/data/iso_639_codes.json
- assets/plezy.png
flutter_launcher_icons:
android: true
+13
View File
@@ -0,0 +1,13 @@
## iOS
| Home | Library | Media Card |
|------|---------|------------|
| ![iOS Home - Content discovery and recommendations](ios-home.png) | ![iOS Library - Media collection view](ios-library.png) | ![iOS Media Card - Playback controls](ios-media-card.png) |
## macOS
![macOS Home - Content discovery and recommendations](macos-home.png)
![macOS Library - Media collection view](macos-library.png)
![macOS Media Card - Playback controls](macos-media-card.png)
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