Compare commits

..
72 Commits
Author SHA1 Message Date
edde746 4dd2d7b011 chore: bump version 2025-11-04 11:01:51 +01:00
edde746 4696b5c7b0 fix: hardware decoding toggle functionality 2025-11-04 11:01:43 +01:00
edde746 852cee8967 ci: sign android build 2025-11-04 11:00:22 +01:00
edde746 2e7babaae5 ci: macOS 26 runners 2025-11-04 10:53:02 +01:00
edde746 65057750f7 feat: file version picker 2025-11-04 10:28:37 +01:00
edde746 e50bd46386 fix: limit hero dots count 2025-11-04 09:40:02 +01:00
edde746 1c67fa3998 feat: mobile double tap rewind/skip 2025-11-04 09:26:03 +01:00
edde746 d586c8c067 fix: allow connections to local only servers 2025-11-04 09:07:04 +01:00
edde746 f1a5493aeb feat: higher playback speed options
add 2.5x and 3x speed options
2025-11-04 08:52:47 +01:00
edde746 7efa96be74 fix: missing subtitles on android 2025-11-04 08:48:04 +01:00
edde746 770cb6b744 feat: customizable seek durations 2025-11-04 08:26:05 +01:00
edde746 5126b67c9c refactor: remove redundant library management in settings 2025-11-04 08:21:52 +01:00
edde746 f0035d1335 fix: seek time overflow 2025-11-04 08:02:00 +01:00
edde746 ca576110b8 Merge branch 'feature/library-reordering-6'
# Conflicts:
#	lib/screens/libraries_screen.dart
#	lib/services/storage_service.dart
2025-11-04 07:50:12 +01:00
edde746 1f59374f62 feat: library hiding 2025-11-04 07:45:24 +01:00
edde746 679e5d5c39 feat: sorting 2025-11-04 07:45:24 +01:00
edde746 73568ee3ae refactor: unify library management 2025-11-04 07:44:36 +01:00
edde746 aa9dd045de Merge branch 'main' into feature/library-reordering-6
# Conflicts:
#	lib/screens/libraries_screen.dart
#	lib/services/storage_service.dart
2025-11-04 06:56:21 +01:00
edde746andGitHub 69e7e796b4 Merge pull request #14 from TheLidlMan/fix/issue-13-poster-sizing
Fix poster sizing on home screen to match libraries view
2025-11-04 06:47:18 +01:00
edde746 95263b7625 feat: library hiding 2025-11-04 06:45:16 +01:00
Sam Matthews 236e3e7cfc Fix poster sizing on home screen to match libraries view
- Increase minimum poster width from 130px to 160px
- Adjust poster sizing to account for MediaCard padding (16px)
- Calculate poster dimensions based on actual display area
- Ensure consistent poster sizing across Home and Libraries screens

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

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

- Changed rating field type from int to double in PlexMetadata model
- Removed incorrect division by 10 in discover screen rating display
- Regenerated JSON serialization to properly parse rating as double
- Rating now displays correctly (e.g., 7.0 instead of 0.7)
2025-11-04 03:12:42 +00:00
edde746 3a5b812a22 refactor: slow down hero scroll 2025-11-04 02:55:44 +01:00
edde746 b01f9ce3f9 fix: crashing when scrolling large libraries 2025-11-04 02:50:39 +01:00
edde746 25ff8f1d1f feat: horizontal scroll arrows on desktop 2025-11-04 02:14:50 +01:00
edde746 ce8d384e7c feat: file info 2025-11-03 15:08:48 +01:00
edde746 bae7b70feb docs: mobile store links 2025-11-02 07:21:41 +01:00
edde746 26e7dba0d0 fix: plex track preference 2025-11-01 12:12:16 +01:00
edde746 00fe8039cc chore: bump version 2025-11-01 09:54:49 +01:00
edde746 7526e80a40 fix: make profile fields optional 2025-11-01 09:51:00 +01:00
edde746 6e1a2e0568 fix: orientation issues when exiting player 2025-11-01 09:35:58 +01:00
edde746 127500329b refactor: remove player navigation animation 2025-11-01 09:28:47 +01:00
edde746 a81cf3b18f fix: not showing selected tracks properly 2025-11-01 08:04:54 +01:00
edde746 66f00d192f fix: buffer size not working 2025-11-01 08:04:33 +01:00
edde746 ad9502d3c7 feat: fastlane & screenshot scripts 2025-11-01 08:03:47 +01:00
edde746 380a15442a ci: fix linux builds 2025-10-31 05:31:14 +01:00
edde746 5c418395b1 chore: bump version
also update screenshots
2025-10-31 05:17:30 +01:00
edde746 90ec76b661 fix: clear all data on logout 2025-10-31 05:12:52 +01:00
edde746 5f1251d82b refactor: fix warnings 2025-10-31 04:27:32 +01:00
edde746 19ab6a21b9 feat: settings page 2025-10-31 03:55:01 +01:00
edde746 e0fc990b0e refactor: back button unification 2025-10-31 00:51:45 +01:00
edde746 36b897f963 feat: profiles 2025-10-30 19:50:50 +01:00
edde746 17dba97dbb fix: no redundant search queries 2025-10-30 13:08:31 +01:00
edde746 564746d6a7 refactor: mobile hero section improvements 2025-10-30 10:29:03 +01:00
edde746 a5063a662e refactor: remove dead code 2025-10-29 14:04:39 +01:00
edde746 8d086d282c chore: update screenshots 2025-10-29 11:01:20 +01:00
edde746 bf509ee57c chore: bump version 2025-10-29 10:51:22 +01:00
edde746 823ba0beab fix: context menu overflowing 2025-10-29 10:50:08 +01:00
edde746 b310d1f169 fix: macos app bar padding issue 2025-10-29 10:49:52 +01:00
edde746 bdd39c252e feat: design improvements 2025-10-29 10:33:16 +01:00
edde746 1d29281143 fix: update watch state properly 2025-10-29 02:35:00 +01:00
edde746 12ee134191 refactor: deduplicate 2025-10-28 10:06:29 +01:00
edde746 9248fb4ddb refactor: episode navigation 2025-10-28 08:10:32 +01:00
edde746 b3696035b5 feat: playback speed controls 2025-10-28 07:59:17 +01:00
edde746 b8a5afc08f feat: keyboard video controls 2025-10-28 07:59:17 +01:00
edde746 0796f9c30d feat: screenshots 2025-10-28 07:59:17 +01:00
edde746 cebe90d39b refactor: deduplicate track controls
also fixes double click to fullscreen issues
2025-10-28 07:59:17 +01:00
edde746 abd5900290 perf(auth): better connection choice 2025-10-28 07:59:16 +01:00
edde746 67934c1f1a chore: bump version 2025-10-25 16:32:30 +02:00
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
96 changed files with 12609 additions and 2749 deletions
+19 -8
View File
@@ -2,9 +2,6 @@ name: Build Flutter App
on:
workflow_dispatch:
push:
tags:
- "v*"
jobs:
build-android:
@@ -50,9 +47,23 @@ jobs:
- name: Install dependencies
run: flutter pub get
- name: Configure Android signing
run: |
echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" | base64 --decode > android/app/upload-keystore.jks
cat > android/key.properties << EOF
storePassword=${{ secrets.ANDROID_STORE_PASSWORD }}
keyPassword=${{ secrets.ANDROID_KEY_PASSWORD }}
keyAlias=${{ secrets.ANDROID_KEY_ALIAS }}
storeFile=upload-keystore.jks
EOF
- name: Build APK
run: flutter build apk --release
- name: Clean up keystore
if: always()
run: rm -f android/app/upload-keystore.jks android/key.properties
- name: Rename APK
run: |
cp build/app/outputs/flutter-apk/app-release.apk plezy-android.apk
@@ -69,7 +80,7 @@ jobs:
path: plezy-android.apk
build-ios:
runs-on: macos-latest
runs-on: macos-26
permissions:
id-token: write
attestations: write
@@ -127,7 +138,7 @@ jobs:
path: plezy-ios.ipa
build-macos:
runs-on: macos-latest
runs-on: macos-26
permissions:
id-token: write
attestations: write
@@ -262,13 +273,13 @@ jobs:
- name: Cache APT packages
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv
packages: clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0
version: 1.0
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv
sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0
- name: Install dependencies
run: flutter pub get
@@ -312,7 +323,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
+11
View File
@@ -43,3 +43,14 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release
# Code duplication reports
duplication-report/
.env.*
.env
!.env.example
**/fastlane/**/
**/fastlane/report.xml
maestro/**/*.png
+21
View File
@@ -0,0 +1,21 @@
{
"threshold": 5,
"reporters": ["html", "console"],
"ignore": [
"**/*.g.dart",
"**/*.freezed.dart",
"**/*.mocks.dart",
"**/generated/**",
"**/*.config.dart"
],
"absolute": true,
"gitignore": true,
"format": ["dart"],
"minLines": 5,
"minTokens": 50,
"output": "./duplication-report",
"mode": "strict",
"formatsExts": {
"dart": ["dart"]
}
}
+14 -19
View File
@@ -1,11 +1,23 @@
# Plezy
<h1>
<img src="assets/plezy.png" alt="Plezy Logo" height="24" style="vertical-align: middle;" />
Plezy
</h1>
Plezy is a modern Plex media client that provides a seamless streaming experience across desktop and mobile platforms. Built with Flutter, it offers native performance and a clean, intuitive interface for browsing and playing your Plex media library.
<p align="center">
<img src="assets/screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
</p>
*See more screenshots in the [screenshots folder](assets/screenshots/#readme)*
## Download
### Mobile
Coming soon
<a href='https://apps.apple.com/us/app/id6754315964'><img height='60' alt='Download on the App Store' src='./assets/app-store-badge.png'/></a>
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
> Google Play version is in closed testing ([required by Google](https://support.google.com/googleplay/android-developer/answer/14151465#overview)). Join the [Google Group](https://groups.google.com/g/plezy-testers) to get access.
### Desktop
- [Windows (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
@@ -34,14 +46,6 @@ Coming soon
- Playback progress sync and resume functionality
- Auto-play next episode
## Platform Support
- ✅ macOS
- ✅ Windows
- ✅ Linux
- ✅ Android
- ✅ iOS
## Prerequisites
- Flutter SDK 3.8.1 or higher
@@ -71,15 +75,6 @@ dart run build_runner build
flutter run
```
## Configuration
On first launch, Plezy will guide you through:
1. Authenticating with your Plex account
2. Selecting your Plex Media Server
3. Testing connections to find the optimal one
Your credentials and preferences are securely stored locally for automatic sign-in on subsequent launches.
## Development
### Code Generation
+6 -1
View File
@@ -49,7 +49,12 @@ android {
buildTypes {
release {
signingConfig = signingConfigs.getByName("release")
// 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
}
}
}
+63
View File
@@ -0,0 +1,63 @@
require 'dotenv/load'
Dotenv.load("../../.env")
default_platform(:android)
platform :android do
desc "Deploy a new version to the Google Play"
lane :deploy do
gradle(task: "clean bundleRelease")
# Get version code from pubspec.yaml
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
pubspec_content = File.read(pubspec_path)
version_match = pubspec_content.match(/version:\s*(.+)\+(\d+)/)
if version_match
version_code = version_match[2].to_i
UI.message("Using version code: #{version_code}")
else
UI.user_error!("Could not extract version code from pubspec.yaml")
end
upload_to_play_store(
version_code: version_code,
skip_upload_changelogs: true,
skip_upload_metadata: true,
skip_upload_images: true,
skip_upload_screenshots: true
)
end
desc "Build release AAB"
lane :build do
# Navigate to Flutter project root and build
sh("cd #{ENV['PWD']}/.. && flutter build appbundle")
end
desc "Build and deploy to Google Play Store"
lane :release do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build appbundle")
# Get version code from pubspec.yaml
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
pubspec_content = File.read(pubspec_path)
version_match = pubspec_content.match(/version:\s*(.+)\+(\d+)/)
if version_match
version_code = version_match[2].to_i
UI.message("Using version code: #{version_code}")
else
UI.user_error!("Could not extract version code from pubspec.yaml")
end
# Upload to Play Store
upload_to_play_store(
track: "internal",
release_status: "draft",
version_code: version_code,
aab: "../build/app/outputs/bundle/release/app-release.aab"
)
end
end
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

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

After

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+49
View File
@@ -0,0 +1,49 @@
require 'dotenv/load'
Dotenv.load("../../.env")
default_platform(:ios)
platform :ios do
desc "Push a new beta build to TestFlight"
lane :beta do
build_app(workspace: "Runner.xcworkspace", scheme: "Runner")
upload_to_testflight
end
desc "Push a new release build to the App Store"
lane :release do
build_app(workspace: "Runner.xcworkspace", scheme: "Runner")
upload_to_app_store
end
desc "Build release IPA"
lane :build do
# Navigate to Flutter project root and build
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
end
desc "Build and deploy to TestFlight"
lane :deploy_testflight do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
# Upload to TestFlight
upload_to_testflight(
skip_waiting_for_build_processing: true
)
end
desc "Build and deploy to App Store"
lane :deploy_appstore do
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build ipa")
# Upload to App Store
upload_to_app_store(
ipa: "../build/ios/ipa/Plezy.ipa",
force: true,
submit_for_review: false,
skip_screenshots: true, # https://github.com/fastlane/fastlane/issues/29735
)
end
end
-111
View File
@@ -1,111 +0,0 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
class PlexAuth {
static const String authUrl = 'https://plex.tv/api/v2';
static const String clientsUrl = 'https://clients.plex.tv/api/v2';
final String clientIdentifier;
final String product;
PlexAuth({
required this.clientIdentifier,
this.product = 'Plex Flutter Client',
});
Map<String, String> get _headers => {
'Accept': 'application/json',
'X-Plex-Client-Identifier': clientIdentifier,
'X-Plex-Product': product,
};
/// Generate a PIN for authentication
Future<Map<String, dynamic>> generatePin({bool strong = true}) async {
final response = await http.post(
Uri.parse('$authUrl/pins?strong=$strong'),
headers: _headers,
);
if (response.statusCode == 201) {
return json.decode(response.body);
} else {
throw Exception('Failed to generate PIN: ${response.body}');
}
}
/// Check PIN status
Future<Map<String, dynamic>> checkPin(int pinId) async {
final response = await http.get(
Uri.parse('$authUrl/pins/$pinId'),
headers: _headers,
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to check PIN: ${response.body}');
}
}
/// Get auth app URL for user to authenticate
String getAuthAppUrl(String code, {String? forwardUrl}) {
final params = {
'clientID': clientIdentifier,
'code': code,
'context[device][product]': product,
if (forwardUrl != null) 'forwardUrl': forwardUrl,
};
final queryString = params.entries
.map(
(e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}',
)
.join('&');
return 'https://app.plex.tv/auth#?$queryString';
}
/// Verify token validity
Future<bool> verifyToken(String token) async {
try {
final response = await http.get(
Uri.parse('$authUrl/user'),
headers: {..._headers, 'X-Plex-Token': token},
);
return response.statusCode == 200;
} catch (e) {
return false;
}
}
/// Get user info
Future<Map<String, dynamic>> getUserInfo(String token) async {
final response = await http.get(
Uri.parse('$authUrl/user'),
headers: {..._headers, 'X-Plex-Token': token},
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to get user info: ${response.body}');
}
}
/// Get available resources (servers)
Future<List<dynamic>> getResources(String token) async {
final response = await http.get(
Uri.parse(
'$clientsUrl/resources?includeHttps=1&includeRelay=1&includeIPv6=1',
),
headers: {..._headers, 'X-Plex-Token': token},
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to get resources: ${response.body}');
}
}
}
+449 -295
View File
@@ -3,11 +3,22 @@ import '../config/plex_config.dart';
import '../models/plex_library.dart';
import '../models/plex_metadata.dart';
import '../models/plex_media_info.dart';
import '../models/plex_file_info.dart';
import '../models/plex_filter.dart';
import '../models/plex_sort.dart';
import '../models/plex_media_version.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;
PlexConfig config;
late final Dio _dio;
PlexClient(this.config) {
@@ -33,6 +44,14 @@ class PlexClient {
);
}
/// Update the token used by this client
void updateToken(String newToken) {
// Update both the Dio headers and the config to ensure consistency
_dio.options.headers['X-Plex-Token'] = newToken;
config = config.copyWith(token: newToken);
appLogger.d('PlexClient token updated (headers and config)');
}
/// Test connection to server
Future<bool> testConnection() async {
try {
@@ -43,12 +62,14 @@ class PlexClient {
}
}
/// Test connection to a specific URL with token
static Future<bool> testConnectionUrl(
/// 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 +85,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 +203,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 +227,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 +248,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 +273,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 +341,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
@@ -313,28 +373,29 @@ class PlexClient {
}
/// Get video URL for direct playback
Future<String?> getVideoUrl(String ratingKey) async {
/// [mediaIndex] specifies which Media item to use (defaults to 0 - first version)
Future<String?> getVideoUrl(String ratingKey, {int mediaIndex = 0}) 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 mediaList = metadataJson['Media'] as List;
// 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?;
// Ensure the requested index is valid
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
mediaIndex = 0;
}
if (partKey != null) {
// Return direct play URL
return '${config.baseUrl}$partKey?X-Plex-Token=${config.token}';
}
}
final media = mediaList[mediaIndex];
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}';
}
}
}
@@ -349,119 +410,112 @@ 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 [];
}
/// Get detailed media info including chapters and tracks
Future<PlexMediaInfo?> getMediaInfo(String ratingKey) async {
/// [mediaIndex] specifies which Media item to use (defaults to 0 - first version)
Future<PlexMediaInfo?> getMediaInfo(String ratingKey, {int mediaIndex = 0}) 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 mediaList = metadataJson['Media'] as List;
// 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?;
// Ensure the requested index is valid
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
mediaIndex = 0;
}
if (partKey != null) {
// Parse streams (audio and subtitle tracks)
final streams = part['Stream'] as List<dynamic>? ?? [];
final audioTracks = <PlexAudioTrack>[];
final subtitleTracks = <PlexSubtitleTrack>[];
final media = mediaList[mediaIndex];
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
final part = media['Part'][0];
final partKey = part['key'] as String?;
for (var stream in streams) {
final streamType = stream['streamType'] as int?;
if (partKey != null) {
// Parse streams (audio and subtitle tracks)
final streams = part['Stream'] as List<dynamic>? ?? [];
final audioTracks = <PlexAudioTrack>[];
final subtitleTracks = <PlexSubtitleTrack>[];
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?,
),
);
}
}
for (var stream in streams) {
final streamType = stream['streamType'] as int?;
// 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,
);
}
}
}
@@ -469,6 +523,92 @@ class PlexClient {
return null;
}
/// Get all available media versions for a media item
/// Returns a list of PlexMediaVersion objects representing different quality/format options
Future<List<PlexMediaVersion>> getMediaVersions(String ratingKey) async {
final response = await _dio.get('/library/metadata/$ratingKey');
final metadataJson = _getFirstMetadataJson(response);
if (metadataJson != null &&
metadataJson['Media'] != null &&
(metadataJson['Media'] as List).isNotEmpty) {
final mediaList = metadataJson['Media'] as List;
return mediaList
.map((media) => PlexMediaVersion.fromJson(media as Map<String, dynamic>))
.toList();
}
return [];
}
/// Get file information for a media item
Future<PlexFileInfo?> getFileInfo(String ratingKey) async {
try {
final response = await _dio.get('/library/metadata/$ratingKey');
final metadataJson = _getFirstMetadataJson(response);
if (metadataJson != null &&
metadataJson['Media'] != null &&
(metadataJson['Media'] as List).isNotEmpty) {
final media = metadataJson['Media'][0];
final part = media['Part'] != null && (media['Part'] as List).isNotEmpty
? media['Part'][0]
: null;
// Extract video stream details
final streams = part?['Stream'] as List<dynamic>? ?? [];
Map<String, dynamic>? videoStream;
Map<String, dynamic>? audioStream;
for (var stream in streams) {
final streamType = stream['streamType'] as int?;
if (streamType == 1 && videoStream == null) {
videoStream = stream;
} else if (streamType == 2 && audioStream == null) {
audioStream = stream;
}
}
return PlexFileInfo(
// Media level properties
container: media['container'] as String?,
videoCodec: media['videoCodec'] as String?,
videoResolution: media['videoResolution'] as String?,
videoFrameRate: media['videoFrameRate'] as String?,
videoProfile: media['videoProfile'] as String?,
width: media['width'] as int?,
height: media['height'] as int?,
aspectRatio: (media['aspectRatio'] as num?)?.toDouble(),
bitrate: media['bitrate'] as int?,
duration: media['duration'] as int?,
audioCodec: media['audioCodec'] as String?,
audioProfile: media['audioProfile'] as String?,
audioChannels: media['audioChannels'] as int?,
optimizedForStreaming: media['optimizedForStreaming'] as bool?,
has64bitOffsets: media['has64bitOffsets'] as bool?,
// Part level properties (file)
filePath: part?['file'] as String?,
fileSize: part?['size'] as int?,
// Video stream details
colorSpace: videoStream?['colorSpace'] as String?,
colorRange: videoStream?['colorRange'] as String?,
colorPrimaries: videoStream?['colorPrimaries'] as String?,
colorTrc: videoStream?['colorTrc'] as String?,
chromaSubsampling: videoStream?['chromaSubsampling'] as String?,
frameRate: (videoStream?['frameRate'] as num?)?.toDouble(),
bitDepth: videoStream?['bitDepth'] as int?,
// Audio stream details
audioChannelLayout: audioStream?['audioChannelLayout'] as String?,
);
}
return null;
} catch (e) {
appLogger.e('Failed to get file info: $e');
return null;
}
}
/// Mark media as watched
Future<void> markAsWatched(String ratingKey) async {
await _dio.get(
@@ -519,100 +659,95 @@ 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);
return _extractDirectoryList(response, PlexFilterValue.fromJson);
}
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))
/// Get available sort options for a library section
Future<List<PlexSort>> getLibrarySorts(String sectionId) async {
try {
// Fetch library content with minimal data to get Sort metadata
final response = await _dio.get(
'/library/sections/$sectionId/all',
queryParameters: {'X-Plex-Container-Size': 0},
);
final container = _getMediaContainer(response);
if (container != null && container['Sort'] != null) {
return (container['Sort'] as List)
.map((json) => PlexSort.fromJson(json as Map<String, dynamic>))
.toList();
}
}
return [];
}
/// Get next episode for a TV show episode
Future<PlexMetadata?> getNextEpisode(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 != -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 (currentSeasonIndex != -1 &&
currentSeasonIndex < seasons.length - 1) {
final nextSeason = seasons[currentSeasonIndex + 1];
final nextSeasonEpisodes = await getChildren(nextSeason.ratingKey);
if (nextSeasonEpisodes.isNotEmpty) {
return nextSeasonEpisodes.first;
}
}
}
// Fallback: return common sort options if API doesn't provide them
return [
PlexSort(
key: 'titleSort',
title: 'Title',
defaultDirection: 'asc',
),
PlexSort(
key: 'addedAt',
descKey: 'addedAt:desc',
title: 'Date Added',
defaultDirection: 'desc',
),
PlexSort(
key: 'originallyAvailableAt',
descKey: 'originallyAvailableAt:desc',
title: 'Release Date',
defaultDirection: 'desc',
),
PlexSort(
key: 'rating',
descKey: 'rating:desc',
title: 'Rating',
defaultDirection: 'desc',
),
];
} catch (e) {
// Silently handle errors
appLogger.e('Failed to get library sorts: $e');
// Return fallback sort options on error
return [
PlexSort(
key: 'titleSort',
title: 'Title',
defaultDirection: 'asc',
),
PlexSort(
key: 'addedAt',
descKey: 'addedAt:desc',
title: 'Date Added',
defaultDirection: 'desc',
),
];
}
return null;
}
/// Get previous episode for a TV show episode
Future<PlexMetadata?> getPreviousEpisode(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;
}
@@ -633,24 +768,43 @@ class PlexClient {
(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 (currentIndex == -1) return null;
final targetIndex = currentIndex + direction;
// Check if target episode is within current season
if (targetIndex >= 0 && targetIndex < episodes.length) {
return episodes[targetIndex];
}
// Need to move to adjacent season
final isAtBoundary = direction > 0
? currentIndex == episodes.length - 1
: currentIndex == 0;
if (isAtBoundary) {
// Get all seasons
final seasons = await getChildren(grandparentKey);
final currentSeasonIndex = seasons.indexWhere(
(s) => s.ratingKey == parentKey,
);
if (currentSeasonIndex > 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;
}
}
}
+97 -102
View File
@@ -1,23 +1,32 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:io' show Platform;
import 'package:media_kit/media_kit.dart';
import 'package:window_manager/window_manager.dart';
import 'client/plex_client.dart';
import 'config/plex_config.dart';
import 'package:provider/provider.dart';
import '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 'providers/user_profile_provider.dart';
import 'providers/plex_client_provider.dart';
import 'providers/theme_provider.dart';
import 'providers/settings_provider.dart';
import 'providers/hidden_libraries_provider.dart';
import 'utils/language_codes.dart';
import 'utils/app_logger.dart';
import 'utils/provider_extensions.dart';
import 'utils/orientation_helper.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Configure image cache for large libraries
PaintingBinding.instance.imageCache.maximumSizeBytes = 500 << 20; // 500MB
PaintingBinding.instance.imageCache.maximumSize = 500; // 500 images
// Initialize window_manager for desktop platforms
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
await windowManager.ensureInitialized();
@@ -29,11 +38,7 @@ void main() async {
// Initialize MediaKit
MediaKit.ensureInitialized();
// Lock orientation to portrait for all screens except video player
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
// Note: Orientation will be set dynamically based on device type in MainApp
await StorageService.getInstance();
@@ -56,20 +61,57 @@ class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Plezy',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepOrange),
useMaterial3: true,
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => PlexClientProvider()),
ChangeNotifierProvider(
create: (context) => UserProfileProvider()..initialize(),
),
ChangeNotifierProvider(create: (context) => ThemeProvider()),
ChangeNotifierProvider(create: (context) => SettingsProvider()),
ChangeNotifierProvider(create: (context) => HiddenLibrariesProvider()),
],
child: Consumer<ThemeProvider>(
builder: (context, themeProvider, child) {
return MaterialApp(
title: 'Plezy',
debugShowCheckedModeBanner: false,
theme: themeProvider.lightTheme,
darkTheme: themeProvider.darkTheme,
themeMode: themeProvider.materialThemeMode,
navigatorObservers: [routeObserver],
home: const OrientationAwareSetup(),
);
},
),
darkTheme: ThemeData.dark(useMaterial3: true),
navigatorObservers: [routeObserver],
home: const SetupScreen(),
);
}
}
class OrientationAwareSetup extends StatefulWidget {
const OrientationAwareSetup({super.key});
@override
State<OrientationAwareSetup> createState() => _OrientationAwareSetupState();
}
class _OrientationAwareSetupState extends State<OrientationAwareSetup> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
_setOrientationPreferences();
}
void _setOrientationPreferences() {
OrientationHelper.restoreDefaultOrientations(context);
}
@override
Widget build(BuildContext context) {
return const SetupScreen();
}
}
class SetupScreen extends StatefulWidget {
const SetupScreen({super.key});
@@ -92,57 +134,66 @@ class _SetupScreenState extends State<SetupScreen> {
final clientId = storage.getClientIdentifier();
final plexToken = storage.getPlexToken();
// Get current user's server token (prioritize over original server token)
final currentUserToken = storage.getToken();
if (serverData != null && clientId != null) {
try {
// Recreate PlexServer from stored data
final server = PlexServer.fromJson(serverData);
// Test connections to find best working one
final connection = await server.findBestWorkingConnection();
// Use current user's token if available, fallback to server's original token
final tokenToUse = currentUserToken ?? server.accessToken;
if (connection != null) {
// Update stored server URL with working connection
await storage.saveServerUrl(connection.uri);
appLogger.d(
'App startup token selection: currentUserToken=${currentUserToken != null ? 'present' : 'null'}, using=${currentUserToken != null ? 'current user' : 'original server'} token',
);
// Create client with working connection
final config = await PlexConfig.create(
baseUrl: connection.uri,
token: server.accessToken,
clientIdentifier: clientId,
);
final client = PlexClient(config);
// Create updated server with correct token for current user
final serverWithCurrentToken = PlexServer(
name: server.name,
clientIdentifier: server.clientIdentifier,
accessToken: tokenToUse,
connections: server.connections,
owned: server.owned,
product: server.product,
platform: server.platform,
lastSeenAt: server.lastSeenAt,
presence: server.presence,
);
// Verify server is accessible
try {
await client.getServerIdentity();
// Connect using the optimized service with current user's token
final result = await ServerConnectionService.connectToServer(
serverWithCurrentToken,
clientIdentifier: clientId,
verifyServer: true,
fetchUserProfile: plexToken != null,
plexToken: plexToken,
);
// Fetch and cache user profile if we have a plex token
PlexUserProfile? userProfile;
if (plexToken != null) {
userProfile = await _fetchAndCacheUserProfile(plexToken);
}
// Handle result
if (result.isSuccess) {
// Success! Set client in provider and navigate to main screen
if (mounted) {
context.plexClient.setClient(result.client!);
// Success! Navigate to main screen
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) =>
MainScreen(client: client, userProfile: userProfile),
builder: (context) => MainScreen(client: result.client!),
),
);
return;
}
} catch (e) {
// Server identity check failed
await storage.clearCredentials();
}
return;
} else {
// No working connections found
// Connection failed, clear credentials
await storage.clearCredentials();
}
} catch (e) {
// Error loading or testing server
appLogger.e('Error during auto-login', error: e);
await storage.clearCredentials();
}
}
@@ -156,62 +207,6 @@ class _SetupScreenState extends State<SetupScreen> {
}
}
Future<PlexUserProfile?> _fetchAndCacheUserProfile(String plexToken) async {
appLogger.d('Fetching user profile from Plex API');
try {
final authService = await PlexAuthService.create();
final profile = await authService.getUserProfile(plexToken);
appLogger.i(
'Successfully fetched user profile',
error: {
'autoSelectAudio': profile.autoSelectAudio,
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
'autoSelectSubtitle': profile.autoSelectSubtitle,
'defaultSubtitleLanguage':
profile.defaultSubtitleLanguage ?? 'not set',
'defaultSubtitleForced': profile.defaultSubtitleForced,
},
);
// Cache the profile
final storage = await StorageService.getInstance();
await storage.saveUserProfile(profile.toJson());
appLogger.d('User profile cached locally');
return profile;
} catch (e) {
appLogger.w(
'Failed to fetch user profile from API, attempting to load from cache',
error: e,
);
// Failed to fetch profile, try to load from cache
final storage = await StorageService.getInstance();
final cachedProfile = storage.getUserProfile();
if (cachedProfile != null) {
final profile = PlexUserProfile.fromJson(cachedProfile);
appLogger.i(
'Loaded user profile from cache',
error: {
'autoSelectAudio': profile.autoSelectAudio,
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
'autoSelectSubtitle': profile.autoSelectSubtitle,
'defaultSubtitleLanguage':
profile.defaultSubtitleLanguage ?? 'not set',
'defaultSubtitleForced': profile.defaultSubtitleForced,
},
);
return profile;
}
appLogger.w(
'No cached user profile available, track selection will use defaults',
);
return null;
}
}
@override
Widget build(BuildContext context) {
return const Scaffold(
+51
View File
@@ -0,0 +1,51 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
/// Mixin for screens that need to update individual items after watch state changes
///
/// This provides a standard implementation for fetching updated metadata
/// and replacing items in lists, while allowing each screen to customize
/// which lists should be updated.
mixin ItemUpdatable<T extends StatefulWidget> on State<T> {
/// The Plex client to use for fetching updated metadata
/// Each screen must provide access to their client
PlexClient get client;
/// Updates a single item in the screen's list(s) after watch state changes
///
/// Fetches the latest metadata with images (including clearLogo) and
/// calls [updateItemInLists] to update the appropriate list(s).
///
/// If the fetch fails, the error is silently caught and the item will
/// be updated on the next full refresh.
Future<void> updateItem(String ratingKey) async {
try {
final updatedMetadata = await client.getMetadataWithImages(ratingKey);
if (updatedMetadata != null) {
setState(() {
updateItemInLists(ratingKey, updatedMetadata);
});
}
} catch (e) {
// Silently fail - the item will update on next full refresh
}
}
/// Override this method to specify which list(s) should be updated
///
/// This method is called within [setState], so you should directly
/// modify your list(s) without calling setState again.
///
/// Example:
/// ```dart
/// @override
/// void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
/// final index = _items.indexWhere((item) => item.ratingKey == ratingKey);
/// if (index != -1) {
/// _items[index] = updatedMetadata;
/// }
/// }
/// ```
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata);
}
+151
View File
@@ -0,0 +1,151 @@
class PlexFileInfo {
// Media level properties
final String? container;
final String? videoCodec;
final String? videoResolution;
final String? videoFrameRate;
final String? videoProfile;
final int? width;
final int? height;
final double? aspectRatio;
final int? bitrate;
final int? duration;
final String? audioCodec;
final String? audioProfile;
final int? audioChannels;
final bool? optimizedForStreaming;
final bool? has64bitOffsets;
// Part level properties (file)
final String? filePath;
final int? fileSize;
// Stream level properties (video stream details)
final String? colorSpace;
final String? colorRange;
final String? colorPrimaries;
final String? colorTrc;
final String? chromaSubsampling;
final double? frameRate;
final int? bitDepth;
final String? audioChannelLayout;
PlexFileInfo({
this.container,
this.videoCodec,
this.videoResolution,
this.videoFrameRate,
this.videoProfile,
this.width,
this.height,
this.aspectRatio,
this.bitrate,
this.duration,
this.audioCodec,
this.audioProfile,
this.audioChannels,
this.optimizedForStreaming,
this.has64bitOffsets,
this.filePath,
this.fileSize,
this.colorSpace,
this.colorRange,
this.colorPrimaries,
this.colorTrc,
this.chromaSubsampling,
this.frameRate,
this.bitDepth,
this.audioChannelLayout,
});
/// Format file size in human-readable format (GB, MB, KB, bytes)
String get fileSizeFormatted {
if (fileSize == null) return 'Unknown';
const kb = 1024;
const mb = kb * 1024;
const gb = mb * 1024;
if (fileSize! >= gb) {
return '${(fileSize! / gb).toStringAsFixed(2)} GB';
} else if (fileSize! >= mb) {
return '${(fileSize! / mb).toStringAsFixed(2)} MB';
} else if (fileSize! >= kb) {
return '${(fileSize! / kb).toStringAsFixed(2)} KB';
} else {
return '$fileSize bytes';
}
}
/// Format duration in HH:MM:SS or MM:SS format
String get durationFormatted {
if (duration == null) return 'Unknown';
final seconds = duration! ~/ 1000;
final hours = seconds ~/ 3600;
final minutes = (seconds % 3600) ~/ 60;
final secs = seconds % 60;
if (hours > 0) {
return '${hours}h ${minutes}m ${secs}s';
} else {
return '${minutes}m ${secs}s';
}
}
/// Format bitrate in Mbps or Kbps
String get bitrateFormatted {
if (bitrate == null) return 'Unknown';
const kbps = 1000;
const mbps = kbps * 1000;
if (bitrate! >= mbps) {
return '${(bitrate! / mbps).toStringAsFixed(2)} Mbps';
} else if (bitrate! >= kbps) {
return '${(bitrate! / kbps).toStringAsFixed(2)} Kbps';
} else {
return '$bitrate bps';
}
}
/// Format resolution as widthxheight
String get resolutionFormatted {
if (width != null && height != null) {
return '${width}x$height';
} else if (videoResolution != null) {
return videoResolution!;
}
return 'Unknown';
}
/// Format aspect ratio
String get aspectRatioFormatted {
if (aspectRatio != null) {
return aspectRatio!.toStringAsFixed(2);
}
return 'Unknown';
}
/// Format frame rate
String get frameRateFormatted {
if (frameRate != null) {
return '${frameRate!.toStringAsFixed(3)} fps';
} else if (videoFrameRate != null) {
return videoFrameRate!;
}
return 'Unknown';
}
/// Format audio channels (e.g., "2 channels (stereo)")
String get audioChannelsFormatted {
if (audioChannels != null) {
String channelText = '$audioChannels channel${audioChannels! > 1 ? 's' : ''}';
if (audioChannelLayout != null) {
channelText += ' ($audioChannelLayout)';
}
return channelText;
}
return 'Unknown';
}
}
+70
View File
@@ -0,0 +1,70 @@
import 'plex_home_user.dart';
class PlexHome {
final int id;
final String name;
final int? guestUserID;
final String guestUserUUID;
final bool guestEnabled;
final bool subscription;
final List<PlexHomeUser> users;
PlexHome({
required this.id,
required this.name,
required this.guestUserID,
required this.guestUserUUID,
required this.guestEnabled,
required this.subscription,
required this.users,
});
factory PlexHome.fromJson(Map<String, dynamic> json) {
final List<dynamic> usersJson = json['users'] as List<dynamic>;
final users = usersJson
.map(
(userJson) => PlexHomeUser.fromJson(userJson as Map<String, dynamic>),
)
.toList();
return PlexHome(
id: (json['id'] as num?)?.toInt() ?? 0,
name: json['name'] as String,
guestUserID: (json['guestUserID'] as num?)?.toInt(),
guestUserUUID: json['guestUserUUID'] as String,
guestEnabled: json['guestEnabled'] as bool,
subscription: json['subscription'] as bool,
users: users,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'guestUserID': guestUserID,
'guestUserUUID': guestUserUUID,
'guestEnabled': guestEnabled,
'subscription': subscription,
'users': users.map((user) => user.toJson()).toList(),
};
}
PlexHomeUser? get adminUser => users.where((user) => user.admin).firstOrNull;
List<PlexHomeUser> get managedUsers =>
users.where((user) => !user.admin).toList();
List<PlexHomeUser> get restrictedUsers =>
users.where((user) => user.restricted).toList();
PlexHomeUser? getUserByUUID(String uuid) {
try {
return users.firstWhere((user) => user.uuid == uuid);
} catch (e) {
return null;
}
}
bool get hasMultipleUsers => users.length > 1;
}
+74
View File
@@ -0,0 +1,74 @@
class PlexHomeUser {
final int id;
final String uuid;
final String title;
final String? username;
final String? email;
final String? friendlyName;
final String thumb;
final bool hasPassword;
final bool restricted;
final int? updatedAt;
final bool admin;
final bool guest;
final bool protected;
PlexHomeUser({
required this.id,
required this.uuid,
required this.title,
this.username,
this.email,
this.friendlyName,
required this.thumb,
required this.hasPassword,
required this.restricted,
required this.updatedAt,
required this.admin,
required this.guest,
required this.protected,
});
factory PlexHomeUser.fromJson(Map<String, dynamic> json) {
return PlexHomeUser(
id: (json['id'] as num?)?.toInt() ?? 0,
uuid: json['uuid'] as String? ?? '',
title: json['title'] as String? ?? 'Unknown',
username: json['username'] as String?,
email: json['email'] as String?,
friendlyName: json['friendlyName'] as String?,
thumb: json['thumb'] as String? ?? '',
hasPassword: json['hasPassword'] as bool? ?? false,
restricted: json['restricted'] as bool? ?? false,
updatedAt: (json['updatedAt'] as num?)?.toInt(),
admin: json['admin'] as bool? ?? false,
guest: json['guest'] as bool? ?? false,
protected: json['protected'] as bool? ?? false,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'uuid': uuid,
'title': title,
'username': username,
'email': email,
'friendlyName': friendlyName,
'thumb': thumb,
'hasPassword': hasPassword,
'restricted': restricted,
'updatedAt': updatedAt,
'admin': admin,
'guest': guest,
'protected': protected,
};
}
String get displayName => friendlyName ?? title;
bool get isAdminUser => admin;
bool get isRestrictedUser => restricted;
bool get isGuestUser => guest;
bool get requiresPassword => protected;
}
+77
View File
@@ -0,0 +1,77 @@
class PlexMediaVersion {
final int id;
final String? videoResolution;
final String? videoCodec;
final int? bitrate;
final int? width;
final int? height;
final String? container;
final String partKey;
PlexMediaVersion({
required this.id,
this.videoResolution,
this.videoCodec,
this.bitrate,
this.width,
this.height,
this.container,
required this.partKey,
});
/// Creates a PlexMediaVersion from Plex API Media object
factory PlexMediaVersion.fromJson(Map<String, dynamic> json) {
// Get the first Part key for playback
final parts = json['Part'] as List<dynamic>?;
final partKey = parts != null && parts.isNotEmpty
? parts[0]['key'] as String? ?? ''
: '';
return PlexMediaVersion(
id: json['id'] as int? ?? 0,
videoResolution: json['videoResolution'] as String?,
videoCodec: json['videoCodec'] as String?,
bitrate: json['bitrate'] as int?,
width: json['width'] as int?,
height: json['height'] as int?,
container: json['container'] as String?,
partKey: partKey,
);
}
/// Display label with detailed information: "1080p H.264 MKV (8.5 Mbps)"
String get displayLabel {
final parts = <String>[];
// Add resolution
if (videoResolution != null && videoResolution!.isNotEmpty) {
parts.add('${videoResolution}p');
} else if (height != null) {
parts.add('${height}p');
}
// Add codec
if (videoCodec != null && videoCodec!.isNotEmpty) {
parts.add(videoCodec!.toUpperCase());
}
// Add container
if (container != null && container!.isNotEmpty) {
parts.add(container!.toUpperCase());
}
// Build main label
String label = parts.isNotEmpty ? parts.join(' ') : 'Unknown';
// Add bitrate in parentheses
if (bitrate != null && bitrate! > 0) {
final bitrateInMbps = (bitrate! / 1000).toStringAsFixed(1);
label += ' ($bitrateInMbps Mbps)';
}
return label;
}
@override
String toString() => displayLabel;
}
+84 -5
View File
@@ -12,7 +12,7 @@ class PlexMetadata {
final String title;
final String? contentRating;
final String? summary;
final int? rating;
final double? rating;
final int? year;
final String? thumb;
final String? art;
@@ -24,6 +24,7 @@ class PlexMetadata {
final String? grandparentArt; // Show art for episodes
final String? grandparentRatingKey; // Show rating key for episodes
final String? parentTitle; // Season title for episodes
final String? parentThumb; // Season poster for episodes
final String? parentRatingKey; // Season rating key for episodes
final int? parentIndex; // Season number
final int? index; // Episode number
@@ -58,6 +59,7 @@ class PlexMetadata {
this.grandparentArt,
this.grandparentRatingKey,
this.parentTitle,
this.parentThumb,
this.parentRatingKey,
this.parentIndex,
this.index,
@@ -68,6 +70,74 @@ class PlexMetadata {
this.viewedLeafCount,
});
/// Create a copy of this metadata with optional field overrides
PlexMetadata copyWith({
String? ratingKey,
String? key,
String? guid,
String? studio,
String? type,
String? title,
String? contentRating,
String? summary,
double? rating,
int? year,
String? thumb,
String? art,
int? duration,
int? addedAt,
int? updatedAt,
String? grandparentTitle,
String? grandparentThumb,
String? grandparentArt,
String? grandparentRatingKey,
String? parentTitle,
String? parentThumb,
String? parentRatingKey,
int? parentIndex,
int? index,
String? grandparentTheme,
int? viewOffset,
int? viewCount,
int? leafCount,
int? viewedLeafCount,
}) {
final copy = PlexMetadata(
ratingKey: ratingKey ?? this.ratingKey,
key: key ?? this.key,
guid: guid ?? this.guid,
studio: studio ?? this.studio,
type: type ?? this.type,
title: title ?? this.title,
contentRating: contentRating ?? this.contentRating,
summary: summary ?? this.summary,
rating: rating ?? this.rating,
year: year ?? this.year,
thumb: thumb ?? this.thumb,
art: art ?? this.art,
duration: duration ?? this.duration,
addedAt: addedAt ?? this.addedAt,
updatedAt: updatedAt ?? this.updatedAt,
grandparentTitle: grandparentTitle ?? this.grandparentTitle,
grandparentThumb: grandparentThumb ?? this.grandparentThumb,
grandparentArt: grandparentArt ?? this.grandparentArt,
grandparentRatingKey: grandparentRatingKey ?? this.grandparentRatingKey,
parentTitle: parentTitle ?? this.parentTitle,
parentThumb: parentThumb ?? this.parentThumb,
parentRatingKey: parentRatingKey ?? this.parentRatingKey,
parentIndex: parentIndex ?? this.parentIndex,
index: index ?? this.index,
grandparentTheme: grandparentTheme ?? this.grandparentTheme,
viewOffset: viewOffset ?? this.viewOffset,
viewCount: viewCount ?? this.viewCount,
leafCount: leafCount ?? this.leafCount,
viewedLeafCount: viewedLeafCount ?? this.viewedLeafCount,
);
// Preserve clearLogo
copy._clearLogo = _clearLogo;
return copy;
}
// Extract clearLogo from Image array in raw JSON
void _extractClearLogo(Map<String, dynamic> json) {
if (!json.containsKey('Image')) return;
@@ -121,12 +191,21 @@ class PlexMetadata {
}
// Helper to get the poster (show poster for episodes/seasons, thumb otherwise)
String? get posterThumb {
// If useSeasonPoster is true, episodes will use season poster instead of series poster
String? posterThumb({bool useSeasonPoster = false}) {
final itemType = type.toLowerCase();
// For episodes and seasons, prefer grandparent thumb (show poster)
if ((itemType == 'episode' || itemType == 'season') &&
grandparentThumb != null) {
if (itemType == 'episode') {
// If season poster is enabled and available, use it
if (useSeasonPoster && parentThumb != null) {
return parentThumb!;
}
// Otherwise fall back to series poster, then item thumb
if (grandparentThumb != null) {
return grandparentThumb!;
}
} else if (itemType == 'season' && grandparentThumb != null) {
// For seasons, always use series poster
return grandparentThumb!;
}
return thumb;
+3 -1
View File
@@ -15,7 +15,7 @@ PlexMetadata _$PlexMetadataFromJson(Map<String, dynamic> json) => PlexMetadata(
title: json['title'] as String,
contentRating: json['contentRating'] as String?,
summary: json['summary'] as String?,
rating: (json['rating'] as num?)?.toInt(),
rating: (json['rating'] as num?)?.toDouble(),
year: (json['year'] as num?)?.toInt(),
thumb: json['thumb'] as String?,
art: json['art'] as String?,
@@ -27,6 +27,7 @@ PlexMetadata _$PlexMetadataFromJson(Map<String, dynamic> json) => PlexMetadata(
grandparentArt: json['grandparentArt'] as String?,
grandparentRatingKey: json['grandparentRatingKey'] as String?,
parentTitle: json['parentTitle'] as String?,
parentThumb: json['parentThumb'] as String?,
parentRatingKey: json['parentRatingKey'] as String?,
parentIndex: (json['parentIndex'] as num?)?.toInt(),
index: (json['index'] as num?)?.toInt(),
@@ -59,6 +60,7 @@ Map<String, dynamic> _$PlexMetadataToJson(PlexMetadata instance) =>
'grandparentArt': instance.grandparentArt,
'grandparentRatingKey': instance.grandparentRatingKey,
'parentTitle': instance.parentTitle,
'parentThumb': instance.parentThumb,
'parentRatingKey': instance.parentRatingKey,
'parentIndex': instance.parentIndex,
'index': instance.index,
+53
View File
@@ -0,0 +1,53 @@
class PlexSort {
final String key;
final String? descKey;
final String title;
final String? defaultDirection;
PlexSort({
required this.key,
this.descKey,
required this.title,
this.defaultDirection,
});
factory PlexSort.fromJson(Map<String, dynamic> json) {
return PlexSort(
key: json['key'] as String,
descKey: json['descKey'] as String?,
title: json['title'] as String,
defaultDirection: json['defaultDirection'] as String?,
);
}
/// Gets the full sort key with direction
/// If [descending] is true, returns the descKey or key:desc
/// Otherwise returns the key for ascending sort
String getSortKey({bool descending = false}) {
if (!descending) {
return key;
}
// Use descKey if available, otherwise append :desc to key
return descKey ?? '$key:desc';
}
/// Returns true if this sort's default direction is descending
bool get isDefaultDescending {
return defaultDirection?.toLowerCase() == 'desc';
}
@override
String toString() {
return 'PlexSort(key: $key, title: $title, defaultDirection: $defaultDirection)';
}
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is PlexSort && other.key == key;
}
@override
int get hashCode => key.hashCode;
}
+137
View File
@@ -0,0 +1,137 @@
import 'plex_user_profile.dart';
class UserSwitchResponse {
final int id;
final String uuid;
final String username;
final String title;
final String email;
final String? friendlyName;
final String? locale;
final bool confirmed;
final int joinedAt;
final bool emailOnlyAuth;
final bool hasPassword;
final bool protected;
final String thumb;
final String authToken;
final bool? mailingListActive;
final String scrobbleTypes;
final String country;
final bool restricted;
final bool? anonymous;
final bool home;
final bool guest;
final int homeSize;
final bool homeAdmin;
final int maxHomeSize;
final PlexUserProfile profile;
final bool twoFactorEnabled;
final bool backupCodesCreated;
final String? attributionPartner;
UserSwitchResponse({
required this.id,
required this.uuid,
required this.username,
required this.title,
required this.email,
this.friendlyName,
this.locale,
required this.confirmed,
required this.joinedAt,
required this.emailOnlyAuth,
required this.hasPassword,
required this.protected,
required this.thumb,
required this.authToken,
this.mailingListActive,
required this.scrobbleTypes,
required this.country,
required this.restricted,
this.anonymous,
required this.home,
required this.guest,
required this.homeSize,
required this.homeAdmin,
required this.maxHomeSize,
required this.profile,
required this.twoFactorEnabled,
required this.backupCodesCreated,
this.attributionPartner,
});
factory UserSwitchResponse.fromJson(Map<String, dynamic> json) {
return UserSwitchResponse(
id: json['id'] as int,
uuid: json['uuid'] as String,
username: json['username'] as String? ?? '',
title: json['title'] as String,
email: json['email'] as String? ?? '',
friendlyName: json['friendlyName'] as String?,
locale: json['locale'] as String?,
confirmed: json['confirmed'] as bool,
joinedAt: json['joinedAt'] as int,
emailOnlyAuth: json['emailOnlyAuth'] as bool,
hasPassword: json['hasPassword'] as bool,
protected: json['protected'] as bool,
thumb: json['thumb'] as String,
authToken: json['authToken'] as String,
mailingListActive: json['mailingListActive'] as bool?,
scrobbleTypes: json['scrobbleTypes'] as String? ?? '',
country: json['country'] as String? ?? '',
restricted: json['restricted'] as bool,
anonymous: json['anonymous'] as bool?,
home: json['home'] as bool,
guest: json['guest'] as bool,
homeSize: json['homeSize'] as int,
homeAdmin: json['homeAdmin'] as bool,
maxHomeSize: json['maxHomeSize'] as int,
profile: PlexUserProfile.fromJson(json),
twoFactorEnabled: json['twoFactorEnabled'] as bool,
backupCodesCreated: json['backupCodesCreated'] as bool,
attributionPartner: json['attributionPartner'] as String?,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'uuid': uuid,
'username': username,
'title': title,
'email': email,
'friendlyName': friendlyName,
'locale': locale,
'confirmed': confirmed,
'joinedAt': joinedAt,
'emailOnlyAuth': emailOnlyAuth,
'hasPassword': hasPassword,
'protected': protected,
'thumb': thumb,
'authToken': authToken,
'mailingListActive': mailingListActive,
'scrobbleTypes': scrobbleTypes,
'country': country,
'restricted': restricted,
'anonymous': anonymous,
'home': home,
'guest': guest,
'homeSize': homeSize,
'homeAdmin': homeAdmin,
'maxHomeSize': maxHomeSize,
'profile': profile.toJson()['profile'],
'twoFactorEnabled': twoFactorEnabled,
'backupCodesCreated': backupCodesCreated,
'attributionPartner': attributionPartner,
};
}
String get displayName => friendlyName ?? title;
bool get isAdminUser => homeAdmin;
bool get isRestrictedUser => restricted;
bool get isGuestUser => guest;
bool get requiresPassword => hasPassword;
bool get isSecureUser => twoFactorEnabled || backupCodesCreated;
}
@@ -0,0 +1,61 @@
import 'package:flutter/foundation.dart';
import '../services/storage_service.dart';
/// Provider for managing hidden library state across the app.
/// This ensures that when a library is hidden/unhidden in one screen,
/// all other screens are automatically updated.
class HiddenLibrariesProvider extends ChangeNotifier {
late StorageService _storageService;
Set<String> _hiddenLibraryKeys = {};
bool _isInitialized = false;
/// Get an unmodifiable copy of hidden library keys
Set<String> get hiddenLibraryKeys => Set.unmodifiable(_hiddenLibraryKeys);
/// Check if the provider has completed initialization
bool get isInitialized => _isInitialized;
HiddenLibrariesProvider() {
_initialize();
}
/// Initialize the provider by loading hidden libraries from storage
Future<void> _initialize() async {
_storageService = await StorageService.getInstance();
_hiddenLibraryKeys = _storageService.getHiddenLibraries();
_isInitialized = true;
notifyListeners();
}
/// Hide a library by its key
/// Updates both in-memory state and persistent storage
Future<void> hideLibrary(String libraryKey) async {
if (!_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..add(libraryKey);
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
notifyListeners();
}
}
/// Unhide a library by its key
/// Updates both in-memory state and persistent storage
Future<void> unhideLibrary(String libraryKey) async {
if (_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..remove(libraryKey);
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
notifyListeners();
}
}
/// Check if a specific library is hidden
bool isLibraryHidden(String libraryKey) {
return _hiddenLibraryKeys.contains(libraryKey);
}
/// Refresh hidden libraries from storage
/// Useful if storage was modified outside the provider
Future<void> refresh() async {
_hiddenLibraryKeys = _storageService.getHiddenLibraries();
notifyListeners();
}
}
+31
View File
@@ -0,0 +1,31 @@
import 'package:flutter/foundation.dart';
import '../client/plex_client.dart';
import '../utils/app_logger.dart';
class PlexClientProvider extends ChangeNotifier {
PlexClient? _client;
PlexClient? get client => _client;
void setClient(PlexClient client) {
_client = client;
appLogger.d('PlexClientProvider: Client set');
notifyListeners();
}
void updateToken(String newToken) {
if (_client != null) {
_client!.updateToken(newToken);
appLogger.d('PlexClientProvider: Token updated');
notifyListeners();
} else {
appLogger.w('PlexClientProvider: Cannot update token - no client set');
}
}
void clearClient() {
_client = null;
appLogger.d('PlexClientProvider: Client cleared');
notifyListeners();
}
}
+49
View File
@@ -0,0 +1,49 @@
import 'package:flutter/material.dart';
import '../services/settings_service.dart';
class SettingsProvider extends ChangeNotifier {
late SettingsService _settingsService;
LibraryDensity _libraryDensity = LibraryDensity.normal;
bool _useSeasonPoster = false;
SettingsProvider() {
_initializeSettings();
}
Future<void> _initializeSettings() async {
_settingsService = await SettingsService.getInstance();
_libraryDensity = _settingsService.getLibraryDensity();
_useSeasonPoster = _settingsService.getUseSeasonPoster();
notifyListeners();
}
LibraryDensity get libraryDensity => _libraryDensity;
bool get useSeasonPoster => _useSeasonPoster;
Future<void> setLibraryDensity(LibraryDensity density) async {
if (_libraryDensity != density) {
_libraryDensity = density;
await _settingsService.setLibraryDensity(density);
notifyListeners();
}
}
Future<void> setUseSeasonPoster(bool value) async {
if (_useSeasonPoster != value) {
_useSeasonPoster = value;
await _settingsService.setUseSeasonPoster(value);
notifyListeners();
}
}
String get libraryDensityDisplayName {
switch (_libraryDensity) {
case LibraryDensity.compact:
return 'Compact';
case LibraryDensity.normal:
return 'Normal';
case LibraryDensity.comfortable:
return 'Comfortable';
}
}
}
+102
View File
@@ -0,0 +1,102 @@
import 'package:flutter/material.dart';
import '../services/settings_service.dart' as settings;
import '../theme/mono_theme.dart';
class ThemeProvider extends ChangeNotifier {
late settings.SettingsService _settingsService;
settings.ThemeMode _themeMode = settings.ThemeMode.system;
late Brightness _systemBrightness;
ThemeProvider() {
_systemBrightness =
WidgetsBinding.instance.platformDispatcher.platformBrightness;
_initializeSettings();
// Listen to system theme changes
WidgetsBinding.instance.platformDispatcher.onPlatformBrightnessChanged =
() {
_systemBrightness =
WidgetsBinding.instance.platformDispatcher.platformBrightness;
if (_themeMode == settings.ThemeMode.system) {
notifyListeners();
}
};
}
Future<void> _initializeSettings() async {
_settingsService = await settings.SettingsService.getInstance();
_themeMode = _settingsService.getThemeMode();
notifyListeners();
}
settings.ThemeMode get themeMode => _themeMode;
ThemeData get lightTheme => monoTheme(dark: false);
ThemeData get darkTheme => monoTheme(dark: true);
ThemeMode get materialThemeMode {
switch (_themeMode) {
case settings.ThemeMode.light:
return ThemeMode.light;
case settings.ThemeMode.dark:
return ThemeMode.dark;
case settings.ThemeMode.system:
return ThemeMode.system;
}
}
bool get isDarkMode {
switch (_themeMode) {
case settings.ThemeMode.light:
return false;
case settings.ThemeMode.dark:
return true;
case settings.ThemeMode.system:
return _systemBrightness == Brightness.dark;
}
}
Future<void> setThemeMode(settings.ThemeMode mode) async {
if (_themeMode != mode) {
_themeMode = mode;
await _settingsService.setThemeMode(mode);
notifyListeners();
}
}
String get themeModeDisplayName {
switch (_themeMode) {
case settings.ThemeMode.light:
return 'Light';
case settings.ThemeMode.dark:
return 'Dark';
case settings.ThemeMode.system:
return 'System';
}
}
IconData get themeModeIcon {
switch (_themeMode) {
case settings.ThemeMode.light:
return Icons.light_mode;
case settings.ThemeMode.dark:
return Icons.dark_mode;
case settings.ThemeMode.system:
return Icons.brightness_auto;
}
}
void toggleTheme() {
switch (_themeMode) {
case settings.ThemeMode.system:
setThemeMode(settings.ThemeMode.light);
break;
case settings.ThemeMode.light:
setThemeMode(settings.ThemeMode.dark);
break;
case settings.ThemeMode.dark:
setThemeMode(settings.ThemeMode.system);
break;
}
}
}
+564
View File
@@ -0,0 +1,564 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import '../models/plex_home.dart';
import '../models/plex_home_user.dart';
import '../models/plex_user_profile.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../widgets/pin_entry_dialog.dart';
import 'plex_client_provider.dart';
class UserProfileProvider extends ChangeNotifier {
PlexHome? _home;
PlexHomeUser? _currentUser;
PlexUserProfile? _profileSettings;
bool _isLoading = false;
String? _error;
PlexHome? get home => _home;
PlexHomeUser? get currentUser => _currentUser;
PlexUserProfile? get profileSettings => _profileSettings;
bool get isLoading => _isLoading;
String? get error => _error;
bool get hasMultipleUsers {
final result = _home?.hasMultipleUsers ?? false;
appLogger.d(
'hasMultipleUsers: _home=${_home != null}, users count=${_home?.users.length ?? 0}, result=$result',
);
return result;
}
PlexAuthService? _authService;
StorageService? _storageService;
// Callback for data invalidation when switching profiles
VoidCallback? _onDataInvalidationRequested;
/// Set a callback to be called when profile switching requires data invalidation
void setDataInvalidationCallback(VoidCallback? callback) {
_onDataInvalidationRequested = callback;
}
/// Trigger data invalidation for all screens
void _invalidateAllData() {
if (_onDataInvalidationRequested != null) {
_onDataInvalidationRequested!();
appLogger.d('Data invalidation triggered for profile switch');
}
}
Future<void> initialize() async {
appLogger.d('UserProfileProvider: Initializing...');
try {
_authService = await PlexAuthService.create();
_storageService = await StorageService.getInstance();
await _loadCachedData();
// If no cached home data or it's expired, try to load from API
if (_home == null) {
appLogger.d(
'UserProfileProvider: No cached home data, attempting to load from API',
);
try {
await loadHomeUsers();
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to load home users during initialization',
error: e,
);
// Don't set error here as it's not critical for app startup
}
}
// Fetch fresh profile settings from API
appLogger.d('UserProfileProvider: Fetching profile settings from API');
try {
await refreshProfileSettings();
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to fetch profile settings during initialization',
error: e,
);
// Don't set error here, cached profile (if any) was already loaded
}
appLogger.d('UserProfileProvider: Initialization complete');
} catch (e) {
appLogger.e(
'UserProfileProvider: Critical initialization failure',
error: e,
);
_setError('Failed to initialize profile services');
// Ensure services are null on failure
_authService = null;
_storageService = null;
}
}
Future<void> _loadCachedData() async {
if (_storageService == null) return;
// Load cached home users
final cachedHomeData = _storageService!.getHomeUsersCache();
if (cachedHomeData != null) {
try {
_home = PlexHome.fromJson(cachedHomeData);
} catch (e) {
appLogger.w('Failed to load cached home data', error: e);
}
}
// Load current user UUID
final currentUserUUID = _storageService!.getCurrentUserUUID();
if (currentUserUUID != null && _home != null) {
_currentUser = _home!.getUserByUUID(currentUserUUID);
}
// Profile settings are NOT cached - they will be fetched fresh from API
// in refreshProfileSettings()
notifyListeners();
}
/// Fetch the user's profile settings from the API
Future<void> refreshProfileSettings() async {
if (_authService == null || _storageService == null) {
appLogger.w('refreshProfileSettings: Services not initialized, skipping');
return;
}
appLogger.d('Fetching user profile settings from Plex API');
try {
final currentToken = _storageService!.getPlexToken();
if (currentToken == null) {
appLogger.w(
'refreshProfileSettings: No Plex token available, cannot fetch profile',
);
return;
}
final profile = await _authService!.getUserProfile(currentToken);
_profileSettings = profile;
appLogger.i('Successfully fetched user profile settings from API');
notifyListeners();
} catch (e) {
appLogger.w('Failed to fetch user profile settings from API', error: e);
// Don't set error state, profile will remain null or keep existing value
}
}
Future<void> loadHomeUsers({bool forceRefresh = false}) async {
appLogger.d('loadHomeUsers called - forceRefresh: $forceRefresh');
// Auto-initialize services if not ready
if (_authService == null || _storageService == null) {
appLogger.d(
'loadHomeUsers: Services not initialized, initializing services...',
);
_authService = await PlexAuthService.create();
_storageService = await StorageService.getInstance();
await _loadCachedData();
// Double-check after initialization
if (_authService == null || _storageService == null) {
appLogger.e('loadHomeUsers: Failed to initialize services');
_setError('Failed to initialize services');
return;
}
}
// Use cached data if available and not forcing refresh
if (!forceRefresh && _home != null) {
appLogger.d(
'loadHomeUsers: Using cached data, users count: ${_home!.users.length}',
);
return;
}
_setLoading(true);
_clearError();
try {
final currentToken = _storageService!.getPlexToken();
if (currentToken == null) {
throw Exception('No Plex.tv authentication token available');
}
appLogger.d('loadHomeUsers: Using Plex.tv token');
appLogger.d('loadHomeUsers: Fetching home users from API');
final home = await _authService!.getHomeUsers(currentToken);
_home = home;
appLogger.i(
'loadHomeUsers: Success! Home users count: ${home.users.length}',
);
appLogger.d(
'loadHomeUsers: Users: ${home.users.map((u) => u.displayName).join(', ')}',
);
// Cache the home data
await _storageService!.saveHomeUsersCache(home.toJson());
// Set current user if not already set
if (_currentUser == null) {
final currentUserUUID = _storageService!.getCurrentUserUUID();
if (currentUserUUID != null) {
_currentUser = home.getUserByUUID(currentUserUUID);
appLogger.d(
'loadHomeUsers: Set current user from UUID: ${_currentUser?.displayName}',
);
} else {
// Default to admin user if no current user set
_currentUser = home.adminUser;
if (_currentUser != null) {
await _storageService!.saveCurrentUserUUID(_currentUser!.uuid);
appLogger.d(
'loadHomeUsers: Set current user to admin: ${_currentUser?.displayName}',
);
}
}
}
notifyListeners();
} catch (e) {
_setError('Failed to load home users: $e');
appLogger.e('Failed to load home users', error: e);
} finally {
_setLoading(false);
}
}
Future<bool> switchToUser(PlexHomeUser user, BuildContext? context) async {
if (_authService == null || _storageService == null) {
_setError('Services not initialized');
return false;
}
if (user.uuid == _currentUser?.uuid) {
// Already on this user
return true;
}
// Extract client provider before async operations
PlexClientProvider? clientProvider;
if (context != null) {
try {
clientProvider = context.plexClient;
} catch (e) {
appLogger.w('Failed to get PlexClientProvider', error: e);
}
}
_setLoading(true);
_clearError();
return await _attemptUserSwitch(user, context, clientProvider, null);
}
Future<bool> _attemptUserSwitch(
PlexHomeUser user,
BuildContext? context,
PlexClientProvider? clientProvider,
String? errorMessage,
) async {
try {
final currentToken = _storageService!.getPlexToken();
if (currentToken == null) {
throw Exception('No Plex.tv authentication token available');
}
// Check if user requires PIN
String? pin;
if (user.requiresPassword && context != null && context.mounted) {
pin = await showPinEntryDialog(
context,
user.displayName,
errorMessage: errorMessage,
);
// User cancelled the PIN dialog
if (pin == null) {
_setLoading(false);
return false;
}
}
final switchResponse = await _authService!.switchToUser(
user.uuid,
currentToken,
pin: pin,
);
// switchResponse.authToken is the new user's Plex.tv token
// We need to fetch servers with this token to get the proper server access token
appLogger.d('Got new user Plex.tv token, fetching servers...');
final servers = await _authService!.fetchServers(
switchResponse.authToken,
);
if (servers.isEmpty) {
throw Exception('No servers available for this user');
}
// Find the current server from storage
final currentServerData = _storageService!.getServerData();
if (currentServerData == null) {
throw Exception('No current server data found');
}
// Find matching server by name or client identifier
final currentServerName = currentServerData['name'] as String?;
final currentServerClientId =
currentServerData['clientIdentifier'] as String?;
final matchingServer = servers.firstWhere(
(server) =>
server.name == currentServerName ||
server.clientIdentifier == currentServerClientId,
orElse: () => servers.first, // Fallback to first server
);
appLogger.d(
'Found matching server: ${matchingServer.name}, getting access token',
);
// Update storage with new tokens
await _storageService!.updateCurrentUser(
user.uuid,
matchingServer
.accessToken, // Use server access token, not Plex.tv token
);
// Also save the new Plex.tv token for future profile operations
await _storageService!.savePlexToken(switchResponse.authToken);
// Update current user
_currentUser = user;
// Update user profile settings (fresh from API)
_profileSettings = switchResponse.profile;
appLogger.d(
'Updated profile settings for user: ${user.displayName}',
error: {
'defaultAudioLanguage':
_profileSettings?.defaultAudioLanguage ?? 'not set',
'defaultSubtitleLanguage':
_profileSettings?.defaultSubtitleLanguage ?? 'not set',
},
);
// Update PlexClient with proper server access token
if (clientProvider != null) {
try {
clientProvider.updateToken(matchingServer.accessToken);
appLogger.d(
'Updated PlexClient with server access token for user: ${user.displayName}',
);
} catch (e) {
appLogger.w('Failed to update PlexClient token', error: e);
}
}
notifyListeners();
// Invalidate all cached data for the new profile
// This will cause screens to refresh and rebuild widgets with the new token
_invalidateAllData();
appLogger.d(
'Profile switch complete, all data and images should refresh with new token',
);
appLogger.i('Successfully switched to user: ${user.displayName}');
return true;
} catch (e) {
// Check if it's a PIN validation error
if (e is DioException && e.response?.statusCode == 403) {
final errors = e.response?.data['errors'] as List?;
if (errors != null && errors.isNotEmpty) {
final errorCode = errors[0]['code'] as int?;
final errorMessage = errors[0]['message'] as String?;
// Error code 1041 means invalid PIN
if (errorCode == 1041) {
appLogger.w('Invalid PIN for user: ${user.displayName}');
_clearError(); // Clear any previous error state
// Retry with error message if context is still available
if (context != null && context.mounted) {
return await _attemptUserSwitch(
user,
context,
clientProvider,
errorMessage ?? 'Incorrect PIN. Please try again.',
);
}
// If context not available, return false without showing error
appLogger.d('Cannot retry PIN entry - context not available');
return false;
}
}
}
// Only show error for non-PIN validation errors
_setError('Failed to switch user: $e');
appLogger.e('Failed to switch to user: ${user.displayName}', error: e);
return false;
} finally {
_setLoading(false);
}
}
Future<void> refreshCurrentUser() async {
if (_currentUser != null) {
await loadHomeUsers(forceRefresh: true);
// Update current user from refreshed data
if (_home != null) {
_currentUser = _home!.getUserByUUID(_currentUser!.uuid);
notifyListeners();
}
}
}
Future<void> logout() async {
if (_storageService == null) return;
_setLoading(true);
try {
await _storageService!.clearUserData();
// Clear user-specific provider state but keep services for future sign-ins
_home = null;
_currentUser = null;
_profileSettings = null;
_onDataInvalidationRequested = null;
_clearError();
notifyListeners();
appLogger.i('User logged out successfully');
} catch (e) {
appLogger.e('Error during logout', error: e);
} finally {
_setLoading(false);
}
}
/// Refresh provider for new server context
/// Call this when switching servers to ensure provider state is synchronized
Future<void> refreshForNewServer([BuildContext? context]) async {
appLogger.d('UserProfileProvider: Refreshing for new server context');
_setLoading(true);
try {
// Clear cached data from previous server (both memory and storage)
_home = null;
_currentUser = null;
_profileSettings = null;
_clearError();
// Re-initialize services with current storage state
_authService = await PlexAuthService.create();
_storageService = await StorageService.getInstance();
// Clear storage state that's specific to the previous server context
await Future.wait([
// Clear home users cache (server-specific)
_storageService!.clearHomeUsersCache(),
// Clear current user UUID (profile-specific, should not persist across servers)
_storageService!.clearCurrentUserUUID(),
]);
appLogger.d('UserProfileProvider: Cleared previous server storage state');
// Load fresh data for the new server (should be empty after clearing cache)
await _loadCachedData();
// Load from API since we cleared the cache
appLogger.d(
'UserProfileProvider: Loading fresh home users for new server',
);
// Store context reference before async operations to avoid build context warnings
final contextForSwitch = context;
try {
await loadHomeUsers();
// After loading home users, if a current user was set (admin user),
// perform a complete profile switch to ensure tokens are properly updated
if (_currentUser != null && contextForSwitch != null) {
appLogger.d(
'UserProfileProvider: Performing complete profile switch to ${_currentUser!.displayName} for new server',
);
// Perform full profile switch which includes API calls and token updates
final userToSwitchTo = _currentUser!;
// ignore: use_build_context_synchronously
final success = await switchToUser(userToSwitchTo, contextForSwitch);
if (success) {
appLogger.d(
'UserProfileProvider: Successfully switched to admin user for new server',
);
} else {
appLogger.w(
'UserProfileProvider: Failed to complete profile switch for new server',
);
}
} else if (_currentUser != null && contextForSwitch == null) {
appLogger.w(
'UserProfileProvider: Cannot perform complete profile switch - no context provided',
);
// Still try to fetch profile settings even without full switch
try {
await refreshProfileSettings();
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to refresh profile settings for new server',
error: e,
);
}
}
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to load home users for new server',
error: e,
);
// Don't set error as it's not critical
}
appLogger.d('UserProfileProvider: Refresh for new server complete');
} catch (e) {
appLogger.e(
'UserProfileProvider: Failed to refresh for new server',
error: e,
);
_setError('Failed to refresh for new server');
} finally {
_setLoading(false);
}
}
void _setLoading(bool loading) {
_isLoading = loading;
notifyListeners();
}
void _setError(String error) {
_error = error;
notifyListeners();
}
void _clearError() {
_error = null;
}
}
+47 -134
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../widgets/desktop_app_bar.dart';
import 'licenses_screen.dart';
class AboutScreen extends StatefulWidget {
const AboutScreen({super.key});
@@ -35,122 +36,63 @@ class _AboutScreenState extends State<AboutScreen> {
return Scaffold(
body: CustomScrollView(
slivers: [
DesktopSliverAppBar(
title: const Text('About'),
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,
),
),
),
CustomAppBar(title: const Text('About'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
// App Icon and Name
Center(
child: Column(
children: [
const SizedBox(height: 24),
Image.asset(
'assets/plezy.png',
width: 80,
height: 80,
),
const SizedBox(height: 16),
Text(
appName,
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
fontWeight: FontWeight.bold,
// App Icon and Name
Center(
child: Column(
children: [
const SizedBox(height: 24),
Image.asset('assets/plezy.png', width: 80, height: 80),
const SizedBox(height: 16),
Text(
appName,
style: Theme.of(context).textTheme.headlineMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
'Version $appVersion',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 24),
Text(
'A beautiful Plex client for Flutter',
style: Theme.of(context).textTheme.bodyLarge,
textAlign: TextAlign.center,
),
],
),
),
const SizedBox(height: 8),
Text(
'Version $appVersion',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 24),
Text(
'A beautiful Plex client for Flutter',
style: Theme.of(context).textTheme.bodyLarge,
textAlign: TextAlign.center,
),
],
),
),
const SizedBox(height: 40),
const SizedBox(height: 40),
// Open Source Licenses
Card(
child: ListTile(
leading: const Icon(Icons.description),
title: const Text('Open Source Licenses'),
subtitle: const Text('View licenses of third-party libraries'),
trailing: const Icon(Icons.chevron_right),
onTap: () {
showLicensePage(
context: context,
applicationName: appName,
applicationVersion: appVersion,
applicationIcon: Image.asset(
'assets/plezy.png',
width: 48,
height: 48,
),
);
},
),
),
const SizedBox(height: 16),
// Key Dependencies
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Key Dependencies',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
// Open Source Licenses
Card(
child: ListTile(
leading: const Icon(Icons.description),
title: const Text('Open Source Licenses'),
subtitle: const Text(
'View licenses of third-party libraries',
),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const LicensesScreen(),
),
);
},
),
const SizedBox(height: 12),
_buildDependencyItem('http', 'HTTP networking'),
_buildDependencyItem('dio', 'Advanced HTTP client'),
_buildDependencyItem('cached_network_image', 'Image caching'),
_buildDependencyItem('media_kit', 'Video playback'),
_buildDependencyItem('shared_preferences', 'Local storage'),
_buildDependencyItem('xml', 'XML parsing'),
_buildDependencyItem('url_launcher', 'External links'),
_buildDependencyItem(
'window_manager',
'Desktop window management',
),
_buildDependencyItem(
'macos_window_utils',
'macOS window controls',
),
_buildDependencyItem('logger', 'Logging'),
],
),
),
),
),
const SizedBox(height: 24),
const SizedBox(height: 24),
]),
),
),
@@ -158,33 +100,4 @@ class _AboutScreenState extends State<AboutScreen> {
),
);
}
Widget _buildDependencyItem(String name, String description) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
const Icon(Icons.circle, size: 6),
const SizedBox(width: 8),
Expanded(
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: name,
style: const TextStyle(fontWeight: FontWeight.w600),
),
TextSpan(
text: ' - $description',
style: const TextStyle(color: Colors.grey),
),
],
style: const TextStyle(fontSize: 13, color: Colors.white),
),
),
),
],
),
);
}
}
+150 -7
View File
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../services/plex_auth_service.dart';
@@ -15,6 +17,7 @@ class _AuthScreenState extends State<AuthScreen> {
bool _isAuthenticating = false;
String? _errorMessage;
late PlexAuthService _authService;
bool _shouldCancelPolling = false;
@override
void initState() {
@@ -30,6 +33,7 @@ class _AuthScreenState extends State<AuthScreen> {
setState(() {
_isAuthenticating = true;
_errorMessage = null;
_shouldCancelPolling = false;
});
try {
@@ -49,8 +53,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 +72,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 +103,105 @@ 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);
}
void _handleDebugTap() {
if (!kDebugMode) return;
_showDebugTokenDialog();
}
void _showDebugTokenDialog() {
final tokenController = TextEditingController();
String? errorMessage;
showDialog<void>(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setDialogState) {
return AlertDialog(
title: const Text('Debug: Enter Plex Token'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: tokenController,
decoration: InputDecoration(
labelText: 'Plex Auth Token',
hintText: 'Enter your Plex.tv token',
errorText: errorMessage,
border: const OutlineInputBorder(),
),
obscureText: true,
maxLines: 1,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
ElevatedButton(
onPressed: () async {
final token = tokenController.text.trim();
if (token.isEmpty) {
setDialogState(() {
errorMessage = 'Please enter a token';
});
return;
}
final navigator = Navigator.of(context);
try {
final isValid = await _authService.verifyToken(token);
if (!isValid) {
setDialogState(() {
errorMessage = 'Invalid token';
});
return;
}
// Store the token
final storage = await StorageService.getInstance();
await storage.savePlexToken(token);
// Close dialog and navigate
if (mounted) {
navigator.pop();
navigator.pushReplacement(
MaterialPageRoute(
builder: (context) => ServerSelectionScreen(
authService: _authService,
plexToken: token,
),
),
);
}
} catch (e) {
setDialogState(() {
errorMessage = 'Failed to verify token: $e';
});
}
},
child: const Text('Authenticate'),
),
],
);
},
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -95,11 +213,7 @@ class _AuthScreenState extends State<AuthScreen> {
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Image.asset(
'assets/plezy.png',
width: 120,
height: 120,
),
Image.asset('assets/plezy.png', width: 120, height: 120),
const SizedBox(height: 24),
Text(
'Plezy',
@@ -117,6 +231,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,
@@ -125,6 +250,24 @@ class _AuthScreenState extends State<AuthScreen> {
),
child: const Text('Sign in with Plex'),
),
if (kDebugMode) ...[
const SizedBox(height: 12),
OutlinedButton(
onPressed: _handleDebugTap,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12),
side: BorderSide(
color: Theme.of(
context,
).colorScheme.outline.withValues(alpha: 0.5),
),
),
child: const Text(
'Debug: Enter Token',
style: TextStyle(fontSize: 12),
),
),
],
if (_errorMessage != null) ...[
const SizedBox(height: 16),
Text(
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+216
View File
@@ -0,0 +1,216 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../widgets/desktop_app_bar.dart';
class MergedLicenseEntry {
final String packageName;
final List<LicenseEntry> licenseEntries;
final Set<String> allPackageNames;
MergedLicenseEntry({
required this.packageName,
required this.licenseEntries,
required this.allPackageNames,
});
}
class LicensesScreen extends StatefulWidget {
const LicensesScreen({super.key});
@override
State<LicensesScreen> createState() => _LicensesScreenState();
}
class _LicensesScreenState extends State<LicensesScreen> {
List<MergedLicenseEntry> _mergedLicenses = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadLicenses();
}
Future<void> _loadLicenses() async {
final licenseMap = <String, List<LicenseEntry>>{};
final allPackageNames = <String, Set<String>>{};
await for (final license in LicenseRegistry.licenses) {
for (final packageName in license.packages) {
if (!licenseMap.containsKey(packageName)) {
licenseMap[packageName] = [];
allPackageNames[packageName] = <String>{};
}
licenseMap[packageName]!.add(license);
allPackageNames[packageName]!.addAll(license.packages);
}
}
final mergedLicenses = licenseMap.entries.map((entry) {
return MergedLicenseEntry(
packageName: entry.key,
licenseEntries: entry.value,
allPackageNames: allPackageNames[entry.key]!,
);
}).toList();
mergedLicenses.sort((a, b) => a.packageName.compareTo(b.packageName));
if (mounted) {
setState(() {
_mergedLicenses = mergedLicenses;
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Licenses'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final mergedLicense = _mergedLicenses[index];
final packageName = mergedLicense.packageName;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
title: Text(
packageName,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
subtitle: mergedLicense.licenseEntries.length > 1
? Text(
'${mergedLicense.licenseEntries.length} licenses',
)
: null,
trailing: const Icon(Icons.chevron_right),
onTap: () => _showLicenseDetail(mergedLicense),
),
);
}, childCount: _mergedLicenses.length),
),
),
],
),
);
}
void _showLicenseDetail(MergedLicenseEntry mergedLicense) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
_LicenseDetailScreen(mergedLicense: mergedLicense),
),
);
}
}
class _LicenseDetailScreen extends StatelessWidget {
final MergedLicenseEntry mergedLicense;
const _LicenseDetailScreen({required this.mergedLicense});
@override
Widget build(BuildContext context) {
final packageName = mergedLicense.packageName;
final licenseEntries = mergedLicense.licenseEntries;
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(title: Text(packageName), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
// Package info card
if (mergedLicense.allPackageNames.length > 1)
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Related Packages',
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
mergedLicense.allPackageNames.join(', '),
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
),
if (mergedLicense.allPackageNames.length > 1)
const SizedBox(height: 16),
// License cards
...licenseEntries.asMap().entries.map((entry) {
final index = entry.key;
final license = entry.value;
final isMultipleLicenses = licenseEntries.length > 1;
return Column(
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isMultipleLicenses
? 'License ${index + 1}'
: 'License',
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 16),
...license.paragraphs.map((paragraph) {
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: SelectableText(
paragraph.text,
style: TextStyle(
fontFamily: paragraph.indent > 0
? 'monospace'
: null,
fontSize: 14,
),
),
);
}),
],
),
),
),
if (index < licenseEntries.length - 1)
const SizedBox(height: 16),
],
);
}),
]),
),
),
],
),
);
}
}
+47 -7
View File
@@ -1,18 +1,18 @@
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_user_profile.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../main.dart';
import '../mixins/refreshable.dart';
import 'discover_screen.dart';
import 'libraries_screen.dart';
import 'search_screen.dart';
import 'settings_screen.dart';
class MainScreen extends StatefulWidget {
final PlexClient client;
final PlexUserProfile? userProfile;
const MainScreen({super.key, required this.client, this.userProfile});
const MainScreen({super.key, required this.client});
@override
State<MainScreen> createState() => _MainScreenState();
@@ -23,6 +23,9 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
late final List<Widget> _screens;
final GlobalKey<State<DiscoverScreen>> _discoverKey = GlobalKey();
final GlobalKey<State<LibrariesScreen>> _librariesKey = GlobalKey();
final GlobalKey<State<SearchScreen>> _searchKey = GlobalKey();
final GlobalKey<State<SettingsScreen>> _settingsKey = GlobalKey();
@override
void initState() {
@@ -31,13 +34,22 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
_screens = [
DiscoverScreen(
key: _discoverKey,
client: widget.client,
userProfile: widget.userProfile,
onBecameVisible: _onDiscoverBecameVisible,
),
LibrariesScreen(client: widget.client, userProfile: widget.userProfile),
SearchScreen(client: widget.client, userProfile: widget.userProfile),
LibrariesScreen(key: _librariesKey),
SearchScreen(key: _searchKey),
SettingsScreen(key: _settingsKey),
];
// Set up data invalidation callback for profile switching
WidgetsBinding.instance.addPostFrameCallback((_) async {
// Initialize UserProfileProvider to ensure it's ready after sign-in
final userProfileProvider = context.userProfile;
await userProfileProvider.initialize();
// Set up data invalidation callback for profile switching
userProfileProvider.setDataInvalidationCallback(_invalidateAllScreens);
});
}
@override
@@ -77,6 +89,29 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
}
}
/// Invalidate all cached data across all screens when profile is switched
void _invalidateAllScreens() {
appLogger.d('Invalidating all screen data due to profile switch');
// Refresh discover screen
final discoverState = _discoverKey.currentState;
if (discoverState != null && discoverState is Refreshable) {
(discoverState as Refreshable).refresh();
}
// Refresh libraries screen
final librariesState = _librariesKey.currentState;
if (librariesState != null && librariesState is Refreshable) {
(librariesState as Refreshable).refresh();
}
// Refresh search screen
final searchState = _searchKey.currentState;
if (searchState != null && searchState is Refreshable) {
(searchState as Refreshable).refresh();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -108,6 +143,11 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
selectedIcon: Icon(Icons.search),
label: 'Search',
),
NavigationDestination(
icon: Icon(Icons.settings_outlined),
selectedIcon: Icon(Icons.settings),
label: 'Settings',
),
],
),
);
+335 -218
View File
@@ -1,25 +1,22 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../client/plex_client.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
import '../widgets/media_context_menu.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/content_rating_formatter.dart';
import '../theme/theme_helper.dart';
import 'season_detail_screen.dart';
import 'video_player_screen.dart';
class MediaDetailScreen extends StatefulWidget {
final PlexClient client;
final PlexMetadata metadata;
final PlexUserProfile? userProfile;
const MediaDetailScreen({
super.key,
required this.client,
required this.metadata,
this.userProfile,
});
const MediaDetailScreen({super.key, required this.metadata});
@override
State<MediaDetailScreen> createState() => _MediaDetailScreenState();
@@ -31,21 +28,36 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
PlexMetadata? _fullMetadata;
PlexMetadata? _onDeckEpisode;
bool _isLoadingMetadata = true;
late final ScrollController _scrollController;
bool _watchStateChanged = false;
@override
void initState() {
super.initState();
_scrollController = ScrollController();
_loadFullMetadata();
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
Future<void> _loadFullMetadata() async {
setState(() {
_isLoadingMetadata = true;
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// Fetch full metadata with clearLogo and OnDeck episode
final result = await widget.client.getMetadataWithImagesAndOnDeck(
final result = await client.getMetadataWithImagesAndOnDeck(
widget.metadata.ratingKey,
);
final metadata = result['metadata'] as PlexMetadata?;
@@ -93,9 +105,13 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
});
try {
final seasons = await widget.client.getChildren(
widget.metadata.ratingKey,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final seasons = await client.getChildren(widget.metadata.ratingKey);
setState(() {
_seasons = seasons;
_isLoadingSeasons = false;
@@ -107,8 +123,50 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
}
}
/// Update watch state without full screen rebuild
/// This preserves scroll position and only updates watch-related data
Future<void> _updateWatchState() async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final metadata = await client.getMetadataWithImages(
widget.metadata.ratingKey,
);
if (metadata != null) {
// For shows, also refetch seasons to update their watch counts
List<PlexMetadata>? updatedSeasons;
if (metadata.type.toLowerCase() == 'show') {
updatedSeasons = await client.getChildren(widget.metadata.ratingKey);
}
// Single setState to minimize rebuilds - scroll position is preserved by controller
setState(() {
_fullMetadata = metadata;
if (updatedSeasons != null) {
_seasons = updatedSeasons;
}
});
}
} catch (e) {
appLogger.e('Failed to update watch state', error: e);
// Silently fail - user can manually refresh if needed
}
}
Future<void> _playFirstEpisode() async {
try {
// Extract context dependencies before async operations
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// If seasons aren't loaded yet, wait for them or load them
if (_seasons.isEmpty && !_isLoadingSeasons) {
await _loadSeasons();
@@ -132,7 +190,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
final firstSeason = _seasons.first;
// Get episodes of the first season
final episodes = await widget.client.getChildren(firstSeason.ratingKey);
final episodes = await client.getChildren(firstSeason.ratingKey);
if (episodes.isEmpty) {
if (mounted) {
@@ -146,17 +204,12 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
// Play the first episode
final firstEpisode = episodes.first;
if (mounted) {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Playing first episode: ${firstEpisode.title}');
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: firstEpisode,
userProfile: widget.userProfile,
),
),
);
await navigateToVideoPlayer(context, metadata: firstEpisode);
appLogger.d('Returned from playback, refreshing metadata');
// Refresh metadata when returning from video player
_loadFullMetadata();
@@ -191,24 +244,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(
@@ -216,19 +260,31 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
children: [
// Background Art
if (metadata.art != null)
CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(metadata.art),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(metadata.art),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
);
},
)
else
Container(
@@ -270,41 +326,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
SizedBox(
height: 120,
width: 400,
child: CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(
metadata.clearLogo,
),
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
placeholder: (context, url) => Align(
alignment: Alignment.centerLeft,
child: Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white.withValues(
alpha: 0.3,
),
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
errorWidget: (context, url, error) {
return Align(
alignment: Alignment.centerLeft,
child: Text(
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Text(
metadata.title,
style: Theme.of(context)
.textTheme
@@ -312,17 +338,66 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(alpha: 0.5),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
metadata.clearLogo,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
placeholder: (context, url) => Align(
alignment: Alignment.centerLeft,
child: Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white.withValues(
alpha: 0.3,
),
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(alpha: 0.5),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
errorWidget: (context, url, error) {
return Align(
alignment: Alignment.centerLeft,
child: Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
);
},
);
},
),
@@ -387,7 +462,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
borderRadius: BorderRadius.circular(6),
),
child: Text(
metadata.contentRating!,
formatContentRating(metadata.contentRating!),
style: const TextStyle(
color: Colors.white,
fontSize: 13,
@@ -447,18 +522,20 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
// Otherwise, play the first episode of the first season
if (metadata.type.toLowerCase() == 'show') {
if (_onDeckEpisode != null) {
appLogger.d('Playing on deck episode: ${_onDeckEpisode!.title}');
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: _onDeckEpisode!,
userProfile: widget.userProfile,
),
),
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d(
'Playing on deck episode: ${_onDeckEpisode!.title}',
);
await navigateToVideoPlayer(
context,
metadata: _onDeckEpisode!,
);
appLogger.d(
'Returned from playback, refreshing metadata',
);
appLogger.d('Returned from playback, refreshing metadata');
// Refresh metadata when returning from video player
_loadFullMetadata();
} else {
@@ -466,19 +543,19 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
await _playFirstEpisode();
}
} else {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Playing: ${metadata.title}');
// For movies or episodes, play directly
await Navigator.push(
await navigateToVideoPlayer(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: metadata,
userProfile: widget.userProfile,
),
),
metadata: metadata,
);
appLogger.d(
'Returned from playback, refreshing metadata',
);
appLogger.d('Returned from playback, refreshing metadata');
// Refresh metadata when returning from video player
_loadFullMetadata();
}
@@ -500,17 +577,20 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
IconButton.filledTonal(
onPressed: () async {
try {
await widget.client.markAsWatched(
metadata.ratingKey,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
await client.markAsWatched(metadata.ratingKey);
if (context.mounted) {
_watchStateChanged = true;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Marked as watched'),
),
);
// Refresh metadata to update UI
_loadFullMetadata();
// Update watch state without full rebuild
_updateWatchState();
}
} catch (e) {
if (context.mounted) {
@@ -532,17 +612,20 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
IconButton.filledTonal(
onPressed: () async {
try {
await widget.client.markAsUnwatched(
metadata.ratingKey,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
await client.markAsUnwatched(metadata.ratingKey);
if (context.mounted) {
_watchStateChanged = true;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Marked as unwatched'),
),
);
// Refresh metadata to update UI
_loadFullMetadata();
// Update watch state without full rebuild
_updateWatchState();
}
} catch (e) {
if (context.mounted) {
@@ -633,7 +716,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
const SizedBox(height: 12),
],
if (metadata.contentRating != null) ...[
_buildInfoRow('Rating', metadata.contentRating!),
_buildInfoRow('Rating', formatContentRating(metadata.contentRating!)),
const SizedBox(height: 12),
],
],
@@ -649,108 +732,142 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
return Card(
clipBehavior: Clip.antiAlias,
child: MediaContextMenu(
client: widget.client,
metadata: season,
onRefresh: _loadFullMetadata,
onTap: () {
Navigator.push(
onRefresh: (ratingKey) {
_watchStateChanged = true;
_updateWatchState();
},
onTap: () async {
final watchStateChanged = await Navigator.push<bool>(
context,
MaterialPageRoute(
builder: (context) =>
SeasonDetailScreen(client: widget.client, season: season),
builder: (context) => SeasonDetailScreen(season: season),
),
);
if (watchStateChanged == true) {
_watchStateChanged = true;
_updateWatchState();
}
},
child: InkWell(
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
// Season poster
if (season.thumb != null)
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(season.thumb),
width: 80,
height: 120,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
),
)
else
Container(
width: 80,
height: 120,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: Semantics(
label: "media-season-${season.ratingKey}",
identifier: "media-season-${season.ratingKey}",
button: true,
hint: "Tap to view ${season.title}",
child: InkWell(
child: Padding(
padding: const EdgeInsets.all(12),
child: Row(
children: [
// Season poster
if (season.thumb != null)
ClipRRect(
borderRadius: BorderRadius.circular(6),
),
child: const Icon(Icons.movie, size: 32),
),
const SizedBox(width: 16),
// Season info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
season.title,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
if (season.leafCount != null)
Text(
'${season.leafCount} episodes',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
),
const SizedBox(height: 8),
if (season.viewedLeafCount != null &&
season.leafCount != null)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
LinearProgressIndicator(
value:
season.viewedLeafCount! / season.leafCount!,
backgroundColor: Theme.of(
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(season.thumb),
width: 80,
height: 120,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
const SizedBox(height: 4),
Text(
'${season.viewedLeafCount}/${season.leafCount} watched',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(color: Colors.grey),
errorWidget: (context, url, error) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
],
),
],
),
),
);
},
),
)
else
Container(
width: 80,
height: 120,
decoration: BoxDecoration(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
),
child: const Icon(Icons.movie, size: 32),
),
const SizedBox(width: 16),
const Icon(Icons.chevron_right),
],
// Season info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
season.title,
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
if (season.leafCount != null)
Text(
'${season.leafCount} episodes',
style: Theme.of(context).textTheme.bodyMedium
?.copyWith(color: Colors.grey),
),
const SizedBox(height: 8),
if (season.viewedLeafCount != null &&
season.leafCount != null)
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 200,
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value:
season.viewedLeafCount! /
season.leafCount!,
backgroundColor: tokens(context).outline,
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary,
),
minHeight: 6,
),
),
),
const SizedBox(height: 4),
Text(
'${season.viewedLeafCount}/${season.leafCount} watched',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(color: Colors.grey),
),
],
),
],
),
),
const Icon(Icons.chevron_right),
],
),
),
),
),
+124
View File
@@ -0,0 +1,124 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/profile_list_tile.dart';
import '../widgets/desktop_app_bar.dart';
class ProfileSwitchScreen extends StatelessWidget {
const ProfileSwitchScreen({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Switch Profile')),
SliverFillRemaining(
child: Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
final users = userProvider.home?.users ?? [];
if (userProvider.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (userProvider.error != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
userProvider.error!,
style: TextStyle(color: theme.colorScheme.error),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
userProvider.refreshCurrentUser();
},
child: const Text('Retry'),
),
],
),
);
}
if (users.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.person_off,
size: 64,
color: theme.colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'No profiles available',
style: theme.textTheme.titleMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 8),
Text(
'Contact your Plex administrator to add profiles',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
],
),
);
}
return ListView.builder(
itemCount: users.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
final user = users[index];
final isCurrentUser =
user.uuid == userProvider.currentUser?.uuid;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Card(
child: ProfileListTile(
user: user,
isCurrentUser: isCurrentUser,
onTap: () => _switchToUser(context, user),
),
),
);
},
);
},
),
),
],
),
);
}
void _switchToUser(BuildContext context, PlexHomeUser user) async {
final userProvider = context.userProfile;
final success = await userProvider.switchToUser(user, context);
if (success && context.mounted) {
Navigator.of(context).pop();
} else if (!success && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to switch to ${user.displayName}'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
}
}
+88 -12
View File
@@ -1,28 +1,34 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../services/settings_service.dart';
import '../providers/settings_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../mixins/refreshable.dart';
import '../mixins/item_updatable.dart';
class SearchScreen extends StatefulWidget {
final PlexClient client;
final PlexUserProfile? userProfile;
const SearchScreen({super.key, required this.client, this.userProfile});
const SearchScreen({super.key});
@override
State<SearchScreen> createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> with Refreshable {
class _SearchScreenState extends State<SearchScreen>
with Refreshable, ItemUpdatable {
@override
PlexClient get client => context.clientSafe;
final _searchController = TextEditingController();
List<PlexMetadata> _searchResults = [];
bool _isSearching = false;
bool _hasSearched = false;
Timer? _debounceTimer;
String _lastSearchedQuery = '';
@override
void initState() {
@@ -49,10 +55,16 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
_searchResults = [];
_hasSearched = false;
_isSearching = false;
_lastSearchedQuery = '';
});
return;
}
// Only search if the query has actually changed
if (query.trim() == _lastSearchedQuery.trim()) {
return;
}
// Start new timer
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
_performSearch(query);
@@ -74,11 +86,18 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
});
try {
final results = await widget.client.search(query);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final results = await client.search(query);
if (mounted) {
setState(() {
_searchResults = results;
_isSearching = false;
_lastSearchedQuery = query.trim();
});
}
} catch (e) {
@@ -101,6 +120,16 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
}
}
@override
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
final index = _searchResults.indexWhere(
(item) => item.ratingKey == ratingKey,
);
if (index != -1) {
_searchResults[index] = updatedMetadata;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -187,8 +216,11 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverGrid(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 180,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: _getMaxCrossAxisExtent(
context,
context.watch<SettingsProvider>().libraryDensity,
),
childAspectRatio: 2 / 3.3,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
@@ -196,10 +228,9 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
delegate: SliverChildBuilderDelegate((context, index) {
final item = _searchResults[index];
return MediaCard(
client: widget.client,
key: Key(item.ratingKey),
item: item,
onRefresh: refresh,
userProfile: widget.userProfile,
onRefresh: updateItem,
);
}, childCount: _searchResults.length),
),
@@ -209,4 +240,49 @@ class _SearchScreenState extends State<SearchScreen> with Refreshable {
),
);
}
double _getMaxCrossAxisExtent(BuildContext context, LibraryDensity density) {
final screenWidth = MediaQuery.of(context).size.width;
final padding = 32.0; // 16px left + 16px right from SliverPadding
final availableWidth = screenWidth - padding;
if (screenWidth >= 900) {
// Wide screens (desktop/large tablet landscape): Responsive division
double divisor;
double maxItemWidth;
switch (density) {
case LibraryDensity.comfortable:
divisor = 6.5;
maxItemWidth = 280;
break;
case LibraryDensity.normal:
divisor = 8.0;
maxItemWidth = 200;
break;
case LibraryDensity.compact:
divisor = 10.0;
maxItemWidth = 160;
break;
}
return (availableWidth / divisor).clamp(0, maxItemWidth);
} else if (screenWidth >= 600) {
// Medium screens (tablets): Fixed 4-5-6 items
int targetItemCount = switch (density) {
LibraryDensity.comfortable => 4,
LibraryDensity.normal => 5,
LibraryDensity.compact => 6,
};
return availableWidth / targetItemCount;
} else {
// Small screens (phones): Fixed 2-3-4 items
int targetItemCount = switch (density) {
LibraryDensity.comfortable => 2,
LibraryDensity.normal => 3,
LibraryDensity.compact => 4,
};
return availableWidth / targetItemCount;
}
}
}
+142 -129
View File
@@ -1,30 +1,33 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../widgets/desktop_app_bar.dart';
import 'video_player_screen.dart';
import '../widgets/media_context_menu.dart';
import '../mixins/item_updatable.dart';
import '../theme/theme_helper.dart';
class SeasonDetailScreen extends StatefulWidget {
final PlexClient client;
final PlexMetadata season;
final PlexUserProfile? userProfile;
const SeasonDetailScreen({
super.key,
required this.client,
required this.season,
this.userProfile,
});
const SeasonDetailScreen({super.key, required this.season});
@override
State<SeasonDetailScreen> createState() => _SeasonDetailScreenState();
}
class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
class _SeasonDetailScreenState extends State<SeasonDetailScreen>
with ItemUpdatable {
@override
PlexClient get client => context.clientSafe;
List<PlexMetadata> _episodes = [];
bool _isLoadingEpisodes = false;
bool _watchStateChanged = false;
@override
void initState() {
@@ -38,7 +41,13 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
});
try {
final episodes = await widget.client.getChildren(widget.season.ratingKey);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final episodes = await client.getChildren(widget.season.ratingKey);
setState(() {
_episodes = episodes;
_isLoadingEpisodes = false;
@@ -50,26 +59,29 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
}
}
@override
Future<void> updateItem(String ratingKey) async {
_watchStateChanged = true;
await super.updateItem(ratingKey);
}
@override
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
final index = _episodes.indexWhere((item) => item.ratingKey == ratingKey);
if (index != -1) {
_episodes[index] = updatedMetadata;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
DesktopSliverAppBar(
CustomAppBar(
title: Text(widget.season.title),
pinned: true,
leading: 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,
),
),
onBackPressed: () => Navigator.pop(context, _watchStateChanged),
),
if (_isLoadingEpisodes)
const SliverFillRemaining(
@@ -81,35 +93,28 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icon(
Icons.movie_outlined,
size: 64,
color: Colors.grey,
color: tokens(context).textMuted,
),
const SizedBox(height: 16),
Text(
'No episodes found',
style: Theme.of(
context,
).textTheme.titleLarge?.copyWith(color: Colors.grey),
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: tokens(context).textMuted,
),
),
],
),
),
)
else
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
if (index.isOdd) {
return const SizedBox(height: 12);
}
final episodeIndex = index ~/ 2;
final episode = _episodes[episodeIndex];
return _buildEpisodeCard(episode);
}, childCount: _episodes.length * 2 - 1),
),
SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final episode = _episodes[index];
return _buildEpisodeCard(episode);
}, childCount: _episodes.length),
),
],
),
@@ -125,25 +130,26 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
? episode.viewOffset! / episode.duration!
: 0.0;
return Card(
clipBehavior: Clip.antiAlias,
return MediaContextMenu(
metadata: episode,
onRefresh: updateItem,
onTap: () async {
await navigateToVideoPlayer(context, metadata: episode);
// Refresh episodes when returning from video player
_loadEpisodes();
},
child: InkWell(
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: episode,
userProfile: widget.userProfile,
),
key: Key(episode.ratingKey),
hoverColor: Theme.of(
context,
).colorScheme.surface.withValues(alpha: 0.05),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: tokens(context).outline, width: 0.5),
),
);
// Refresh episodes when returning from video player
_loadEpisodes();
},
child: Padding(
padding: const EdgeInsets.all(12),
),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -157,22 +163,42 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
child: AspectRatio(
aspectRatio: 16 / 9,
child: episode.thumb != null
? CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(
episode.thumb,
),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
? Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Center(
child: Icon(Icons.movie, size: 40),
),
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
episode.thumb,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) =>
Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(
Icons.movie,
size: 32,
),
),
);
},
)
: Container(
color: Theme.of(
@@ -214,31 +240,6 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
),
),
// Watched indicator
if (episode.isWatched)
Positioned(
top: 4,
right: 4,
child: Container(
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: Colors.green,
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.3),
blurRadius: 4,
),
],
),
child: const Icon(
Icons.check,
color: Colors.white,
size: 12,
),
),
),
// Progress bar at bottom
if (hasProgress && !episode.isWatched)
Positioned(
@@ -252,36 +253,11 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
),
child: LinearProgressIndicator(
value: progress,
backgroundColor: Colors.grey.withValues(alpha: 0.3),
backgroundColor: tokens(context).outline,
minHeight: 3,
),
),
),
// Duration badge
if (episode.duration != null)
Positioned(
bottom: 4,
right: 4,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 2,
),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(3),
),
child: Text(
_formatDuration(episode.duration!),
style: const TextStyle(
color: Colors.white,
fontSize: 10,
fontWeight: FontWeight.w600,
),
),
),
),
],
),
),
@@ -339,13 +315,50 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen> {
Text(
episode.summary!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.grey,
color: tokens(context).textMuted,
height: 1.3,
),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
],
// Metadata row (duration, watched status)
const SizedBox(height: 8),
Row(
children: [
if (episode.duration != null)
Text(
_formatDuration(episode.duration!),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
if (episode.duration != null && episode.isWatched) ...[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Text(
'•',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
),
Text(
'Watched ✓',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
],
],
),
],
),
),
@@ -363,9 +376,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')}';
}
}
}
+158 -73
View File
@@ -1,9 +1,11 @@
import 'package:flutter/material.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../client/plex_client.dart';
import '../config/plex_config.dart';
import '../services/server_connection_service.dart';
import '../widgets/server_list_tile.dart';
import '../widgets/desktop_app_bar.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import 'main_screen.dart';
class ServerSelectionScreen extends StatefulWidget {
@@ -24,13 +26,26 @@ class _ServerSelectionScreenState extends State<ServerSelectionScreen> {
List<PlexServer>? _servers;
bool _isLoading = true;
String? _errorMessage;
String? _currentServerUrl;
@override
void initState() {
super.initState();
_loadCurrentServerUrl();
_loadServers();
}
Future<void> _loadCurrentServerUrl() async {
try {
final storage = await StorageService.getInstance();
setState(() {
_currentServerUrl = storage.getServerUrl();
});
} catch (e) {
appLogger.w('Failed to load current server URL', error: e);
}
}
Future<void> _loadServers() async {
try {
final servers = await widget.authService.fetchServers(widget.plexToken);
@@ -58,100 +73,170 @@ class _ServerSelectionScreenState extends State<ServerSelectionScreen> {
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text('Testing connections...'),
Text('Connecting to server...'),
],
),
),
);
}
// Test connections to find best working one
final connection = await server.findBestWorkingConnection();
try {
// Get client identifier and storage
final storage = await StorageService.getInstance();
final clientId =
storage.getClientIdentifier() ?? widget.authService.clientIdentifier;
// Close loading dialog
if (mounted) {
Navigator.pop(context);
}
// Get current profile context to maintain profile across server switch
final currentUserUUID = storage.getCurrentUserUUID();
if (connection == null) {
PlexServer serverWithCorrectToken = server;
// If we have a current profile, get a profile-specific token for this server
if (currentUserUUID != null) {
try {
// Switch to the current profile on the new server to get the correct token
final switchResponse = await widget.authService.switchToUser(
currentUserUUID,
widget.plexToken,
);
// Get servers with the profile's Plex.tv token to get profile-specific server tokens
final servers = await widget.authService.fetchServers(
switchResponse.authToken,
);
// Find the matching server with the profile-specific token
final matchingServer = servers.firstWhere(
(s) =>
s.name == server.name ||
s.clientIdentifier == server.clientIdentifier,
orElse: () => server, // Fallback to original server
);
serverWithCorrectToken = matchingServer;
appLogger.d(
'Got profile-specific token for server ${server.name} and user UUID $currentUserUUID',
);
} catch (e) {
appLogger.w(
'Failed to get profile-specific token, using default server token',
error: e,
);
// Continue with original server token as fallback
}
}
// Connect using the server with the correct token
final result = await ServerConnectionService.connectToServer(
serverWithCorrectToken,
clientIdentifier: clientId,
plexToken: widget.plexToken,
);
// Close loading dialog
if (mounted) {
Navigator.pop(context);
}
// Handle result
if (result.isSuccess) {
// Set client in provider before navigation (same pattern as auto-login)
if (mounted) {
context.plexClient.setClient(result.client!);
// Navigate to main app and clear navigation stack
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: result.client!),
),
(route) => false, // Remove all routes
);
}
} else {
// Show error
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(result.error ?? 'Connection failed')),
);
}
}
} catch (e) {
// Close loading dialog on error
if (mounted) {
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('No working connections found for this server'),
),
SnackBar(content: Text('Failed to connect to server: $e')),
);
}
return;
appLogger.e('Server selection failed', error: e);
}
}
// Store server information
final storage = await StorageService.getInstance();
await storage.saveServerData(server.toJson());
await storage.saveServerUrl(connection.uri);
await storage.saveServerAccessToken(server.accessToken);
await storage.savePlexToken(widget.plexToken);
bool _isCurrentServer(PlexServer server) {
if (_currentServerUrl == null) return false;
// Get client identifier
final clientId =
storage.getClientIdentifier() ?? widget.authService.clientIdentifier;
// Create client and navigate to main app
final config = await PlexConfig.create(
baseUrl: connection.uri,
token: server.accessToken,
clientIdentifier: clientId,
);
final client = PlexClient(config);
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => MainScreen(client: client)),
);
// Check all server connections to see if any match the current server URL
for (final connection in server.connections) {
if (connection.uri == _currentServerUrl) {
return true;
}
}
return false;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Select Server')),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_errorMessage!,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Select Server')),
SliverFillRemaining(
child: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_errorMessage!,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadServers,
child: const Text('Retry'),
),
],
),
textAlign: TextAlign.center,
)
: _servers == null || _servers!.isEmpty
? const Center(child: Text('No servers found'))
: ListView.builder(
itemCount: _servers!.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
final server = _servers![index];
final isCurrentServer = _isCurrentServer(server);
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Card(
child: ServerListTile(
server: server,
isCurrentServer: isCurrentServer,
onTap: () => _selectServer(server),
),
),
);
},
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadServers,
child: const Text('Retry'),
),
],
),
)
: _servers == null || _servers!.isEmpty
? const Center(child: Text('No servers found'))
: ListView.builder(
itemCount: _servers!.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
final server = _servers![index];
return Card(
child: ServerListTile(
server: server,
onTap: () => _selectServer(server),
),
);
},
),
),
],
),
);
}
}
+814
View File
@@ -0,0 +1,814 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import '../providers/theme_provider.dart';
import '../providers/settings_provider.dart';
import '../services/settings_service.dart' as settings;
import '../services/keyboard_shortcuts_service.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/hotkey_recorder_widget.dart';
import 'about_screen.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
late settings.SettingsService _settingsService;
late KeyboardShortcutsService _keyboardService;
bool _isLoading = true;
bool _enableDebugLogging = false;
bool _enableHardwareDecoding = true;
int _bufferSize = 128;
int _seekTimeSmall = 10;
int _seekTimeLarge = 30;
@override
void initState() {
super.initState();
_loadSettings();
}
Future<void> _loadSettings() async {
_settingsService = await settings.SettingsService.getInstance();
_keyboardService = await KeyboardShortcutsService.getInstance();
setState(() {
_enableDebugLogging = _settingsService.getEnableDebugLogging();
_enableHardwareDecoding = _settingsService.getEnableHardwareDecoding();
_bufferSize = _settingsService.getBufferSize();
_seekTimeSmall = _settingsService.getSeekTimeSmall();
_seekTimeLarge = _settingsService.getSeekTimeLarge();
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Settings'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildAppearanceSection(),
const SizedBox(height: 24),
_buildVideoPlaybackSection(),
const SizedBox(height: 24),
_buildKeyboardShortcutsSection(),
const SizedBox(height: 24),
_buildAdvancedSection(),
const SizedBox(height: 24),
_buildAboutSection(),
const SizedBox(height: 24),
]),
),
),
],
),
);
}
Widget _buildAppearanceSection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Appearance',
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
Consumer<ThemeProvider>(
builder: (context, themeProvider, child) {
return ListTile(
leading: Icon(themeProvider.themeModeIcon),
title: const Text('Theme'),
subtitle: Text(themeProvider.themeModeDisplayName),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showThemeDialog(themeProvider),
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return ListTile(
leading: const Icon(Icons.grid_view),
title: const Text('Library Density'),
subtitle: Text(settingsProvider.libraryDensityDisplayName),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showLibraryDensityDialog(),
);
},
),
Consumer<SettingsProvider>(
builder: (context, settingsProvider, child) {
return SwitchListTile(
secondary: const Icon(Icons.image),
title: const Text('Use Season Posters'),
subtitle: const Text(
'Show season poster instead of series poster for episodes',
),
value: settingsProvider.useSeasonPoster,
onChanged: (value) async {
await settingsProvider.setUseSeasonPoster(value);
},
);
},
),
],
),
);
}
Widget _buildVideoPlaybackSection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Video Playback',
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
SwitchListTile(
secondary: const Icon(Icons.hardware),
title: const Text('Hardware Decoding'),
subtitle: const Text('Use hardware acceleration when available'),
value: _enableHardwareDecoding,
onChanged: (value) async {
setState(() {
_enableHardwareDecoding = value;
});
await _settingsService.setEnableHardwareDecoding(value);
},
),
ListTile(
leading: const Icon(Icons.memory),
title: const Text('Buffer Size'),
subtitle: Text('${_bufferSize}MB'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showBufferSizeDialog(),
),
ListTile(
leading: const Icon(Icons.replay_10),
title: const Text('Small Skip Duration'),
subtitle: Text('$_seekTimeSmall seconds'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showSeekTimeSmallDialog(),
),
ListTile(
leading: const Icon(Icons.replay_30),
title: const Text('Large Skip Duration'),
subtitle: Text('$_seekTimeLarge seconds'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showSeekTimeLargeDialog(),
),
],
),
);
}
Widget _buildKeyboardShortcutsSection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Keyboard Shortcuts',
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
ListTile(
leading: const Icon(Icons.keyboard),
title: const Text('Video Player Controls'),
subtitle: const Text('Customize keyboard shortcuts'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showKeyboardShortcutsDialog(),
),
],
),
);
}
Widget _buildAdvancedSection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Advanced',
style: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
),
),
SwitchListTile(
secondary: const Icon(Icons.bug_report),
title: const Text('Debug Logging'),
subtitle: const Text('Enable detailed logging for troubleshooting'),
value: _enableDebugLogging,
onChanged: (value) async {
setState(() {
_enableDebugLogging = value;
});
await _settingsService.setEnableDebugLogging(value);
},
),
ListTile(
leading: const Icon(Icons.cleaning_services),
title: const Text('Clear Cache'),
subtitle: const Text('Free up storage space'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showClearCacheDialog(),
),
ListTile(
leading: const Icon(Icons.restore),
title: const Text('Reset Settings'),
subtitle: const Text('Reset all settings to defaults'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showResetSettingsDialog(),
),
],
),
);
}
Widget _buildAboutSection() {
return Card(
child: ListTile(
leading: const Icon(Icons.info),
title: const Text('About'),
subtitle: const Text('App information and licenses'),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const AboutScreen()),
);
},
),
);
}
void _showThemeDialog(ThemeProvider themeProvider) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Theme'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: Icon(
themeProvider.themeMode == settings.ThemeMode.system
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('System'),
subtitle: const Text('Follow system settings'),
onTap: () {
themeProvider.setThemeMode(settings.ThemeMode.system);
Navigator.pop(context);
},
),
ListTile(
leading: Icon(
themeProvider.themeMode == settings.ThemeMode.light
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('Light'),
onTap: () {
themeProvider.setThemeMode(settings.ThemeMode.light);
Navigator.pop(context);
},
),
ListTile(
leading: Icon(
themeProvider.themeMode == settings.ThemeMode.dark
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('Dark'),
onTap: () {
themeProvider.setThemeMode(settings.ThemeMode.dark);
Navigator.pop(context);
},
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
],
);
},
);
}
void _showBufferSizeDialog() {
final options = [64, 128, 256, 512, 1024];
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Buffer Size'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: options.map((size) {
return ListTile(
leading: Icon(
_bufferSize == size
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: Text('${size}MB'),
onTap: () {
setState(() {
_bufferSize = size;
_settingsService.setBufferSize(size);
});
Navigator.pop(context);
},
);
}).toList(),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
],
);
},
);
}
void _showSeekTimeSmallDialog() {
final controller = TextEditingController(text: _seekTimeSmall.toString());
String? errorText;
showDialog(
context: context,
builder: (BuildContext dialogContext) {
return StatefulBuilder(
builder: (context, setDialogState) {
return AlertDialog(
title: const Text('Small Skip Duration'),
content: TextField(
controller: controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Seconds',
hintText: 'Enter duration (1-120)',
errorText: errorText,
suffixText: 's',
),
autofocus: true,
onChanged: (value) {
final parsed = int.tryParse(value);
setDialogState(() {
if (parsed == null) {
errorText = 'Please enter a valid number';
} else if (parsed < 1 || parsed > 120) {
errorText = 'Duration must be between 1 and 120 seconds';
} else {
errorText = null;
}
});
},
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('Cancel'),
),
TextButton(
onPressed: () async {
final parsed = int.tryParse(controller.text);
if (parsed != null && parsed >= 1 && parsed <= 120) {
setState(() {
_seekTimeSmall = parsed;
_settingsService.setSeekTimeSmall(parsed);
});
// Reload keyboard shortcuts service to use new settings
await _keyboardService.refreshFromStorage();
if (dialogContext.mounted) {
Navigator.pop(dialogContext);
}
}
},
child: const Text('Save'),
),
],
);
},
);
},
);
}
void _showSeekTimeLargeDialog() {
final controller = TextEditingController(text: _seekTimeLarge.toString());
String? errorText;
showDialog(
context: context,
builder: (BuildContext dialogContext) {
return StatefulBuilder(
builder: (context, setDialogState) {
return AlertDialog(
title: const Text('Large Skip Duration'),
content: TextField(
controller: controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Seconds',
hintText: 'Enter duration (1-120)',
errorText: errorText,
suffixText: 's',
),
autofocus: true,
onChanged: (value) {
final parsed = int.tryParse(value);
setDialogState(() {
if (parsed == null) {
errorText = 'Please enter a valid number';
} else if (parsed < 1 || parsed > 120) {
errorText = 'Duration must be between 1 and 120 seconds';
} else {
errorText = null;
}
});
},
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: const Text('Cancel'),
),
TextButton(
onPressed: () async {
final parsed = int.tryParse(controller.text);
if (parsed != null && parsed >= 1 && parsed <= 120) {
setState(() {
_seekTimeLarge = parsed;
_settingsService.setSeekTimeLarge(parsed);
});
// Reload keyboard shortcuts service to use new settings
await _keyboardService.refreshFromStorage();
if (dialogContext.mounted) {
Navigator.pop(dialogContext);
}
}
},
child: const Text('Save'),
),
],
);
},
);
},
);
}
void _showKeyboardShortcutsDialog() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
_KeyboardShortcutsScreen(keyboardService: _keyboardService),
),
);
}
void _showClearCacheDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Clear Cache'),
content: const Text(
'This will clear all cached images and data. The app may take longer to load content after clearing the cache.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
TextButton(
onPressed: () async {
final navigator = Navigator.of(context);
final messenger = ScaffoldMessenger.of(context);
await _settingsService.clearCache();
if (mounted) {
navigator.pop();
messenger.showSnackBar(
const SnackBar(content: Text('Cache cleared successfully')),
);
}
},
child: const Text('Clear'),
),
],
);
},
);
}
void _showResetSettingsDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Reset Settings'),
content: const Text(
'This will reset all settings to their default values. This action cannot be undone.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
TextButton(
onPressed: () async {
final navigator = Navigator.of(context);
final messenger = ScaffoldMessenger.of(context);
await _settingsService.resetAllSettings();
await _keyboardService.resetToDefaults();
if (mounted) {
navigator.pop();
messenger.showSnackBar(
const SnackBar(
content: Text('Settings reset successfully'),
),
);
// Reload settings
_loadSettings();
}
},
child: const Text('Reset'),
),
],
);
},
);
}
void _showLibraryDensityDialog() {
final settingsProvider = context.read<SettingsProvider>();
showDialog(
context: context,
builder: (BuildContext context) {
return Consumer<SettingsProvider>(
builder: (context, provider, child) {
return AlertDialog(
title: const Text('Library Density'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: Icon(
provider.libraryDensity == settings.LibraryDensity.compact
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('Compact'),
subtitle: const Text('Smaller cards, more items visible'),
onTap: () async {
await settingsProvider.setLibraryDensity(
settings.LibraryDensity.compact,
);
if (context.mounted) Navigator.pop(context);
},
),
ListTile(
leading: Icon(
provider.libraryDensity == settings.LibraryDensity.normal
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('Normal'),
subtitle: const Text('Default size'),
onTap: () async {
await settingsProvider.setLibraryDensity(
settings.LibraryDensity.normal,
);
if (context.mounted) Navigator.pop(context);
},
),
ListTile(
leading: Icon(
provider.libraryDensity ==
settings.LibraryDensity.comfortable
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('Comfortable'),
subtitle: const Text('Larger cards, fewer items visible'),
onTap: () async {
await settingsProvider.setLibraryDensity(
settings.LibraryDensity.comfortable,
);
if (context.mounted) Navigator.pop(context);
},
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
],
);
},
);
},
);
}
}
class _KeyboardShortcutsScreen extends StatefulWidget {
final KeyboardShortcutsService keyboardService;
const _KeyboardShortcutsScreen({required this.keyboardService});
@override
State<_KeyboardShortcutsScreen> createState() =>
_KeyboardShortcutsScreenState();
}
class _KeyboardShortcutsScreenState extends State<_KeyboardShortcutsScreen> {
Map<String, HotKey> _hotkeys = {};
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadHotkeys();
}
Future<void> _loadHotkeys() async {
await widget.keyboardService.refreshFromStorage();
setState(() {
_hotkeys = widget.keyboardService.hotkeys;
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(body: Center(child: CircularProgressIndicator()));
}
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: const Text('Keyboard Shortcuts'),
pinned: true,
actions: [
TextButton(
onPressed: () async {
final messenger = ScaffoldMessenger.of(context);
await widget.keyboardService.resetToDefaults();
await _loadHotkeys();
if (mounted) {
messenger.showSnackBar(
const SnackBar(
content: Text('Shortcuts reset to defaults'),
),
);
}
},
child: const Text('Reset'),
),
],
),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
final actions = _hotkeys.keys.toList();
final action = actions[index];
final hotkey = _hotkeys[action]!;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
title: Text(
widget.keyboardService.getActionDisplayName(action),
),
subtitle: Text(action),
trailing: Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
border: Border.all(
color: Theme.of(context).dividerColor,
),
borderRadius: BorderRadius.circular(6),
),
child: Text(
widget.keyboardService.formatHotkey(hotkey),
style: const TextStyle(fontFamily: 'monospace'),
),
),
onTap: () => _editHotkey(action, hotkey),
),
);
}, childCount: _hotkeys.length),
),
),
],
),
);
}
void _editHotkey(String action, HotKey currentHotkey) {
showDialog(
context: context,
builder: (BuildContext context) {
return HotKeyRecorderWidget(
actionName: widget.keyboardService.getActionDisplayName(action),
currentHotKey: currentHotkey,
onHotKeyRecorded: (newHotkey) async {
final navigator = Navigator.of(context);
final messenger = ScaffoldMessenger.of(context);
// Check for conflicts
final existingAction = widget.keyboardService.getActionForHotkey(
newHotkey,
);
if (existingAction != null && existingAction != action) {
navigator.pop();
messenger.showSnackBar(
SnackBar(
content: Text(
'Shortcut already assigned to ${widget.keyboardService.getActionDisplayName(existingAction)}',
),
),
);
return;
}
// Save the new hotkey
await widget.keyboardService.setHotkey(action, newHotkey);
if (mounted) {
// Update UI directly instead of reloading from storage
setState(() {
_hotkeys[action] = newHotkey;
});
navigator.pop();
messenger.showSnackBar(
SnackBar(
content: Text(
'Shortcut updated for ${widget.keyboardService.getActionDisplayName(action)}',
),
),
);
}
},
onCancel: () => Navigator.pop(context),
);
},
);
}
}
+288 -152
View File
@@ -3,27 +3,33 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/plex_video_controls.dart';
import '../utils/language_codes.dart';
import '../utils/app_logger.dart';
import '../services/settings_service.dart';
import '../utils/orientation_helper.dart';
import '../utils/video_player_navigation.dart';
import '../utils/platform_detector.dart';
import '../models/plex_media_version.dart';
class VideoPlayerScreen extends StatefulWidget {
final PlexClient client;
final PlexMetadata metadata;
final AudioTrack? preferredAudioTrack;
final SubtitleTrack? preferredSubtitleTrack;
final PlexUserProfile? userProfile;
final double? preferredPlaybackRate;
final int selectedMediaIndex;
const VideoPlayerScreen({
super.key,
required this.client,
required this.metadata,
this.preferredAudioTrack,
this.preferredSubtitleTrack,
this.userProfile,
this.preferredPlaybackRate,
this.selectedMediaIndex = 0,
});
@override
@@ -31,22 +37,23 @@ class VideoPlayerScreen extends StatefulWidget {
}
class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
late final Player player;
late final VideoController controller;
Player? player;
VideoController? controller;
bool _isPlayerInitialized = false;
Timer? _progressTimer;
PlexMetadata? _nextEpisode;
PlexMetadata? _previousEpisode;
bool _isLoadingNext = false;
bool _showPlayNextDialog = false;
PlexClientProvider? _cachedClientProvider;
bool _isPhone = false;
List<PlexMediaVersion> _availableVersions = [];
@override
void initState() {
super.initState();
appLogger.d('VideoPlayerScreen initialized for: ${widget.metadata.title}');
if (widget.userProfile != null) {
appLogger.d('Using user profile for track selection');
}
if (widget.preferredAudioTrack != null) {
appLogger.d(
'Preferred audio track: ${widget.preferredAudioTrack!.title ?? widget.preferredAudioTrack!.id} (${widget.preferredAudioTrack!.language ?? "unknown"})',
@@ -59,42 +66,101 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
appLogger.d('Preferred subtitle track: $subtitleDesc');
}
// Create player and controller
player = Player(configuration: PlayerConfiguration(libass: true));
controller = VideoController(player);
// Get the video URL and start playback
_startPlayback();
// Set fullscreen mode and landscape orientation
_setLandscapeOrientation();
// Listen to playback state changes
player.stream.playing.listen(_onPlayingStateChanged);
// Listen to completion
player.stream.completed.listen(_onVideoCompleted);
// Start periodic progress updates
_startProgressTracking();
// Load next/previous episodes
_loadAdjacentEpisodes();
// Initialize player asynchronously with buffer size from settings
_initializePlayer();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Ensure landscape orientation is set even after navigation
_setLandscapeOrientation();
// Cache provider reference for safe access in dispose()
try {
_cachedClientProvider = context.plexClient;
} catch (e) {
appLogger.w('Failed to cache PlexClientProvider', error: e);
_cachedClientProvider = null;
}
// Cache device type for safe access in dispose()
try {
_isPhone = PlatformDetector.isPhone(context);
} catch (e) {
appLogger.w('Failed to determine device type', error: e);
_isPhone = false; // Default to tablet/desktop (all orientations)
}
}
void _setLandscapeOrientation() {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
OrientationHelper.setLandscapeOrientation();
}
Future<void> _initializePlayer() async {
try {
// Load buffer size from settings
final settingsService = await SettingsService.getInstance();
final bufferSizeMB = settingsService.getBufferSize();
final bufferSizeBytes = bufferSizeMB * 1024 * 1024;
final enableHardwareDecoding = settingsService.getEnableHardwareDecoding();
// Create player with configuration
player = Player(
configuration: PlayerConfiguration(
libass: true,
libassAndroidFont: 'assets/droid-sans.ttf',
libassAndroidFontName: 'Droid Sans Fallback',
bufferSize: bufferSizeBytes,
),
);
controller = VideoController(
player!,
configuration: VideoControllerConfiguration(
enableHardwareAcceleration: enableHardwareDecoding,
),
);
// Notify that player is ready
if (mounted) {
setState(() {
_isPlayerInitialized = true;
});
}
// Get the video URL and start playback
_startPlayback();
// Load available media versions
_loadMediaVersions();
// Set fullscreen mode and landscape orientation
if (mounted) {
try {
_setLandscapeOrientation();
} catch (e) {
appLogger.w('Failed to set landscape orientation', error: e);
// Don't crash if orientation fails - video can still play
}
}
// Listen to playback state changes
player!.stream.playing.listen(_onPlayingStateChanged);
// Listen to completion
player!.stream.completed.listen(_onVideoCompleted);
// Start periodic progress updates
_startProgressTracking();
// Load next/previous episodes
_loadAdjacentEpisodes();
} catch (e) {
appLogger.e('Failed to initialize player', error: e);
if (mounted) {
setState(() {
_isPlayerInitialized = false;
});
}
}
}
Future<void> _loadAdjacentEpisodes() async {
@@ -103,8 +169,12 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
try {
final next = await widget.client.getNextEpisode(widget.metadata);
final previous = await widget.client.getPreviousEpisode(widget.metadata);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final next = await client.findAdjacentEpisode(widget.metadata, 1);
final previous = await client.findAdjacentEpisode(widget.metadata, -1);
if (mounted) {
setState(() {
@@ -119,18 +189,25 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
Future<void> _startPlayback() async {
try {
// Get the direct file URL from the server
final videoUrl = await widget.client.getVideoUrl(
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// Get the direct file URL from the server using the selected media index
final videoUrl = await client.getVideoUrl(
widget.metadata.ratingKey,
mediaIndex: widget.selectedMediaIndex,
);
if (videoUrl != null) {
// Open video without auto-playing
await player.open(Media(videoUrl), play: false);
await player!.open(Media(videoUrl), play: false);
// Wait for media to be ready (duration > 0)
int attempts = 0;
while (player.state.duration.inMilliseconds == 0 && attempts < 50) {
while (player!.state.duration.inMilliseconds == 0 && attempts < 100) {
await Future.delayed(const Duration(milliseconds: 100));
attempts++;
}
@@ -141,11 +218,11 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
final resumePosition = Duration(
milliseconds: widget.metadata.viewOffset!,
);
await player.seek(resumePosition);
await player!.seek(resumePosition);
}
// Start playback after seeking
await player.play();
await player!.play();
// Wait for tracks to be loaded, then apply preferred tracks
_waitForTracksAndApply();
@@ -165,6 +242,24 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
}
/// Load available media versions for this item
Future<void> _loadMediaVersions() async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final versions = await client.getMediaVersions(widget.metadata.ratingKey);
if (mounted) {
setState(() {
_availableVersions = versions;
});
}
} catch (e) {
appLogger.e('Error loading media versions: $e');
}
}
@override
void dispose() {
// Stop progress tracking
@@ -173,59 +268,87 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Send final stopped state
_sendProgress('stopped');
// Restore system UI
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
// Restore portrait-only orientation
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
// Restore system UI and orientation preferences
OrientationHelper.restoreSystemUI();
player.dispose();
// Restore orientation based on cached device type (no context needed)
try {
if (_isPhone) {
// Phone: portrait only
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
} else {
// Tablet/Desktop: all orientations
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
} catch (e) {
appLogger.w('Failed to restore orientation in dispose', error: e);
}
player?.dispose();
super.dispose();
}
void _startProgressTracking() {
// Send progress update every 10 seconds
_progressTimer = Timer.periodic(const Duration(seconds: 10), (timer) {
if (player.state.playing) {
if (player?.state.playing ?? false) {
_sendProgress('playing');
}
});
}
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 +356,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 +418,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(
@@ -398,6 +508,9 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
Future<void> processTracks(Tracks tracks) async {
appLogger.d('Starting track selection process');
// Get profile settings for track selection
final profileSettings = context.profileSettings;
// Get real tracks (excluding auto and no)
final realAudioTracks = tracks.audio
.where((t) => t.id != 'auto' && t.id != 'no')
@@ -444,11 +557,11 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
// Priority 2: If no preferred track matched, try user profile preferences
if (trackToSelect == null && widget.userProfile != null) {
if (trackToSelect == null && profileSettings != null) {
appLogger.d('Priority 2: Checking user profile preferences');
trackToSelect = _findAudioTrackByProfile(
realAudioTracks,
widget.userProfile!,
profileSettings,
);
} else if (trackToSelect == null) {
appLogger.d('Priority 2: No user profile available');
@@ -470,7 +583,7 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
appLogger.i(
'Final audio selection: ${trackToSelect.title ?? "Track ${trackToSelect.id}"} (${trackToSelect.language ?? "unknown"})',
);
player.setAudioTrack(trackToSelect);
player!.setAudioTrack(trackToSelect);
} else {
appLogger.d('No audio tracks available');
}
@@ -506,12 +619,12 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Priority 2: If no preferred match, apply user profile preferences
if (subtitleToSelect == null &&
widget.userProfile != null &&
profileSettings != null &&
realSubtitleTracks.isNotEmpty) {
appLogger.d('Priority 2: Checking user profile preferences');
subtitleToSelect = _findSubtitleTrackByProfile(
realSubtitleTracks,
widget.userProfile!,
profileSettings,
);
} else if (subtitleToSelect == null && realSubtitleTracks.isNotEmpty) {
appLogger.d('Priority 2: No user profile available');
@@ -543,13 +656,21 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
? 'OFF'
: '${subtitleToSelect.title ?? "Track ${subtitleToSelect.id}"} (${subtitleToSelect.language ?? "unknown"})';
appLogger.i('Final subtitle selection: $finalSubtitle');
player.setSubtitleTrack(subtitleToSelect);
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');
}
// Check if tracks are already available in current state
final currentTracks = player.state.tracks;
final currentTracks = player!.state.tracks;
if (currentTracks.audio.isNotEmpty || currentTracks.subtitle.isNotEmpty) {
await processTracks(currentTracks);
return;
@@ -557,7 +678,7 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// If not, listen to tracks stream for when they become available
bool applied = false;
final subscription = player.stream.tracks.listen((tracks) async {
final subscription = player!.stream.tracks.listen((tracks) async {
// Check if tracks are loaded (have at least one track) and not yet applied
if (!applied && (tracks.audio.isNotEmpty || tracks.subtitle.isNotEmpty)) {
applied = true;
@@ -577,11 +698,18 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
void _sendProgress(String state) {
final position = player.state.position.inMilliseconds;
final duration = player.state.duration.inMilliseconds;
// Don't send misleading data if player isn't available
if (player == null) return;
final position = player!.state.position.inMilliseconds;
final duration = player!.state.duration.inMilliseconds;
if (duration > 0) {
widget.client
final clientProvider = _cachedClientProvider;
final client = clientProvider?.client;
if (client == null) return;
client
.updateProgress(
widget.metadata.ratingKey,
time: position,
@@ -610,63 +738,70 @@ 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 {
// If player isn't available, navigate without preserving settings
if (player == null) {
if (mounted) {
navigateToVideoPlayer(
context,
metadata: episodeMetadata,
usePushReplacement: true,
);
}
return;
}
// Capture current track selection BEFORE pausing
final currentAudioTrack = player.state.track.audio;
final currentSubtitleTrack = player.state.track.subtitle;
final currentAudioTrack = player!.state.track.audio;
final currentSubtitleTrack = player!.state.track.subtitle;
// Pause and stop current playback
player.pause();
player!.pause();
_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) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: _previousEpisode!,
preferredAudioTrack: currentAudioTrack,
preferredSubtitleTrack: currentSubtitleTrack,
userProfile: widget.userProfile,
),
),
final currentRate = player!.state.rate;
navigateToVideoPlayer(
context,
metadata: episodeMetadata,
preferredAudioTrack: currentAudioTrack,
preferredSubtitleTrack: currentSubtitleTrack,
preferredPlaybackRate: currentRate,
usePushReplacement: true,
);
}
}
@override
Widget build(BuildContext context) {
// Show loading indicator while player initializes
if (!_isPlayerInitialized || controller == null || player == null) {
return const Scaffold(
backgroundColor: Colors.black,
body: Center(child: CircularProgressIndicator(color: Colors.white)),
);
}
return PopScope(
canPop: true,
canPop:
false, // Disable swipe-back gesture to prevent interference with timeline scrubbing
onPopInvokedWithResult: (didPop, result) {
// Allow programmatic back navigation from UI controls
if (!didPop) {
Navigator.of(context).pop(true);
}
},
child: Scaffold(
backgroundColor: Colors.black,
body: Stack(
@@ -674,13 +809,14 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Video player
Center(
child: Video(
controller: controller,
controller: controller!,
controls: (state) => plexVideoControlsBuilder(
player,
widget.client,
player!,
widget.metadata,
onNext: _nextEpisode != null ? _playNext : null,
onPrevious: _previousEpisode != null ? _playPrevious : null,
availableVersions: _availableVersions,
selectedMediaIndex: widget.selectedMediaIndex,
),
),
),
@@ -0,0 +1,396 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import 'settings_service.dart';
class KeyboardShortcutsService {
static KeyboardShortcutsService? _instance;
late SettingsService _settingsService;
Map<String, String> _shortcuts =
{}; // Legacy string shortcuts for backward compatibility
Map<String, HotKey> _hotkeys = {}; // New HotKey objects
int _seekTimeSmall = 10; // Default, loaded from settings
int _seekTimeLarge = 30; // Default, loaded from settings
KeyboardShortcutsService._();
static Future<KeyboardShortcutsService> getInstance() async {
if (_instance == null) {
_instance = KeyboardShortcutsService._();
await _instance!._init();
}
return _instance!;
}
Future<void> _init() async {
_settingsService = await SettingsService.getInstance();
// Ensure settings service is fully initialized before loading data
await Future.delayed(Duration.zero); // Allow event loop to complete
_shortcuts = _settingsService
.getKeyboardShortcuts(); // Keep for legacy compatibility
_hotkeys = await _settingsService.getKeyboardHotkeys(); // Primary method
_seekTimeSmall = _settingsService.getSeekTimeSmall();
_seekTimeLarge = _settingsService.getSeekTimeLarge();
}
Map<String, String> get shortcuts => Map.from(_shortcuts);
Map<String, HotKey> get hotkeys => Map.from(_hotkeys);
String getShortcut(String action) {
return _shortcuts[action] ?? '';
}
HotKey? getHotkey(String action) {
return _hotkeys[action];
}
Future<void> setShortcut(String action, String key) async {
_shortcuts[action] = key;
await _settingsService.setKeyboardShortcuts(_shortcuts);
}
Future<void> setHotkey(String action, HotKey hotkey) async {
// Update local cache first
_hotkeys[action] = hotkey;
// Save to persistent storage
await _settingsService.setKeyboardHotkey(action, hotkey);
// Verify local cache is still correct
if (_hotkeys[action] != hotkey) {
_hotkeys[action] = hotkey; // Restore correct value
}
}
Future<void> refreshFromStorage() async {
_hotkeys = await _settingsService.getKeyboardHotkeys();
_seekTimeSmall = _settingsService.getSeekTimeSmall();
_seekTimeLarge = _settingsService.getSeekTimeLarge();
}
Future<void> resetToDefaults() async {
_shortcuts = _settingsService.getDefaultKeyboardShortcuts();
_hotkeys = _settingsService.getDefaultKeyboardHotkeys();
await _settingsService.setKeyboardShortcuts(_shortcuts);
await _settingsService.setKeyboardHotkeys(_hotkeys);
// Refresh cache to ensure consistency
await refreshFromStorage();
}
// Format HotKey for display
String formatHotkey(HotKey? hotKey) {
if (hotKey == null) return 'No shortcut set';
final modifiers = <String>[];
for (final modifier in hotKey.modifiers ?? []) {
switch (modifier) {
case HotKeyModifier.alt:
modifiers.add('Alt');
break;
case HotKeyModifier.control:
modifiers.add('Ctrl');
break;
case HotKeyModifier.shift:
modifiers.add('Shift');
break;
case HotKeyModifier.meta:
modifiers.add('Meta');
break;
case HotKeyModifier.capsLock:
modifiers.add('CapsLock');
break;
case HotKeyModifier.fn:
modifiers.add('Fn');
break;
}
}
// Format the key name
String keyName = hotKey.key.keyLabel;
if (keyName.startsWith('PhysicalKeyboardKey#')) {
keyName = keyName.substring(20, keyName.length - 1);
}
if (keyName.startsWith('key')) {
keyName = keyName.substring(3).toUpperCase();
}
// Special cases for common keys
switch (keyName.toLowerCase()) {
case 'space':
keyName = 'Space';
break;
case 'arrowup':
keyName = 'Arrow Up';
break;
case 'arrowdown':
keyName = 'Arrow Down';
break;
case 'arrowleft':
keyName = 'Arrow Left';
break;
case 'arrowright':
keyName = 'Arrow Right';
break;
case 'equal':
keyName = 'Plus';
break;
case 'minus':
keyName = 'Minus';
break;
}
return modifiers.isEmpty ? keyName : '${modifiers.join(' + ')} + $keyName';
}
// Handle keyboard input for video player
KeyEventResult handleVideoPlayerKeyEvent(
KeyEvent event,
Player player,
VoidCallback? onToggleFullscreen,
VoidCallback? onToggleSubtitles,
VoidCallback? onNextAudioTrack,
VoidCallback? onNextSubtitleTrack,
VoidCallback? onNextChapter,
VoidCallback? onPreviousChapter,
) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
final physicalKey = event.physicalKey;
final isShiftPressed = HardwareKeyboard.instance.isShiftPressed;
final isControlPressed = HardwareKeyboard.instance.isControlPressed;
final isAltPressed = HardwareKeyboard.instance.isAltPressed;
final isMetaPressed = HardwareKeyboard.instance.isMetaPressed;
// Check each hotkey
for (final entry in _hotkeys.entries) {
final action = entry.key;
final hotkey = entry.value;
// Check if the physical key matches
if (physicalKey != hotkey.key) continue;
// Check if modifiers match
final requiredModifiers = hotkey.modifiers ?? [];
bool modifiersMatch = true;
// Check each required modifier
for (final modifier in requiredModifiers) {
switch (modifier) {
case HotKeyModifier.shift:
if (!isShiftPressed) modifiersMatch = false;
break;
case HotKeyModifier.control:
if (!isControlPressed) modifiersMatch = false;
break;
case HotKeyModifier.alt:
if (!isAltPressed) modifiersMatch = false;
break;
case HotKeyModifier.meta:
if (!isMetaPressed) modifiersMatch = false;
break;
case HotKeyModifier.capsLock:
// CapsLock is typically not used for shortcuts, ignore for now
break;
case HotKeyModifier.fn:
// Fn key is typically not used for shortcuts, ignore for now
break;
}
if (!modifiersMatch) break;
}
// Check that no extra modifiers are pressed
if (modifiersMatch) {
final hasShift = requiredModifiers.contains(HotKeyModifier.shift);
final hasControl = requiredModifiers.contains(HotKeyModifier.control);
final hasAlt = requiredModifiers.contains(HotKeyModifier.alt);
final hasMeta = requiredModifiers.contains(HotKeyModifier.meta);
if (isShiftPressed != hasShift ||
isControlPressed != hasControl ||
isAltPressed != hasAlt ||
isMetaPressed != hasMeta) {
continue;
}
_executeAction(
action,
player,
onToggleFullscreen,
onToggleSubtitles,
onNextAudioTrack,
onNextSubtitleTrack,
onNextChapter,
onPreviousChapter,
);
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
/// Seeks by the given offset (can be positive or negative) while clamping
/// the result between 0 and the video duration
void _seekWithClamping(Player player, Duration offset) {
final currentPosition = player.state.position;
final duration = player.state.duration;
final newPosition = currentPosition + offset;
// Clamp between 0 and video duration
final clampedPosition = newPosition.isNegative
? Duration.zero
: (newPosition > duration ? duration : newPosition);
player.seek(clampedPosition);
}
void _executeAction(
String action,
Player player,
VoidCallback? onToggleFullscreen,
VoidCallback? onToggleSubtitles,
VoidCallback? onNextAudioTrack,
VoidCallback? onNextSubtitleTrack,
VoidCallback? onNextChapter,
VoidCallback? onPreviousChapter,
) {
switch (action) {
case 'play_pause':
player.playOrPause();
break;
case 'volume_up':
final newVolume = (player.state.volume + 10).clamp(0.0, 100.0);
player.setVolume(newVolume);
break;
case 'volume_down':
final newVolume = (player.state.volume - 10).clamp(0.0, 100.0);
player.setVolume(newVolume);
break;
case 'seek_forward':
_seekWithClamping(player, Duration(seconds: _seekTimeSmall));
break;
case 'seek_backward':
_seekWithClamping(player, Duration(seconds: -_seekTimeSmall));
break;
case 'seek_forward_large':
_seekWithClamping(player, Duration(seconds: _seekTimeLarge));
break;
case 'seek_backward_large':
_seekWithClamping(player, Duration(seconds: -_seekTimeLarge));
break;
case 'fullscreen_toggle':
onToggleFullscreen?.call();
break;
case 'mute_toggle':
player.setVolume(player.state.volume > 0 ? 0.0 : 100.0);
break;
case 'subtitle_toggle':
onToggleSubtitles?.call();
break;
case 'audio_track_next':
onNextAudioTrack?.call();
break;
case 'subtitle_track_next':
onNextSubtitleTrack?.call();
break;
case 'chapter_next':
onNextChapter?.call();
break;
case 'chapter_previous':
onPreviousChapter?.call();
break;
case 'speed_increase':
final newRate = (player.state.rate + 0.1).clamp(0.1, 3.0);
player.setRate(newRate);
break;
case 'speed_decrease':
final newRate = (player.state.rate - 0.1).clamp(0.1, 3.0);
player.setRate(newRate);
break;
case 'speed_reset':
player.setRate(1.0);
break;
}
}
// Get human-readable action names
String getActionDisplayName(String action) {
switch (action) {
case 'play_pause':
return 'Play/Pause';
case 'volume_up':
return 'Volume Up';
case 'volume_down':
return 'Volume Down';
case 'seek_forward':
return 'Seek Forward (${_seekTimeSmall}s)';
case 'seek_backward':
return 'Seek Backward (${_seekTimeSmall}s)';
case 'seek_forward_large':
return 'Seek Forward (${_seekTimeLarge}s)';
case 'seek_backward_large':
return 'Seek Backward (${_seekTimeLarge}s)';
case 'fullscreen_toggle':
return 'Toggle Fullscreen';
case 'mute_toggle':
return 'Toggle Mute';
case 'subtitle_toggle':
return 'Toggle Subtitles';
case 'audio_track_next':
return 'Next Audio Track';
case 'subtitle_track_next':
return 'Next Subtitle Track';
case 'chapter_next':
return 'Next Chapter';
case 'chapter_previous':
return 'Previous Chapter';
case 'speed_increase':
return 'Increase Speed';
case 'speed_decrease':
return 'Decrease Speed';
case 'speed_reset':
return 'Reset Speed';
default:
return action;
}
}
// Validate if a key combination is valid (legacy method for backward compatibility)
bool isValidKeyShortcut(String keyString) {
// For backward compatibility, assume all non-empty strings are valid
// The new system will use HotKey objects for validation
return keyString.isNotEmpty;
}
// Check if a shortcut is already assigned to another action
String? getActionForShortcut(String keyString) {
for (final entry in _shortcuts.entries) {
if (entry.value == keyString) {
return entry.key;
}
}
return null;
}
// Check if a hotkey is already assigned to another action
String? getActionForHotkey(HotKey hotkey) {
for (final entry in _hotkeys.entries) {
if (_hotkeyEquals(entry.value, hotkey)) {
return entry.key;
}
}
return null;
}
// Helper method to compare two HotKey objects
bool _hotkeyEquals(HotKey a, HotKey b) {
if (a.key != b.key) return false;
final aModifiers = Set.from(a.modifiers ?? []);
final bModifiers = Set.from(b.modifiers ?? []);
return aModifiers.length == bModifiers.length &&
aModifiers.every((modifier) => bModifiers.contains(modifier));
}
}
+258 -107
View File
@@ -4,6 +4,8 @@ import 'package:uuid/uuid.dart';
import 'storage_service.dart';
import '../client/plex_client.dart';
import '../models/plex_user_profile.dart';
import '../models/plex_home.dart';
import '../models/user_switch_response.dart';
class PlexAuthService {
static const String _appName = 'Plezy';
@@ -11,7 +13,7 @@ class PlexAuthService {
static const String _clientsApi = 'https://clients.plex.tv/api/v2';
final Dio _dio;
late final String _clientIdentifier;
final String _clientIdentifier;
PlexAuthService._(this._dio, this._clientIdentifier);
@@ -20,33 +22,43 @@ class PlexAuthService {
final dio = Dio();
// Get or create client identifier
String? clientId = storage.getClientIdentifier();
if (clientId == null) {
clientId = const Uuid().v4();
await storage.saveClientIdentifier(clientId);
String? clientIdentifier = storage.getClientIdentifier();
if (clientIdentifier == null) {
clientIdentifier = const Uuid().v4();
await storage.saveClientIdentifier(clientIdentifier);
}
return PlexAuthService._(dio, clientId);
return PlexAuthService._(dio, clientIdentifier);
}
String get clientIdentifier => _clientIdentifier;
Options _getCommonOptions({String? authToken}) {
final headers = {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
};
if (authToken != null) {
headers['X-Plex-Token'] = authToken;
}
return Options(headers: headers);
}
Future<Response> _getUser(String authToken) {
return _dio.get(
'$_plexApiBase/user',
options: _getCommonOptions(authToken: authToken),
);
}
/// Verify if a plex.tv token is valid
Future<bool> verifyToken(String token) async {
Future<bool> verifyToken(String authToken) async {
try {
final response = await _dio.get(
'$_plexApiBase/user',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Token': token,
},
validateStatus: (status) => status != null && status < 500,
),
);
return response.statusCode == 200;
await _getUser(authToken);
return true;
} catch (e) {
return false;
}
@@ -56,13 +68,7 @@ class PlexAuthService {
Future<Map<String, dynamic>> createPin() async {
final response = await _dio.post(
'$_plexApiBase/pins?strong=true',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
},
),
options: _getCommonOptions(),
);
return response.data as Map<String, dynamic>;
@@ -91,12 +97,7 @@ class PlexAuthService {
try {
final response = await _dio.get(
'$_plexApiBase/pins/$pinId',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Client-Identifier': _clientIdentifier,
},
),
options: _getCommonOptions(),
);
final data = response.data as Map<String, dynamic>;
@@ -109,11 +110,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 +134,10 @@ class PlexAuthService {
}
/// Fetch available Plex servers for the authenticated user
Future<List<PlexServer>> fetchServers(String plexToken) async {
Future<List<PlexServer>> fetchServers(String authToken) async {
final response = await _dio.get(
'$_clientsApi/resources?includeHttps=1&includeRelay=1&includeIPv6=1',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Token': plexToken,
},
),
options: _getCommonOptions(authToken: authToken),
);
final List<dynamic> resources = response.data as List<dynamic>;
@@ -150,38 +150,78 @@ class PlexAuthService {
}
/// Get user information
Future<Map<String, dynamic>> getUserInfo(String token) async {
final response = await _dio.get(
'$_plexApiBase/user',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Token': token,
},
),
);
Future<Map<String, dynamic>> getUserInfo(String authToken) async {
final response = await _getUser(authToken);
return response.data as Map<String, dynamic>;
}
/// Get user profile with preferences (audio/subtitle settings)
Future<PlexUserProfile> getUserProfile(String token) async {
Future<PlexUserProfile> getUserProfile(String authToken) async {
final response = await _dio.get(
'$_clientsApi/user',
options: Options(
headers: {
'Accept': 'application/json',
'X-Plex-Product': _appName,
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Token': token,
},
),
options: _getCommonOptions(authToken: authToken),
);
return PlexUserProfile.fromJson(response.data as Map<String, dynamic>);
}
/// Get home users for the authenticated user
Future<PlexHome> getHomeUsers(String authToken) async {
final response = await _dio.get(
'$_clientsApi/home/users',
options: _getCommonOptions(authToken: authToken),
);
return PlexHome.fromJson(response.data as Map<String, dynamic>);
}
/// Switch to a different user in the home
Future<UserSwitchResponse> switchToUser(
String userUUID,
String currentToken, {
String? pin,
}) async {
final queryParams = {
'includeSubscriptions': '1',
'includeProviders': '1',
'includeSettings': '1',
'includeSharedSettings': '1',
'X-Plex-Product': _appName,
'X-Plex-Version': '1.1.0',
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Platform': 'Flutter',
'X-Plex-Platform-Version': '3.8.1',
'X-Plex-Token': currentToken,
'X-Plex-Language': 'en',
if (pin != null) 'pin': pin,
};
final queryString = queryParams.entries
.map(
(e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}',
)
.join('&');
final response = await _dio.post(
'$_clientsApi/home/users/$userUUID/switch?$queryString',
options: Options(
headers: {'Accept': 'application/json', 'Content-Length': '0'},
),
);
return UserSwitchResponse.fromJson(response.data as Map<String, dynamic>);
}
}
/// Helper class to track connection candidates during testing
class _ConnectionCandidate {
final PlexConnection connection;
final String url;
final bool isPlexDirectUri;
_ConnectionCandidate(this.connection, this.url, this.isPlexDirectUri);
}
/// Represents a Plex Media Server
@@ -253,68 +293,175 @@ class PlexServer {
/// Check if server is online using the presence field
bool get isOnline => presence;
PlexConnection? _selectBest(Iterable<PlexConnection> candidates) {
final local = candidates.where((c) => c.local && !c.relay).toList();
if (local.isNotEmpty) return local.first;
final remote = candidates.where((c) => !c.local && !c.relay).toList();
if (remote.isNotEmpty) return remote.first;
final relay = candidates.where((c) => c.relay).toList();
if (relay.isNotEmpty) return relay.first;
if (candidates.isNotEmpty) return candidates.first;
return null;
}
/// Get the best connection URL
/// Priority: local > remote > relay
PlexConnection? getBestConnection() {
if (connections.isEmpty) return null;
// Try to find local connection first
final local = connections.where((c) => c.local && !c.relay).toList();
if (local.isNotEmpty) return local.first;
// Try remote (non-relay) connection
final remote = connections.where((c) => !c.local && !c.relay).toList();
if (remote.isNotEmpty) return remote.first;
// Fall back to relay as last resort
final relay = connections.where((c) => c.relay).toList();
if (relay.isNotEmpty) return relay.first;
// Return any connection
return connections.first;
return _selectBest(connections);
}
/// Find the best working connection by testing them
/// Tests ALL connections simultaneously and returns the best working one
/// 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 {
if (connections.isEmpty) return null;
/// Tests both plex.direct URI and direct IP for each connection
Stream<PlexConnection> findBestWorkingConnection() async* {
if (connections.isEmpty) return;
// Test all connections simultaneously
final results = await Future.wait(
connections.map((connection) async {
final works = await PlexClient.testConnectionUrl(
connection.uri,
// Create candidates: test both uri and directUrl for each connection
final candidates = <_ConnectionCandidate>[];
for (final connection in connections) {
candidates.add(_ConnectionCandidate(connection, connection.uri, true));
candidates.add(_ConnectionCandidate(connection, connection.directUrl, false));
}
// Phase 1: Race to find first working connection
final completer = Completer<_ConnectionCandidate?>();
_ConnectionCandidate? firstCandidate;
int completedTests = 0;
// Start testing all candidates simultaneously
for (final candidate in candidates) {
PlexClient.testConnectionWithLatency(candidate.url, accessToken).then((
result,
) {
completedTests++;
// If this is the first successful connection, emit it immediately
if (result.success && !completer.isCompleted) {
completer.complete(candidate);
}
// If all tests complete without success, complete with null
if (completedTests == candidates.length && !completer.isCompleted) {
completer.complete(null);
}
});
}
// Wait for and emit the first successful connection
firstCandidate = await completer.future;
if (firstCandidate == null) {
return; // No working connections found
}
// Update the connection object to use the working URL
final firstConnection = _updateConnectionUrl(
firstCandidate.connection,
firstCandidate.url,
);
yield firstConnection;
// Phase 2: Continue testing in background to find best connection
// Test each candidate 2-3 times and average the latency
final candidateResults = <_ConnectionCandidate, ConnectionTestResult>{};
await Future.wait(
candidates.map((candidate) async {
final result = await PlexClient.testConnectionWithAverageLatency(
candidate.url,
accessToken,
attempts: 2,
);
return works ? connection : null;
if (result.success) {
candidateResults[candidate] = result;
}
}),
);
// Filter out failed connections
final workingConnections = results
.where((c) => c != null)
.cast<PlexConnection>()
// If no connections succeeded, we're done
if (candidateResults.isEmpty) {
return;
}
// Find the best connection considering priority, latency, and URL type
final bestCandidate = _selectBestCandidateWithLatency(candidateResults);
// Emit the best connection if it's different from the first one
if (bestCandidate != null) {
final bestConnection = _updateConnectionUrl(
bestCandidate.connection,
bestCandidate.url,
);
if (bestConnection.uri != firstConnection.uri) {
yield bestConnection;
}
}
}
/// Update a connection's URI to use the specified URL
PlexConnection _updateConnectionUrl(PlexConnection connection, String url) {
// If the URL matches the original URI, return as-is
if (url == connection.uri) {
return connection;
}
// Otherwise, create a new connection with the directUrl as the uri
return PlexConnection(
protocol: connection.protocol,
address: connection.address,
port: connection.port,
uri: url,
local: connection.local,
relay: connection.relay,
ipv6: connection.ipv6,
);
}
/// Select the best candidate considering priority, latency, and URL type preference
_ConnectionCandidate? _selectBestCandidateWithLatency(
Map<_ConnectionCandidate, ConnectionTestResult> results,
) {
// Group candidates by connection type (local/remote/relay)
final localCandidates = results.entries
.where((e) => e.key.connection.local && !e.key.connection.relay)
.toList();
final remoteCandidates = results.entries
.where((e) => !e.key.connection.local && !e.key.connection.relay)
.toList();
final relayCandidates = results.entries
.where((e) => e.key.connection.relay)
.toList();
if (workingConnections.isEmpty) return null;
// Find best in each category
return _findLowestLatencyCandidate(localCandidates) ??
_findLowestLatencyCandidate(remoteCandidates) ??
_findLowestLatencyCandidate(relayCandidates);
}
// From working connections, prefer local > remote > relay
final localWorking = workingConnections
.where((c) => c.local && !c.relay)
.toList();
if (localWorking.isNotEmpty) return localWorking.first;
/// Find the candidate with lowest latency, preferring plex.direct URI on tie
_ConnectionCandidate? _findLowestLatencyCandidate(
List<MapEntry<_ConnectionCandidate, ConnectionTestResult>> entries,
) {
if (entries.isEmpty) return null;
final remoteWorking = workingConnections
.where((c) => !c.local && !c.relay)
.toList();
if (remoteWorking.isNotEmpty) return remoteWorking.first;
// Sort by latency first, then by URL type (prefer plex.direct)
entries.sort((a, b) {
final latencyCompare = a.value.latencyMs.compareTo(b.value.latencyMs);
if (latencyCompare != 0) return latencyCompare;
final relayWorking = workingConnections.where((c) => c.relay).toList();
if (relayWorking.isNotEmpty) return relayWorking.first;
// If latencies are equal, prefer plex.direct URI (isPlexDirectUri = true)
if (a.key.isPlexDirectUri && !b.key.isPlexDirectUri) return -1;
if (!a.key.isPlexDirectUri && b.key.isPlexDirectUri) return 1;
return 0;
});
// Fallback to any working connection
return workingConnections.first;
return entries.first.key;
}
}
@@ -362,6 +509,10 @@ class PlexConnection {
};
}
/// Get the direct URL constructed from address and port
/// This bypasses plex.direct DNS and connects directly to the IP
String get directUrl => '$protocol://$address:$port';
String get displayType {
if (relay) return 'Relay';
if (local) return 'Local';
+151
View File
@@ -0,0 +1,151 @@
import 'plex_auth_service.dart';
import 'storage_service.dart';
import '../client/plex_client.dart';
import '../config/plex_config.dart';
import '../models/plex_user_profile.dart';
import '../utils/app_logger.dart';
/// Result of a server connection attempt
class ServerConnectionResult {
final PlexClient? client;
final PlexUserProfile? userProfile;
final String? error;
ServerConnectionResult({this.client, this.userProfile, this.error});
bool get isSuccess => client != null;
}
/// Service for handling optimized server connections
/// Implements fast-first connection with background optimization
class ServerConnectionService {
/// Connect to a Plex server with optimized connection testing
///
/// Returns immediately with first working connection, then continues
/// testing in background to find the optimal connection.
///
/// Parameters:
/// - [server]: The PlexServer to connect to
/// - [clientIdentifier]: Client identifier for the PlexClient
/// - [plexToken]: Optional plex.tv token to save to storage
/// - [verifyServer]: Whether to verify server is accessible before returning
/// - [fetchUserProfile]: Whether to fetch and cache user profile
/// - [onProgress]: Callback for progress updates (e.g., show/hide loading)
static Future<ServerConnectionResult> connectToServer(
PlexServer server, {
required String clientIdentifier,
String? plexToken,
bool verifyServer = false,
bool fetchUserProfile = false,
void Function(String message)? onProgress,
}) async {
PlexConnection? firstConnection;
final storage = await StorageService.getInstance();
try {
// Listen to the connection stream for progressive connection testing
await for (final connection in server.findBestWorkingConnection()) {
if (firstConnection == null) {
// First emission - use this connection immediately
firstConnection = connection;
if (onProgress != null) {
onProgress('Connected to ${connection.displayType} endpoint');
}
// Save server information to storage
await storage.saveServerData(server.toJson());
await storage.saveServerUrl(connection.uri);
await storage.saveServerAccessToken(server.accessToken);
// Save plex token if provided
if (plexToken != null) {
await storage.savePlexToken(plexToken);
}
// Create client with working connection
final config = await PlexConfig.create(
baseUrl: connection.uri,
token: server.accessToken,
clientIdentifier: clientIdentifier,
);
final client = PlexClient(config);
// Verify server is accessible if requested
if (verifyServer) {
try {
await client.getServerIdentity();
} catch (e) {
appLogger.w('Server identity verification failed', error: e);
await storage.clearCredentials();
return ServerConnectionResult(
error: 'Server is not accessible: $e',
);
}
}
// Fetch user profile if requested
PlexUserProfile? userProfile;
if (fetchUserProfile && plexToken != null) {
userProfile = await _fetchUserProfile(plexToken);
}
// Return success result
// Note: Stream continues in background to find better connection
return ServerConnectionResult(
client: client,
userProfile: userProfile,
);
} else {
// Second emission - better connection found
// Update stored connection seamlessly for future app launches
await storage.saveServerUrl(connection.uri);
appLogger.d(
'Switched to better connection: ${connection.displayType} (${connection.uri})',
);
}
}
// Handle case where no connections were found
if (firstConnection == null) {
return ServerConnectionResult(
error: 'No working connections found for this server',
);
}
// Should never reach here due to return in the stream loop
return ServerConnectionResult(
error: 'Unexpected error in connection flow',
);
} catch (e) {
appLogger.e('Error connecting to server', error: e);
return ServerConnectionResult(error: 'Connection failed: $e');
}
}
/// Fetch user profile from Plex API
static Future<PlexUserProfile?> _fetchUserProfile(String plexToken) async {
appLogger.d('Fetching user profile from Plex API');
try {
final authService = await PlexAuthService.create();
final profile = await authService.getUserProfile(plexToken);
appLogger.i(
'Successfully fetched user profile from API',
error: {
'autoSelectAudio': profile.autoSelectAudio,
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
'autoSelectSubtitle': profile.autoSelectSubtitle,
'defaultSubtitleLanguage':
profile.defaultSubtitleLanguage ?? 'not set',
'defaultSubtitleForced': profile.defaultSubtitleForced,
},
);
return profile;
} catch (e) {
appLogger.w('Failed to fetch user profile from API', error: e);
return null;
}
}
}
+681
View File
@@ -0,0 +1,681 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
enum ThemeMode { system, light, dark }
enum LibraryDensity { compact, normal, comfortable }
class SettingsService {
static const String _keyThemeMode = 'theme_mode';
static const String _keyEnableDebugLogging = 'enable_debug_logging';
static const String _keyBufferSize = 'buffer_size';
static const String _keyKeyboardShortcuts = 'keyboard_shortcuts';
static const String _keyKeyboardHotkeys = 'keyboard_hotkeys';
static const String _keyEnableHardwareDecoding = 'enable_hardware_decoding';
static const String _keyPreferredVideoCodec = 'preferred_video_codec';
static const String _keyPreferredAudioCodec = 'preferred_audio_codec';
static const String _keyLibraryDensity = 'library_density';
static const String _keyUseSeasonPoster = 'use_season_poster';
static const String _keySeekTimeSmall = 'seek_time_small';
static const String _keySeekTimeLarge = 'seek_time_large';
static const String _keyMediaVersionPreferences = 'media_version_preferences';
static SettingsService? _instance;
late SharedPreferences _prefs;
SettingsService._();
static Future<SettingsService> getInstance() async {
if (_instance == null) {
_instance = SettingsService._();
await _instance!._init();
}
return _instance!;
}
Future<void> _init() async {
_prefs = await SharedPreferences.getInstance();
}
// Theme Mode
Future<void> setThemeMode(ThemeMode mode) async {
await _prefs.setString(_keyThemeMode, mode.name);
}
ThemeMode getThemeMode() {
final modeString = _prefs.getString(_keyThemeMode);
return ThemeMode.values.firstWhere(
(mode) => mode.name == modeString,
orElse: () => ThemeMode.system,
);
}
// Debug Logging
Future<void> setEnableDebugLogging(bool enabled) async {
await _prefs.setBool(_keyEnableDebugLogging, enabled);
}
bool getEnableDebugLogging() {
return _prefs.getBool(_keyEnableDebugLogging) ?? false;
}
// Buffer Size (in MB)
Future<void> setBufferSize(int sizeInMB) async {
await _prefs.setInt(_keyBufferSize, sizeInMB);
}
int getBufferSize() {
return _prefs.getInt(_keyBufferSize) ?? 128; // Default 128MB
}
// Hardware Decoding
Future<void> setEnableHardwareDecoding(bool enabled) async {
await _prefs.setBool(_keyEnableHardwareDecoding, enabled);
}
bool getEnableHardwareDecoding() {
return _prefs.getBool(_keyEnableHardwareDecoding) ??
true; // Default enabled
}
// Preferred Video Codec
Future<void> setPreferredVideoCodec(String codec) async {
await _prefs.setString(_keyPreferredVideoCodec, codec);
}
String getPreferredVideoCodec() {
return _prefs.getString(_keyPreferredVideoCodec) ?? 'auto';
}
// Preferred Audio Codec
Future<void> setPreferredAudioCodec(String codec) async {
await _prefs.setString(_keyPreferredAudioCodec, codec);
}
String getPreferredAudioCodec() {
return _prefs.getString(_keyPreferredAudioCodec) ?? 'auto';
}
// Library Density
Future<void> setLibraryDensity(LibraryDensity density) async {
await _prefs.setString(_keyLibraryDensity, density.name);
}
LibraryDensity getLibraryDensity() {
final densityString = _prefs.getString(_keyLibraryDensity);
return LibraryDensity.values.firstWhere(
(density) => density.name == densityString,
orElse: () => LibraryDensity.normal,
);
}
// Use Season Poster
Future<void> setUseSeasonPoster(bool enabled) async {
await _prefs.setBool(_keyUseSeasonPoster, enabled);
}
bool getUseSeasonPoster() {
return _prefs.getBool(_keyUseSeasonPoster) ?? false; // Default: false (use series poster)
}
// Seek Time Small (in seconds)
Future<void> setSeekTimeSmall(int seconds) async {
await _prefs.setInt(_keySeekTimeSmall, seconds);
}
int getSeekTimeSmall() {
return _prefs.getInt(_keySeekTimeSmall) ?? 10; // Default: 10 seconds
}
// Seek Time Large (in seconds)
Future<void> setSeekTimeLarge(int seconds) async {
await _prefs.setInt(_keySeekTimeLarge, seconds);
}
int getSeekTimeLarge() {
return _prefs.getInt(_keySeekTimeLarge) ?? 30; // Default: 30 seconds
}
// Keyboard Shortcuts (Legacy String-based)
Map<String, String> getDefaultKeyboardShortcuts() {
return {
'play_pause': 'Space',
'volume_up': 'Arrow Up',
'volume_down': 'Arrow Down',
'seek_forward': 'Arrow Right',
'seek_backward': 'Arrow Left',
'seek_forward_large': 'Shift+Arrow Right',
'seek_backward_large': 'Shift+Arrow Left',
'fullscreen_toggle': 'F',
'mute_toggle': 'M',
'subtitle_toggle': 'S',
'audio_track_next': 'A',
'subtitle_track_next': 'Shift+S',
'chapter_next': 'N',
'chapter_previous': 'P',
'speed_increase': 'Plus',
'speed_decrease': 'Minus',
'speed_reset': 'R',
};
}
// HotKey Objects (New implementation)
Map<String, HotKey> getDefaultKeyboardHotkeys() {
return {
'play_pause': HotKey(key: PhysicalKeyboardKey.space),
'volume_up': HotKey(key: PhysicalKeyboardKey.arrowUp),
'volume_down': HotKey(key: PhysicalKeyboardKey.arrowDown),
'seek_forward': HotKey(key: PhysicalKeyboardKey.arrowRight),
'seek_backward': HotKey(key: PhysicalKeyboardKey.arrowLeft),
'seek_forward_large': HotKey(
key: PhysicalKeyboardKey.arrowRight,
modifiers: [HotKeyModifier.shift],
),
'seek_backward_large': HotKey(
key: PhysicalKeyboardKey.arrowLeft,
modifiers: [HotKeyModifier.shift],
),
'fullscreen_toggle': HotKey(key: PhysicalKeyboardKey.keyF),
'mute_toggle': HotKey(key: PhysicalKeyboardKey.keyM),
'subtitle_toggle': HotKey(key: PhysicalKeyboardKey.keyS),
'audio_track_next': HotKey(key: PhysicalKeyboardKey.keyA),
'subtitle_track_next': HotKey(
key: PhysicalKeyboardKey.keyS,
modifiers: [HotKeyModifier.shift],
),
'chapter_next': HotKey(key: PhysicalKeyboardKey.keyN),
'chapter_previous': HotKey(key: PhysicalKeyboardKey.keyP),
'speed_increase': HotKey(key: PhysicalKeyboardKey.equal),
'speed_decrease': HotKey(key: PhysicalKeyboardKey.minus),
'speed_reset': HotKey(key: PhysicalKeyboardKey.keyR),
};
}
Future<void> setKeyboardShortcuts(Map<String, String> shortcuts) async {
final jsonString = json.encode(shortcuts);
await _prefs.setString(_keyKeyboardShortcuts, jsonString);
}
Map<String, String> getKeyboardShortcuts() {
final jsonString = _prefs.getString(_keyKeyboardShortcuts);
if (jsonString == null) return getDefaultKeyboardShortcuts();
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
final shortcuts = decoded.map(
(key, value) => MapEntry(key, value.toString()),
);
// Merge with defaults to ensure all keys exist
final defaults = getDefaultKeyboardShortcuts();
defaults.addAll(shortcuts);
return defaults;
} catch (e) {
return getDefaultKeyboardShortcuts();
}
}
Future<void> setKeyboardShortcut(String action, String key) async {
final shortcuts = getKeyboardShortcuts();
shortcuts[action] = key;
await setKeyboardShortcuts(shortcuts);
}
String getKeyboardShortcut(String action) {
final shortcuts = getKeyboardShortcuts();
return shortcuts[action] ?? '';
}
Future<void> resetKeyboardShortcuts() async {
await setKeyboardShortcuts(getDefaultKeyboardShortcuts());
}
// HotKey Objects Methods
Future<void> setKeyboardHotkeys(Map<String, HotKey> hotkeys) async {
final Map<String, Map<String, dynamic>> serializedHotkeys = {};
for (final entry in hotkeys.entries) {
serializedHotkeys[entry.key] = _serializeHotKey(entry.value);
}
final jsonString = json.encode(serializedHotkeys);
await _prefs.setString(_keyKeyboardHotkeys, jsonString);
}
Future<Map<String, HotKey>> getKeyboardHotkeys() async {
final jsonString = _prefs.getString(_keyKeyboardHotkeys);
if (jsonString == null) {
return getDefaultKeyboardHotkeys();
}
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
final Map<String, HotKey> hotkeys = {};
for (final entry in decoded.entries) {
final hotKey = _deserializeHotKey(entry.value as Map<String, dynamic>);
if (hotKey != null) {
hotkeys[entry.key] = hotKey;
}
}
// Merge with defaults to ensure all keys exist, but keep saved hotkeys priority
final defaults = getDefaultKeyboardHotkeys();
final result = <String, HotKey>{};
// Start with defaults
result.addAll(defaults);
// Override with saved hotkeys (this preserves user customizations)
result.addAll(hotkeys);
return result;
} catch (e) {
return getDefaultKeyboardHotkeys();
}
}
Future<void> setKeyboardHotkey(String action, HotKey hotKey) async {
final hotkeys = await getKeyboardHotkeys();
hotkeys[action] = hotKey;
await setKeyboardHotkeys(hotkeys);
}
Future<HotKey?> getKeyboardHotkey(String action) async {
final hotkeys = await getKeyboardHotkeys();
return hotkeys[action];
}
Future<void> resetKeyboardHotkeys() async {
await setKeyboardHotkeys(getDefaultKeyboardHotkeys());
}
// Helper methods for HotKey serialization
Map<String, dynamic> _serializeHotKey(HotKey hotKey) {
return {
'key': hotKey.key.toString(),
'modifiers': hotKey.modifiers?.map((m) => m.name).toList() ?? [],
};
}
HotKey? _deserializeHotKey(Map<String, dynamic> data) {
try {
final keyString = data['key'] as String;
final modifierNames = (data['modifiers'] as List<dynamic>).cast<String>();
final modifiers = modifierNames
.map((name) {
switch (name) {
case 'alt':
return HotKeyModifier.alt;
case 'control':
return HotKeyModifier.control;
case 'shift':
return HotKeyModifier.shift;
case 'meta':
return HotKeyModifier.meta;
case 'capsLock':
return HotKeyModifier.capsLock;
case 'fn':
return HotKeyModifier.fn;
default:
return null;
}
})
.where((m) => m != null)
.cast<HotKeyModifier>()
.toList();
final key = _findKeyByString(keyString);
if (key != null) {
return HotKey(
key: key,
modifiers: modifiers.isNotEmpty ? modifiers : null,
);
}
} catch (e) {
// Ignore deserialization errors
}
return null;
}
// Helper method to find PhysicalKeyboardKey by string representation
PhysicalKeyboardKey? _findKeyByString(String keyString) {
// Handle exact string matches first for better performance
const keyMap = {
'PhysicalKeyboardKey#0002c': PhysicalKeyboardKey.space,
'PhysicalKeyboardKey#7002a': PhysicalKeyboardKey.backspace,
'PhysicalKeyboardKey#7004c': PhysicalKeyboardKey.delete,
'PhysicalKeyboardKey#70028': PhysicalKeyboardKey.enter,
'PhysicalKeyboardKey#70029': PhysicalKeyboardKey.escape,
'PhysicalKeyboardKey#7002b': PhysicalKeyboardKey.tab,
'PhysicalKeyboardKey#7004a': PhysicalKeyboardKey.home,
'PhysicalKeyboardKey#7004d': PhysicalKeyboardKey.end,
'PhysicalKeyboardKey#7004b': PhysicalKeyboardKey.pageUp,
'PhysicalKeyboardKey#7004e': PhysicalKeyboardKey.pageDown,
'PhysicalKeyboardKey#70050': PhysicalKeyboardKey.arrowLeft,
'PhysicalKeyboardKey#70052': PhysicalKeyboardKey.arrowUp,
'PhysicalKeyboardKey#7004f': PhysicalKeyboardKey.arrowRight,
'PhysicalKeyboardKey#70051': PhysicalKeyboardKey.arrowDown,
};
// Check exact matches first
if (keyMap.containsKey(keyString)) {
return keyMap[keyString];
}
// Alternative approach: extract USB HID usage code from the toString() output
// Format: PhysicalKeyboardKey#ec9ed(usbHidUsage: "0x0007002c", debugName: "Space")
try {
final usbHidMatch = RegExp(
r'usbHidUsage: "0x([0-9a-fA-F]+)"',
).firstMatch(keyString);
if (usbHidMatch != null) {
final usbHidCode = usbHidMatch.group(1)!.toLowerCase();
// Map USB HID codes to PhysicalKeyboardKey objects
const usbHidMap = {
'0007002c': PhysicalKeyboardKey.space,
'0007002a': PhysicalKeyboardKey.backspace,
'0007004c': PhysicalKeyboardKey.delete,
'00070028': PhysicalKeyboardKey.enter,
'00070029': PhysicalKeyboardKey.escape,
'0007002b': PhysicalKeyboardKey.tab,
'00070039': PhysicalKeyboardKey.capsLock,
// Function keys
'0007003a': PhysicalKeyboardKey.f1,
'0007003b': PhysicalKeyboardKey.f2,
'0007003c': PhysicalKeyboardKey.f3,
'0007003d': PhysicalKeyboardKey.f4,
'0007003e': PhysicalKeyboardKey.f5,
'0007003f': PhysicalKeyboardKey.f6,
'00070040': PhysicalKeyboardKey.f7,
'00070041': PhysicalKeyboardKey.f8,
'00070042': PhysicalKeyboardKey.f9,
'00070043': PhysicalKeyboardKey.f10,
'00070044': PhysicalKeyboardKey.f11,
'00070045': PhysicalKeyboardKey.f12,
// Number keys
'00070027': PhysicalKeyboardKey.digit0,
'0007001e': PhysicalKeyboardKey.digit1,
'0007001f': PhysicalKeyboardKey.digit2,
'00070020': PhysicalKeyboardKey.digit3,
'00070021': PhysicalKeyboardKey.digit4,
'00070022': PhysicalKeyboardKey.digit5,
'00070023': PhysicalKeyboardKey.digit6,
'00070024': PhysicalKeyboardKey.digit7,
'00070025': PhysicalKeyboardKey.digit8,
'00070026': PhysicalKeyboardKey.digit9,
// Letter keys
'00070004': PhysicalKeyboardKey.keyA,
'00070005': PhysicalKeyboardKey.keyB,
'00070006': PhysicalKeyboardKey.keyC,
'00070007': PhysicalKeyboardKey.keyD,
'00070008': PhysicalKeyboardKey.keyE,
'00070009': PhysicalKeyboardKey.keyF,
'0007000a': PhysicalKeyboardKey.keyG,
'0007000b': PhysicalKeyboardKey.keyH,
'0007000c': PhysicalKeyboardKey.keyI,
'0007000d': PhysicalKeyboardKey.keyJ,
'0007000e': PhysicalKeyboardKey.keyK,
'0007000f': PhysicalKeyboardKey.keyL,
'00070010': PhysicalKeyboardKey.keyM,
'00070011': PhysicalKeyboardKey.keyN,
'00070012': PhysicalKeyboardKey.keyO,
'00070013': PhysicalKeyboardKey.keyP,
'00070014': PhysicalKeyboardKey.keyQ,
'00070015': PhysicalKeyboardKey.keyR,
'00070016': PhysicalKeyboardKey.keyS,
'00070017': PhysicalKeyboardKey.keyT,
'00070018': PhysicalKeyboardKey.keyU,
'00070019': PhysicalKeyboardKey.keyV,
'0007001a': PhysicalKeyboardKey.keyW,
'0007001b': PhysicalKeyboardKey.keyX,
'0007001c': PhysicalKeyboardKey.keyY,
'0007001d': PhysicalKeyboardKey.keyZ,
// Arrow keys
'00070050': PhysicalKeyboardKey.arrowLeft,
'00070052': PhysicalKeyboardKey.arrowUp,
'0007004f': PhysicalKeyboardKey.arrowRight,
'00070051': PhysicalKeyboardKey.arrowDown,
// Other common keys
'0007002d': PhysicalKeyboardKey.equal,
'0007002e': PhysicalKeyboardKey.minus,
'0007004a': PhysicalKeyboardKey.home,
'0007004d': PhysicalKeyboardKey.end,
'0007004b': PhysicalKeyboardKey.pageUp,
'0007004e': PhysicalKeyboardKey.pageDown,
};
if (usbHidMap.containsKey(usbHidCode)) {
return usbHidMap[usbHidCode];
}
}
} catch (e) {
// Ignore parsing errors
}
// Fall back to contains() checks for partial matches
if (keyString.contains('space')) {
return PhysicalKeyboardKey.space;
} else if (keyString.contains('arrowUp')) {
return PhysicalKeyboardKey.arrowUp;
} else if (keyString.contains('arrowDown')) {
return PhysicalKeyboardKey.arrowDown;
} else if (keyString.contains('arrowLeft')) {
return PhysicalKeyboardKey.arrowLeft;
} else if (keyString.contains('arrowRight')) {
return PhysicalKeyboardKey.arrowRight;
} else if (keyString.contains('equal')) {
return PhysicalKeyboardKey.equal;
} else if (keyString.contains('minus')) {
return PhysicalKeyboardKey.minus;
} else if (keyString.contains('escape')) {
return PhysicalKeyboardKey.escape;
} else if (keyString.contains('enter')) {
return PhysicalKeyboardKey.enter;
} else if (keyString.contains('tab')) {
return PhysicalKeyboardKey.tab;
} else if (keyString.contains('backspace')) {
return PhysicalKeyboardKey.backspace;
} else if (keyString.contains('delete')) {
return PhysicalKeyboardKey.delete;
} else if (keyString.contains('home')) {
return PhysicalKeyboardKey.home;
} else if (keyString.contains('end')) {
return PhysicalKeyboardKey.end;
} else if (keyString.contains('pageUp')) {
return PhysicalKeyboardKey.pageUp;
} else if (keyString.contains('pageDown')) {
return PhysicalKeyboardKey.pageDown;
} else {
// Try function keys F1-F12
for (int i = 1; i <= 12; i++) {
if (keyString.contains('f$i') || keyString.contains('F$i')) {
switch (i) {
case 1:
return PhysicalKeyboardKey.f1;
case 2:
return PhysicalKeyboardKey.f2;
case 3:
return PhysicalKeyboardKey.f3;
case 4:
return PhysicalKeyboardKey.f4;
case 5:
return PhysicalKeyboardKey.f5;
case 6:
return PhysicalKeyboardKey.f6;
case 7:
return PhysicalKeyboardKey.f7;
case 8:
return PhysicalKeyboardKey.f8;
case 9:
return PhysicalKeyboardKey.f9;
case 10:
return PhysicalKeyboardKey.f10;
case 11:
return PhysicalKeyboardKey.f11;
case 12:
return PhysicalKeyboardKey.f12;
}
}
}
// Try number keys 0-9
for (int i = 0; i <= 9; i++) {
if (keyString.contains('digit$i') || keyString.contains('Digit$i')) {
switch (i) {
case 0:
return PhysicalKeyboardKey.digit0;
case 1:
return PhysicalKeyboardKey.digit1;
case 2:
return PhysicalKeyboardKey.digit2;
case 3:
return PhysicalKeyboardKey.digit3;
case 4:
return PhysicalKeyboardKey.digit4;
case 5:
return PhysicalKeyboardKey.digit5;
case 6:
return PhysicalKeyboardKey.digit6;
case 7:
return PhysicalKeyboardKey.digit7;
case 8:
return PhysicalKeyboardKey.digit8;
case 9:
return PhysicalKeyboardKey.digit9;
}
}
}
// Try letter keys A-Z (both upper and lower case patterns)
const letterKeys = {
'A': PhysicalKeyboardKey.keyA,
'B': PhysicalKeyboardKey.keyB,
'C': PhysicalKeyboardKey.keyC,
'D': PhysicalKeyboardKey.keyD,
'E': PhysicalKeyboardKey.keyE,
'F': PhysicalKeyboardKey.keyF,
'G': PhysicalKeyboardKey.keyG,
'H': PhysicalKeyboardKey.keyH,
'I': PhysicalKeyboardKey.keyI,
'J': PhysicalKeyboardKey.keyJ,
'K': PhysicalKeyboardKey.keyK,
'L': PhysicalKeyboardKey.keyL,
'M': PhysicalKeyboardKey.keyM,
'N': PhysicalKeyboardKey.keyN,
'O': PhysicalKeyboardKey.keyO,
'P': PhysicalKeyboardKey.keyP,
'Q': PhysicalKeyboardKey.keyQ,
'R': PhysicalKeyboardKey.keyR,
'S': PhysicalKeyboardKey.keyS,
'T': PhysicalKeyboardKey.keyT,
'U': PhysicalKeyboardKey.keyU,
'V': PhysicalKeyboardKey.keyV,
'W': PhysicalKeyboardKey.keyW,
'X': PhysicalKeyboardKey.keyX,
'Y': PhysicalKeyboardKey.keyY,
'Z': PhysicalKeyboardKey.keyZ,
};
for (final entry in letterKeys.entries) {
if (keyString.contains('key${entry.key}') ||
keyString.contains('Key${entry.key}')) {
return entry.value;
}
}
return null;
}
}
// Media Version Preferences
/// Save media version preference for a series
/// [seriesRatingKey] is the grandparentRatingKey for TV series, or ratingKey for movies
/// [mediaIndex] is the index of the selected media version
Future<void> setMediaVersionPreference(String seriesRatingKey, int mediaIndex) async {
final preferences = _getMediaVersionPreferences();
preferences[seriesRatingKey] = mediaIndex;
final jsonString = json.encode(preferences);
await _prefs.setString(_keyMediaVersionPreferences, jsonString);
}
/// Get saved media version preference for a series
/// Returns null if no preference is saved
int? getMediaVersionPreference(String seriesRatingKey) {
final preferences = _getMediaVersionPreferences();
return preferences[seriesRatingKey];
}
/// Clear media version preference for a series
Future<void> clearMediaVersionPreference(String seriesRatingKey) async {
final preferences = _getMediaVersionPreferences();
preferences.remove(seriesRatingKey);
final jsonString = json.encode(preferences);
await _prefs.setString(_keyMediaVersionPreferences, jsonString);
}
/// Get all media version preferences
Map<String, int> _getMediaVersionPreferences() {
final jsonString = _prefs.getString(_keyMediaVersionPreferences);
if (jsonString == null) return {};
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
return decoded.map((key, value) => MapEntry(key, value as int));
} catch (e) {
return {};
}
}
// Reset all settings to defaults
Future<void> resetAllSettings() async {
await Future.wait([
_prefs.remove(_keyThemeMode),
_prefs.remove(_keyEnableDebugLogging),
_prefs.remove(_keyBufferSize),
_prefs.remove(_keyKeyboardShortcuts),
_prefs.remove(_keyKeyboardHotkeys),
_prefs.remove(_keyEnableHardwareDecoding),
_prefs.remove(_keyPreferredVideoCodec),
_prefs.remove(_keyPreferredAudioCodec),
_prefs.remove(_keyLibraryDensity),
_prefs.remove(_keyUseSeasonPoster),
_prefs.remove(_keySeekTimeSmall),
_prefs.remove(_keySeekTimeLarge),
_prefs.remove(_keyMediaVersionPreferences),
]);
}
// Clear cache (for storage cleanup)
Future<void> clearCache() async {
// This would be expanded to clear various cache directories
// For now, we'll just clear any cache-related preferences
await Future.wait([
// Add cache clearing logic here
]);
}
// Get all settings as a map for debugging/export
Future<Map<String, dynamic>> getAllSettings() async {
final hotkeys = await getKeyboardHotkeys();
return {
'themeMode': getThemeMode().name,
'enableDebugLogging': getEnableDebugLogging(),
'bufferSize': getBufferSize(),
'enableHardwareDecoding': getEnableHardwareDecoding(),
'preferredVideoCodec': getPreferredVideoCodec(),
'preferredAudioCodec': getPreferredAudioCodec(),
'libraryDensity': getLibraryDensity().name,
'useSeasonPoster': getUseSeasonPoster(),
'seekTimeSmall': getSeekTimeSmall(),
'seekTimeLarge': getSeekTimeLarge(),
'keyboardShortcuts': getKeyboardShortcuts(),
'keyboardHotkeys': hotkeys.map(
(key, value) => MapEntry(key, _serializeHotKey(value)),
),
};
}
}
+137 -1
View File
@@ -8,8 +8,14 @@ class StorageService {
static const String _keyServerData = 'server_data';
static const String _keyClientId = 'client_identifier';
static const String _keySelectedLibraryIndex = 'selected_library_index';
static const String _keySelectedLibraryKey = 'selected_library_key';
static const String _keyLibraryFilters = 'library_filters';
static const String _keyLibraryOrder = 'library_order';
static const String _keyUserProfile = 'user_profile';
static const String _keyCurrentUserUUID = 'current_user_uuid';
static const String _keyHomeUsersCache = 'home_users_cache';
static const String _keyHomeUsersCacheExpiry = 'home_users_cache_expiry';
static const String _keyHiddenLibraries = 'hidden_libraries';
static StorageService? _instance;
late SharedPreferences _prefs;
@@ -117,6 +123,9 @@ class StorageService {
_prefs.remove(_keyServerData),
_prefs.remove(_keyClientId),
_prefs.remove(_keyUserProfile),
_prefs.remove(_keyCurrentUserUUID),
_prefs.remove(_keyHomeUsersCache),
_prefs.remove(_keyHomeUsersCacheExpiry),
]);
}
@@ -129,7 +138,7 @@ class StorageService {
};
}
// Selected Library Index
// Selected Library Index (deprecated - use library key instead)
Future<void> saveSelectedLibraryIndex(int index) async {
await _prefs.setInt(_keySelectedLibraryIndex, index);
}
@@ -138,6 +147,15 @@ class StorageService {
return _prefs.getInt(_keySelectedLibraryIndex);
}
// Selected Library Key (replaces index-based selection)
Future<void> saveSelectedLibraryKey(String key) async {
await _prefs.setString(_keySelectedLibraryKey, key);
}
String? getSelectedLibraryKey() {
return _prefs.getString(_keySelectedLibraryKey);
}
// Library Filters (stored as JSON string)
Future<void> saveLibraryFilters(Map<String, String> filters) async {
final jsonString = json.encode(filters);
@@ -156,12 +174,66 @@ class StorageService {
}
}
// Library Sort (per-library, stored individually)
Future<void> saveLibrarySort(String sectionId, String sortKey) async {
await _prefs.setString('library_sort_$sectionId', sortKey);
}
String getLibrarySort(String sectionId) {
// Return saved sort or default to titleSort (alphabetical)
return _prefs.getString('library_sort_$sectionId') ?? 'titleSort';
}
// Hidden Libraries (stored as JSON array of library section IDs)
Future<void> saveHiddenLibraries(Set<String> libraryKeys) async {
final list = libraryKeys.toList();
final jsonString = json.encode(list);
await _prefs.setString(_keyHiddenLibraries, jsonString);
}
Set<String> getHiddenLibraries() {
final jsonString = _prefs.getString(_keyHiddenLibraries);
if (jsonString == null) return {};
try {
final list = json.decode(jsonString) as List<dynamic>;
return list.map((e) => e.toString()).toSet();
} catch (e) {
return {};
}
}
// Clear library preferences
Future<void> clearLibraryPreferences() async {
await Future.wait([
_prefs.remove(_keySelectedLibraryIndex),
_prefs.remove(_keyLibraryFilters),
_prefs.remove(_keyLibraryOrder),
_prefs.remove(_keyHiddenLibraries),
]);
// Also clear all library sort preferences
final keys = _prefs.getKeys();
final sortKeys = keys.where((key) => key.startsWith('library_sort_'));
await Future.wait(sortKeys.map((key) => _prefs.remove(key)));
}
// Library Order (stored as JSON list of library keys)
Future<void> saveLibraryOrder(List<String> libraryKeys) async {
final jsonString = json.encode(libraryKeys);
await _prefs.setString(_keyLibraryOrder, jsonString);
}
List<String>? getLibraryOrder() {
final jsonString = _prefs.getString(_keyLibraryOrder);
if (jsonString == null) return null;
try {
final decoded = json.decode(jsonString) as List<dynamic>;
return decoded.map((e) => e.toString()).toList();
} catch (e) {
return null;
}
}
// User Profile (stored as JSON string)
@@ -180,4 +252,68 @@ class StorageService {
return null;
}
}
// Current User UUID
Future<void> saveCurrentUserUUID(String uuid) async {
await _prefs.setString(_keyCurrentUserUUID, uuid);
}
String? getCurrentUserUUID() {
return _prefs.getString(_keyCurrentUserUUID);
}
// Home Users Cache (stored as JSON string with expiry)
Future<void> saveHomeUsersCache(Map<String, dynamic> homeData) async {
final jsonString = json.encode(homeData);
await _prefs.setString(_keyHomeUsersCache, jsonString);
// Set cache expiry to 1 hour from now
final expiry = DateTime.now()
.add(const Duration(hours: 1))
.millisecondsSinceEpoch;
await _prefs.setInt(_keyHomeUsersCacheExpiry, expiry);
}
Map<String, dynamic>? getHomeUsersCache() {
final expiry = _prefs.getInt(_keyHomeUsersCacheExpiry);
if (expiry == null || DateTime.now().millisecondsSinceEpoch > expiry) {
// Cache expired, clear it
clearHomeUsersCache();
return null;
}
final jsonString = _prefs.getString(_keyHomeUsersCache);
if (jsonString == null) return null;
try {
return json.decode(jsonString) as Map<String, dynamic>;
} catch (e) {
return null;
}
}
Future<void> clearHomeUsersCache() async {
await Future.wait([
_prefs.remove(_keyHomeUsersCache),
_prefs.remove(_keyHomeUsersCacheExpiry),
]);
}
// Clear current user UUID (for server switching)
Future<void> clearCurrentUserUUID() async {
await _prefs.remove(_keyCurrentUserUUID);
}
// Clear all user-related data (for logout)
Future<void> clearUserData() async {
await Future.wait([clearCredentials(), clearLibraryPreferences()]);
}
// Update current user after switching
Future<void> updateCurrentUser(String userUUID, String authToken) async {
await Future.wait([
saveCurrentUserUUID(userUUID),
saveToken(authToken), // Update the main token
]);
}
}
+167
View File
@@ -0,0 +1,167 @@
import 'package:flutter/material.dart';
import 'mono_tokens.dart';
ThemeData monoTheme({required bool dark}) {
// neutral greys tuned for crisp contrast
final c = dark
? (
bg: const Color(0xFF0E0F12),
surface: const Color(0xFF15171C),
outline: const Color(0x1FFFFFFF),
text: const Color(0xFFEDEDED),
textMuted: const Color(0x99EDEDED),
)
: (
bg: const Color(0xFFF7F7F8),
surface: const Color(0xFFFFFFFF),
outline: const Color(0x19000000),
text: const Color(0xFF111111),
textMuted: const Color(0x99111111),
);
final base = ThemeData(
useMaterial3: true,
brightness: dark ? Brightness.dark : Brightness.light,
colorScheme: ColorScheme(
brightness: dark ? Brightness.dark : Brightness.light,
primary: c.text,
onPrimary: dark ? const Color(0xFF0E0F12) : Colors.white,
secondary: c.text,
onSecondary: c.bg,
surface: c.surface,
onSurface: c.text,
error: const Color(0xFFB00020),
onError: Colors.white,
tertiary: c.text,
onTertiary: c.bg,
primaryContainer: c.surface,
onPrimaryContainer: c.text,
secondaryContainer: c.surface,
onSecondaryContainer: c.text,
surfaceContainerHighest: c.surface,
surfaceContainerLow: c.bg,
surfaceDim: c.bg,
surfaceBright: c.surface,
outline: c.outline,
shadow: Colors.transparent,
scrim: Colors.black,
inverseSurface: c.text,
onInverseSurface: c.bg,
inversePrimary: c.bg,
),
// remove "Material feel"
splashFactory: NoSplash.splashFactory,
highlightColor: Colors.transparent,
dividerColor: c.outline,
scaffoldBackgroundColor: c.bg,
appBarTheme: AppBarTheme(
backgroundColor: c.bg,
elevation: 0,
scrolledUnderElevation: 0,
centerTitle: false,
foregroundColor: c.text,
titleTextStyle: TextStyle(
color: c.text,
fontSize: 18,
fontWeight: FontWeight.w700,
letterSpacing: -0.2,
),
),
textTheme: Typography.englishLike2021
.apply(bodyColor: c.text, displayColor: c.text)
.copyWith(
displayLarge: const TextStyle(
fontWeight: FontWeight.w700,
letterSpacing: -0.5,
),
titleMedium: const TextStyle(fontWeight: FontWeight.w600),
bodyMedium: TextStyle(color: c.text),
bodySmall: TextStyle(color: c.textMuted),
),
cardTheme: CardThemeData(
color: c.surface,
elevation: 0,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: c.surface,
isDense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: c.outline),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: c.outline),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: c.text.withValues(alpha: 0.5)),
),
hintStyle: TextStyle(color: c.textMuted),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ButtonStyle(
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 18, vertical: 14),
),
elevation: const WidgetStatePropertyAll(0),
backgroundColor: WidgetStatePropertyAll(c.text),
foregroundColor: WidgetStatePropertyAll(dark ? c.bg : Colors.white),
shape: const WidgetStatePropertyAll(StadiumBorder()),
),
),
filledButtonTheme: FilledButtonThemeData(
style: ButtonStyle(
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 18, vertical: 14),
),
elevation: const WidgetStatePropertyAll(0),
backgroundColor: WidgetStatePropertyAll(c.text),
foregroundColor: WidgetStatePropertyAll(dark ? c.bg : Colors.white),
shape: const WidgetStatePropertyAll(StadiumBorder()),
),
),
dividerTheme: DividerThemeData(space: 0, thickness: 1, color: c.outline),
listTileTheme: ListTileThemeData(
dense: true,
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
iconColor: c.text,
textColor: c.text,
),
// minimal bottom bar
navigationBarTheme: NavigationBarThemeData(
backgroundColor: c.bg,
elevation: 0,
indicatorColor: Colors.transparent,
labelTextStyle: WidgetStatePropertyAll(
TextStyle(color: c.textMuted, fontSize: 11),
),
iconTheme: WidgetStateProperty.resolveWith((states) {
final active = states.contains(WidgetState.selected);
return IconThemeData(opacity: active ? 1 : .6, size: 22, color: c.text);
}),
),
);
return base.copyWith(
extensions: [
MonoTokens(
radiusSm: 8,
radiusMd: 12,
space: 12,
fast: const Duration(milliseconds: 120),
normal: const Duration(milliseconds: 200),
bg: c.bg,
surface: c.surface,
outline: c.outline,
text: c.text,
textMuted: c.textMuted,
splashFactory: NoSplash.splashFactory,
),
],
);
}
+89
View File
@@ -0,0 +1,89 @@
import 'dart:ui';
import 'package:flutter/material.dart';
@immutable
class MonoTokens extends ThemeExtension<MonoTokens> {
final double radiusSm;
final double radiusMd;
final double space;
final Duration fast;
final Duration normal;
final Color bg;
final Color surface;
final Color outline;
final Color text;
final Color textMuted;
final InteractiveInkFeatureFactory? splashFactory;
const MonoTokens({
required this.radiusSm,
required this.radiusMd,
required this.space,
required this.fast,
required this.normal,
required this.bg,
required this.surface,
required this.outline,
required this.text,
required this.textMuted,
required this.splashFactory,
});
@override
MonoTokens copyWith({
double? radiusSm,
double? radiusMd,
double? space,
Duration? fast,
Duration? normal,
Color? bg,
Color? surface,
Color? outline,
Color? text,
Color? textMuted,
InteractiveInkFeatureFactory? splashFactory,
}) => MonoTokens(
radiusSm: radiusSm ?? this.radiusSm,
radiusMd: radiusMd ?? this.radiusMd,
space: space ?? this.space,
fast: fast ?? this.fast,
normal: normal ?? this.normal,
bg: bg ?? this.bg,
surface: surface ?? this.surface,
outline: outline ?? this.outline,
text: text ?? this.text,
textMuted: textMuted ?? this.textMuted,
splashFactory: splashFactory ?? this.splashFactory,
);
@override
ThemeExtension<MonoTokens> lerp(covariant MonoTokens? other, double t) {
if (other == null) return this;
Color lerpC(Color a, Color b) => Color.lerp(a, b, t)!;
return MonoTokens(
radiusSm: lerpDouble(radiusSm, other.radiusSm, t)!,
radiusMd: lerpDouble(radiusMd, other.radiusMd, t)!,
space: lerpDouble(space, other.space, t)!,
fast: Duration(
milliseconds: lerpDouble(
fast.inMilliseconds.toDouble(),
other.fast.inMilliseconds.toDouble(),
t,
)!.round(),
),
normal: Duration(
milliseconds: lerpDouble(
normal.inMilliseconds.toDouble(),
other.normal.inMilliseconds.toDouble(),
t,
)!.round(),
),
bg: lerpC(bg, other.bg),
surface: lerpC(surface, other.surface),
outline: lerpC(outline, other.outline),
text: lerpC(text, other.text),
textMuted: lerpC(textMuted, other.textMuted),
splashFactory: other.splashFactory,
);
}
}
+6
View File
@@ -0,0 +1,6 @@
import 'package:flutter/material.dart';
import 'mono_tokens.dart';
/// Helper function to access MonoTokens from context
MonoTokens tokens(BuildContext context) =>
Theme.of(context).extension<MonoTokens>()!;
+1 -11
View File
@@ -11,14 +11,4 @@ import 'package:logger/logger.dart';
/// appLogger.w('Warning message');
/// appLogger.e('Error message', error: e, stackTrace: stackTrace);
/// ```
final appLogger = Logger(
printer: PrettyPrinter(
methodCount: 2,
errorMethodCount: 8,
lineLength: 120,
colors: true,
printEmojis: true,
dateTimeFormat: DateTimeFormat.onlyTimeAndSinceStart,
),
level: Level.debug,
);
final appLogger = Logger(printer: SimplePrinter(), level: Level.debug);
+17
View File
@@ -0,0 +1,17 @@
/// Utility function to format content ratings by removing country prefixes
String formatContentRating(String? contentRating) {
if (contentRating == null || contentRating.isEmpty) {
return '';
}
// Remove common country prefixes like "gb/", "us/", "de/", etc.
// The pattern matches: lowercase letters followed by a forward slash
final regex = RegExp(r'^[a-z]{2,3}/(.+)$', caseSensitive: false);
final match = regex.firstMatch(contentRating);
if (match != null && match.groupCount >= 1) {
return match.group(1) ?? contentRating;
}
return contentRating;
}
+166
View File
@@ -0,0 +1,166 @@
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;
/// Right padding for mobile devices to prevent actions from being too close to edge
static const double mobileRight = 6.0;
}
/// Helper class for adjusting app bar widgets to account for desktop window controls
class DesktopAppBarHelper {
/// Builds actions list with appropriate right padding for macOS and mobile
static List<Widget>? buildAdjustedActions(List<Widget>? actions) {
double? rightPadding;
if (Platform.isMacOS) {
rightPadding = DesktopWindowPadding.macOSRight;
} else if (Platform.isIOS || Platform.isAndroid) {
rightPadding = DesktopWindowPadding.mobileRight;
}
// If no platform-specific padding needed, return original actions
if (rightPadding == null) {
return actions;
}
// Add padding to keep actions away from edge
if (actions != null) {
return [...actions, SizedBox(width: rightPadding)];
} else {
return [SizedBox(width: rightPadding)];
}
}
/// 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,
);
},
);
}
}
+50
View File
@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'platform_detector.dart';
/// Helper class for managing device orientation preferences across the app.
class OrientationHelper {
/// Restores default orientation preferences based on device type.
///
/// For phones: Locks to portrait-only (up and down)
/// For tablets/desktop: Allows all orientations
///
/// This should be called when leaving full-screen experiences like
/// the video player to restore the app's default orientation behavior.
static void restoreDefaultOrientations(BuildContext context) {
final isPhone = PlatformDetector.isPhone(context);
if (isPhone) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
} else {
// For tablets and desktop, allow all orientations
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
}
/// Sets orientation to landscape-only mode.
///
/// Used by the video player to force landscape orientation during playback.
static void setLandscapeOrientation() {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
DeviceOrientation.landscapeRight,
]);
}
/// Restores edge-to-edge system UI mode.
///
/// Should be called when exiting full-screen mode.
static void restoreSystemUI() {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
}
}
+37
View File
@@ -0,0 +1,37 @@
import 'package:flutter/material.dart';
import 'dart:math';
/// Utility class for platform detection
class PlatformDetector {
/// Detects if running on a mobile platform (iOS or Android)
/// Uses Theme for consistent platform detection across the app
static bool isMobile(BuildContext context) {
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.android;
}
/// Detects if running on a desktop platform (Windows, macOS, or Linux)
static bool isDesktop(BuildContext context) {
return !isMobile(context);
}
/// Detects if the device is likely a tablet based on screen size
/// Uses diagonal screen size to determine if device is a tablet
static bool isTablet(BuildContext context) {
final data = MediaQuery.of(context);
final size = data.size;
final diagonal = sqrt(size.width * size.width + size.height * size.height);
final devicePixelRatio = data.devicePixelRatio;
// Convert diagonal from logical pixels to inches (assuming 160 DPI as baseline)
final diagonalInches = diagonal / (devicePixelRatio * 160 / 2.54);
// Consider devices with diagonal >= 7 inches as tablets
return diagonalInches >= 7.0;
}
/// Detects if the device is a phone (mobile but not tablet)
static bool isPhone(BuildContext context) {
return isMobile(context) && !isTablet(context);
}
}
-37
View File
@@ -1,37 +0,0 @@
/// Utility class for building Plex API headers
class PlexHeaders {
/// Standard Plex headers required for API requests
static const String plexClientIdentifier = 'X-Plex-Client-Identifier';
static const String plexProduct = 'X-Plex-Product';
static const String plexVersion = 'X-Plex-Version';
static const String plexToken = 'X-Plex-Token';
static const String plexPlatform = 'X-Plex-Platform';
static const String plexPlatformVersion = 'X-Plex-Platform-Version';
static const String plexDevice = 'X-Plex-Device';
/// Builds standard Plex headers with optional token
static Map<String, String> buildHeaders({
required String clientIdentifier,
String? token,
String product = 'Plezy',
String version = '1.0',
String platform = 'Flutter',
String platformVersion = '1.0',
String device = 'Mobile',
}) {
final headers = {
plexClientIdentifier: clientIdentifier,
plexProduct: product,
plexVersion: version,
plexPlatform: platform,
plexPlatformVersion: platformVersion,
plexDevice: device,
};
if (token != null) {
headers[plexToken] = token;
}
return headers;
}
}
+36
View File
@@ -0,0 +1,36 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/plex_client_provider.dart';
import '../providers/user_profile_provider.dart';
import '../providers/hidden_libraries_provider.dart';
import '../client/plex_client.dart';
import '../models/plex_user_profile.dart';
extension ProviderExtensions on BuildContext {
PlexClientProvider get plexClient =>
Provider.of<PlexClientProvider>(this, listen: false);
UserProfileProvider get userProfile =>
Provider.of<UserProfileProvider>(this, listen: false);
PlexClientProvider watchPlexClient() =>
Provider.of<PlexClientProvider>(this, listen: true);
UserProfileProvider watchUserProfile() =>
Provider.of<UserProfileProvider>(this, listen: true);
HiddenLibrariesProvider get hiddenLibraries =>
Provider.of<HiddenLibrariesProvider>(this, listen: false);
HiddenLibrariesProvider watchHiddenLibraries() =>
Provider.of<HiddenLibrariesProvider>(this, listen: true);
// Direct client access (nullable)
PlexClient? get client => plexClient.client;
// Null-safe client access
PlexClient get clientSafe => plexClient.client!;
// Direct profile settings access (nullable)
PlexUserProfile? get profileSettings => userProfile.profileSettings;
}
+28
View File
@@ -0,0 +1,28 @@
import 'package:flutter/material.dart';
import '../models/plex_home_user.dart';
import 'provider_extensions.dart';
class UserSwitchingUtils {
static Future<bool> switchToUser(
BuildContext context,
PlexHomeUser user, {
bool popOnSuccess = false,
}) async {
final userProvider = context.userProfile;
final success = await userProvider.switchToUser(user, context);
if (success && context.mounted && popOnSuccess) {
Navigator.of(context).pop();
} else if (!success && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to switch to ${user.displayName}'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
return success;
}
}
+67
View File
@@ -0,0 +1,67 @@
import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import '../models/plex_metadata.dart';
import '../screens/video_player_screen.dart';
import '../services/settings_service.dart';
/// Navigates to the VideoPlayerScreen with instant transitions to prevent white flash.
///
/// This utility function provides a consistent way to navigate to the video player
/// across the app, using PageRouteBuilder with zero-duration transitions to eliminate
/// the white flash that occurs with MaterialPageRoute.
///
/// Parameters:
/// - [context]: The build context for navigation
/// - [metadata]: The Plex metadata for the content to play
/// - [preferredAudioTrack]: Optional audio track to select on playback start
/// - [preferredSubtitleTrack]: Optional subtitle track to select on playback start
/// - [preferredPlaybackRate]: Optional playback speed to set on playback start
/// - [selectedMediaIndex]: Optional media version index to use; if not provided,
/// loads the saved preference for the series/movie. Defaults to 0 if no preference exists.
/// - [usePushReplacement]: If true, replaces current route instead of pushing;
/// useful for episode-to-episode navigation. Defaults to false.
///
/// Returns a Future that completes with a boolean indicating whether the content
/// was watched, or null if navigation was cancelled.
Future<bool?> navigateToVideoPlayer(
BuildContext context, {
required PlexMetadata metadata,
AudioTrack? preferredAudioTrack,
SubtitleTrack? preferredSubtitleTrack,
double? preferredPlaybackRate,
int? selectedMediaIndex,
bool usePushReplacement = false,
}) async {
// Load saved media version preference if not explicitly provided
int mediaIndex = selectedMediaIndex ?? 0;
if (selectedMediaIndex == null) {
try {
final settingsService = await SettingsService.getInstance();
final seriesKey = metadata.grandparentRatingKey ?? metadata.ratingKey;
final savedPreference = settingsService.getMediaVersionPreference(seriesKey);
if (savedPreference != null) {
mediaIndex = savedPreference;
}
} catch (e) {
// Ignore errors loading preference, use default
}
}
final route = PageRouteBuilder<bool>(
pageBuilder: (context, animation, secondaryAnimation) => VideoPlayerScreen(
metadata: metadata,
preferredAudioTrack: preferredAudioTrack,
preferredSubtitleTrack: preferredSubtitleTrack,
preferredPlaybackRate: preferredPlaybackRate,
selectedMediaIndex: mediaIndex,
),
transitionDuration: Duration.zero,
reverseTransitionDuration: Duration.zero,
);
if (usePushReplacement) {
return Navigator.of(context).pushReplacement<bool, bool>(route);
} else {
return Navigator.push<bool>(context, route);
}
}
+161
View File
@@ -0,0 +1,161 @@
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 StatefulWidget {
/// 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;
@override
State<AppBarBackButton> createState() => _AppBarBackButtonState();
}
class _AppBarBackButtonState extends State<AppBarBackButton>
with TickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _backgroundAnimation;
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: const Duration(milliseconds: 150),
vsync: this,
);
_backgroundAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _onHoverChange(bool isHovered) {
if (isHovered) {
_animationController.forward();
} else {
_animationController.reverse();
}
}
void _handlePressed() {
if (widget.onPressed != null) {
widget.onPressed!();
} else {
Navigator.of(context).pop();
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isDarkTheme = theme.brightness == Brightness.dark;
final Color effectiveColor;
switch (widget.style) {
case BackButtonStyle.plain:
effectiveColor =
widget.color ?? (isDarkTheme ? Colors.white : Colors.black);
break;
case BackButtonStyle.circular:
case BackButtonStyle.video:
effectiveColor = widget.color ?? Colors.white;
break;
}
final Color baseColor;
final Color hoverColor;
switch (widget.style) {
case BackButtonStyle.circular:
baseColor = Colors.black.withValues(alpha: 0.3);
hoverColor = Colors.black.withValues(alpha: 0.5);
break;
case BackButtonStyle.plain:
hoverColor = (isDarkTheme ? Colors.white : Colors.black).withValues(
alpha: 0.2,
);
baseColor = Colors.transparent;
break;
case BackButtonStyle.video:
baseColor = Colors.transparent;
hoverColor = Colors.black.withValues(alpha: 0.3);
break;
}
final button = MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) => _onHoverChange(true),
onExit: (_) => _onHoverChange(false),
child: GestureDetector(
onTap: _handlePressed,
child: AnimatedBuilder(
animation: _backgroundAnimation,
builder: (context, child) {
final currentColor = Color.lerp(
baseColor,
hoverColor,
_backgroundAnimation.value,
);
return Container(
margin: const EdgeInsets.all(8),
width: 40,
height: 40,
decoration: BoxDecoration(
color: currentColor,
shape: BoxShape.circle,
),
child: Icon(Icons.arrow_back, color: effectiveColor, size: 20),
);
},
),
),
);
return widget.style == BackButtonStyle.circular
? SafeArea(child: button)
: button;
}
}
+137
View File
@@ -0,0 +1,137 @@
import 'package:flutter/material.dart';
import '../utils/platform_detector.dart';
/// A menu action item for context menus
class ContextMenuItem {
final String value;
final IconData icon;
final String label;
const ContextMenuItem({
required this.value,
required this.icon,
required this.label,
});
}
/// A wrapper widget that shows context menus differently based on platform.
/// On mobile (iOS/Android): Shows a bottom sheet on long-press
/// On desktop (Windows/macOS/Linux): Shows a popup menu on right-click or long-press
class ContextMenuWrapper extends StatefulWidget {
final Widget child;
final List<ContextMenuItem> menuItems;
final Function(String)? onMenuItemSelected;
final VoidCallback? onTap;
final String? title;
const ContextMenuWrapper({
super.key,
required this.child,
required this.menuItems,
this.onMenuItemSelected,
this.onTap,
this.title,
});
@override
State<ContextMenuWrapper> createState() => _ContextMenuWrapperState();
}
class _ContextMenuWrapperState extends State<ContextMenuWrapper> {
Offset _tapPosition = Offset.zero;
void _storeTapPosition(TapDownDetails details) {
_tapPosition = details.globalPosition;
}
Future<void> _showContextMenu(BuildContext context) async {
final useBottomSheet = PlatformDetector.isMobile(context);
String? selected;
if (useBottomSheet) {
// Mobile: Show bottom sheet
selected = await showModalBottomSheet<String>(
context: context,
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (widget.title != null)
Padding(
padding: const EdgeInsets.all(16),
child: Text(
widget.title!,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
...widget.menuItems.map(
(item) => ListTile(
leading: Icon(item.icon),
title: Text(item.label),
onTap: () => Navigator.pop(context, item.value),
),
),
],
),
),
);
} else {
// Desktop: Show popup menu
final RenderBox overlay =
Overlay.of(context).context.findRenderObject() as RenderBox;
final overlayRect = Rect.fromPoints(
_tapPosition,
_tapPosition.translate(1, 1),
);
final menuItems = widget.menuItems
.map(
(item) => PopupMenuItem<String>(
value: item.value,
child: Row(
children: [
Icon(item.icon, size: 20),
const SizedBox(width: 12),
Expanded(child: Text(item.label)),
],
),
),
)
.toList();
selected = await showMenu<String>(
context: context,
position: RelativeRect.fromRect(
overlayRect,
Offset.zero & overlay.size,
),
items: menuItems,
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
popUpAnimationStyle: AnimationStyle(
duration: const Duration(milliseconds: 150),
reverseDuration: const Duration(milliseconds: 100),
),
);
}
if (selected != null && widget.onMenuItemSelected != null) {
widget.onMenuItemSelected!(selected);
}
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: widget.onTap,
onTapDown: _storeTapPosition,
onLongPress: () => _showContextMenu(context),
onSecondaryTapDown: _storeTapPosition,
onSecondaryTap: () => _showContextMenu(context),
child: widget.child,
);
}
}
+174 -164
View File
@@ -1,62 +1,7 @@
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import '../utils/desktop_window_padding.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 'app_bar_back_button.dart';
/// A custom app bar that automatically handles desktop window controls spacing.
/// Use this instead of AppBar for consistent desktop platform behavior.
@@ -86,43 +31,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 +48,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,70 +93,39 @@ class DesktopSliverAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Add right padding for desktop platforms
List<Widget>? adjustedActions = actions;
// Determine the effective leading widget
Widget? effectiveLeading = leading;
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)];
// If no leading is provided but automaticallyImplyLeading is true,
// create a back button manually so it goes through our padding logic
if (leading == null && automaticallyImplyLeading) {
final parentRoute = ModalRoute.of(context);
final canPop = parentRoute?.canPop ?? false;
if (canPop) {
effectiveLeading = IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
);
}
}
// 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,
automaticallyImplyLeading: automaticallyImplyLeading,
title: title != null
? DesktopTitleBarPadding(
leftPadding: effectiveLeading != null ? 0 : null,
child: title!,
)
: null,
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
leading: DesktopAppBarHelper.buildAdjustedLeading(
effectiveLeading,
includeGestureDetector: true,
),
leadingWidth: DesktopAppBarHelper.calculateLeadingWidth(effectiveLeading),
automaticallyImplyLeading:
false, // Always false since we handle it manually
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
@@ -258,8 +134,142 @@ class DesktopSliverAppBar extends StatelessWidget {
floating: floating,
pinned: pinned,
expandedHeight: expandedHeight,
flexibleSpace: adjustedFlexibleSpace,
flexibleSpace: DesktopAppBarHelper.buildAdjustedFlexibleSpace(
flexibleSpace,
),
bottom: bottom,
);
}
}
/// Convenient wrapper for DesktopAppBar with built-in back button handling
class PlexAppBar extends StatelessWidget implements PreferredSizeWidget {
final Widget? title;
final List<Widget>? actions;
final VoidCallback? onBackPressed;
final double? elevation;
final Color? backgroundColor;
final Color? surfaceTintColor;
final Color? shadowColor;
final double? scrolledUnderElevation;
const PlexAppBar({
super.key,
this.title,
this.actions,
this.onBackPressed,
this.elevation,
this.backgroundColor,
this.surfaceTintColor,
this.shadowColor,
this.scrolledUnderElevation,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
return DesktopAppBar(
key: ValueKey('plex_app_bar_$isFullscreen'),
title: title,
actions: actions,
leading: _shouldShowBackButton(context)
? AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: onBackPressed,
)
: null,
automaticallyImplyLeading: false,
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
scrolledUnderElevation: scrolledUnderElevation,
);
},
);
}
bool _shouldShowBackButton(BuildContext context) {
final parentRoute = ModalRoute.of(context);
return parentRoute?.canPop ?? false;
}
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
/// Convenient wrapper for DesktopSliverAppBar with built-in back button handling
class CustomAppBar extends StatelessWidget {
final Widget? title;
final List<Widget>? actions;
final VoidCallback? onBackPressed;
final double? elevation;
final Color? backgroundColor;
final Color? surfaceTintColor;
final Color? shadowColor;
final double? scrolledUnderElevation;
final bool floating;
final bool pinned;
final double? expandedHeight;
final Widget? flexibleSpace;
final PreferredSizeWidget? bottom;
const CustomAppBar({
super.key,
this.title,
this.actions,
this.onBackPressed,
this.elevation,
this.backgroundColor,
this.surfaceTintColor,
this.shadowColor,
this.scrolledUnderElevation,
this.floating = false,
this.pinned = false,
this.expandedHeight,
this.flexibleSpace,
this.bottom,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
return DesktopSliverAppBar(
key: ValueKey('plex_sliver_app_bar_$isFullscreen'),
title: title,
actions: actions,
leading: _shouldShowBackButton(context)
? AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: onBackPressed,
)
: null,
automaticallyImplyLeading: false,
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
scrolledUnderElevation: scrolledUnderElevation,
floating: floating,
pinned: pinned,
expandedHeight: expandedHeight,
flexibleSpace: flexibleSpace,
bottom: bottom,
);
},
);
}
bool _shouldShowBackButton(BuildContext context) {
final parentRoute = ModalRoute.of(context);
return parentRoute?.canPop ?? false;
}
}
+179
View File
@@ -0,0 +1,179 @@
import 'package:flutter/material.dart';
import '../models/plex_file_info.dart';
class FileInfoBottomSheet extends StatelessWidget {
final PlexFileInfo fileInfo;
final String title;
const FileInfoBottomSheet({
super.key,
required this.fileInfo,
required this.title,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.grey[900],
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
),
),
child: SafeArea(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.75,
child: Column(
children: [
// Header
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(
Icons.info_outline,
color: Colors.white,
size: 24,
),
const SizedBox(width: 12),
Expanded(
child: Text(
'File Info',
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
const Divider(color: Colors.grey, height: 1),
// Content
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
// Title
if (title.isNotEmpty) ...[
Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 20),
],
// Video Section
_buildSectionHeader('Video'),
const SizedBox(height: 8),
_buildInfoRow('Codec', fileInfo.videoCodec ?? 'Unknown'),
_buildInfoRow('Resolution', fileInfo.resolutionFormatted),
_buildInfoRow('Bitrate', fileInfo.bitrateFormatted),
_buildInfoRow('Frame Rate', fileInfo.frameRateFormatted),
_buildInfoRow('Aspect Ratio', fileInfo.aspectRatioFormatted),
if (fileInfo.videoProfile != null)
_buildInfoRow('Profile', fileInfo.videoProfile!),
if (fileInfo.bitDepth != null)
_buildInfoRow('Bit Depth', '${fileInfo.bitDepth} bit'),
if (fileInfo.colorSpace != null)
_buildInfoRow('Color Space', fileInfo.colorSpace!),
if (fileInfo.colorRange != null)
_buildInfoRow('Color Range', fileInfo.colorRange!),
if (fileInfo.colorPrimaries != null)
_buildInfoRow('Color Primaries', fileInfo.colorPrimaries!),
if (fileInfo.chromaSubsampling != null)
_buildInfoRow('Chroma Subsampling', fileInfo.chromaSubsampling!),
const SizedBox(height: 20),
// Audio Section
_buildSectionHeader('Audio'),
const SizedBox(height: 8),
_buildInfoRow('Codec', fileInfo.audioCodec ?? 'Unknown'),
_buildInfoRow('Channels', fileInfo.audioChannelsFormatted),
if (fileInfo.audioProfile != null)
_buildInfoRow('Profile', fileInfo.audioProfile!),
const SizedBox(height: 20),
// File Section
_buildSectionHeader('File'),
const SizedBox(height: 8),
if (fileInfo.filePath != null)
_buildInfoRow('Path', fileInfo.filePath!, isMonospace: true),
_buildInfoRow('Size', fileInfo.fileSizeFormatted),
_buildInfoRow('Container', fileInfo.container ?? 'Unknown'),
_buildInfoRow('Duration', fileInfo.durationFormatted),
const SizedBox(height: 20),
// Advanced Section
_buildSectionHeader('Advanced'),
const SizedBox(height: 8),
_buildInfoRow(
'Optimized for Streaming',
fileInfo.optimizedForStreaming == true ? 'Yes' : 'No',
),
_buildInfoRow(
'64-bit Offsets',
fileInfo.has64bitOffsets == true ? 'Yes' : 'No',
),
],
),
),
],
),
),
),
);
}
Widget _buildSectionHeader(String title) {
return Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
);
}
Widget _buildInfoRow(String label, String value, {bool isMonospace = false}) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 140,
child: Text(
label,
style: TextStyle(
color: Colors.grey[400],
fontSize: 14,
),
),
),
Expanded(
child: Text(
value,
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontFamily: isMonospace ? 'monospace' : null,
),
),
),
],
),
);
}
}
@@ -0,0 +1,194 @@
import 'package:flutter/material.dart';
import '../utils/platform_detector.dart';
/// A wrapper widget that adds hover-activated navigation arrows to horizontal scrolling content.
/// The arrows only appear on desktop/web platforms and hide at scroll boundaries.
///
/// This widget creates and manages its own ScrollController internally. Use the [builder]
/// constructor to access the ScrollController for the scrollable child widget.
class HorizontalScrollWithArrows extends StatefulWidget {
final Widget Function(ScrollController) builder;
final double scrollAmount;
const HorizontalScrollWithArrows({
super.key,
required this.builder,
this.scrollAmount = 0.8, // Scroll by 80% of viewport width by default
});
@override
State<HorizontalScrollWithArrows> createState() =>
_HorizontalScrollWithArrowsState();
}
class _HorizontalScrollWithArrowsState
extends State<HorizontalScrollWithArrows> {
late final ScrollController _scrollController;
bool _isHovering = false;
bool _canScrollLeft = false;
bool _canScrollRight = false;
@override
void initState() {
super.initState();
_scrollController = ScrollController();
_scrollController.addListener(_updateScrollState);
// Initial state update after first frame
WidgetsBinding.instance.addPostFrameCallback((_) => _updateScrollState());
}
@override
void dispose() {
_scrollController.removeListener(_updateScrollState);
_scrollController.dispose();
super.dispose();
}
void _updateScrollState() {
if (!mounted) return;
final position = _scrollController.position;
setState(() {
_canScrollLeft = position.pixels > 0;
_canScrollRight = position.pixels < position.maxScrollExtent;
});
}
void _scrollLeft() {
final position = _scrollController.position;
final targetScroll = (position.pixels -
(position.viewportDimension * widget.scrollAmount))
.clamp(0.0, position.maxScrollExtent);
_scrollController.animateTo(
targetScroll,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
void _scrollRight() {
final position = _scrollController.position;
final targetScroll = (position.pixels +
(position.viewportDimension * widget.scrollAmount))
.clamp(0.0, position.maxScrollExtent);
_scrollController.animateTo(
targetScroll,
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
@override
Widget build(BuildContext context) {
final child = widget.builder(_scrollController);
if (!PlatformDetector.isDesktop(context)) {
// On mobile, just return the child without arrows
return child;
}
return MouseRegion(
onEnter: (_) => setState(() => _isHovering = true),
onExit: (_) => setState(() => _isHovering = false),
child: Stack(
children: [
child,
// Left arrow
Positioned(
left: 8,
top: 0,
bottom: 0,
child: Center(
child: AnimatedOpacity(
opacity: (_isHovering && _canScrollLeft) ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
child: IgnorePointer(
ignoring: !(_isHovering && _canScrollLeft),
child: _NavigationArrow(
icon: Icons.chevron_left,
onPressed: _scrollLeft,
),
),
),
),
),
// Right arrow
Positioned(
right: 8,
top: 0,
bottom: 0,
child: Center(
child: AnimatedOpacity(
opacity: (_isHovering && _canScrollRight) ? 1.0 : 0.0,
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOut,
child: IgnorePointer(
ignoring: !(_isHovering && _canScrollRight),
child: _NavigationArrow(
icon: Icons.chevron_right,
onPressed: _scrollRight,
),
),
),
),
),
],
),
);
}
}
class _NavigationArrow extends StatefulWidget {
final IconData icon;
final VoidCallback onPressed;
const _NavigationArrow({
required this.icon,
required this.onPressed,
});
@override
State<_NavigationArrow> createState() => _NavigationArrowState();
}
class _NavigationArrowState extends State<_NavigationArrow> {
bool _isPressed = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTapDown: (_) => setState(() => _isPressed = true),
onTapUp: (_) {
setState(() => _isPressed = false);
widget.onPressed();
},
onTapCancel: () => setState(() => _isPressed = false),
child: Container(
width: 48,
height: 48,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.black.withValues(alpha: _isPressed ? 0.9 : 0.7),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.3),
blurRadius: 8,
spreadRadius: 0,
),
],
),
child: Icon(
widget.icon,
color: Colors.white,
size: 32,
),
),
),
);
}
}
+114
View File
@@ -0,0 +1,114 @@
import 'package:flutter/material.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
class HotKeyRecorderWidget extends StatefulWidget {
final String actionName;
final HotKey? currentHotKey;
final Function(HotKey) onHotKeyRecorded;
final VoidCallback onCancel;
const HotKeyRecorderWidget({
super.key,
required this.actionName,
this.currentHotKey,
required this.onHotKeyRecorded,
required this.onCancel,
});
@override
State<HotKeyRecorderWidget> createState() => _HotKeyRecorderWidgetState();
}
class _HotKeyRecorderWidgetState extends State<HotKeyRecorderWidget> {
HotKey? _recordedHotKey;
@override
void initState() {
super.initState();
_recordedHotKey = widget.currentHotKey;
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text('Set Shortcut for ${widget.actionName}'),
content: SizedBox(
width: double.maxFinite,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Current shortcut:',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 6),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
border: Border.all(color: Theme.of(context).dividerColor),
borderRadius: BorderRadius.circular(6),
),
child: Row(
children: [
Expanded(
child: HotKeyRecorder(
initalHotKey: _recordedHotKey,
onHotKeyRecorded: (hotKey) {
setState(() {
_recordedHotKey = hotKey;
});
},
),
),
if (_recordedHotKey != null)
IconButton(
icon: const Icon(Icons.backspace, size: 18),
onPressed: () {
setState(() {
_recordedHotKey = null;
});
},
padding: EdgeInsets.zero,
constraints: const BoxConstraints(
minWidth: 24,
minHeight: 24,
),
tooltip: 'Clear shortcut',
),
],
),
),
const SizedBox(height: 8),
Text(
'Press any key combination to set a new shortcut',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.7),
),
textAlign: TextAlign.center,
),
],
),
),
),
actions: [
TextButton(onPressed: widget.onCancel, child: const Text('Cancel')),
TextButton(
onPressed: _recordedHotKey != null
? () => widget.onHotKeyRecorded(_recordedHotKey!)
: null,
child: const Text('Save'),
),
],
);
}
}
+245 -229
View File
@@ -1,29 +1,28 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../client/plex_client.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../providers/settings_provider.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.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 {
final PlexClient client;
final PlexMetadata item;
final double? width;
final double? height;
final VoidCallback? onRefresh;
final PlexUserProfile? userProfile;
final void Function(String ratingKey)? onRefresh;
const MediaCard({
super.key,
required this.client,
required this.item,
this.width,
this.height,
this.onRefresh,
this.userProfile,
});
@override
@@ -32,53 +31,42 @@ class MediaCard extends StatefulWidget {
class _MediaCardState extends State<MediaCard> {
void _handleTap(BuildContext context) async {
final client = context.client;
if (client == null) return;
final itemType = widget.item.type.toLowerCase();
// For episodes, start playback directly
if (itemType == 'episode') {
final result = await Navigator.push<bool>(
final result = await navigateToVideoPlayer(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: widget.item,
userProfile: widget.userProfile,
),
),
metadata: widget.item,
);
// 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
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SeasonDetailScreen(
client: widget.client,
season: widget.item,
userProfile: widget.userProfile,
),
builder: (context) => SeasonDetailScreen(season: widget.item),
),
);
// 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>(
context,
MaterialPageRoute(
builder: (context) => MediaDetailScreen(
client: widget.client,
metadata: widget.item,
userProfile: widget.userProfile,
),
builder: (context) => MediaDetailScreen(metadata: widget.item),
),
);
// Refresh parent screen if result indicates it's needed
if (result == true) {
widget.onRefresh?.call();
widget.onRefresh?.call(widget.item.ratingKey);
}
}
}
@@ -88,198 +76,83 @@ class _MediaCardState extends State<MediaCard> {
return SizedBox(
width: widget.width,
child: MediaContextMenu(
client: widget.client,
metadata: widget.item,
onRefresh: widget.onRefresh,
onTap: () => _handleTap(context),
child: InkWell(
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Poster
if (widget.height != null)
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),
),
child: Semantics(
label: "media-card-${widget.item.ratingKey}",
identifier: "media-card-${widget.item.ratingKey}",
button: true,
child: InkWell(
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Poster
if (widget.height != null)
SizedBox(
width: double.infinity,
height: widget.height,
child: _buildPosterWithOverlay(context),
)
else
Expanded(child: _buildPosterWithOverlay(context)),
const SizedBox(height: 4),
// Text content
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
widget.item.displayTitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
height: 1.1,
),
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,
),
],
),
if (widget.item.displaySubtitle != null)
Text(
widget.item.displaySubtitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
child: const Icon(
Icons.check,
color: Colors.white,
size: 16,
)
else if (widget.item.parentTitle != null)
Text(
widget.item.parentTitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
),
),
// 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),
)
else if (widget.item.year != null)
Text(
'${widget.item.year}',
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 11,
height: 1.1,
),
child: LinearProgressIndicator(
value:
widget.item.viewOffset! /
widget.item.duration!,
backgroundColor: Colors.black.withValues(
alpha: 0.5,
),
valueColor: const AlwaysStoppedAnimation<Color>(
Colors.red,
),
minHeight: 4,
),
),
),
],
),
)
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,
),
),
),
],
),
],
),
const SizedBox(height: 4),
// Text content
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
widget.item.displayTitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
height: 1.1,
),
),
if (widget.item.displaySubtitle != null)
Text(
widget.item.displaySubtitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.grey,
fontSize: 11,
height: 1.1,
),
)
else if (widget.item.parentTitle != null)
Text(
widget.item.parentTitle!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.grey,
fontSize: 11,
height: 1.1,
),
)
else if (widget.item.year != null)
Text(
'${widget.item.year}',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.grey,
fontSize: 11,
height: 1.1,
),
),
],
),
],
],
),
),
),
),
@@ -287,27 +160,170 @@ 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(
imageUrl: widget.client.getThumbnailUrl(widget.item.posterThumb),
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
filterQuality: FilterQuality.high,
placeholder: (context, url) => Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: const Center(child: Icon(Icons.broken_image, size: 40)),
),
final useSeasonPoster = context.watch<SettingsProvider>().useSeasonPoster;
final posterUrl = widget.item.posterThumb(useSeasonPoster: useSeasonPoster);
if (posterUrl != null) {
return Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return const SkeletonLoader(
child: Center(
child: Icon(Icons.movie, size: 40, color: Colors.white54),
),
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(posterUrl),
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
filterQuality: FilterQuality.medium,
fadeInDuration: const Duration(milliseconds: 300),
placeholder: (context, url) => const SkeletonLoader(),
errorWidget: (context, url, error) => Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: const Center(child: Icon(Icons.broken_image, size: 40)),
),
);
},
);
} else {
return Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: const Center(child: Icon(Icons.movie, size: 40)),
return const SkeletonLoader(
child: Center(
child: Icon(Icons.movie, size: 40, color: Colors.white54),
),
);
}
}
}
/// 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,
),
),
),
],
);
}
}
/// Skeleton loader widget with subtle opacity pulse animation
class SkeletonLoader extends StatefulWidget {
final Widget? child;
final BorderRadius? borderRadius;
const SkeletonLoader({super.key, this.child, this.borderRadius});
@override
State<SkeletonLoader> createState() => _SkeletonLoaderState();
}
class _SkeletonLoaderState extends State<SkeletonLoader>
with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: const Duration(milliseconds: 1500),
vsync: this,
);
_animation = Tween<double>(begin: 0.3, end: 0.7).animate(
CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
);
_animationController.repeat(reverse: true);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Semantics(
label: "skeleton-loader",
identifier: "skeleton-loader",
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest
.withValues(alpha: _animation.value),
borderRadius: widget.borderRadius ?? BorderRadius.circular(8),
),
child: widget.child,
),
);
},
);
}
}
+197 -121
View File
@@ -1,9 +1,10 @@
import 'dart:io';
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../utils/provider_extensions.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
import '../widgets/file_info_bottom_sheet.dart';
/// Helper class to store menu action data
class _MenuAction {
@@ -11,25 +12,19 @@ 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)
/// to any media item with appropriate actions based on the item type.
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;
const MediaContextMenu({
super.key,
required this.client,
required this.metadata,
this.onRefresh,
this.onTap,
@@ -48,6 +43,9 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
}
void _showContextMenu(BuildContext context) async {
final client = context.client;
if (client == null) return;
final itemType = widget.metadata.type.toLowerCase();
final isPartiallyWatched =
widget.metadata.viewedLeafCount != null &&
@@ -87,11 +85,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'),
);
}
@@ -106,6 +100,17 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
);
}
// File Info (for episodes and movies)
if (itemType == 'episode' || itemType == 'movie') {
menuActions.add(
_MenuAction(
value: 'fileinfo',
icon: Icons.info_outline,
label: 'File Info',
),
);
}
String? selected;
if (useBottomSheet) {
@@ -125,27 +130,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 +170,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,99 +199,151 @@ 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,
() => 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,
() => 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(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(season: metadata),
'Error loading season',
);
break;
case 'fileinfo':
await _showFileInfo(context);
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;
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
try {
final metadata = await 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')));
}
}
}
/// Show file info bottom sheet
Future<void> _showFileInfo(BuildContext context) async {
final client = context.client;
if (client == null) return;
try {
// Show loading indicator
if (context.mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const Center(
child: CircularProgressIndicator(),
),
);
}
// Fetch file info
final fileInfo = await client.getFileInfo(widget.metadata.ratingKey);
// Close loading indicator
if (context.mounted) {
Navigator.pop(context);
}
if (fileInfo != null && context.mounted) {
// Show file info bottom sheet
await showModalBottomSheet(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (context) => FileInfoBottomSheet(
fileInfo: fileInfo,
title: widget.metadata.title,
),
);
} else if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('File information not available')),
);
}
} catch (e) {
// Close loading indicator if it's still open
if (context.mounted && Navigator.canPop(context)) {
Navigator.pop(context);
}
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error loading file info: $e')),
);
}
}
}
+158
View File
@@ -0,0 +1,158 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Dialog for entering a PIN to access a protected profile
class PinEntryDialog extends StatefulWidget {
final String userName;
final String? errorMessage;
const PinEntryDialog({super.key, required this.userName, this.errorMessage});
@override
State<PinEntryDialog> createState() => _PinEntryDialogState();
}
class _PinEntryDialogState extends State<PinEntryDialog>
with SingleTickerProviderStateMixin {
final _pinController = TextEditingController();
final _focusNode = FocusNode();
bool _obscureText = true;
late AnimationController _shakeController;
late Animation<double> _shakeAnimation;
@override
void initState() {
super.initState();
// Setup shake animation
_shakeController = AnimationController(
duration: const Duration(milliseconds: 600),
vsync: this,
);
// Create a shake effect that oscillates
_shakeAnimation =
TweenSequence<double>([
TweenSequenceItem(tween: Tween(begin: 0.0, end: 10.0), weight: 1),
TweenSequenceItem(tween: Tween(begin: 10.0, end: -10.0), weight: 1),
TweenSequenceItem(tween: Tween(begin: -10.0, end: 10.0), weight: 1),
TweenSequenceItem(tween: Tween(begin: 10.0, end: -10.0), weight: 1),
TweenSequenceItem(tween: Tween(begin: -10.0, end: 0.0), weight: 1),
]).animate(
CurvedAnimation(parent: _shakeController, curve: Curves.easeInOut),
);
// Auto-focus the PIN field when dialog opens
WidgetsBinding.instance.addPostFrameCallback((_) {
_focusNode.requestFocus();
// If there's an error message, trigger shake and clear field
if (widget.errorMessage != null) {
_pinController.clear();
_shakeController.forward(from: 0);
}
});
}
@override
void dispose() {
_pinController.dispose();
_focusNode.dispose();
_shakeController.dispose();
super.dispose();
}
void _submit() {
final pin = _pinController.text.trim();
if (pin.isEmpty) {
return;
}
Navigator.of(context).pop(pin);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return AnimatedBuilder(
animation: _shakeAnimation,
builder: (context, child) {
return Transform.translate(
offset: Offset(_shakeAnimation.value, 0),
child: child,
);
},
child: AlertDialog(
title: Row(
children: [
Icon(
Icons.lock_outline,
size: 24,
color: theme.colorScheme.primary,
),
const SizedBox(width: 12),
Expanded(
child: Text(widget.userName, overflow: TextOverflow.ellipsis),
),
],
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _pinController,
focusNode: _focusNode,
obscureText: _obscureText,
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(10),
],
decoration: InputDecoration(
hintText: 'Enter PIN',
border: const OutlineInputBorder(),
errorText: widget.errorMessage,
errorMaxLines: 2,
suffixIcon: IconButton(
icon: Icon(
_obscureText ? Icons.visibility_off : Icons.visibility,
size: 20,
),
onPressed: () {
setState(() {
_obscureText = !_obscureText;
});
},
tooltip: _obscureText ? 'Show PIN' : 'Hide PIN',
),
),
onSubmitted: (_) => _submit(),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(null),
child: const Text('Cancel'),
),
FilledButton(onPressed: _submit, child: const Text('Submit')),
],
),
);
}
}
/// Shows the PIN entry dialog and returns the entered PIN, or null if cancelled
Future<String?> showPinEntryDialog(
BuildContext context,
String userName, {
String? errorMessage,
}) {
return showDialog<String>(
context: context,
barrierDismissible: false,
builder: (context) =>
PinEntryDialog(userName: userName, errorMessage: errorMessage),
);
}
File diff suppressed because it is too large Load Diff
+114
View File
@@ -0,0 +1,114 @@
import 'package:flutter/material.dart';
import '../models/plex_home_user.dart';
import 'user_avatar_widget.dart';
class ProfileListTile extends StatelessWidget {
final PlexHomeUser user;
final VoidCallback onTap;
final bool isCurrentUser;
final bool showTrailingIcon;
const ProfileListTile({
super.key,
required this.user,
required this.onTap,
this.isCurrentUser = false,
this.showTrailingIcon = true,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return ListTile(
leading: UserAvatarWidget(user: user, size: 40, showIndicators: false),
title: Text(user.displayName),
subtitle: _hasUserAttributes()
? Row(children: _buildUserAttributes(theme))
: null,
trailing: isCurrentUser
? Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: theme.colorScheme.primary,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'CURRENT',
style: TextStyle(
fontSize: 10,
color: theme.colorScheme.onPrimary,
fontWeight: FontWeight.bold,
letterSpacing: 0.5,
),
),
)
: (showTrailingIcon ? const Icon(Icons.chevron_right) : null),
onTap: isCurrentUser ? null : onTap,
enabled: !isCurrentUser,
);
}
bool _hasUserAttributes() {
return user.isAdminUser || user.isRestrictedUser || user.requiresPassword;
}
List<Widget> _buildUserAttributes(ThemeData theme) {
final attributes = <Widget>[];
final labels = <String>[];
if (user.isAdminUser) {
labels.add('Admin');
}
if (user.isRestrictedUser && !user.isAdminUser) {
labels.add('Restricted');
}
if (user.requiresPassword) {
labels.add('Protected');
}
for (int i = 0; i < labels.length; i++) {
if (i > 0) {
attributes.addAll([
const SizedBox(width: 8),
Text(
'•',
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
),
),
const SizedBox(width: 8),
]);
}
attributes.add(
Text(
labels[i],
style: TextStyle(
fontSize: 12,
color: _getAttributeColor(labels[i], theme),
fontWeight: FontWeight.w500,
),
),
);
}
return attributes;
}
Color _getAttributeColor(String attribute, ThemeData theme) {
switch (attribute) {
case 'Admin':
return theme.colorScheme.primary;
case 'Restricted':
return theme.colorScheme.warning ?? Colors.orange;
case 'Protected':
return theme.colorScheme.secondary;
default:
return theme.colorScheme.onSurface;
}
}
}
+88
View File
@@ -0,0 +1,88 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/user_switching_utils.dart';
import 'user_avatar_widget.dart';
import '../screens/profile_switch_screen.dart';
class ProfileSelector extends StatelessWidget {
final double avatarSize;
final bool showCurrentUserOnly;
const ProfileSelector({
super.key,
this.avatarSize = 32,
this.showCurrentUserOnly = false,
});
@override
Widget build(BuildContext context) {
return Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
if (userProvider.currentUser == null) {
return const SizedBox.shrink();
}
if (showCurrentUserOnly || !userProvider.hasMultipleUsers) {
// Show only current user avatar
return UserAvatarWidget(
user: userProvider.currentUser!,
size: avatarSize,
onTap: userProvider.hasMultipleUsers
? () => _showProfileSwitchDialog(context)
: null,
);
}
// Show horizontal list of users
return SizedBox(
height: avatarSize + 8,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: userProvider.home?.users.length ?? 0,
separatorBuilder: (context, index) => const SizedBox(width: 8),
itemBuilder: (context, index) {
final users = userProvider.home!.users;
final user = users[index];
final isCurrentUser = user.uuid == userProvider.currentUser?.uuid;
return Container(
decoration: isCurrentUser
? BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Theme.of(context).colorScheme.primary,
width: 2,
),
)
: null,
child: Padding(
padding: EdgeInsets.all(isCurrentUser ? 2 : 0),
child: UserAvatarWidget(
user: user,
size: avatarSize - (isCurrentUser ? 4 : 0),
onTap: isCurrentUser
? () => _showProfileSwitchDialog(context)
: () => _switchToUser(context, user),
),
),
);
},
),
);
},
);
}
void _showProfileSwitchDialog(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ProfileSwitchScreen()),
);
}
void _switchToUser(BuildContext context, PlexHomeUser user) async {
await UserSwitchingUtils.switchToUser(context, user);
}
}
+87
View File
@@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/user_switching_utils.dart';
import 'profile_list_tile.dart';
class ProfileSwitchDialog extends StatelessWidget {
const ProfileSwitchDialog({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
final users = userProvider.home?.users ?? [];
return AlertDialog(
content: SizedBox(
width: double.maxFinite,
height: users.isEmpty ? 100 : (users.length * 72.0).clamp(100, 400),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (userProvider.isLoading)
const Expanded(
child: Center(child: CircularProgressIndicator()),
)
else if (users.isEmpty)
const Expanded(
child: Center(child: Text('No users available')),
)
else
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
final isCurrentUser =
user.uuid == userProvider.currentUser?.uuid;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Card(
child: ProfileListTile(
user: user,
isCurrentUser: isCurrentUser,
onTap: () => _switchToUser(context, user),
),
),
);
},
),
),
if (userProvider.error != null)
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text(
userProvider.error!,
style: TextStyle(
color: theme.colorScheme.error,
fontSize: 12,
),
textAlign: TextAlign.center,
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
],
);
},
);
}
void _switchToUser(BuildContext context, PlexHomeUser user) async {
await UserSwitchingUtils.switchToUser(context, user, popOnSuccess: true);
}
}
+79 -41
View File
@@ -5,60 +5,98 @@ class ServerListTile extends StatelessWidget {
final PlexServer server;
final VoidCallback onTap;
final bool showTrailingIcon;
final bool isCurrentServer;
const ServerListTile({
super.key,
required this.server,
required this.onTap,
this.showTrailingIcon = true,
this.isCurrentServer = false,
});
@override
Widget build(BuildContext context) {
final isOnline = server.isOnline;
return ListTile(
leading: Icon(
Icons.dns,
color: isOnline
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.5),
return Semantics(
selected: isCurrentServer,
identifier: server.name,
label: server.name,
child: ListTile(
key: ValueKey(server.name),
leading: Icon(
Icons.dns,
color: isOnline
? Theme.of(context).colorScheme.primary
: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.5),
semanticLabel: 'Server',
),
title: Text(server.name),
subtitle: Semantics(
label:
'${isOnline ? 'Online' : 'Offline'}, ${server.owned ? 'Owned' : 'Shared'}',
excludeSemantics: true,
child: Row(
children: [
Semantics(
excludeSemantics: true,
child: Icon(
isOnline ? Icons.circle : Icons.circle_outlined,
size: 10,
color: isOnline ? Colors.green : Colors.grey,
),
),
const SizedBox(width: 4),
Text(
isOnline ? 'Online' : 'Offline',
style: TextStyle(
fontSize: 12,
color: isOnline ? Colors.green : Colors.grey,
),
),
const SizedBox(width: 8),
Semantics(
excludeSemantics: true,
child: Text(
'•',
style: TextStyle(
fontSize: 12,
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.5),
),
),
),
const SizedBox(width: 8),
Text(
server.owned ? 'Owned' : 'Shared',
style: const TextStyle(fontSize: 12),
),
],
),
),
trailing: isCurrentServer
? Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'CURRENT',
style: TextStyle(
fontSize: 10,
color: Theme.of(context).colorScheme.onPrimary,
fontWeight: FontWeight.bold,
letterSpacing: 0.5,
),
),
)
: (showTrailingIcon ? const Icon(Icons.chevron_right) : null),
onTap: isCurrentServer ? null : onTap,
enabled: !isCurrentServer,
),
title: Text(server.name),
subtitle: Row(
children: [
Icon(
isOnline ? Icons.circle : Icons.circle_outlined,
size: 10,
color: isOnline ? Colors.green : Colors.grey,
),
const SizedBox(width: 4),
Text(
isOnline ? 'Online' : 'Offline',
style: TextStyle(
fontSize: 12,
color: isOnline ? Colors.green : Colors.grey,
),
),
const SizedBox(width: 8),
Text(
'•',
style: TextStyle(
fontSize: 12,
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.5),
),
),
const SizedBox(width: 8),
Text(
server.owned ? 'Owned' : 'Shared',
style: const TextStyle(fontSize: 12),
),
],
),
trailing: showTrailingIcon ? const Icon(Icons.chevron_right) : null,
onTap: onTap,
);
}
}
+235
View File
@@ -0,0 +1,235 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../models/plex_home_user.dart';
class UserAvatarWidget extends StatelessWidget {
final PlexHomeUser user;
final double size;
final bool showIndicators;
final bool useTextLabels;
final VoidCallback? onTap;
const UserAvatarWidget({
super.key,
required this.user,
this.size = 40,
this.showIndicators = true,
this.useTextLabels = false,
this.onTap,
});
Widget _buildPlaceholderAvatar(ThemeData theme) {
return Container(
width: size,
height: size,
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
shape: BoxShape.circle,
),
child: Icon(
Icons.person,
size: size * 0.6,
color: theme.colorScheme.onSurfaceVariant,
),
);
}
List<Widget> _buildTextLabels(ThemeData theme) {
if (!useTextLabels || !showIndicators) return [];
final labels = <Widget>[];
if (user.isAdminUser) {
labels.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.primary,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Admin',
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
);
}
if (user.isRestrictedUser && !user.isAdminUser) {
labels.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.warning ?? Colors.orange,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Restricted',
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
);
}
if (user.requiresPassword) {
labels.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.secondary,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Protected',
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSecondary,
fontWeight: FontWeight.bold,
),
),
),
);
}
if (labels.isEmpty) return [];
return [
const SizedBox(height: 4),
Wrap(
spacing: 4,
runSpacing: 2,
alignment: WrapAlignment.center,
children: labels,
),
];
}
Widget _buildAvatar(ThemeData theme) {
return SizedBox(
width: size,
height: size,
child: Stack(
children: [
// Avatar image
ClipOval(
child: CachedNetworkImage(
imageUrl: user.thumb,
width: size,
height: size,
fit: BoxFit.cover,
placeholder: (context, url) => _buildPlaceholderAvatar(theme),
errorWidget: (context, url, error) =>
_buildPlaceholderAvatar(theme),
),
),
// Indicators (only show icon indicators when not using text labels)
if (showIndicators && !useTextLabels) ...[
// Admin badge
if (user.isAdminUser)
Positioned(
top: 0,
right: 0,
child: Container(
width: size * 0.3,
height: size * 0.3,
decoration: BoxDecoration(
color: theme.colorScheme.primary,
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.surface,
width: 1,
),
),
child: Icon(
Icons.admin_panel_settings,
size: size * 0.2,
color: theme.colorScheme.onPrimary,
),
),
),
// Restricted badge
if (user.isRestrictedUser && !user.isAdminUser)
Positioned(
top: 0,
right: 0,
child: Container(
width: size * 0.3,
height: size * 0.3,
decoration: BoxDecoration(
color: theme.colorScheme.warning ?? Colors.orange,
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.surface,
width: 1,
),
),
child: Icon(
Icons.security,
size: size * 0.2,
color: theme.colorScheme.onPrimary,
),
),
),
// Password indicator
if (user.requiresPassword)
Positioned(
bottom: 0,
right: 0,
child: Container(
width: size * 0.25,
height: size * 0.25,
decoration: BoxDecoration(
color: theme.colorScheme.secondary,
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.surface,
width: 1,
),
),
child: Icon(
Icons.lock,
size: size * 0.15,
color: theme.colorScheme.onSecondary,
),
),
),
],
],
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
if (useTextLabels) {
// Return avatar with text labels below
return GestureDetector(
onTap: onTap,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [_buildAvatar(theme), ..._buildTextLabels(theme)],
),
);
} else {
// Return just the avatar (original behavior)
return GestureDetector(onTap: onTap, child: _buildAvatar(theme));
}
}
}
// Extension to add warning color to ColorScheme if not available
extension ColorSchemeExtension on ColorScheme {
Color? get warning => brightness == Brightness.light
? Colors.orange.shade600
: Colors.orange.shade400;
}
@@ -6,6 +6,7 @@
#include "generated_plugin_registrant.h"
#include <hotkey_manager_linux/hotkey_manager_linux_plugin.h>
#include <media_kit_libs_linux/media_kit_libs_linux_plugin.h>
#include <media_kit_video/media_kit_video_plugin.h>
#include <screen_retriever_linux/screen_retriever_linux_plugin.h>
@@ -14,6 +15,9 @@
#include <window_manager/window_manager_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) hotkey_manager_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "HotkeyManagerLinuxPlugin");
hotkey_manager_linux_plugin_register_with_registrar(hotkey_manager_linux_registrar);
g_autoptr(FlPluginRegistrar) media_kit_libs_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "MediaKitLibsLinuxPlugin");
media_kit_libs_linux_plugin_register_with_registrar(media_kit_libs_linux_registrar);
+1
View File
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
hotkey_manager_linux
media_kit_libs_linux
media_kit_video
screen_retriever_linux
@@ -5,6 +5,7 @@
import FlutterMacOS
import Foundation
import hotkey_manager_macos
import macos_window_utils
import media_kit_libs_macos_video
import media_kit_video
@@ -19,6 +20,7 @@ import wakelock_plus
import window_manager
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
HotkeyManagerMacosPlugin.register(with: registry.registrar(forPlugin: "HotkeyManagerMacosPlugin"))
MacOSWindowUtilsPlugin.register(with: registry.registrar(forPlugin: "MacOSWindowUtilsPlugin"))
MediaKitLibsMacosVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitLibsMacosVideoPlugin"))
MediaKitVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitVideoPlugin"))
+13
View File
@@ -1,5 +1,9 @@
PODS:
- FlutterMacOS (1.0.0)
- HotKey (0.2.1)
- hotkey_manager_macos (0.0.1):
- FlutterMacOS
- HotKey
- macos_window_utils (1.0.0):
- FlutterMacOS
- media_kit_libs_macos_video (1.0.4):
@@ -30,6 +34,7 @@ PODS:
DEPENDENCIES:
- FlutterMacOS (from `Flutter/ephemeral`)
- hotkey_manager_macos (from `Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos`)
- macos_window_utils (from `Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos`)
- media_kit_libs_macos_video (from `Flutter/ephemeral/.symlinks/plugins/media_kit_libs_macos_video/macos`)
- media_kit_video (from `Flutter/ephemeral/.symlinks/plugins/media_kit_video/macos`)
@@ -43,9 +48,15 @@ DEPENDENCIES:
- wakelock_plus (from `Flutter/ephemeral/.symlinks/plugins/wakelock_plus/macos`)
- window_manager (from `Flutter/ephemeral/.symlinks/plugins/window_manager/macos`)
SPEC REPOS:
trunk:
- HotKey
EXTERNAL SOURCES:
FlutterMacOS:
:path: Flutter/ephemeral
hotkey_manager_macos:
:path: Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos
macos_window_utils:
:path: Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos
media_kit_libs_macos_video:
@@ -73,6 +84,8 @@ EXTERNAL SOURCES:
SPEC CHECKSUMS:
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
HotKey: 400beb7caa29054ea8d864c96f5ba7e5b4852277
hotkey_manager_macos: a4317849af96d2430fa89944d3c58977ca089fbe
macos_window_utils: 23f54331a0fd51eea9e0ed347253bf48fd379d1d
media_kit_libs_macos_video: 85a23e549b5f480e72cae3e5634b5514bc692f65
media_kit_video: fa6564e3799a0a28bff39442334817088b7ca758
+7
View File
@@ -0,0 +1,7 @@
appId: com.edde746.plezy
---
- tapOn: "Debug: Enter Token"
- tapOn: "Plex Auth Token"
- inputText: ${MAESTRO_PLEX_TOKEN}
- tapOn: "Authenticate"
- tapOn: ${MAESTRO_PLEX_SERVER_NAME}
+49
View File
@@ -0,0 +1,49 @@
appId: com.edde746.plezy
env:
PREFIX: ./${maestro.platform}/
---
- evalScript: ${output.suffix = '-' + Date.now().toString()}
- launchApp:
clearState: true
stopApp: false
- runFlow: auth.yaml
- assertVisible:
id: "media-hero-${MAESTRO_EPISODE}"
- tapOn: "Pause auto-scroll"
- waitForAnimationToEnd
- tapOn:
text: "Play auto-scroll"
waitToSettleTimeoutMs: 800
- takeScreenshot: "${PREFIX}1-home${output.suffix}"
- tapOn: "Libraries.*"
- tapOn:
text: "TV Shows"
waitToSettleTimeoutMs: 200
- runFlow:
when:
true: ${MAESTRO_COLLECTION != ""}
commands:
- tapOn: "Filters"
- tapOn: "Collection"
- tapOn: "${MAESTRO_COLLECTION}"
- repeat:
while:
visible: "skeleton-loader"
commands:
- assertNotVisible: "skeleton-loader"
- takeScreenshot: "${PREFIX}2-library${output.suffix}"
- scrollUntilVisible:
element:
id: "media-card-${MAESTRO_SHOW}"
- tapOn:
id: "media-card-${MAESTRO_SHOW}"
- waitForAnimationToEnd:
timeout: 5000
- takeScreenshot: "${PREFIX}3-media-card${output.suffix}"
- scrollUntilVisible:
element:
id: "media-season-.*"
- tapOn:
id: "media-season-.*"
- takeScreenshot: "${PREFIX}4-season${output.suffix}"
+62 -70
View File
@@ -185,14 +185,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.6"
dart_service_protocol_shared:
dependency: transitive
description:
name: dart_service_protocol_shared
sha256: "1737875c176d7e3d87bb3a359182828b542fe20a0b34198b8d31a81af5c7a76d"
url: "https://pub.dev"
source: hosted
version: "0.0.3"
dart_style:
dependency: transitive
description:
@@ -225,14 +217,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.1"
dtd:
dependency: "direct main"
description:
name: dtd
sha256: "09ddb228b3d1478a093556357692a4c203ff4f9d5f8cda05dfdca0ff3fb7c5d3"
url: "https://pub.dev"
source: hosted
version: "4.0.0"
fake_async:
dependency: transitive
description:
@@ -294,14 +278,6 @@ 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
@@ -328,8 +304,48 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.3.2"
http:
hotkey_manager:
dependency: "direct main"
description:
name: hotkey_manager
sha256: "06f0655b76c8dd322fb7101dc615afbdbf39c3d3414df9e059c33892104479cd"
url: "https://pub.dev"
source: hosted
version: "0.2.3"
hotkey_manager_linux:
dependency: transitive
description:
name: hotkey_manager_linux
sha256: "83676bda8210a3377bc6f1977f193bc1dbdd4c46f1bdd02875f44b6eff9a8473"
url: "https://pub.dev"
source: hosted
version: "0.2.0"
hotkey_manager_macos:
dependency: transitive
description:
name: hotkey_manager_macos
sha256: "03b5967e64357b9ac05188ea4a5df6fe4ed4205762cb80aaccf8916ee1713c96"
url: "https://pub.dev"
source: hosted
version: "0.2.0"
hotkey_manager_platform_interface:
dependency: transitive
description:
name: hotkey_manager_platform_interface
sha256: "98ffca25b8cc9081552902747b2942e3bc37855389a4218c9d50ca316b653b13"
url: "https://pub.dev"
source: hosted
version: "0.2.0"
hotkey_manager_windows:
dependency: transitive
description:
name: hotkey_manager_windows
sha256: "0d03ced9fe563ed0b68f0a0e1b22c9ffe26eb8053cb960e401f68a4f070e0117"
url: "https://pub.dev"
source: hosted
version: "0.2.0"
http:
dependency: transitive
description:
name: http
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
@@ -376,14 +392,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.9.0"
json_rpc_2:
dependency: transitive
description:
name: json_rpc_2
sha256: "3c46c2633aec07810c3d6a2eb08d575b5b4072980db08f1344e66aeb53d6e4a7"
url: "https://pub.dev"
source: hosted
version: "4.0.0"
json_serializable:
dependency: "direct dev"
description:
@@ -545,6 +553,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
octo_image:
dependency: transitive
description:
@@ -585,14 +601,6 @@ 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:
@@ -681,6 +689,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.0.3"
provider:
dependency: "direct main"
description:
name: provider
sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272"
url: "https://pub.dev"
source: hosted
version: "6.1.5+1"
pub_semver:
dependency: transitive
description:
@@ -982,14 +998,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
unified_analytics:
uni_platform:
dependency: transitive
description:
name: unified_analytics
sha256: "8d1429a4b27320a9c4fc854287d18c8fde1549bf622165c5837202a9f370b53d"
name: uni_platform
sha256: e02213a7ee5352212412ca026afd41d269eb00d982faa552f419ffc2debfad84
url: "https://pub.dev"
source: hosted
version: "8.0.5"
version: "0.1.3"
universal_platform:
dependency: transitive
description:
@@ -1078,30 +1094,6 @@ 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:
@@ -1199,7 +1191,7 @@ packages:
source: hosted
version: "1.1.0"
xml:
dependency: "direct main"
dependency: transitive
description:
name: xml
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
+4 -5
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 1.0.1+3
version: 1.3.0+9
environment:
sdk: ^3.8.1
@@ -9,12 +9,9 @@ environment:
dependencies:
flutter:
sdk: flutter
http: ^1.2.0
dio: ^5.4.0
json_annotation: ^4.8.1
xml: ^6.5.0
shared_preferences: ^2.2.2
dtd: ^4.0.0
cached_network_image: ^3.4.1
media_kit: ^1.1.10+1
media_kit_video: ^1.2.4
@@ -24,8 +21,9 @@ 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
provider: ^6.1.2
hotkey_manager: ^0.2.3
dependency_overrides:
media_kit:
@@ -46,6 +44,7 @@ flutter:
assets:
- lib/data/iso_639_codes.json
- assets/plezy.png
- assets/droid-sans.ttf
flutter_launcher_icons:
android: true
+396
View File
@@ -0,0 +1,396 @@
#!/bin/bash
# Android Screenshot Automation Script
# Starts emulators, runs Flutter app, executes maestro tests, and organizes screenshots
set -e # Exit on any error
# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
MAESTRO_DIR="$PROJECT_ROOT/maestro"
FASTLANE_IMAGES_DIR="$PROJECT_ROOT/android/fastlane/metadata/android/en-GB/images"
ENV_FILE="$PROJECT_ROOT/.env"
# Source common screenshot functions
source "${SCRIPT_DIR}/screenshot_common.sh"
# Check if required tools are installed
check_dependencies() {
# Check common dependencies first
if ! check_common_dependencies; then
exit 1
fi
log_info "Checking Android-specific dependencies..."
# Try to find emulator binary
if ! command -v emulator &> /dev/null; then
# Try common Android SDK locations
POSSIBLE_PATHS=(
"$ANDROID_HOME/emulator/emulator"
"$ANDROID_SDK_ROOT/emulator/emulator"
"~/Android/Sdk/emulator/emulator"
"~/Library/Android/sdk/emulator/emulator"
)
EMULATOR_PATH=""
for path in "${POSSIBLE_PATHS[@]}"; do
if [ -f "$path" ]; then
EMULATOR_PATH="$path"
break
fi
done
if [ -z "$EMULATOR_PATH" ]; then
log_error "Android emulator not found. Please ensure Android SDK is installed and ANDROID_HOME is set."
exit 1
fi
# Create an alias for emulator
alias emulator="$EMULATOR_PATH"
fi
log_success "All dependencies found"
}
# Get list of available AVDs
get_avds() {
# Parse flutter emulators output to get Android emulator IDs
flutter emulators 2>/dev/null | grep "android$" | awk '{print $1}'
}
# Stop all running emulators
stop_emulators() {
log_info "Stopping any running emulators..."
# Get list of running emulators
local running_emulators=$(adb devices | grep emulator | cut -f1)
if [ -n "$running_emulators" ]; then
for emulator in $running_emulators; do
log_info "Stopping emulator $emulator"
adb -s "$emulator" emu kill 2>/dev/null || true
done
# Wait for emulators to fully stop - check periodically
log_info "Waiting for emulators to fully shut down..."
local timeout=30 # 30 seconds timeout
local elapsed=0
while [ $elapsed -lt $timeout ]; do
local still_running=$(adb devices | grep emulator | cut -f1)
if [ -z "$still_running" ]; then
log_success "All emulators stopped"
return 0
fi
sleep 2
elapsed=$((elapsed + 2))
# Show progress every 6 seconds
if [ $((elapsed % 6)) -eq 0 ]; then
log_info "Still waiting for emulators to stop... (${elapsed}s elapsed)"
fi
done
log_warning "Timeout waiting for emulators to stop completely"
else
log_info "No emulators are currently running"
fi
}
# Start emulator and wait for it to be ready
start_emulator() {
local avd_name="$1"
local device_type="$2"
log_info "Starting $device_type emulator: $avd_name"
# Double-check if any emulator is still running
local running_emulators=$(adb devices | grep emulator | cut -f1)
if [ -n "$running_emulators" ]; then
log_warning "Emulator still running: $running_emulators"
log_info "Forcing stop before starting new emulator..."
stop_emulators
fi
# Start emulator in background with proper output redirection
log_info "Launching emulator..."
flutter emulators --launch "$avd_name" > /dev/null 2>&1 &
local emulator_pid=$!
log_info "Waiting for $device_type emulator to boot..."
# Wait for emulator to appear in adb devices
local timeout=120 # 2 minutes timeout
local elapsed=0
while [ $elapsed -lt $timeout ]; do
if adb devices | grep -q "emulator.*device"; then
log_success "$device_type emulator is ready"
return 0
fi
sleep 2
elapsed=$((elapsed + 2))
# Show progress every 10 seconds
if [ $((elapsed % 10)) -eq 0 ]; then
log_info "Still waiting... (${elapsed}s elapsed)"
fi
done
log_error "Timeout waiting for $device_type emulator to start"
return 1
}
# Detect device type based on screen size
detect_device_type() {
local device_id="$1"
# Get screen density and size
local density=$(adb -s "$device_id" shell wm density | cut -d: -f2 | tr -d ' ')
local size=$(adb -s "$device_id" shell wm size | cut -d: -f2 | tr -d ' ')
# Extract width and height
local width=$(echo "$size" | cut -d'x' -f1)
local height=$(echo "$size" | cut -d'x' -f2)
# Calculate diagonal in inches (approximate)
local diagonal_pixels=$(echo "sqrt($width*$width + $height*$height)" | bc -l)
local diagonal_inches=$(echo "$diagonal_pixels / $density" | bc -l)
# Convert to integer for comparison
local diagonal_int=$(echo "$diagonal_inches" | cut -d'.' -f1)
if [ "$diagonal_int" -ge 9 ]; then
echo "tablet"
else
echo "phone"
fi
}
# Run Flutter app on specified device
run_flutter_app() {
local device_id="$1"
local device_type="$2"
log_info "Running Flutter app on $device_type ($device_id)"
cd "$PROJECT_ROOT"
flutter run -d "$device_id" --hot &
local flutter_pid=$!
# Wait for app to be installed and launched
sleep 30
# Check if app is running
if adb -s "$device_id" shell pm list packages | grep -q "com.edde746.plezy"; then
log_success "Flutter app is running on $device_type"
return 0
else
log_error "Failed to start Flutter app on $device_type"
return 1
fi
}
# Detect device type based on image dimensions
detect_device_type() {
local image_path="$1"
local dimensions=$(get_image_dimensions "$image_path")
if [ -z "$dimensions" ]; then
log_warning "Could not get dimensions for $image_path"
echo "phone" # Default to phone
return
fi
local width=$(echo "$dimensions" | cut -d',' -f1)
local height=$(echo "$dimensions" | cut -d',' -f2)
# Determine shorter and longer sides
local shorter_side=$((width < height ? width : height))
local longer_side=$((width > height ? width : height))
# Calculate diagonal using shell arithmetic (approximate)
# For simplicity, we'll use the shorter side as the main criteria
# Tablets typically have shorter side >= 1200px
# Phones typically have shorter side < 1200px
if [ "$shorter_side" -ge 1200 ]; then
echo "tablet"
else
echo "phone"
fi
}
# Organize screenshots into correct fastlane folders
organize_screenshots() {
log_info "Organizing screenshots using ffprobe analysis..."
# Create directories if they don't exist
mkdir -p "$FASTLANE_IMAGES_DIR/phoneScreenshots"
mkdir -p "$FASTLANE_IMAGES_DIR/sevenInchScreenshots"
mkdir -p "$FASTLANE_IMAGES_DIR/tenInchScreenshots"
# Find all screenshot files generated by maestro
local android_screenshots_dir="$MAESTRO_DIR/android"
if [ ! -d "$android_screenshots_dir" ]; then
log_warning "No Android screenshots directory found at $android_screenshots_dir"
return 1
fi
local screenshots=($(find "$android_screenshots_dir" -name "*.png" | sort))
if [ ${#screenshots[@]} -eq 0 ]; then
log_warning "No Android screenshots found in $android_screenshots_dir"
return 1
fi
log_info "Found ${#screenshots[@]} screenshots"
# Group screenshots by device type
local phone_screenshots=()
local tablet_screenshots=()
for screenshot in "${screenshots[@]}"; do
local device_type=$(detect_device_type "$screenshot")
log_image_info "$screenshot" "$device_type"
if [ "$device_type" = "tablet" ]; then
tablet_screenshots+=("$screenshot")
else
phone_screenshots+=("$screenshot")
fi
done
# Copy and rename phone screenshots
local phone_count=1
for screenshot in "${phone_screenshots[@]}"; do
if [ $phone_count -gt 4 ]; then
break # Limit to 4 screenshots
fi
local target_name="${phone_count}_en-GB.png"
# Copy to phone directory
cp "$screenshot" "$FASTLANE_IMAGES_DIR/phoneScreenshots/$target_name"
# Copy to seven inch directory (phone screenshots go here too)
cp "$screenshot" "$FASTLANE_IMAGES_DIR/sevenInchScreenshots/$target_name"
log_success "Copied phone screenshot $phone_count: $(basename "$screenshot")"
phone_count=$((phone_count + 1))
done
# Copy and rename tablet screenshots
local tablet_count=1
for screenshot in "${tablet_screenshots[@]}"; do
if [ $tablet_count -gt 4 ]; then
break # Limit to 4 screenshots
fi
local target_name="${tablet_count}_en-GB.png"
cp "$screenshot" "$FASTLANE_IMAGES_DIR/tenInchScreenshots/$target_name"
log_success "Copied tablet screenshot $tablet_count: $(basename "$screenshot")"
tablet_count=$((tablet_count + 1))
done
log_success "Organized $((phone_count-1)) phone screenshots and $((tablet_count-1)) tablet screenshots"
}
# Cleanup function
cleanup() {
log_info "Cleaning up..."
# Kill any running Flutter processes
pkill -f "flutter run" 2>/dev/null || true
# Stop emulators using our function
stop_emulators
log_success "Cleanup completed"
}
# Main execution
main() {
log_info "Starting Android screenshot automation..."
# Set up cleanup trap
trap cleanup EXIT INT TERM
# Clean up old screenshots at the very beginning
clean_old_screenshots "android ios"
# Check dependencies
check_dependencies
# Stop any running emulators first
stop_emulators
# Get available AVDs
log_info "Getting available Android Virtual Devices..."
# Store AVDs in an array, handling potential spaces in names
local avds_raw=$(get_avds)
if [ -z "$avds_raw" ]; then
log_error "No Android Virtual Devices found. Please create AVDs first."
log_info "Create AVDs using: flutter emulators --create"
exit 1
fi
# Convert to array (each line is an AVD)
IFS=$'\n' read -d '' -r -a avds <<< "$avds_raw" || true
log_info "Found ${#avds[@]} Android AVD(s): ${avds[*]}"
# For now, we'll use the first two AVDs as phone and tablet
# In a real scenario, you'd want to specify which AVDs to use
local phone_avd="${avds[0]}"
local tablet_avd="${avds[1]:-${avds[0]}}" # Use first AVD if only one available
if [ ${#avds[@]} -eq 1 ]; then
log_warning "Only one AVD available. Using it for both phone and tablet tests."
fi
# Start phone emulator
start_emulator "$phone_avd" "phone"
# Get device ID for phone
local phone_device=$(adb devices | grep emulator | head -n1 | cut -f1)
# Run Flutter app on phone
run_flutter_app "$phone_device" "phone"
# Run maestro tests for phone
MAESTRO_DEVICE="$phone_device" run_maestro_tests
# If we have a different tablet AVD, start it
if [ "$phone_avd" != "$tablet_avd" ]; then
# Stop phone emulator
log_info "Switching from phone to tablet emulator"
stop_emulators
# Start tablet emulator
start_emulator "$tablet_avd" "tablet"
# Get device ID for tablet
local tablet_device=$(adb devices | grep emulator | head -n1 | cut -f1)
# Run Flutter app on tablet
run_flutter_app "$tablet_device" "tablet"
# Run maestro tests for tablet
MAESTRO_DEVICE="$tablet_device" run_maestro_tests
fi
# Organize screenshots
organize_screenshots
log_success "Android screenshot automation completed successfully!"
}
# Run main function if script is executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
+421
View File
@@ -0,0 +1,421 @@
#!/bin/bash
# iOS Screenshot Automation Script
# Starts simulators, runs Flutter app, executes maestro tests, and organizes screenshots
set -e # Exit on any error
# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
MAESTRO_DIR="$PROJECT_ROOT/maestro"
FASTLANE_SCREENSHOTS_DIR="$PROJECT_ROOT/ios/fastlane/screenshots/en-US"
ENV_FILE="$PROJECT_ROOT/.env"
# Source common screenshot functions
source "${SCRIPT_DIR}/screenshot_common.sh"
# Check if required tools are installed
check_dependencies() {
# Check common dependencies first
if ! check_common_dependencies; then
exit 1
fi
log_info "Checking iOS-specific dependencies..."
if ! command -v xcrun &> /dev/null; then
log_error "xcrun is not installed - Xcode is required"
exit 1
fi
log_success "All dependencies found"
}
# Get list of available iOS simulators
get_simulators() {
xcrun simctl list devices available -j | python3 -c "
import sys, json
data = json.load(sys.stdin)
for runtime, devices in data['devices'].items():
if 'iOS' in runtime and devices:
for device in devices:
if device['isAvailable']:
print(f\"{device['udid']}|{device['name']}\")
" 2>/dev/null || echo ""
}
# Stop all running simulators
stop_simulators() {
log_info "Stopping any running simulators..."
# Get list of running simulators
local running_simulators=$(xcrun simctl list devices | grep "Booted" | grep -oE "[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}" || echo "")
if [ -n "$running_simulators" ]; then
while IFS= read -r simulator; do
log_info "Stopping simulator $simulator"
xcrun simctl shutdown "$simulator" 2>/dev/null || true
done <<< "$running_simulators"
# Wait for simulators to fully stop
log_info "Waiting for simulators to fully shut down..."
sleep 3
log_success "All simulators stopped"
else
log_info "No simulators are currently running"
fi
}
# Start simulator and wait for it to be ready
start_simulator() {
local simulator_udid="$1"
local simulator_name="$2"
local device_type="$3"
log_info "Starting $device_type simulator: $simulator_name"
# Double-check if any simulator is still running
local running_simulators=$(xcrun simctl list devices | grep "Booted" | grep -oE "[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}" || echo "")
if [ -n "$running_simulators" ]; then
log_warning "Simulator still running"
log_info "Forcing stop before starting new simulator..."
stop_simulators
fi
# Start simulator
log_info "Launching simulator..."
xcrun simctl boot "$simulator_udid" 2>/dev/null || log_warning "Simulator may already be booting"
log_info "Waiting for $device_type simulator to be ready..."
# Wait for simulator to boot
local timeout=120 # 2 minutes timeout
local elapsed=0
while [ $elapsed -lt $timeout ]; do
local state=$(xcrun simctl list devices | grep "$simulator_udid" | grep -oE "(Booted|Shutdown)")
if [ "$state" = "Booted" ]; then
# Give it a bit more time to fully initialize
sleep 5
log_success "$device_type simulator is ready"
return 0
fi
sleep 2
elapsed=$((elapsed + 2))
# Show progress every 10 seconds
if [ $((elapsed % 10)) -eq 0 ]; then
log_info "Still waiting... (${elapsed}s elapsed)"
fi
done
log_error "Timeout waiting for $device_type simulator to start"
return 1
}
# Rotate simulator to landscape
rotate_simulator_landscape() {
local simulator_udid="$1"
log_info "Rotating simulator to landscape orientation..."
# Open Simulator app and bring it to front
open -a Simulator
sleep 2
# Use AppleScript to send rotation keyboard shortcut (Cmd+Left arrow rotates counterclockwise)
# Key code 123 is left arrow
osascript -e 'tell application "Simulator" to activate' \
-e 'tell application "System Events" to key code 123 using command down'
sleep 2
log_success "Simulator rotated to landscape"
}
# Detect device type based on image dimensions for iOS
detect_ios_device_type() {
local image_path="$1"
local dimensions=$(get_image_dimensions "$image_path")
if [ -z "$dimensions" ]; then
log_warning "Could not get dimensions for $image_path"
echo "iphone_6_5" # Default
return
fi
local width=$(echo "$dimensions" | cut -d',' -f1)
local height=$(echo "$dimensions" | cut -d',' -f2)
# Determine shorter and longer sides (for portrait orientation)
local shorter_side=$((width < height ? width : height))
local longer_side=$((width > height ? width : height))
# iOS App Store screenshot sizes (based on shorter side in portrait)
# Reference: https://help.apple.com/app-store-connect/#/devd274dd925
# iPad Pro 12.9" (3rd gen and later): 2048 x 2732
if [ "$shorter_side" -ge 2000 ] && [ "$longer_side" -ge 2700 ]; then
echo "ipad_pro_12_9_3rd_gen"
# iPad Pro 12.9" (2nd gen): 2048 x 2732
elif [ "$shorter_side" -ge 2000 ] && [ "$longer_side" -ge 2700 ]; then
echo "ipad_pro_12_9_2nd_gen"
# iPhone 6.9" display (iPhone Air Pro Max, 16 Pro Max, etc.): 1320 x 2868
elif [ "$shorter_side" -ge 1300 ] && [ "$longer_side" -ge 2800 ]; then
echo "iphone_6_9"
# iPhone 6.7" display (iPhone 14 Pro Max, etc.): 1290 x 2796
elif [ "$shorter_side" -ge 1250 ] && [ "$longer_side" -ge 2700 ]; then
echo "iphone_6_7"
# iPhone 6.3" display (iPhone 17, 16 Pro, 15 Pro, 14 Pro): 1206 x 2622
elif [ "$shorter_side" -ge 1200 ] && [ "$shorter_side" -lt 1242 ] && [ "$longer_side" -ge 2600 ] && [ "$longer_side" -lt 2688 ]; then
echo "iphone_6_3"
# iPhone 6.5" display (iPhone 14 Plus, 13 Pro Max, 11 Pro Max, XS Max, etc.): 1242 x 2688 or 1284 x 2778
elif [ "$shorter_side" -ge 1200 ] && [ "$longer_side" -ge 2600 ]; then
echo "iphone_6_5"
# iPhone 5.5" display (iPhone 8 Plus, etc.): 1242 x 2208
elif [ "$shorter_side" -ge 1200 ] && [ "$longer_side" -ge 2200 ]; then
echo "iphone_5_5"
else
# Default to 6.5" for unknown iPhone sizes
echo "iphone_6_5"
fi
}
# Run Flutter app on specified device
run_flutter_app() {
local device_id="$1"
local device_type="$2"
log_info "Running Flutter app on $device_type ($device_id)"
cd "$PROJECT_ROOT"
flutter run -d "$device_id" --hot &
local flutter_pid=$!
# Wait for app to be installed and launched
log_info "Waiting for Flutter app to launch..."
sleep 40 # iOS typically takes longer to launch
# Check if simulator is still running
local state=$(xcrun simctl list devices | grep "$device_id" | grep -oE "(Booted|Shutdown)")
if [ "$state" = "Booted" ]; then
log_success "Flutter app should be running on $device_type"
return 0
else
log_error "Simulator not running anymore"
return 1
fi
}
# Map device type to fastlane naming convention
get_fastlane_device_name() {
local device_type="$1"
case "$device_type" in
ipad_pro_12_9_3rd_gen|ipad_pro_12_9_2nd_gen)
echo "IPAD_PRO_3GEN_129"
;;
iphone_6_9)
echo "IPHONE_69"
;;
iphone_6_7)
echo "IPHONE_67"
;;
iphone_6_5)
echo "IPHONE_65"
;;
iphone_6_3)
echo "IPHONE_63"
;;
iphone_5_5)
echo "IPHONE_55"
;;
*)
echo "IPHONE_67" # Default to 6.7"
;;
esac
}
# Organize screenshots into correct fastlane folders
organize_screenshots() {
log_info "Organizing screenshots using ffprobe analysis..."
# Ensure target directory exists
mkdir -p "$FASTLANE_SCREENSHOTS_DIR"
# Find all screenshot files generated by maestro
local ios_screenshots_dir="$MAESTRO_DIR/ios"
if [ ! -d "$ios_screenshots_dir" ]; then
log_warning "No iOS screenshots directory found at $ios_screenshots_dir"
return 1
fi
local screenshots=($(find "$ios_screenshots_dir" -name "*.png" | sort))
if [ ${#screenshots[@]} -eq 0 ]; then
log_warning "No iOS screenshots found in $ios_screenshots_dir"
return 1
fi
log_info "Found ${#screenshots[@]} screenshots"
# First pass: detect and log all device types
local device_types=()
for screenshot in "${screenshots[@]}"; do
local device_type=$(detect_ios_device_type "$screenshot")
log_image_info "$screenshot" "$device_type"
# Add to device_types if not already present
local found=0
for dt in "${device_types[@]}"; do
if [ "$dt" = "$device_type" ]; then
found=1
break
fi
done
if [ $found -eq 0 ]; then
device_types+=("$device_type")
fi
done
# Second pass: copy and rename screenshots for each device type
for device_type in "${device_types[@]}"; do
local fastlane_name=$(get_fastlane_device_name "$device_type")
local count=0
for screenshot in "${screenshots[@]}"; do
local detected_type=$(detect_ios_device_type "$screenshot")
# Only process screenshots matching this device type
if [ "$detected_type" = "$device_type" ]; then
# Format: {index}_APP_{DEVICE_TYPE}_{index}.png
local target_name="${count}_APP_${fastlane_name}_${count}.png"
cp "$screenshot" "$FASTLANE_SCREENSHOTS_DIR/$target_name"
log_success "Copied $device_type screenshot: $(basename "$screenshot") -> $target_name"
count=$((count + 1))
fi
done
done
log_success "Screenshot organization completed"
}
# Cleanup function
cleanup() {
log_info "Cleaning up..."
# Kill any running Flutter processes
pkill -f "flutter run" 2>/dev/null || true
# Stop simulators
stop_simulators
log_success "Cleanup completed"
}
# Main execution
main() {
log_info "Starting iOS screenshot automation..."
# Set up cleanup trap
trap cleanup EXIT INT TERM
# Clean up old screenshots at the very beginning
clean_old_screenshots "ios"
# Clean up old fastlane screenshots to prevent mixing old/new with different naming
log_info "Cleaning old fastlane screenshots..."
if [ -d "$FASTLANE_SCREENSHOTS_DIR" ]; then
rm -rf "$FASTLANE_SCREENSHOTS_DIR"/*
log_success "Fastlane screenshots directory cleaned"
fi
# Check dependencies
check_dependencies
# Stop any running simulators first
stop_simulators
# Get available simulators
log_info "Getting available iOS Simulators..."
local simulators_raw=$(get_simulators)
if [ -z "$simulators_raw" ]; then
log_error "No iOS Simulators found. Please install simulators via Xcode."
exit 1
fi
# Parse simulators into arrays
declare -a simulator_udids
declare -a simulator_names
while IFS='|' read -r udid name; do
simulator_udids+=("$udid")
simulator_names+=("$name")
done <<< "$simulators_raw"
log_info "Found ${#simulator_udids[@]} iOS Simulator(s)"
# Find iPhone Air and iPad Pro 13" simulators
local iphone_idx=-1
local ipad_idx=-1
for i in "${!simulator_names[@]}"; do
if [[ "${simulator_names[$i]}" =~ iPhone\ Air ]] && [ $iphone_idx -eq -1 ]; then
iphone_idx=$i
log_info "Found iPhone Air: ${simulator_names[$i]}"
elif [[ "${simulator_names[$i]}" =~ iPad.*13 ]] && [ $ipad_idx -eq -1 ]; then
ipad_idx=$i
log_info "Found iPad Pro 13\": ${simulator_names[$i]}"
fi
done
if [ $iphone_idx -eq -1 ]; then
log_error "iPhone Air simulator not found. Please create it in Xcode."
exit 1
fi
if [ $ipad_idx -eq -1 ]; then
log_error "iPad Pro 13\" simulator not found. Please create it in Xcode."
exit 1
fi
log_info "Using iPhone: ${simulator_names[$iphone_idx]}"
log_info "Using iPad: ${simulator_names[$ipad_idx]}"
# Start iPhone Air simulator
start_simulator "${simulator_udids[$iphone_idx]}" "${simulator_names[$iphone_idx]}" "iPhone Air"
# Run Flutter app on iPhone Air
run_flutter_app "${simulator_udids[$iphone_idx]}" "iPhone Air"
# Run maestro tests for iPhone Air
run_maestro_tests "${simulator_udids[$iphone_idx]}"
# Stop iPhone simulator and switch to iPad
log_info "Switching from iPhone Air to iPad Pro 13\" simulator"
stop_simulators
# Start iPad Pro 13" simulator
start_simulator "${simulator_udids[$ipad_idx]}" "${simulator_names[$ipad_idx]}" "iPad Pro 13\""
# Rotate iPad to landscape
# rotate_simulator_landscape "${simulator_udids[$ipad_idx]}"
# Run Flutter app on iPad
run_flutter_app "${simulator_udids[$ipad_idx]}" "iPad Pro 13\""
# Run maestro tests for iPad
run_maestro_tests "${simulator_udids[$ipad_idx]}"
# Organize screenshots
organize_screenshots
log_success "iOS screenshot automation completed successfully!"
}
# Run main function if script is executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
+135
View File
@@ -0,0 +1,135 @@
#!/bin/bash
# Plezy Release Automation Script
# This script automates the release process for both iOS and Android
set -e
# Get the script's directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$SCRIPT_DIR/.."
# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color
# Load environment variables from .env
if [ -f "$PROJECT_ROOT/.env" ]; then
# Export variables without executing the file
set -a
source "$PROJECT_ROOT/.env"
set +a
echo -e "${GREEN}✅ Loaded environment variables from .env${NC}"
else
echo -e "${RED}❌ Error: .env file not found${NC}"
exit 1
fi
# Function to show help
show_help() {
echo -e "${BLUE}Plezy Release Automation${NC}"
echo ""
echo "Usage: ./scripts/release.sh <command>"
echo ""
echo "Available commands:"
echo " sync - Sync iOS release notes to Android changelog"
echo " android - Build and release to Google Play Store"
echo " ios - Build and release to App Store"
echo " all - Sync changelogs and release to both platforms"
echo " clean - Clean build artifacts"
echo " help - Show this help message"
echo ""
echo "Prerequisites:"
echo " - .env file must be configured with credentials"
echo " - iOS release notes updated in ios/fastlane/metadata/en-US/release_notes.txt"
echo " - Version bumped in pubspec.yaml"
echo ""
echo "Example:"
echo " ./scripts/release.sh all"
}
# Function to sync changelogs
sync_changelogs() {
echo -e "${YELLOW}📝 Syncing changelogs...${NC}"
"$SCRIPT_DIR/sync_changelogs.sh"
}
# Function to release Android
release_android() {
echo -e "${GREEN}🤖 Building and releasing Android app...${NC}"
cd "$PROJECT_ROOT/android"
fastlane release
cd "$PROJECT_ROOT"
}
# Function to release iOS
release_ios() {
echo -e "${GREEN}🍎 Building and releasing iOS app...${NC}"
cd "$PROJECT_ROOT/ios"
fastlane deploy_appstore
cd "$PROJECT_ROOT"
}
# Function to release all
release_all() {
sync_changelogs
echo ""
release_android
echo ""
release_ios
echo ""
echo -e "${GREEN}✅ Release complete for both platforms!${NC}"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo " 1. Check Google Play Console for the draft release"
echo " 2. Check App Store Connect for the uploaded build"
echo " 3. Submit for review when ready"
}
# Function to clean build artifacts
clean() {
echo -e "${YELLOW}🧹 Cleaning build artifacts...${NC}"
cd "$PROJECT_ROOT/android"
./gradlew clean 2>/dev/null || true
cd "$PROJECT_ROOT/ios"
xcodebuild clean -workspace Runner.xcworkspace -scheme Runner 2>/dev/null || true
cd "$PROJECT_ROOT"
flutter clean
echo -e "${GREEN}✅ Clean complete!${NC}"
}
# Main script logic
if [ $# -eq 0 ]; then
show_help
exit 0
fi
case "$1" in
sync)
sync_changelogs
;;
android)
release_android
;;
ios)
release_ios
;;
all)
release_all
;;
clean)
clean
;;
help|--help|-h)
show_help
;;
*)
echo -e "${RED}❌ Unknown command: $1${NC}"
echo ""
show_help
exit 1
;;
esac
+184
View File
@@ -0,0 +1,184 @@
#!/bin/bash
# Screenshot Automation Common Functions
# Shared functionality between Android and iOS screenshot scripts
# This script should be sourced, not executed directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
echo "This script should be sourced, not executed directly"
exit 1
fi
# Configuration - these should be set before sourcing this file, but defaults provided
SCRIPT_DIR="${SCRIPT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"
PROJECT_ROOT="${PROJECT_ROOT:-$(dirname "$SCRIPT_DIR")}"
MAESTRO_DIR="${MAESTRO_DIR:-$PROJECT_ROOT/maestro}"
ENV_FILE="${ENV_FILE:-$PROJECT_ROOT/.env}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Logging functions
log_info() {
echo -e "${BLUE}[INFO]${NC} $1"
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $1"
}
log_warning() {
echo -e "${YELLOW}[WARNING]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Check common dependencies (flutter, maestro, dotenv, ffprobe)
check_common_dependencies() {
log_info "Checking common dependencies..."
local all_found=true
if ! command -v flutter &> /dev/null; then
log_error "Flutter is not installed or not in PATH"
all_found=false
fi
if ! command -v maestro &> /dev/null; then
log_error "Maestro is not installed or not in PATH"
all_found=false
fi
if ! command -v dotenv &> /dev/null; then
log_error "dotenv is not installed or not in PATH"
all_found=false
fi
if ! command -v ffprobe &> /dev/null; then
log_error "ffprobe is not installed or not in PATH (part of ffmpeg)"
all_found=false
fi
if [ "$all_found" = false ]; then
return 1
fi
log_success "Common dependencies found"
return 0
}
# Get image dimensions using ffprobe
get_image_dimensions() {
local image_path="$1"
ffprobe -v quiet -select_streams v:0 -show_entries stream=width,height -of csv=p=0 "$image_path" 2>/dev/null
}
# Log image information for debugging
log_image_info() {
local image_path="$1"
local device_type="$2"
local dimensions=$(get_image_dimensions "$image_path")
local filename=$(basename "$image_path")
if [ -n "$dimensions" ]; then
local width=$(echo "$dimensions" | cut -d',' -f1)
local height=$(echo "$dimensions" | cut -d',' -f2)
log_info "Screenshot: $filename - ${width}x${height} - $device_type"
else
log_warning "Could not analyze: $filename - assuming $device_type"
fi
}
# Clean up old maestro screenshots for specified platform(s)
# Usage: clean_old_screenshots "android" or clean_old_screenshots "ios" or clean_old_screenshots "android ios"
clean_old_screenshots() {
local platforms="$1"
log_info "Cleaning up old screenshots..."
for platform in $platforms; do
local platform_dir="$MAESTRO_DIR/$platform"
if [ -d "$platform_dir" ]; then
local old_count=$(find "$platform_dir" -name "*.png" 2>/dev/null | wc -l)
if [ "$old_count" -gt 0 ]; then
log_info "Removing $old_count old screenshot(s) from maestro/$platform/"
rm -f "$platform_dir"/*.png
else
log_info "No old screenshots found in maestro/$platform/"
fi
else
log_info "No $platform screenshot directory found"
fi
done
log_success "Screenshot cleanup completed"
}
# Execute maestro tests
# Usage: run_maestro_tests [device_id]
run_maestro_tests() {
local device_id="${1:-}"
if [ -n "$device_id" ]; then
log_info "Running maestro screenshot tests on device $device_id..."
else
log_info "Running maestro screenshot tests..."
fi
# Check if .env file exists
if [ ! -f "$ENV_FILE" ]; then
log_error "Environment file not found at $ENV_FILE"
log_info "Please create a .env file with required Maestro variables"
return 1
fi
log_info "Using environment file: $ENV_FILE"
cd "$MAESTRO_DIR"
# Run maestro tests with optional device specification
if [ -n "$device_id" ]; then
log_info "Executing: MAESTRO_DEVICE=$device_id dotenv -f $ENV_FILE run maestro test screenshots.yaml"
MAESTRO_DEVICE="$device_id" dotenv -f "$ENV_FILE" run maestro test screenshots.yaml
else
log_info "Executing: dotenv -f $ENV_FILE run maestro test screenshots.yaml"
dotenv -f "$ENV_FILE" run maestro test screenshots.yaml
fi
local maestro_exit_code=$?
if [ $maestro_exit_code -eq 0 ]; then
log_success "Maestro tests completed successfully"
return 0
else
log_error "Maestro tests failed with exit code $maestro_exit_code"
return 1
fi
}
# Run Flutter app on specified device
# Platform-specific validation should be done in the calling script
run_flutter_app() {
local device_id="$1"
local device_type="$2"
local wait_time="${3:-30}" # Optional wait time, default 30s
log_info "Running Flutter app on $device_type ($device_id)"
cd "$PROJECT_ROOT"
flutter run -d "$device_id" --hot &
local flutter_pid=$!
# Wait for app to be installed and launched
log_info "Waiting for Flutter app to launch..."
sleep "$wait_time"
log_success "Flutter app should be running on $device_type"
return 0
}
+59
View File
@@ -0,0 +1,59 @@
#!/bin/bash
# Sync changelogs between iOS and Android
# This script copies the iOS release notes to the Android changelog for the current version
set -e
# Get the script's directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$SCRIPT_DIR/.."
# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color
echo -e "${GREEN}📝 Syncing changelogs between iOS and Android${NC}"
# Extract version code from pubspec.yaml
PUBSPEC_PATH="$PROJECT_ROOT/pubspec.yaml"
if [ ! -f "$PUBSPEC_PATH" ]; then
echo -e "${RED}Error: pubspec.yaml not found at $PUBSPEC_PATH${NC}"
exit 1
fi
VERSION_CODE=$(grep -E "version:\s*(.+)\+(\d+)" "$PUBSPEC_PATH" | sed -E 's/.*\+([0-9]+).*/\1/')
if [ -z "$VERSION_CODE" ]; then
echo -e "${RED}Error: Could not extract version code from pubspec.yaml${NC}"
exit 1
fi
echo -e "${YELLOW}Current version code: $VERSION_CODE${NC}"
# Define paths
IOS_RELEASE_NOTES="$PROJECT_ROOT/ios/fastlane/metadata/en-US/release_notes.txt"
ANDROID_CHANGELOG="$PROJECT_ROOT/android/fastlane/metadata/android/en-GB/changelogs/$VERSION_CODE.txt"
# Check if iOS release notes exist
if [ ! -f "$IOS_RELEASE_NOTES" ]; then
echo -e "${RED}Error: iOS release notes not found at $IOS_RELEASE_NOTES${NC}"
exit 1
fi
# Create Android changelogs directory if it doesn't exist
ANDROID_CHANGELOGS_DIR="$(dirname "$ANDROID_CHANGELOG")"
mkdir -p "$ANDROID_CHANGELOGS_DIR"
# Copy iOS release notes to Android changelog
cp "$IOS_RELEASE_NOTES" "$ANDROID_CHANGELOG"
echo -e "${GREEN}✅ Successfully synced changelog!${NC}"
echo -e " iOS release notes → Android changelog ($VERSION_CODE.txt)"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo "1. Review the changelog at: $ANDROID_CHANGELOG"
echo "2. Commit the changes"
echo "3. Run fastlane to deploy"
@@ -6,6 +6,7 @@
#include "generated_plugin_registrant.h"
#include <hotkey_manager_windows/hotkey_manager_windows_plugin_c_api.h>
#include <media_kit_libs_windows_video/media_kit_libs_windows_video_plugin_c_api.h>
#include <media_kit_video/media_kit_video_plugin_c_api.h>
#include <screen_retriever_windows/screen_retriever_windows_plugin_c_api.h>
@@ -14,6 +15,8 @@
#include <window_manager/window_manager_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
HotkeyManagerWindowsPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("HotkeyManagerWindowsPluginCApi"));
MediaKitLibsWindowsVideoPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("MediaKitLibsWindowsVideoPluginCApi"));
MediaKitVideoPluginCApiRegisterWithRegistrar(
+1
View File
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
hotkey_manager_windows
media_kit_libs_windows_video
media_kit_video
screen_retriever_windows