Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36c6adb50c | ||
|
|
4180ab6248 | ||
|
|
597640ece5 | ||
|
|
4031b6043c | ||
|
|
57676178e2 | ||
|
|
4430581806 | ||
|
|
7236702818 | ||
|
|
0774263d83 | ||
|
|
6243195b21 | ||
|
|
8d8423d136 | ||
|
|
2f7c1084cb | ||
|
|
03495b1ea3 | ||
|
|
a48032c706 | ||
|
|
357a4a5590 | ||
|
|
81adf86769 | ||
|
|
50264d52f3 | ||
|
|
2603a3992c | ||
|
|
3f95b4d822 | ||
|
|
3b8c944512 | ||
|
|
d646adca89 | ||
|
|
3e7a9231b7 | ||
|
|
dd76e59bf1 | ||
|
|
bc54a2230b | ||
|
|
4b972b0992 | ||
|
|
1cab790570 | ||
|
|
feb9254aea | ||
|
|
9a2e5e5358 | ||
|
|
e260f801d6 | ||
|
|
2ac3555567 | ||
|
|
dafdea282e | ||
|
|
aa1efdff64 | ||
|
|
3d5c7f7e3b | ||
|
|
1ec9fbcc02 | ||
|
|
8e00ad0551 | ||
|
|
deadbd1be7 | ||
|
|
3d3358e4f9 | ||
|
|
51cb83cef9 | ||
|
|
0e2fe8a9f3 | ||
|
|
63fa08798c | ||
|
|
94e6c4109a | ||
|
|
4dd2d7b011 | ||
|
|
4696b5c7b0 | ||
|
|
852cee8967 | ||
|
|
2e7babaae5 | ||
|
|
65057750f7 | ||
|
|
e50bd46386 | ||
|
|
1c67fa3998 | ||
|
|
d586c8c067 | ||
|
|
f1a5493aeb | ||
|
|
7efa96be74 | ||
|
|
770cb6b744 | ||
|
|
5126b67c9c | ||
|
|
f0035d1335 | ||
|
|
ca576110b8 | ||
|
|
1f59374f62 | ||
|
|
679e5d5c39 | ||
|
|
73568ee3ae | ||
|
|
aa9dd045de | ||
|
|
69e7e796b4 | ||
|
|
95263b7625 | ||
|
|
236e3e7cfc | ||
|
|
f06deba0cc | ||
|
|
dcb4f3ee8a | ||
|
|
4246d7689d | ||
|
|
781aa4640e | ||
|
|
ed668ba0e4 | ||
|
|
fffe342dd1 | ||
|
|
b5349d7b3d | ||
|
|
f7d98fbe44 | ||
|
|
3a5b812a22 | ||
|
|
b01f9ce3f9 | ||
|
|
25ff8f1d1f | ||
|
|
ce8d384e7c | ||
|
|
bae7b70feb | ||
|
|
26e7dba0d0 | ||
|
|
00fe8039cc | ||
|
|
7526e80a40 | ||
|
|
6e1a2e0568 | ||
|
|
127500329b | ||
|
|
a81cf3b18f | ||
|
|
66f00d192f | ||
|
|
ad9502d3c7 | ||
|
|
380a15442a |
+108
-14
@@ -2,9 +2,6 @@ name: Build Flutter App
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
|
||||
jobs:
|
||||
build-android:
|
||||
@@ -50,8 +47,22 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Configure Android signing
|
||||
run: |
|
||||
echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" | base64 --decode > android/app/upload-keystore.jks
|
||||
cat > android/key.properties << EOF
|
||||
storePassword=${{ secrets.ANDROID_STORE_PASSWORD }}
|
||||
keyPassword=${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
keyAlias=${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
storeFile=upload-keystore.jks
|
||||
EOF
|
||||
|
||||
- name: Build APK
|
||||
run: flutter build apk --release
|
||||
run: flutter build apk --release --dart-define=ENABLE_UPDATE_CHECK=true
|
||||
|
||||
- name: Clean up keystore
|
||||
if: always()
|
||||
run: rm -f android/app/upload-keystore.jks android/key.properties
|
||||
|
||||
- name: Rename APK
|
||||
run: |
|
||||
@@ -69,7 +80,7 @@ jobs:
|
||||
path: plezy-android.apk
|
||||
|
||||
build-ios:
|
||||
runs-on: macos-latest
|
||||
runs-on: macos-26
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
@@ -107,7 +118,7 @@ jobs:
|
||||
run: flutter pub get
|
||||
|
||||
- name: Build iOS (no codesign)
|
||||
run: flutter build ios --release --no-codesign
|
||||
run: flutter build ios --release --no-codesign --dart-define=ENABLE_UPDATE_CHECK=true
|
||||
|
||||
- name: Create IPA
|
||||
run: |
|
||||
@@ -127,7 +138,7 @@ jobs:
|
||||
path: plezy-ios.ipa
|
||||
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
runs-on: macos-26
|
||||
permissions:
|
||||
id-token: write
|
||||
attestations: write
|
||||
@@ -165,12 +176,88 @@ jobs:
|
||||
run: flutter pub get
|
||||
|
||||
- name: Build macOS
|
||||
run: flutter build macos --release
|
||||
run: flutter build macos --release --dart-define=ENABLE_UPDATE_CHECK=true
|
||||
|
||||
- name: Import Code Signing Certificate
|
||||
env:
|
||||
MACOS_CERTIFICATE_BASE64: ${{ secrets.MACOS_CERTIFICATE_BASE64 }}
|
||||
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
run: |
|
||||
# Create temporary keychain
|
||||
KEYCHAIN_PATH=$RUNNER_TEMP/build.keychain
|
||||
security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
|
||||
security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
|
||||
security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
|
||||
|
||||
# Import certificate to keychain
|
||||
CERTIFICATE_PATH=$RUNNER_TEMP/certificate.p12
|
||||
echo "$MACOS_CERTIFICATE_BASE64" | base64 --decode -o $CERTIFICATE_PATH
|
||||
security import $CERTIFICATE_PATH -k $KEYCHAIN_PATH -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
|
||||
security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
|
||||
|
||||
# Add keychain to search list
|
||||
security list-keychains -d user -s $KEYCHAIN_PATH login.keychain
|
||||
|
||||
- name: Sign Application
|
||||
env:
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
# Find the identity
|
||||
IDENTITY=$(security find-identity -v -p codesigning | grep "Developer ID Application" | head -1 | grep -o '".*"' | tr -d '"')
|
||||
echo "Signing with identity: $IDENTITY"
|
||||
|
||||
APP_PATH="build/macos/Build/Products/Release/plezy.app"
|
||||
|
||||
# Sign all frameworks and dylibs first (inside-out signing)
|
||||
find "$APP_PATH/Contents/Frameworks" -name "*.framework" -o -name "*.dylib" | while read framework; do
|
||||
echo "Signing: $framework"
|
||||
codesign --force --sign "$IDENTITY" --timestamp --options runtime "$framework"
|
||||
done
|
||||
|
||||
# Sign the app bundle itself
|
||||
echo "Signing app bundle: $APP_PATH"
|
||||
codesign --force --sign "$IDENTITY" --timestamp --options runtime --entitlements macos/Runner/Release.entitlements "$APP_PATH"
|
||||
|
||||
- name: Verify Signature
|
||||
run: |
|
||||
APP_PATH="build/macos/Build/Products/Release/plezy.app"
|
||||
echo "Verifying signature..."
|
||||
codesign -dvvv "$APP_PATH"
|
||||
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
|
||||
|
||||
- name: Notarize Application
|
||||
env:
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
APP_PATH="build/macos/Build/Products/Release/plezy.app"
|
||||
|
||||
# Create a temporary ZIP for notarization submission
|
||||
echo "Creating ZIP for notarization..."
|
||||
ditto -c -k --keepParent "$APP_PATH" notarization.zip
|
||||
|
||||
# Submit for notarization
|
||||
echo "Submitting to Apple's notary service..."
|
||||
xcrun notarytool submit notarization.zip \
|
||||
--apple-id "$APPLE_ID" \
|
||||
--password "$APPLE_APP_SPECIFIC_PASSWORD" \
|
||||
--team-id "$APPLE_TEAM_ID" \
|
||||
--wait
|
||||
|
||||
# Staple the notarization ticket to the app
|
||||
echo "Stapling notarization ticket..."
|
||||
xcrun stapler staple "$APP_PATH"
|
||||
|
||||
# Verify stapling
|
||||
echo "Verifying notarization..."
|
||||
xcrun stapler validate "$APP_PATH"
|
||||
|
||||
- name: Create ZIP
|
||||
run: |
|
||||
cd build/macos/Build/Products/Release
|
||||
zip -r $GITHUB_WORKSPACE/plezy-macos.zip plezy.app
|
||||
ditto -c -k --sequesterRsrc --keepParent plezy.app $GITHUB_WORKSPACE/plezy-macos.zip
|
||||
|
||||
- name: Attest macOS ZIP
|
||||
uses: actions/attest-build-provenance@v2
|
||||
@@ -211,7 +298,7 @@ jobs:
|
||||
run: flutter pub get
|
||||
|
||||
- name: Build Windows
|
||||
run: flutter build windows --release
|
||||
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true
|
||||
|
||||
- name: Build Windows Installer
|
||||
run: .\windows\build-installer.ps1
|
||||
@@ -262,19 +349,19 @@ jobs:
|
||||
- name: Cache APT packages
|
||||
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||
with:
|
||||
packages: clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv
|
||||
packages: clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0
|
||||
version: 1.0
|
||||
|
||||
- name: Install Linux dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv
|
||||
sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libasound2-dev libmpv-dev mpv keybinder-3.0
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
- name: Build Linux
|
||||
run: flutter build linux --release
|
||||
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true
|
||||
|
||||
- name: Create Archive
|
||||
run: |
|
||||
@@ -293,7 +380,14 @@ jobs:
|
||||
path: plezy-linux.tar.gz
|
||||
|
||||
create-release:
|
||||
needs: [build-android, build-ios, build-macos, build-windows, build-linux]
|
||||
needs:
|
||||
[
|
||||
build-android,
|
||||
build-ios,
|
||||
build-macos,
|
||||
build-windows,
|
||||
build-linux,
|
||||
]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
+7
-2
@@ -47,5 +47,10 @@ app.*.map.json
|
||||
# Code duplication reports
|
||||
duplication-report/
|
||||
|
||||
# Test credentials (do not commit!)
|
||||
.env.test
|
||||
.env.*
|
||||
.env
|
||||
!.env.example
|
||||
|
||||
**/fastlane/**/
|
||||
**/fastlane/report.xml
|
||||
maestro/**/*.png
|
||||
|
||||
@@ -14,7 +14,10 @@ Plezy is a modern Plex media client that provides a seamless streaming experienc
|
||||
## Download
|
||||
|
||||
### Mobile
|
||||
Coming soon
|
||||
<a href='https://apps.apple.com/us/app/id6754315964'><img height='60' alt='Download on the App Store' src='./assets/app-store-badge.png'/></a>
|
||||
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
|
||||
|
||||
> Google Play version is in closed testing ([required by Google](https://support.google.com/googleplay/android-developer/answer/14151465#overview)). Join the [Google Group](https://groups.google.com/g/plezy-testers-2) to get access.
|
||||
|
||||
### Desktop
|
||||
- [Windows (x64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
|
||||
|
||||
@@ -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 |
@@ -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
|
||||
+367
-8
@@ -3,7 +3,11 @@ 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 '../models/plex_hub.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
/// Result of testing a connection, including success status and latency
|
||||
@@ -26,6 +30,8 @@ class PlexClient {
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(seconds: 30),
|
||||
validateStatus: (status) => status != null && status < 500,
|
||||
responseType: ResponseType.json,
|
||||
contentType: 'application/json; charset=utf-8',
|
||||
),
|
||||
);
|
||||
|
||||
@@ -74,6 +80,8 @@ class PlexClient {
|
||||
connectTimeout: timeout,
|
||||
receiveTimeout: timeout,
|
||||
validateStatus: (status) => status != null && status < 500,
|
||||
responseType: ResponseType.json,
|
||||
contentType: 'application/json; charset=utf-8',
|
||||
),
|
||||
);
|
||||
|
||||
@@ -332,23 +340,35 @@ class PlexClient {
|
||||
return results;
|
||||
}
|
||||
|
||||
/// Get recently added media
|
||||
/// Get recently added media (filtered to video content only)
|
||||
Future<List<PlexMetadata>> getRecentlyAdded({int limit = 50}) async {
|
||||
final response = await _dio.get(
|
||||
'/library/recentlyAdded',
|
||||
queryParameters: {'X-Plex-Container-Size': limit, 'includeGuids': 1},
|
||||
);
|
||||
return _extractMetadataList(response);
|
||||
final allItems = _extractMetadataList(response);
|
||||
|
||||
// Filter out music content (artists, albums, tracks)
|
||||
return allItems.where((item) {
|
||||
final type = item.type.toLowerCase();
|
||||
return type != 'artist' && type != 'album' && type != 'track';
|
||||
}).toList();
|
||||
}
|
||||
|
||||
/// Get on deck items (continue watching)
|
||||
/// Get on deck items (continue watching, filtered to video content only)
|
||||
Future<List<PlexMetadata>> getOnDeck() async {
|
||||
final response = await _dio.get('/library/onDeck');
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null && container['Metadata'] != null) {
|
||||
return (container['Metadata'] as List)
|
||||
final allItems = (container['Metadata'] as List)
|
||||
.map((json) => PlexMetadata.fromJsonWithImages(json))
|
||||
.toList();
|
||||
|
||||
// Filter out music content (artists, albums, tracks)
|
||||
return allItems.where((item) {
|
||||
final type = item.type.toLowerCase();
|
||||
return type != 'artist' && type != 'album' && type != 'track';
|
||||
}).toList();
|
||||
}
|
||||
return [];
|
||||
}
|
||||
@@ -359,6 +379,44 @@ class PlexClient {
|
||||
return _extractMetadataList(response);
|
||||
}
|
||||
|
||||
/// Get all unwatched episodes for a TV show across all seasons
|
||||
Future<List<PlexMetadata>> getAllUnwatchedEpisodes(
|
||||
String showRatingKey,
|
||||
) async {
|
||||
final allEpisodes = <PlexMetadata>[];
|
||||
|
||||
// Get all seasons for the show
|
||||
final seasons = await getChildren(showRatingKey);
|
||||
|
||||
// Get episodes from each season
|
||||
for (final season in seasons) {
|
||||
if (season.type == 'season') {
|
||||
final episodes = await getChildren(season.ratingKey);
|
||||
|
||||
// Filter for unwatched episodes
|
||||
final unwatchedEpisodes = episodes
|
||||
.where((ep) => ep.type == 'episode' && (ep.viewCount ?? 0) == 0)
|
||||
.toList();
|
||||
|
||||
allEpisodes.addAll(unwatchedEpisodes);
|
||||
}
|
||||
}
|
||||
|
||||
return allEpisodes;
|
||||
}
|
||||
|
||||
/// Get all unwatched episodes in a specific season
|
||||
Future<List<PlexMetadata>> getUnwatchedEpisodesInSeason(
|
||||
String seasonRatingKey,
|
||||
) async {
|
||||
final episodes = await getChildren(seasonRatingKey);
|
||||
|
||||
// Filter for unwatched episodes
|
||||
return episodes
|
||||
.where((ep) => ep.type == 'episode' && (ep.viewCount ?? 0) == 0)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Get thumbnail URL
|
||||
String getThumbnailUrl(String? thumbPath) {
|
||||
if (thumbPath == null || thumbPath.isEmpty) return '';
|
||||
@@ -370,14 +428,22 @@ 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 (metadataJson != null &&
|
||||
metadataJson['Media'] != null &&
|
||||
(metadataJson['Media'] as List).isNotEmpty) {
|
||||
final media = metadataJson['Media'][0];
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
}
|
||||
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
@@ -418,14 +484,25 @@ class PlexClient {
|
||||
}
|
||||
|
||||
/// 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 (metadataJson != null &&
|
||||
metadataJson['Media'] != null &&
|
||||
(metadataJson['Media'] as List).isNotEmpty) {
|
||||
final media = metadataJson['Media'][0];
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
|
||||
// Ensure the requested index is valid
|
||||
if (mediaIndex < 0 || mediaIndex >= mediaList.length) {
|
||||
mediaIndex = 0;
|
||||
}
|
||||
|
||||
final media = mediaList[mediaIndex];
|
||||
if (media['Part'] != null && (media['Part'] as List).isNotEmpty) {
|
||||
final part = media['Part'][0];
|
||||
final partKey = part['key'] as String?;
|
||||
@@ -504,6 +581,94 @@ 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(
|
||||
@@ -573,6 +738,94 @@ class PlexClient {
|
||||
return _extractDirectoryList(response, PlexFilterValue.fromJson);
|
||||
}
|
||||
|
||||
/// Get available sort options for a library section
|
||||
Future<List<PlexSort>> getLibrarySorts(String sectionId) async {
|
||||
try {
|
||||
// Use the dedicated sorts endpoint
|
||||
final response = await _dio.get('/library/sections/$sectionId/sorts');
|
||||
|
||||
// Parse the Directory array (not Sort array) per the API spec
|
||||
final sorts = _extractDirectoryList(response, PlexSort.fromJson);
|
||||
|
||||
if (sorts.isNotEmpty) {
|
||||
return sorts;
|
||||
}
|
||||
|
||||
// Fallback: return common sort options if API doesn't provide them
|
||||
return _getFallbackSorts(sectionId);
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to get library sorts: $e');
|
||||
// Return fallback sort options on error
|
||||
return _getFallbackSorts(sectionId);
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<PlexSort>> _getFallbackSorts(String sectionId) async {
|
||||
try {
|
||||
// Get library type to determine which sorts to include
|
||||
final librariesResponse = await _dio.get('/library/sections');
|
||||
final libraries = _extractDirectoryList(
|
||||
librariesResponse,
|
||||
PlexLibrary.fromJson,
|
||||
);
|
||||
final library = libraries.firstWhere(
|
||||
(lib) => lib.key == sectionId,
|
||||
orElse: () => libraries.first,
|
||||
);
|
||||
|
||||
final fallbackSorts = <PlexSort>[
|
||||
PlexSort(key: 'titleSort', title: 'Title', defaultDirection: 'asc'),
|
||||
PlexSort(
|
||||
key: 'addedAt',
|
||||
descKey: 'addedAt:desc',
|
||||
title: 'Date Added',
|
||||
defaultDirection: 'desc',
|
||||
),
|
||||
];
|
||||
|
||||
// Add "Latest Episode Air Date" only for TV show libraries
|
||||
if (library.type.toLowerCase() == 'show') {
|
||||
fallbackSorts.add(
|
||||
PlexSort(
|
||||
key: 'episode.originallyAvailableAt',
|
||||
descKey: 'episode.originallyAvailableAt:desc',
|
||||
title: 'Latest Episode Air Date',
|
||||
defaultDirection: 'desc',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
fallbackSorts.addAll([
|
||||
PlexSort(
|
||||
key: 'originallyAvailableAt',
|
||||
descKey: 'originallyAvailableAt:desc',
|
||||
title: 'Release Date',
|
||||
defaultDirection: 'desc',
|
||||
),
|
||||
PlexSort(
|
||||
key: 'rating',
|
||||
descKey: 'rating:desc',
|
||||
title: 'Rating',
|
||||
defaultDirection: 'desc',
|
||||
),
|
||||
]);
|
||||
|
||||
return fallbackSorts;
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to get fallback sorts: $e');
|
||||
// Return minimal fallback options
|
||||
return [
|
||||
PlexSort(key: 'titleSort', title: 'Title', defaultDirection: 'asc'),
|
||||
PlexSort(
|
||||
key: 'addedAt',
|
||||
descKey: 'addedAt:desc',
|
||||
title: 'Date Added',
|
||||
defaultDirection: 'desc',
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// Find adjacent episode in a given direction
|
||||
///
|
||||
/// [direction]: +1 for next episode, -1 for previous episode
|
||||
@@ -648,4 +901,110 @@ class PlexClient {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Get library hubs (recommendations for a specific library section)
|
||||
/// Returns a list of recommendation hubs like "Trending Movies", "Top in Genre", etc.
|
||||
Future<List<PlexHub>> getLibraryHubs(
|
||||
String sectionId, {
|
||||
int limit = 10,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
'/hubs/sections/$sectionId',
|
||||
queryParameters: {'count': limit, 'includeGuids': 1},
|
||||
);
|
||||
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null && container['Hub'] != null) {
|
||||
final hubs = <PlexHub>[];
|
||||
for (final hubJson in container['Hub'] as List) {
|
||||
try {
|
||||
final hub = PlexHub.fromJson(hubJson);
|
||||
// Only include hubs that have items and are movie/show content
|
||||
if (hub.items.isNotEmpty) {
|
||||
// Filter out non-video content types
|
||||
final videoItems = hub.items.where((item) {
|
||||
final type = item.type.toLowerCase();
|
||||
return type == 'movie' || type == 'show';
|
||||
}).toList();
|
||||
|
||||
if (videoItems.isNotEmpty) {
|
||||
hubs.add(
|
||||
PlexHub(
|
||||
hubKey: hub.hubKey,
|
||||
title: hub.title,
|
||||
type: hub.type,
|
||||
hubIdentifier: hub.hubIdentifier,
|
||||
size: hub.size,
|
||||
more: hub.more,
|
||||
items: videoItems,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to parse hub', error: e);
|
||||
}
|
||||
}
|
||||
return hubs;
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to get library hubs: $e');
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Get full content from a hub using its hub key
|
||||
/// Returns the complete list of metadata items in the hub
|
||||
Future<List<PlexMetadata>> getHubContent(String hubKey) async {
|
||||
try {
|
||||
final response = await _dio.get(hubKey);
|
||||
final allItems = _extractMetadataList(response);
|
||||
|
||||
// Filter out non-video content types
|
||||
return allItems.where((item) {
|
||||
final type = item.type.toLowerCase();
|
||||
return type == 'movie' || type == 'show';
|
||||
}).toList();
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to get hub content: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Get playlist content by playlist ID
|
||||
/// Returns the list of metadata items in the playlist
|
||||
Future<List<PlexMetadata>> getPlaylist(String playlistId) async {
|
||||
try {
|
||||
final response = await _dio.get('/playlists/$playlistId/items');
|
||||
return _extractMetadataList(response);
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to get playlist: $e');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Library Management Methods
|
||||
// ============================================================================
|
||||
|
||||
/// Scan/refresh a library section to detect new files
|
||||
Future<void> scanLibrary(String sectionId) async {
|
||||
await _dio.get('/library/sections/$sectionId/refresh');
|
||||
}
|
||||
|
||||
/// Refresh metadata for a library section
|
||||
Future<void> refreshLibraryMetadata(String sectionId) async {
|
||||
await _dio.get('/library/sections/$sectionId/refresh?force=1');
|
||||
}
|
||||
|
||||
/// Empty trash for a library section
|
||||
Future<void> emptyLibraryTrash(String sectionId) async {
|
||||
await _dio.put('/library/sections/$sectionId/emptyTrash');
|
||||
}
|
||||
|
||||
/// Analyze library section
|
||||
Future<void> analyzeLibrary(String sectionId) async {
|
||||
await _dio.get('/library/sections/$sectionId/analyze');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ class PlexConfig {
|
||||
'X-Plex-Platform': platform,
|
||||
if (device != null) 'X-Plex-Device': device!,
|
||||
if (acceptJson) 'Accept': 'application/json',
|
||||
'Accept-Charset': 'utf-8',
|
||||
};
|
||||
|
||||
if (token != null) {
|
||||
|
||||
+129
-16
@@ -1,9 +1,9 @@
|
||||
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 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'screens/main_screen.dart';
|
||||
import 'screens/auth_screen.dart';
|
||||
import 'services/storage_service.dart';
|
||||
@@ -11,16 +11,26 @@ import 'services/plex_auth_service.dart';
|
||||
import 'services/server_connection_service.dart';
|
||||
import 'services/macos_titlebar_service.dart';
|
||||
import 'services/fullscreen_state_manager.dart';
|
||||
import 'services/update_service.dart';
|
||||
import 'services/settings_service.dart';
|
||||
import 'providers/user_profile_provider.dart';
|
||||
import 'providers/plex_client_provider.dart';
|
||||
import 'providers/theme_provider.dart';
|
||||
import 'providers/settings_provider.dart';
|
||||
import 'providers/hidden_libraries_provider.dart';
|
||||
import 'providers/playback_state_provider.dart';
|
||||
import 'utils/language_codes.dart';
|
||||
import 'utils/app_logger.dart';
|
||||
import 'utils/provider_extensions.dart';
|
||||
import 'utils/orientation_helper.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
// Configure image cache for large libraries
|
||||
PaintingBinding.instance.imageCache.maximumSizeBytes = 500 << 20; // 500MB
|
||||
PaintingBinding.instance.imageCache.maximumSize = 500; // 500 images
|
||||
|
||||
// Initialize window_manager for desktop platforms
|
||||
if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
|
||||
await windowManager.ensureInitialized();
|
||||
@@ -32,17 +42,18 @@ void main() async {
|
||||
// Initialize MediaKit
|
||||
MediaKit.ensureInitialized();
|
||||
|
||||
// Lock orientation to portrait for all screens except video player
|
||||
await SystemChrome.setPreferredOrientations([
|
||||
DeviceOrientation.portraitUp,
|
||||
DeviceOrientation.portraitDown,
|
||||
]);
|
||||
// Note: Orientation will be set dynamically based on device type in MainApp
|
||||
|
||||
await StorageService.getInstance();
|
||||
|
||||
// Initialize language codes for track selection
|
||||
await LanguageCodes.initialize();
|
||||
|
||||
// Initialize logger level based on debug setting
|
||||
final settings = await SettingsService.getInstance();
|
||||
final debugEnabled = settings.getEnableDebugLogging();
|
||||
setLoggerLevel(debugEnabled);
|
||||
|
||||
// Start global fullscreen state monitoring
|
||||
FullscreenStateManager().startMonitoring();
|
||||
|
||||
@@ -66,6 +77,9 @@ class MainApp extends StatelessWidget {
|
||||
create: (context) => UserProfileProvider()..initialize(),
|
||||
),
|
||||
ChangeNotifierProvider(create: (context) => ThemeProvider()),
|
||||
ChangeNotifierProvider(create: (context) => SettingsProvider()),
|
||||
ChangeNotifierProvider(create: (context) => HiddenLibrariesProvider()),
|
||||
ChangeNotifierProvider(create: (context) => PlaybackStateProvider()),
|
||||
],
|
||||
child: Consumer<ThemeProvider>(
|
||||
builder: (context, themeProvider, child) {
|
||||
@@ -76,7 +90,7 @@ class MainApp extends StatelessWidget {
|
||||
darkTheme: themeProvider.darkTheme,
|
||||
themeMode: themeProvider.materialThemeMode,
|
||||
navigatorObservers: [routeObserver],
|
||||
home: const SetupScreen(),
|
||||
home: const OrientationAwareSetup(),
|
||||
);
|
||||
},
|
||||
),
|
||||
@@ -84,6 +98,30 @@ class MainApp extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
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});
|
||||
|
||||
@@ -98,6 +136,78 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
_loadSavedCredentials();
|
||||
}
|
||||
|
||||
void _checkForUpdatesOnStartup() async {
|
||||
// Delay slightly to allow UI to settle
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
try {
|
||||
final updateInfo = await UpdateService.checkForUpdatesOnStartup();
|
||||
|
||||
if (updateInfo != null && updateInfo['hasUpdate'] == true && mounted) {
|
||||
_showUpdateDialog(updateInfo);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Error checking for updates', error: e);
|
||||
}
|
||||
}
|
||||
|
||||
void _showUpdateDialog(Map<String, dynamic> updateInfo) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext dialogContext) {
|
||||
return AlertDialog(
|
||||
title: const Text('Update Available'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Version ${updateInfo['latestVersion']} is available',
|
||||
style: Theme.of(dialogContext).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Current: ${updateInfo['currentVersion']}',
|
||||
style: Theme.of(dialogContext).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(dialogContext);
|
||||
},
|
||||
child: const Text('Later'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
await UpdateService.skipVersion(updateInfo['latestVersion']);
|
||||
if (dialogContext.mounted) {
|
||||
Navigator.pop(dialogContext);
|
||||
}
|
||||
},
|
||||
child: const Text('Skip This Version'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final url = Uri.parse(updateInfo['releaseUrl']);
|
||||
if (await canLaunchUrl(url)) {
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
if (dialogContext.mounted) {
|
||||
Navigator.pop(dialogContext);
|
||||
}
|
||||
},
|
||||
child: const Text('View Release'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _loadSavedCredentials() async {
|
||||
final storage = await StorageService.getInstance();
|
||||
|
||||
@@ -145,19 +255,22 @@ class _SetupScreenState extends State<SetupScreen> {
|
||||
|
||||
// Handle result
|
||||
if (result.isSuccess) {
|
||||
// Success! Set client in provider and navigate to main screen
|
||||
// Success! Set client in provider
|
||||
if (mounted) {
|
||||
context.plexClient.setClient(result.client!);
|
||||
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MainScreen(
|
||||
client: result.client!,
|
||||
userProfile: result.userProfile,
|
||||
// Check for updates BEFORE navigation to keep context valid
|
||||
_checkForUpdatesOnStartup();
|
||||
|
||||
// Navigate to main screen after update check is initiated
|
||||
if (mounted) {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MainScreen(client: result.client!),
|
||||
),
|
||||
),
|
||||
);
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import 'plex_home_user.dart';
|
||||
class PlexHome {
|
||||
final int id;
|
||||
final String name;
|
||||
final int guestUserID;
|
||||
final int? guestUserID;
|
||||
final String guestUserUUID;
|
||||
final bool guestEnabled;
|
||||
final bool subscription;
|
||||
@@ -28,9 +28,9 @@ class PlexHome {
|
||||
.toList();
|
||||
|
||||
return PlexHome(
|
||||
id: json['id'] as int,
|
||||
id: (json['id'] as num?)?.toInt() ?? 0,
|
||||
name: json['name'] as String,
|
||||
guestUserID: json['guestUserID'] as int,
|
||||
guestUserID: (json['guestUserID'] as num?)?.toInt(),
|
||||
guestUserUUID: json['guestUserUUID'] as String,
|
||||
guestEnabled: json['guestEnabled'] as bool,
|
||||
subscription: json['subscription'] as bool,
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlexHomeUser {
|
||||
final String thumb;
|
||||
final bool hasPassword;
|
||||
final bool restricted;
|
||||
final int updatedAt;
|
||||
final int? updatedAt;
|
||||
final bool admin;
|
||||
final bool guest;
|
||||
final bool protected;
|
||||
@@ -31,19 +31,19 @@ class PlexHomeUser {
|
||||
|
||||
factory PlexHomeUser.fromJson(Map<String, dynamic> json) {
|
||||
return PlexHomeUser(
|
||||
id: json['id'] as int,
|
||||
uuid: json['uuid'] as String,
|
||||
title: json['title'] as String,
|
||||
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,
|
||||
restricted: json['restricted'] as bool,
|
||||
updatedAt: json['updatedAt'] as int,
|
||||
admin: json['admin'] as bool,
|
||||
guest: json['guest'] as bool,
|
||||
protected: json['protected'] as bool,
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -70,5 +70,5 @@ class PlexHomeUser {
|
||||
bool get isAdminUser => admin;
|
||||
bool get isRestrictedUser => restricted;
|
||||
bool get isGuestUser => guest;
|
||||
bool get requiresPassword => hasPassword;
|
||||
bool get requiresPassword => protected;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'plex_metadata.dart';
|
||||
|
||||
/// Represents a Plex hub/recommendation section (e.g., Trending Movies, Top Thrillers)
|
||||
class PlexHub {
|
||||
final String hubKey;
|
||||
final String title;
|
||||
final String type;
|
||||
final String? hubIdentifier;
|
||||
final int size;
|
||||
final bool more;
|
||||
final List<PlexMetadata> items;
|
||||
|
||||
PlexHub({
|
||||
required this.hubKey,
|
||||
required this.title,
|
||||
required this.type,
|
||||
this.hubIdentifier,
|
||||
required this.size,
|
||||
required this.more,
|
||||
required this.items,
|
||||
});
|
||||
|
||||
factory PlexHub.fromJson(Map<String, dynamic> json) {
|
||||
final metadataList = <PlexMetadata>[];
|
||||
|
||||
// Hubs can contain either Metadata or Directory entries
|
||||
if (json['Metadata'] != null) {
|
||||
for (final item in json['Metadata'] as List) {
|
||||
try {
|
||||
metadataList.add(PlexMetadata.fromJson(item));
|
||||
} catch (e) {
|
||||
// Skip items that fail to parse
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (json['Directory'] != null) {
|
||||
for (final item in json['Directory'] as List) {
|
||||
try {
|
||||
metadataList.add(PlexMetadata.fromJson(item));
|
||||
} catch (e) {
|
||||
// Skip items that fail to parse
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return PlexHub(
|
||||
hubKey: json['key'] as String? ?? '',
|
||||
title: json['title'] as String? ?? 'Unknown',
|
||||
type: json['type'] as String? ?? 'hub',
|
||||
hubIdentifier: json['hubIdentifier'] as String?,
|
||||
size: (json['size'] as num?)?.toInt() ?? metadataList.length,
|
||||
more: json['more'] == true || json['more'] == 1,
|
||||
items: metadataList,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../services/storage_service.dart';
|
||||
|
||||
/// Provider for managing hidden library state across the app.
|
||||
/// This ensures that when a library is hidden/unhidden in one screen,
|
||||
/// all other screens are automatically updated.
|
||||
class HiddenLibrariesProvider extends ChangeNotifier {
|
||||
late StorageService _storageService;
|
||||
Set<String> _hiddenLibraryKeys = {};
|
||||
bool _isInitialized = false;
|
||||
|
||||
/// Get an unmodifiable copy of hidden library keys
|
||||
Set<String> get hiddenLibraryKeys => Set.unmodifiable(_hiddenLibraryKeys);
|
||||
|
||||
/// Check if the provider has completed initialization
|
||||
bool get isInitialized => _isInitialized;
|
||||
|
||||
HiddenLibrariesProvider() {
|
||||
_initialize();
|
||||
}
|
||||
|
||||
/// Initialize the provider by loading hidden libraries from storage
|
||||
Future<void> _initialize() async {
|
||||
_storageService = await StorageService.getInstance();
|
||||
_hiddenLibraryKeys = _storageService.getHiddenLibraries();
|
||||
_isInitialized = true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Hide a library by its key
|
||||
/// Updates both in-memory state and persistent storage
|
||||
Future<void> hideLibrary(String libraryKey) async {
|
||||
if (!_hiddenLibraryKeys.contains(libraryKey)) {
|
||||
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..add(libraryKey);
|
||||
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// Unhide a library by its key
|
||||
/// Updates both in-memory state and persistent storage
|
||||
Future<void> unhideLibrary(String libraryKey) async {
|
||||
if (_hiddenLibraryKeys.contains(libraryKey)) {
|
||||
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..remove(libraryKey);
|
||||
await _storageService.saveHiddenLibraries(_hiddenLibraryKeys);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if a specific library is hidden
|
||||
bool isLibraryHidden(String libraryKey) {
|
||||
return _hiddenLibraryKeys.contains(libraryKey);
|
||||
}
|
||||
|
||||
/// Refresh hidden libraries from storage
|
||||
/// Useful if storage was modified outside the provider
|
||||
Future<void> refresh() async {
|
||||
_hiddenLibraryKeys = _storageService.getHiddenLibraries();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
|
||||
/// Manages shuffle playback state for TV shows and seasons.
|
||||
/// This provider is session-only and does not persist across app restarts.
|
||||
class PlaybackStateProvider with ChangeNotifier {
|
||||
List<PlexMetadata> _shuffleQueue = [];
|
||||
String?
|
||||
_shuffleContextKey; // The show/season ratingKey for this shuffle session
|
||||
int _currentIndex = 0;
|
||||
|
||||
/// Whether shuffle mode is currently active
|
||||
bool get isShuffleActive => _shuffleQueue.isNotEmpty;
|
||||
|
||||
/// The context key (show or season ratingKey) for the current shuffle session
|
||||
String? get shuffleContextKey => _shuffleContextKey;
|
||||
|
||||
/// Sets a new shuffle queue and starts shuffle mode
|
||||
void setShuffleQueue(List<PlexMetadata> episodes, String contextKey) {
|
||||
_shuffleQueue = List.from(episodes);
|
||||
_shuffleContextKey = contextKey;
|
||||
_currentIndex = 0;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Gets the next episode in the shuffle queue.
|
||||
/// Returns null if queue is exhausted or current episode is not in queue.
|
||||
PlexMetadata? getNextEpisode(String currentEpisodeKey) {
|
||||
if (_shuffleQueue.isEmpty) return null;
|
||||
|
||||
// Find current episode in queue
|
||||
final currentIndex = _shuffleQueue.indexWhere(
|
||||
(ep) => ep.ratingKey == currentEpisodeKey,
|
||||
);
|
||||
|
||||
if (currentIndex == -1) {
|
||||
// Current episode not in queue, clear shuffle
|
||||
clearShuffle();
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if there's a next episode
|
||||
if (currentIndex + 1 >= _shuffleQueue.length) {
|
||||
// Queue exhausted
|
||||
return null;
|
||||
}
|
||||
|
||||
_currentIndex = currentIndex + 1;
|
||||
return _shuffleQueue[_currentIndex];
|
||||
}
|
||||
|
||||
/// Clears the shuffle queue and exits shuffle mode
|
||||
void clearShuffle() {
|
||||
_shuffleQueue = [];
|
||||
_shuffleContextKey = null;
|
||||
_currentIndex = 0;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Gets the total number of episodes in the current shuffle queue
|
||||
int get queueLength => _shuffleQueue.length;
|
||||
|
||||
/// Gets the current position in the queue (1-indexed)
|
||||
int get currentPosition => _currentIndex + 1;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../services/settings_service.dart';
|
||||
|
||||
class SettingsProvider extends ChangeNotifier {
|
||||
late SettingsService _settingsService;
|
||||
LibraryDensity _libraryDensity = LibraryDensity.normal;
|
||||
bool _useSeasonPoster = false;
|
||||
bool _showHeroSection = true;
|
||||
|
||||
SettingsProvider() {
|
||||
_initializeSettings();
|
||||
}
|
||||
|
||||
Future<void> _initializeSettings() async {
|
||||
_settingsService = await SettingsService.getInstance();
|
||||
_libraryDensity = _settingsService.getLibraryDensity();
|
||||
_useSeasonPoster = _settingsService.getUseSeasonPoster();
|
||||
_showHeroSection = _settingsService.getShowHeroSection();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
LibraryDensity get libraryDensity => _libraryDensity;
|
||||
bool get useSeasonPoster => _useSeasonPoster;
|
||||
bool get showHeroSection => _showHeroSection;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setShowHeroSection(bool value) async {
|
||||
if (_showHeroSection != value) {
|
||||
_showHeroSection = value;
|
||||
await _settingsService.setShowHeroSection(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
String get libraryDensityDisplayName {
|
||||
switch (_libraryDensity) {
|
||||
case LibraryDensity.compact:
|
||||
return 'Compact';
|
||||
case LibraryDensity.normal:
|
||||
return 'Normal';
|
||||
case LibraryDensity.comfortable:
|
||||
return 'Comfortable';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,16 +8,19 @@ class ThemeProvider extends ChangeNotifier {
|
||||
late Brightness _systemBrightness;
|
||||
|
||||
ThemeProvider() {
|
||||
_systemBrightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;
|
||||
_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();
|
||||
}
|
||||
};
|
||||
WidgetsBinding.instance.platformDispatcher.onPlatformBrightnessChanged =
|
||||
() {
|
||||
_systemBrightness =
|
||||
WidgetsBinding.instance.platformDispatcher.platformBrightness;
|
||||
if (_themeMode == settings.ThemeMode.system) {
|
||||
notifyListeners();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Future<void> _initializeSettings() async {
|
||||
@@ -96,4 +99,4 @@ class ThemeProvider extends ChangeNotifier {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,25 @@
|
||||
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 {
|
||||
@@ -66,6 +71,19 @@ class UserProfileProvider extends ChangeNotifier {
|
||||
// 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(
|
||||
@@ -98,9 +116,41 @@ class UserProfileProvider extends ChangeNotifier {
|
||||
_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');
|
||||
|
||||
@@ -206,15 +256,41 @@ class UserProfileProvider extends ChangeNotifier {
|
||||
_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
|
||||
@@ -263,8 +339,17 @@ class UserProfileProvider extends ChangeNotifier {
|
||||
// Update current user
|
||||
_currentUser = user;
|
||||
|
||||
// Save user profile
|
||||
await _storageService!.saveUserProfile(switchResponse.profile.toJson());
|
||||
// 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) {
|
||||
@@ -291,6 +376,36 @@ class UserProfileProvider extends ChangeNotifier {
|
||||
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;
|
||||
@@ -322,6 +437,7 @@ class UserProfileProvider extends ChangeNotifier {
|
||||
// Clear user-specific provider state but keep services for future sign-ins
|
||||
_home = null;
|
||||
_currentUser = null;
|
||||
_profileSettings = null;
|
||||
_onDataInvalidationRequested = null;
|
||||
|
||||
_clearError();
|
||||
@@ -346,6 +462,7 @@ class UserProfileProvider extends ChangeNotifier {
|
||||
// Clear cached data from previous server (both memory and storage)
|
||||
_home = null;
|
||||
_currentUser = null;
|
||||
_profileSettings = null;
|
||||
_clearError();
|
||||
|
||||
// Re-initialize services with current storage state
|
||||
@@ -401,6 +518,15 @@ class UserProfileProvider extends ChangeNotifier {
|
||||
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(
|
||||
|
||||
@@ -92,7 +92,6 @@ class _AboutScreenState extends State<AboutScreen> {
|
||||
),
|
||||
),
|
||||
|
||||
|
||||
const SizedBox(height: 24),
|
||||
]),
|
||||
),
|
||||
@@ -101,5 +100,4 @@ class _AboutScreenState extends State<AboutScreen> {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
@@ -110,6 +112,96 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
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(
|
||||
@@ -158,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(
|
||||
|
||||
+664
-355
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,362 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../client/plex_client.dart';
|
||||
import '../models/plex_hub.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_sort.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../services/settings_service.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../widgets/media_card.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/sort_bottom_sheet.dart';
|
||||
import '../mixins/refreshable.dart';
|
||||
|
||||
/// Screen to display full content of a recommendation hub
|
||||
class HubDetailScreen extends StatefulWidget {
|
||||
final PlexHub hub;
|
||||
|
||||
const HubDetailScreen({super.key, required this.hub});
|
||||
|
||||
@override
|
||||
State<HubDetailScreen> createState() => _HubDetailScreenState();
|
||||
}
|
||||
|
||||
class _HubDetailScreenState extends State<HubDetailScreen> with Refreshable {
|
||||
PlexClient get client => context.clientSafe;
|
||||
|
||||
List<PlexMetadata> _items = [];
|
||||
List<PlexMetadata> _filteredItems = [];
|
||||
List<PlexSort> _sortOptions = [];
|
||||
PlexSort? _selectedSort;
|
||||
bool _isSortDescending = false;
|
||||
bool _isLoading = false;
|
||||
String? _errorMessage;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Start with items already loaded in the hub
|
||||
_items = widget.hub.items;
|
||||
_filteredItems = widget.hub.items;
|
||||
// Load more items if available
|
||||
if (widget.hub.more) {
|
||||
_loadMoreItems();
|
||||
}
|
||||
// Load sorts based on the library type
|
||||
_loadSorts();
|
||||
}
|
||||
|
||||
Future<void> _loadSorts() async {
|
||||
try {
|
||||
final clientProvider = context.plexClient;
|
||||
final client = clientProvider.client;
|
||||
if (client == null) return;
|
||||
|
||||
// Get the library key from the hub key
|
||||
// Hub keys can have various formats:
|
||||
// - /hubs/sections/1/...
|
||||
// - /library/sections/1/all?...
|
||||
final hubKey = widget.hub.hubKey;
|
||||
appLogger.d('Hub key: $hubKey');
|
||||
|
||||
RegExpMatch? match;
|
||||
|
||||
// Try different patterns
|
||||
match = RegExp(r'/hubs/sections/(\d+)').firstMatch(hubKey);
|
||||
if (match == null) {
|
||||
match = RegExp(r'/library/sections/(\d+)').firstMatch(hubKey);
|
||||
}
|
||||
if (match == null) {
|
||||
match = RegExp(r'sections/(\d+)').firstMatch(hubKey);
|
||||
}
|
||||
|
||||
if (match != null) {
|
||||
final sectionId = match.group(1)!;
|
||||
appLogger.d('Loading sorts for section: $sectionId');
|
||||
|
||||
// Load sorts for this library
|
||||
final sorts = await client.getLibrarySorts(sectionId);
|
||||
|
||||
appLogger.d('Loaded ${sorts.length} sorts');
|
||||
|
||||
setState(() {
|
||||
_sortOptions = sorts.isNotEmpty ? sorts : _getDefaultSortOptions();
|
||||
// Don't set a default sort - let items stay in original order
|
||||
});
|
||||
} else {
|
||||
appLogger.w('Could not extract section ID from hub key: $hubKey');
|
||||
// Provide default sort options even if we can't get library-specific ones
|
||||
setState(() {
|
||||
_sortOptions = _getDefaultSortOptions();
|
||||
// Don't set a default sort - let items stay in original order
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to load sorts', error: e);
|
||||
// Provide default sort options on error
|
||||
setState(() {
|
||||
_sortOptions = _getDefaultSortOptions();
|
||||
// Don't set a default sort - let items stay in original order
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
List<PlexSort> _getDefaultSortOptions() {
|
||||
return [
|
||||
PlexSort(key: 'titleSort', title: 'Title', defaultDirection: 'asc'),
|
||||
PlexSort(
|
||||
key: 'year',
|
||||
descKey: 'year:desc',
|
||||
title: 'Release Year',
|
||||
defaultDirection: 'desc',
|
||||
),
|
||||
PlexSort(
|
||||
key: 'addedAt',
|
||||
descKey: 'addedAt:desc',
|
||||
title: 'Date Added',
|
||||
defaultDirection: 'desc',
|
||||
),
|
||||
PlexSort(
|
||||
key: 'rating',
|
||||
descKey: 'rating:desc',
|
||||
title: 'Rating',
|
||||
defaultDirection: 'desc',
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
void _applySort() {
|
||||
setState(() {
|
||||
_filteredItems = List.from(_items);
|
||||
|
||||
// Apply sorting
|
||||
if (_selectedSort != null) {
|
||||
final sortKey = _selectedSort!.key;
|
||||
_filteredItems.sort((a, b) {
|
||||
int comparison = 0;
|
||||
|
||||
switch (sortKey) {
|
||||
case 'titleSort':
|
||||
case 'title':
|
||||
comparison = a.title.compareTo(b.title);
|
||||
break;
|
||||
case 'addedAt':
|
||||
comparison = (a.addedAt ?? 0).compareTo(b.addedAt ?? 0);
|
||||
break;
|
||||
case 'originallyAvailableAt':
|
||||
case 'year':
|
||||
comparison = (a.year ?? 0).compareTo(b.year ?? 0);
|
||||
break;
|
||||
case 'rating':
|
||||
comparison = (a.rating ?? 0).compareTo(b.rating ?? 0);
|
||||
break;
|
||||
default:
|
||||
comparison = a.title.compareTo(b.title);
|
||||
}
|
||||
|
||||
return _isSortDescending ? -comparison : comparison;
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _showSortBottomSheet() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => SortBottomSheet(
|
||||
sortOptions: _sortOptions,
|
||||
selectedSort: _selectedSort,
|
||||
isSortDescending: _isSortDescending,
|
||||
onSortChanged: (sort, descending) {
|
||||
setState(() {
|
||||
_selectedSort = sort;
|
||||
_isSortDescending = descending;
|
||||
});
|
||||
_applySort();
|
||||
},
|
||||
onClear: () {
|
||||
setState(() {
|
||||
// Reset to no sorting (original order)
|
||||
_selectedSort = null;
|
||||
_isSortDescending = false;
|
||||
});
|
||||
_applySort();
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _loadMoreItems() async {
|
||||
if (_isLoading) return;
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
try {
|
||||
final clientProvider = context.plexClient;
|
||||
final client = clientProvider.client;
|
||||
if (client == null) {
|
||||
throw Exception('No client available');
|
||||
}
|
||||
|
||||
// Fetch more items from the hub using the hubKey
|
||||
final response = await client.getHubContent(widget.hub.hubKey);
|
||||
|
||||
setState(() {
|
||||
_items = response;
|
||||
_filteredItems = response;
|
||||
_isLoading = false;
|
||||
});
|
||||
|
||||
// Apply any existing sort
|
||||
_applySort();
|
||||
|
||||
appLogger.d(
|
||||
'Loaded ${response.length} items for hub: ${widget.hub.title}',
|
||||
);
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to load hub content', error: e);
|
||||
setState(() {
|
||||
_errorMessage = 'Failed to load content: $e';
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _handleItemRefresh(String ratingKey) {
|
||||
// Refresh the specific item in the list
|
||||
setState(() {
|
||||
final index = _items.indexWhere((item) => item.ratingKey == ratingKey);
|
||||
if (index != -1) {
|
||||
// The item will be refreshed by the MediaCard itself
|
||||
appLogger.d('Item refresh requested for: $ratingKey');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void refresh() {
|
||||
_loadMoreItems();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(
|
||||
title: Text(widget.hub.title),
|
||||
pinned: true,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.swap_vert, semanticLabel: 'Sort'),
|
||||
onPressed: _showSortBottomSheet,
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_errorMessage != null)
|
||||
SliverFillRemaining(
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.error_outline,
|
||||
size: 48,
|
||||
color: Colors.red,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(_errorMessage!),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: _loadMoreItems,
|
||||
child: const Text('Retry'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (_filteredItems.isEmpty && _isLoading)
|
||||
const SliverFillRemaining(
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
else if (_filteredItems.isEmpty)
|
||||
const SliverFillRemaining(
|
||||
child: Center(child: Text('No items found')),
|
||||
)
|
||||
else
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
sliver: SliverGrid(
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: _getMaxCrossAxisExtent(
|
||||
context,
|
||||
context.watch<SettingsProvider>().libraryDensity,
|
||||
),
|
||||
childAspectRatio: 2 / 3.3,
|
||||
crossAxisSpacing: 0,
|
||||
mainAxisSpacing: 0,
|
||||
),
|
||||
delegate: SliverChildBuilderDelegate((context, index) {
|
||||
return MediaCard(
|
||||
item: _filteredItems[index],
|
||||
onRefresh: _handleItemRefresh,
|
||||
);
|
||||
}, childCount: _filteredItems.length),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
double _getMaxCrossAxisExtent(BuildContext context, LibraryDensity density) {
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
final padding = 16.0; // 8px left + 8px right
|
||||
final availableWidth = screenWidth - padding;
|
||||
|
||||
if (screenWidth >= 900) {
|
||||
// Wide screens (desktop/large tablet landscape): Responsive division
|
||||
double divisor;
|
||||
double maxItemWidth;
|
||||
|
||||
switch (density) {
|
||||
case LibraryDensity.comfortable:
|
||||
divisor = 6.5;
|
||||
maxItemWidth = 280;
|
||||
break;
|
||||
case LibraryDensity.normal:
|
||||
divisor = 8.0;
|
||||
maxItemWidth = 200;
|
||||
break;
|
||||
case LibraryDensity.compact:
|
||||
divisor = 10.0;
|
||||
maxItemWidth = 160;
|
||||
break;
|
||||
}
|
||||
|
||||
return (availableWidth / divisor).clamp(0, maxItemWidth);
|
||||
} else if (screenWidth >= 600) {
|
||||
// Medium screens (tablets): Fixed 4-5-6 items
|
||||
int targetItemCount = switch (density) {
|
||||
LibraryDensity.comfortable => 4,
|
||||
LibraryDensity.normal => 5,
|
||||
LibraryDensity.compact => 6,
|
||||
};
|
||||
return availableWidth / targetItemCount;
|
||||
} else {
|
||||
// Small screens (phones): Fixed 2-3-4 items
|
||||
int targetItemCount = switch (density) {
|
||||
LibraryDensity.comfortable => 2,
|
||||
LibraryDensity.normal => 3,
|
||||
LibraryDensity.compact => 4,
|
||||
};
|
||||
return availableWidth / targetItemCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1049
-80
File diff suppressed because it is too large
Load Diff
@@ -67,9 +67,7 @@ class _LicensesScreenState extends State<LicensesScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_isLoading) {
|
||||
return const Scaffold(
|
||||
body: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
@@ -79,30 +77,29 @@ class _LicensesScreenState extends State<LicensesScreen> {
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildBuilderDelegate(
|
||||
(context, index) {
|
||||
final mergedLicense = _mergedLicenses[index];
|
||||
final packageName = mergedLicense.packageName;
|
||||
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,
|
||||
),
|
||||
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,
|
||||
),
|
||||
subtitle: mergedLicense.licenseEntries.length > 1
|
||||
? Text(
|
||||
'${mergedLicense.licenseEntries.length} licenses',
|
||||
)
|
||||
: null,
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => _showLicenseDetail(mergedLicense),
|
||||
),
|
||||
);
|
||||
}, childCount: _mergedLicenses.length),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -114,9 +111,8 @@ class _LicensesScreenState extends State<LicensesScreen> {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => _LicenseDetailScreen(
|
||||
mergedLicense: mergedLicense,
|
||||
),
|
||||
builder: (context) =>
|
||||
_LicenseDetailScreen(mergedLicense: mergedLicense),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -125,9 +121,7 @@ class _LicensesScreenState extends State<LicensesScreen> {
|
||||
class _LicenseDetailScreen extends StatelessWidget {
|
||||
final MergedLicenseEntry mergedLicense;
|
||||
|
||||
const _LicenseDetailScreen({
|
||||
required this.mergedLicense,
|
||||
});
|
||||
const _LicenseDetailScreen({required this.mergedLicense});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -137,10 +131,7 @@ class _LicenseDetailScreen extends StatelessWidget {
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(
|
||||
title: Text(packageName),
|
||||
pinned: true,
|
||||
),
|
||||
CustomAppBar(title: Text(packageName), pinned: true),
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
sliver: SliverList(
|
||||
@@ -155,9 +146,8 @@ class _LicenseDetailScreen extends StatelessWidget {
|
||||
children: [
|
||||
Text(
|
||||
'Related Packages',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
style: Theme.of(context).textTheme.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
@@ -186,10 +176,11 @@ class _LicenseDetailScreen extends StatelessWidget {
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
isMultipleLicenses ? 'License ${index + 1}' : 'License',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
isMultipleLicenses
|
||||
? 'License ${index + 1}'
|
||||
: 'License',
|
||||
style: Theme.of(context).textTheme.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
...license.paragraphs.map((paragraph) {
|
||||
@@ -198,7 +189,9 @@ class _LicenseDetailScreen extends StatelessWidget {
|
||||
child: SelectableText(
|
||||
paragraph.text,
|
||||
style: TextStyle(
|
||||
fontFamily: paragraph.indent > 0 ? 'monospace' : null,
|
||||
fontFamily: paragraph.indent > 0
|
||||
? 'monospace'
|
||||
: null,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
@@ -220,4 +213,4 @@ class _LicenseDetailScreen extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
|
||||
class LogsScreen extends StatefulWidget {
|
||||
const LogsScreen({super.key});
|
||||
|
||||
@override
|
||||
State<LogsScreen> createState() => _LogsScreenState();
|
||||
}
|
||||
|
||||
class _LogsScreenState extends State<LogsScreen> {
|
||||
List<LogEntry> _logs = [];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadLogs();
|
||||
}
|
||||
|
||||
void _loadLogs() {
|
||||
setState(() {
|
||||
_logs = MemoryLogOutput.getLogs();
|
||||
});
|
||||
}
|
||||
|
||||
String _formatTime(DateTime time) {
|
||||
final hour = time.hour.toString().padLeft(2, '0');
|
||||
final minute = time.minute.toString().padLeft(2, '0');
|
||||
final second = time.second.toString().padLeft(2, '0');
|
||||
final millisecond = time.millisecond.toString().padLeft(3, '0');
|
||||
return '$hour:$minute:$second.$millisecond';
|
||||
}
|
||||
|
||||
void _clearLogs() {
|
||||
setState(() {
|
||||
MemoryLogOutput.clearLogs();
|
||||
_logs = [];
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Logs cleared')),
|
||||
);
|
||||
}
|
||||
|
||||
void _copyAllLogs() {
|
||||
final buffer = StringBuffer();
|
||||
bool isFirst = true;
|
||||
for (final log in _logs.reversed) {
|
||||
if (!isFirst) {
|
||||
buffer.write('\n');
|
||||
}
|
||||
isFirst = false;
|
||||
|
||||
buffer.write(
|
||||
'[${_formatTime(log.timestamp)}] [${log.level.name.toUpperCase()}] ${log.message}');
|
||||
if (log.error != null) {
|
||||
buffer.write('\nError: ${log.error}');
|
||||
}
|
||||
if (log.stackTrace != null) {
|
||||
buffer.write('\nStack trace:\n${log.stackTrace}');
|
||||
}
|
||||
}
|
||||
Clipboard.setData(ClipboardData(text: buffer.toString()));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Logs copied to clipboard')),
|
||||
);
|
||||
}
|
||||
|
||||
Color _getLevelColor(Level level) {
|
||||
switch (level) {
|
||||
case Level.error:
|
||||
case Level.fatal:
|
||||
return Colors.red;
|
||||
case Level.warning:
|
||||
return Colors.orange;
|
||||
case Level.info:
|
||||
return Colors.blue;
|
||||
case Level.debug:
|
||||
case Level.trace:
|
||||
return Colors.grey;
|
||||
default:
|
||||
return Colors.grey;
|
||||
}
|
||||
}
|
||||
|
||||
IconData _getLevelIcon(Level level) {
|
||||
switch (level) {
|
||||
case Level.error:
|
||||
case Level.fatal:
|
||||
return Icons.error;
|
||||
case Level.warning:
|
||||
return Icons.warning;
|
||||
case Level.info:
|
||||
return Icons.info;
|
||||
case Level.debug:
|
||||
case Level.trace:
|
||||
return Icons.bug_report;
|
||||
default:
|
||||
return Icons.circle;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
CustomAppBar(
|
||||
title: const Text('Logs'),
|
||||
pinned: true,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh),
|
||||
onPressed: _loadLogs,
|
||||
tooltip: 'Refresh',
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.copy),
|
||||
onPressed: _logs.isNotEmpty ? _copyAllLogs : null,
|
||||
tooltip: 'Copy All',
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
onPressed: _logs.isNotEmpty ? _clearLogs : null,
|
||||
tooltip: 'Clear Logs',
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_logs.isEmpty)
|
||||
const SliverFillRemaining(
|
||||
child: Center(
|
||||
child: Text('No logs available'),
|
||||
),
|
||||
)
|
||||
else
|
||||
SliverPadding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
sliver: SliverList(
|
||||
delegate: SliverChildBuilderDelegate(
|
||||
(context, index) {
|
||||
final log = _logs[index];
|
||||
return _LogEntryCard(
|
||||
log: log,
|
||||
formatTime: _formatTime,
|
||||
levelColor: _getLevelColor(log.level),
|
||||
levelIcon: _getLevelIcon(log.level),
|
||||
);
|
||||
},
|
||||
childCount: _logs.length,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LogEntryCard extends StatefulWidget {
|
||||
final LogEntry log;
|
||||
final String Function(DateTime) formatTime;
|
||||
final Color levelColor;
|
||||
final IconData levelIcon;
|
||||
|
||||
const _LogEntryCard({
|
||||
required this.log,
|
||||
required this.formatTime,
|
||||
required this.levelColor,
|
||||
required this.levelIcon,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_LogEntryCard> createState() => _LogEntryCardState();
|
||||
}
|
||||
|
||||
class _LogEntryCardState extends State<_LogEntryCard> {
|
||||
bool _isExpanded = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasErrorOrStackTrace =
|
||||
widget.log.error != null || widget.log.stackTrace != null;
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 0),
|
||||
child: InkWell(
|
||||
onTap: hasErrorOrStackTrace
|
||||
? () => setState(() => _isExpanded = !_isExpanded)
|
||||
: null,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(
|
||||
widget.levelIcon,
|
||||
color: widget.levelColor,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
widget.log.level.name.toUpperCase(),
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: widget.levelColor,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
widget.formatTime(widget.log.timestamp),
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodySmall
|
||||
?.copyWith(
|
||||
color: Theme.of(context)
|
||||
.textTheme
|
||||
.bodySmall
|
||||
?.color
|
||||
?.withValues(alpha: 0.6),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
widget.log.message,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (hasErrorOrStackTrace)
|
||||
Icon(
|
||||
_isExpanded
|
||||
? Icons.expand_less
|
||||
: Icons.expand_more,
|
||||
color: Theme.of(context)
|
||||
.iconTheme
|
||||
.color
|
||||
?.withValues(alpha: 0.6),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_isExpanded && hasErrorOrStackTrace) ...[
|
||||
const SizedBox(height: 12),
|
||||
const Divider(),
|
||||
const SizedBox(height: 8),
|
||||
if (widget.log.error != null) ...[
|
||||
Text(
|
||||
'Error:',
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
color: widget.levelColor,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? Colors.grey[900]
|
||||
: Colors.grey[200],
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: SelectableText(
|
||||
widget.log.error.toString(),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (widget.log.stackTrace != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'Stack Trace:',
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
color: widget.levelColor,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? Colors.grey[900]
|
||||
: Colors.grey[200],
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: SelectableText(
|
||||
widget.log.stackTrace.toString(),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
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';
|
||||
@@ -12,9 +11,8 @@ 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();
|
||||
@@ -36,11 +34,10 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
|
||||
_screens = [
|
||||
DiscoverScreen(
|
||||
key: _discoverKey,
|
||||
userProfile: widget.userProfile,
|
||||
onBecameVisible: _onDiscoverBecameVisible,
|
||||
),
|
||||
LibrariesScreen(key: _librariesKey, userProfile: widget.userProfile),
|
||||
SearchScreen(key: _searchKey, userProfile: widget.userProfile),
|
||||
LibrariesScreen(key: _librariesKey),
|
||||
SearchScreen(key: _searchKey),
|
||||
SettingsScreen(key: _settingsKey),
|
||||
];
|
||||
|
||||
|
||||
@@ -2,26 +2,21 @@ import 'package:flutter/material.dart';
|
||||
import 'package:cached_network_image/cached_network_image.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 PlexMetadata metadata;
|
||||
final PlexUserProfile? userProfile;
|
||||
|
||||
const MediaDetailScreen({
|
||||
super.key,
|
||||
required this.metadata,
|
||||
this.userProfile,
|
||||
});
|
||||
const MediaDetailScreen({super.key, required this.metadata});
|
||||
|
||||
@override
|
||||
State<MediaDetailScreen> createState() => _MediaDetailScreenState();
|
||||
@@ -214,15 +209,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
if (client == null) return;
|
||||
|
||||
appLogger.d('Playing first episode: ${firstEpisode.title}');
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
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();
|
||||
@@ -475,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,
|
||||
@@ -542,14 +529,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
appLogger.d(
|
||||
'Playing on deck episode: ${_onDeckEpisode!.title}',
|
||||
);
|
||||
await Navigator.push(
|
||||
await navigateToVideoPlayer(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
metadata: _onDeckEpisode!,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
),
|
||||
metadata: _onDeckEpisode!,
|
||||
);
|
||||
appLogger.d(
|
||||
'Returned from playback, refreshing metadata',
|
||||
@@ -567,14 +549,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
|
||||
appLogger.d('Playing: ${metadata.title}');
|
||||
// For movies or episodes, play directly
|
||||
await Navigator.push(
|
||||
await navigateToVideoPlayer(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
metadata: metadata,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
),
|
||||
metadata: metadata,
|
||||
);
|
||||
appLogger.d(
|
||||
'Returned from playback, refreshing metadata',
|
||||
@@ -739,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),
|
||||
],
|
||||
],
|
||||
@@ -772,120 +749,125 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
|
||||
_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: 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,
|
||||
),
|
||||
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),
|
||||
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,
|
||||
),
|
||||
errorWidget: (context, url, error) => Container(
|
||||
width: 80,
|
||||
height: 120,
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
child: const Icon(Icons.movie, size: 32),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
if (season.leafCount != null)
|
||||
)
|
||||
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),
|
||||
|
||||
// Season info
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${season.leafCount} episodes',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodyMedium?.copyWith(color: Colors.grey),
|
||||
season.title,
|
||||
style: Theme.of(context).textTheme.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
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,
|
||||
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,
|
||||
),
|
||||
minHeight: 6,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${season.viewedLeafCount}/${season.leafCount} watched',
|
||||
style: Theme.of(context).textTheme.bodySmall
|
||||
?.copyWith(color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
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),
|
||||
],
|
||||
const Icon(Icons.chevron_right),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
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';
|
||||
@@ -10,9 +12,7 @@ import '../mixins/refreshable.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
|
||||
class SearchScreen extends StatefulWidget {
|
||||
final PlexUserProfile? userProfile;
|
||||
|
||||
const SearchScreen({super.key, this.userProfile});
|
||||
const SearchScreen({super.key});
|
||||
|
||||
@override
|
||||
State<SearchScreen> createState() => _SearchScreenState();
|
||||
@@ -216,8 +216,11 @@ class _SearchScreenState extends State<SearchScreen>
|
||||
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,
|
||||
@@ -228,7 +231,6 @@ class _SearchScreenState extends State<SearchScreen>
|
||||
key: Key(item.ratingKey),
|
||||
item: item,
|
||||
onRefresh: updateItem,
|
||||
userProfile: widget.userProfile,
|
||||
);
|
||||
}, childCount: _searchResults.length),
|
||||
),
|
||||
@@ -238,4 +240,49 @@ class _SearchScreenState extends State<SearchScreen>
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,20 +3,18 @@ import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../client/plex_client.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_user_profile.dart';
|
||||
import '../providers/plex_client_provider.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../utils/video_player_navigation.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/media_context_menu.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
import '../theme/theme_helper.dart';
|
||||
import 'video_player_screen.dart';
|
||||
|
||||
class SeasonDetailScreen extends StatefulWidget {
|
||||
final PlexMetadata season;
|
||||
final PlexUserProfile? userProfile;
|
||||
|
||||
const SeasonDetailScreen({super.key, required this.season, this.userProfile});
|
||||
const SeasonDetailScreen({super.key, required this.season});
|
||||
|
||||
@override
|
||||
State<SeasonDetailScreen> createState() => _SeasonDetailScreenState();
|
||||
@@ -136,15 +134,7 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
|
||||
metadata: episode,
|
||||
onRefresh: updateItem,
|
||||
onTap: () async {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
metadata: episode,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
),
|
||||
);
|
||||
await navigateToVideoPlayer(context, metadata: episode);
|
||||
// Refresh episodes when returning from video player
|
||||
_loadEpisodes();
|
||||
},
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:hotkey_manager/hotkey_manager.dart';
|
||||
import 'package:url_launcher/url_launcher.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 '../services/update_service.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/hotkey_recorder_widget.dart';
|
||||
import 'about_screen.dart';
|
||||
import 'logs_screen.dart';
|
||||
|
||||
class SettingsScreen extends StatefulWidget {
|
||||
const SettingsScreen({super.key});
|
||||
@@ -22,8 +26,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
|
||||
bool _enableDebugLogging = false;
|
||||
bool _enableHardwareDecoding = true;
|
||||
int _videoBufferSize = 64;
|
||||
int _audioBufferSize = 8;
|
||||
int _bufferSize = 128;
|
||||
int _seekTimeSmall = 10;
|
||||
int _seekTimeLarge = 30;
|
||||
|
||||
// Update checking state
|
||||
bool _isCheckingForUpdate = false;
|
||||
Map<String, dynamic>? _updateInfo;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -38,8 +47,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
setState(() {
|
||||
_enableDebugLogging = _settingsService.getEnableDebugLogging();
|
||||
_enableHardwareDecoding = _settingsService.getEnableHardwareDecoding();
|
||||
_videoBufferSize = _settingsService.getVideoBufferSize();
|
||||
_audioBufferSize = _settingsService.getAudioBufferSize();
|
||||
_bufferSize = _settingsService.getBufferSize();
|
||||
_seekTimeSmall = _settingsService.getSeekTimeSmall();
|
||||
_seekTimeLarge = _settingsService.getSeekTimeLarge();
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
@@ -47,9 +57,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_isLoading) {
|
||||
return const Scaffold(
|
||||
body: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
@@ -68,6 +76,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
const SizedBox(height: 24),
|
||||
_buildAdvancedSection(),
|
||||
const SizedBox(height: 24),
|
||||
if (UpdateService.isUpdateCheckEnabled) ...[
|
||||
_buildUpdateSection(),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
_buildAboutSection(),
|
||||
const SizedBox(height: 24),
|
||||
]),
|
||||
@@ -87,9 +99,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
'Appearance',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
Consumer<ThemeProvider>(
|
||||
@@ -103,6 +115,47 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
},
|
||||
),
|
||||
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);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
return SwitchListTile(
|
||||
secondary: const Icon(Icons.featured_play_list),
|
||||
title: const Text('Show Hero Section'),
|
||||
subtitle: const Text(
|
||||
'Display featured content carousel on home screen',
|
||||
),
|
||||
value: settingsProvider.showHeroSection,
|
||||
onChanged: (value) async {
|
||||
await settingsProvider.setShowHeroSection(value);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -117,9 +170,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
'Video Playback',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
SwitchListTile(
|
||||
@@ -136,17 +189,24 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.memory),
|
||||
title: const Text('Video Buffer Size'),
|
||||
subtitle: Text('${_videoBufferSize}MB'),
|
||||
title: const Text('Buffer Size'),
|
||||
subtitle: Text('${_bufferSize}MB'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => _showBufferSizeDialog(true),
|
||||
onTap: () => _showBufferSizeDialog(),
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.audiotrack),
|
||||
title: const Text('Audio Buffer Size'),
|
||||
subtitle: Text('${_audioBufferSize}MB'),
|
||||
leading: const Icon(Icons.replay_10),
|
||||
title: const Text('Small Skip Duration'),
|
||||
subtitle: Text('$_seekTimeSmall seconds'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => _showBufferSizeDialog(false),
|
||||
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(),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -162,9 +222,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
'Keyboard Shortcuts',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
@@ -179,7 +239,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Widget _buildAdvancedSection() {
|
||||
return Card(
|
||||
child: Column(
|
||||
@@ -189,9 +248,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
'Advanced',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
SwitchListTile(
|
||||
@@ -206,6 +265,20 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
await _settingsService.setEnableDebugLogging(value);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.article),
|
||||
title: const Text('View Logs'),
|
||||
subtitle: const Text('View application logs'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const LogsScreen(),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.cleaning_services),
|
||||
title: const Text('Clear Cache'),
|
||||
@@ -225,6 +298,53 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildUpdateSection() {
|
||||
final hasUpdate = _updateInfo != null && _updateInfo!['hasUpdate'] == true;
|
||||
|
||||
return Card(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
'Updates',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
leading: Icon(
|
||||
hasUpdate ? Icons.system_update : Icons.check_circle,
|
||||
color: hasUpdate ? Colors.orange : null,
|
||||
),
|
||||
title: Text(hasUpdate ? 'Update Available' : 'Check for Updates'),
|
||||
subtitle: hasUpdate
|
||||
? Text('Version ${_updateInfo!['latestVersion']} is available')
|
||||
: const Text('Check for the latest version on GitHub'),
|
||||
trailing: _isCheckingForUpdate
|
||||
? const SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.chevron_right),
|
||||
onTap: _isCheckingForUpdate
|
||||
? null
|
||||
: () {
|
||||
if (hasUpdate) {
|
||||
_showUpdateDialog();
|
||||
} else {
|
||||
_checkForUpdates();
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildAboutSection() {
|
||||
return Card(
|
||||
child: ListTile(
|
||||
@@ -242,7 +362,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
void _showThemeDialog(ThemeProvider themeProvider) {
|
||||
showDialog(
|
||||
context: context,
|
||||
@@ -302,36 +421,28 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
void _showBufferSizeDialog(bool isVideo) {
|
||||
final currentSize = isVideo ? _videoBufferSize : _audioBufferSize;
|
||||
final title = isVideo ? 'Video Buffer Size' : 'Audio Buffer Size';
|
||||
final options = isVideo ? [16, 32, 64, 128, 256] : [2, 4, 8, 16, 32];
|
||||
void _showBufferSizeDialog() {
|
||||
final options = [64, 128, 256, 512, 1024];
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Text(title),
|
||||
title: const Text('Buffer Size'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: options.map((size) {
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
currentSize == size
|
||||
_bufferSize == size
|
||||
? Icons.radio_button_checked
|
||||
: Icons.radio_button_unchecked,
|
||||
),
|
||||
title: Text('${size}MB'),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
if (isVideo) {
|
||||
_videoBufferSize = size;
|
||||
_settingsService.setVideoBufferSize(size);
|
||||
} else {
|
||||
_audioBufferSize = size;
|
||||
_settingsService.setAudioBufferSize(size);
|
||||
}
|
||||
_bufferSize = size;
|
||||
_settingsService.setBufferSize(size);
|
||||
});
|
||||
Navigator.pop(context);
|
||||
},
|
||||
@@ -349,13 +460,140 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
),
|
||||
builder: (context) =>
|
||||
_KeyboardShortcutsScreen(keyboardService: _keyboardService),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -417,7 +655,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
if (mounted) {
|
||||
navigator.pop();
|
||||
messenger.showSnackBar(
|
||||
const SnackBar(content: Text('Settings reset successfully')),
|
||||
const SnackBar(
|
||||
content: Text('Settings reset successfully'),
|
||||
),
|
||||
);
|
||||
// Reload settings
|
||||
_loadSettings();
|
||||
@@ -431,6 +671,162 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _checkForUpdates() async {
|
||||
setState(() {
|
||||
_isCheckingForUpdate = true;
|
||||
});
|
||||
|
||||
try {
|
||||
final updateInfo = await UpdateService.checkForUpdates();
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_updateInfo = updateInfo;
|
||||
_isCheckingForUpdate = false;
|
||||
});
|
||||
|
||||
if (updateInfo == null || updateInfo['hasUpdate'] != true) {
|
||||
// Show "no updates" message
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('You are on the latest version'),
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isCheckingForUpdate = false;
|
||||
});
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Failed to check for updates'),
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _showUpdateDialog() {
|
||||
if (_updateInfo == null) return;
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Update Available'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Version ${_updateInfo!['latestVersion']} is available',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Current: ${_updateInfo!['currentVersion']}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Close'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
final url = Uri.parse(_updateInfo!['releaseUrl']);
|
||||
if (await canLaunchUrl(url)) {
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
child: const Text('View Release'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -439,7 +835,8 @@ class _KeyboardShortcutsScreen extends StatefulWidget {
|
||||
const _KeyboardShortcutsScreen({required this.keyboardService});
|
||||
|
||||
@override
|
||||
State<_KeyboardShortcutsScreen> createState() => _KeyboardShortcutsScreenState();
|
||||
State<_KeyboardShortcutsScreen> createState() =>
|
||||
_KeyboardShortcutsScreenState();
|
||||
}
|
||||
|
||||
class _KeyboardShortcutsScreenState extends State<_KeyboardShortcutsScreen> {
|
||||
@@ -463,9 +860,7 @@ class _KeyboardShortcutsScreenState extends State<_KeyboardShortcutsScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_isLoading) {
|
||||
return const Scaffold(
|
||||
body: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
return const Scaffold(body: Center(child: CircularProgressIndicator()));
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
@@ -482,7 +877,9 @@ class _KeyboardShortcutsScreenState extends State<_KeyboardShortcutsScreen> {
|
||||
await _loadHotkeys();
|
||||
if (mounted) {
|
||||
messenger.showSnackBar(
|
||||
const SnackBar(content: Text('Shortcuts reset to defaults')),
|
||||
const SnackBar(
|
||||
content: Text('Shortcuts reset to defaults'),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -493,34 +890,38 @@ class _KeyboardShortcutsScreenState extends State<_KeyboardShortcutsScreen> {
|
||||
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]!;
|
||||
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),
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
child: ListTile(
|
||||
title: Text(
|
||||
widget.keyboardService.getActionDisplayName(action),
|
||||
),
|
||||
);
|
||||
},
|
||||
childCount: _hotkeys.length,
|
||||
),
|
||||
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),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -540,12 +941,16 @@ class _KeyboardShortcutsScreenState extends State<_KeyboardShortcutsScreen> {
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
|
||||
// Check for conflicts
|
||||
final existingAction = widget.keyboardService.getActionForHotkey(newHotkey);
|
||||
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)}'),
|
||||
content: Text(
|
||||
'Shortcut already assigned to ${widget.keyboardService.getActionDisplayName(existingAction)}',
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
@@ -564,7 +969,9 @@ class _KeyboardShortcutsScreenState extends State<_KeyboardShortcutsScreen> {
|
||||
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Shortcut updated for ${widget.keyboardService.getActionDisplayName(action)}'),
|
||||
content: Text(
|
||||
'Shortcut updated for ${widget.keyboardService.getActionDisplayName(action)}',
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -574,4 +981,4 @@ class _KeyboardShortcutsScreenState extends State<_KeyboardShortcutsScreen> {
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,20 +3,27 @@ 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 'package:provider/provider.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_user_profile.dart';
|
||||
import '../providers/plex_client_provider.dart';
|
||||
import '../providers/playback_state_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 PlexMetadata metadata;
|
||||
final AudioTrack? preferredAudioTrack;
|
||||
final SubtitleTrack? preferredSubtitleTrack;
|
||||
final double? preferredPlaybackRate;
|
||||
final PlexUserProfile? userProfile;
|
||||
final int selectedMediaIndex;
|
||||
|
||||
const VideoPlayerScreen({
|
||||
super.key,
|
||||
@@ -24,7 +31,7 @@ class VideoPlayerScreen extends StatefulWidget {
|
||||
this.preferredAudioTrack,
|
||||
this.preferredSubtitleTrack,
|
||||
this.preferredPlaybackRate,
|
||||
this.userProfile,
|
||||
this.selectedMediaIndex = 0,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -32,23 +39,25 @@ 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 = [];
|
||||
StreamSubscription<PlayerLog>? _logSubscription;
|
||||
StreamSubscription<String>? _errorSubscription;
|
||||
|
||||
@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"})',
|
||||
@@ -61,27 +70,8 @@ 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
|
||||
@@ -96,16 +86,94 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
_cachedClientProvider = null;
|
||||
}
|
||||
|
||||
// Ensure landscape orientation is set even after navigation
|
||||
_setLandscapeOrientation();
|
||||
// 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();
|
||||
final debugLoggingEnabled = settingsService.getEnableDebugLogging();
|
||||
|
||||
// Create player with configuration
|
||||
player = Player(
|
||||
configuration: PlayerConfiguration(
|
||||
libass: true,
|
||||
libassAndroidFont: 'assets/droid-sans.ttf',
|
||||
libassAndroidFontName: 'Droid Sans Fallback',
|
||||
bufferSize: bufferSizeBytes,
|
||||
logLevel: debugLoggingEnabled ? MPVLogLevel.debug : MPVLogLevel.error,
|
||||
),
|
||||
);
|
||||
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);
|
||||
|
||||
// Listen to MPV logs
|
||||
_logSubscription = player!.stream.log.listen(_onPlayerLog);
|
||||
|
||||
// Listen to MPV errors
|
||||
_errorSubscription = player!.stream.error.listen(_onPlayerError);
|
||||
|
||||
// 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 {
|
||||
@@ -118,8 +186,22 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
final client = clientProvider.client;
|
||||
if (client == null) return;
|
||||
|
||||
final next = await client.findAdjacentEpisode(widget.metadata, 1);
|
||||
final previous = await client.findAdjacentEpisode(widget.metadata, -1);
|
||||
final playbackState = context.read<PlaybackStateProvider>();
|
||||
|
||||
PlexMetadata? next;
|
||||
PlexMetadata? previous;
|
||||
|
||||
// Check if shuffle mode is active
|
||||
if (playbackState.isShuffleActive) {
|
||||
// Get next episode from shuffle queue
|
||||
next = playbackState.getNextEpisode(widget.metadata.ratingKey);
|
||||
// No previous episode in shuffle mode
|
||||
previous = null;
|
||||
} else {
|
||||
// Use normal sequential episode loading
|
||||
next = await client.findAdjacentEpisode(widget.metadata, 1);
|
||||
previous = await client.findAdjacentEpisode(widget.metadata, -1);
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
@@ -140,16 +222,19 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
throw Exception('No client available');
|
||||
}
|
||||
|
||||
// Get the direct file URL from the server
|
||||
final videoUrl = await client.getVideoUrl(widget.metadata.ratingKey);
|
||||
// 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++;
|
||||
}
|
||||
@@ -160,11 +245,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();
|
||||
@@ -184,30 +269,68 @@ 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
|
||||
_progressTimer?.cancel();
|
||||
|
||||
// Cancel stream subscriptions
|
||||
_logSubscription?.cancel();
|
||||
_errorSubscription?.cancel();
|
||||
|
||||
// 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');
|
||||
}
|
||||
});
|
||||
@@ -283,7 +406,7 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
) {
|
||||
appLogger.d('Audio track selection using user profile');
|
||||
appLogger.d(
|
||||
'Profile settings - autoSelectAudio: ${profile.autoSelectAudio}, defaultAudioLanguage: ${profile.defaultAudioLanguage}',
|
||||
'Profile settings - autoSelectAudio: ${profile.autoSelectAudio}, defaultAudioLanguage: ${profile.defaultAudioLanguage}, defaultAudioLanguages: ${profile.defaultAudioLanguages}',
|
||||
);
|
||||
|
||||
if (availableTracks.isEmpty || !profile.autoSelectAudio) {
|
||||
@@ -293,31 +416,44 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
return null;
|
||||
}
|
||||
|
||||
final preferredLanguage = profile.defaultAudioLanguage;
|
||||
if (preferredLanguage == null || preferredLanguage.isEmpty) {
|
||||
appLogger.d('Cannot use profile: No defaultAudioLanguage specified');
|
||||
// Build list of preferred languages
|
||||
final preferredLanguages = <String>[];
|
||||
if (profile.defaultAudioLanguage != null &&
|
||||
profile.defaultAudioLanguage!.isNotEmpty) {
|
||||
preferredLanguages.add(profile.defaultAudioLanguage!);
|
||||
}
|
||||
if (profile.defaultAudioLanguages != null) {
|
||||
preferredLanguages.addAll(profile.defaultAudioLanguages!);
|
||||
}
|
||||
|
||||
if (preferredLanguages.isEmpty) {
|
||||
appLogger.d('Cannot use profile: No defaultAudioLanguage(s) specified');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get all possible language code variations (e.g., "en" → ["en", "eng"])
|
||||
final languageVariations = LanguageCodes.getVariations(preferredLanguage);
|
||||
appLogger.d(
|
||||
'Checking language variations: ${languageVariations.join(", ")}',
|
||||
);
|
||||
appLogger.d('Preferred languages: ${preferredLanguages.join(", ")}');
|
||||
|
||||
// Try to find track matching any language variation
|
||||
for (var track in availableTracks) {
|
||||
final trackLang = track.language?.toLowerCase();
|
||||
if (trackLang != null && languageVariations.contains(trackLang)) {
|
||||
appLogger.d(
|
||||
'Found audio track matching profile language "$preferredLanguage" (matched: "$trackLang"): ${track.title ?? "Track ${track.id}"}',
|
||||
);
|
||||
return track;
|
||||
// Try to find track matching any preferred language
|
||||
for (final preferredLanguage in preferredLanguages) {
|
||||
// Get all possible language code variations (e.g., "en" → ["en", "eng"])
|
||||
final languageVariations = LanguageCodes.getVariations(preferredLanguage);
|
||||
appLogger.d(
|
||||
'Checking language variations for "$preferredLanguage": ${languageVariations.join(", ")}',
|
||||
);
|
||||
|
||||
for (var track in availableTracks) {
|
||||
final trackLang = track.language?.toLowerCase();
|
||||
if (trackLang != null && languageVariations.contains(trackLang)) {
|
||||
appLogger.d(
|
||||
'Found audio track matching profile language "$preferredLanguage" (matched: "$trackLang"): ${track.title ?? "Track ${track.id}"}',
|
||||
);
|
||||
return track;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
appLogger.d(
|
||||
'No audio track found matching profile language "$preferredLanguage" or its variations',
|
||||
'No audio track found matching profile languages or their variations',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
@@ -342,11 +478,12 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
|
||||
SubtitleTrack? _findSubtitleTrackByProfile(
|
||||
List<SubtitleTrack> availableTracks,
|
||||
PlexUserProfile profile,
|
||||
) {
|
||||
PlexUserProfile profile, {
|
||||
AudioTrack? selectedAudioTrack,
|
||||
}) {
|
||||
appLogger.d('Subtitle track selection using user profile');
|
||||
appLogger.d(
|
||||
'Profile settings - autoSelectSubtitle: ${profile.autoSelectSubtitle}, defaultSubtitleLanguage: ${profile.defaultSubtitleLanguage}, defaultSubtitleForced: ${profile.defaultSubtitleForced}',
|
||||
'Profile settings - autoSelectSubtitle: ${profile.autoSelectSubtitle}, defaultSubtitleLanguage: ${profile.defaultSubtitleLanguage}, defaultSubtitleLanguages: ${profile.defaultSubtitleLanguages}, defaultSubtitleForced: ${profile.defaultSubtitleForced}, defaultSubtitleAccessibility: ${profile.defaultSubtitleAccessibility}',
|
||||
);
|
||||
|
||||
if (availableTracks.isEmpty) {
|
||||
@@ -354,68 +491,211 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
return null;
|
||||
}
|
||||
|
||||
// If autoSelectSubtitle is 0, don't select any subtitle
|
||||
if (!profile.shouldAutoSelectSubtitle) {
|
||||
// Mode 0: Manually selected - return OFF
|
||||
if (profile.autoSelectSubtitle == 0) {
|
||||
appLogger.d(
|
||||
'Profile specifies no auto-select (autoSelectSubtitle=0) - Subtitles OFF',
|
||||
'Profile specifies manual mode (autoSelectSubtitle=0) - Subtitles OFF',
|
||||
);
|
||||
return SubtitleTrack.no();
|
||||
}
|
||||
|
||||
final preferredLanguage = profile.defaultSubtitleLanguage;
|
||||
if (preferredLanguage == null || preferredLanguage.isEmpty) {
|
||||
appLogger.d('Cannot use profile: No defaultSubtitleLanguage specified');
|
||||
// Mode 1: Shown with foreign audio
|
||||
if (profile.autoSelectSubtitle == 1) {
|
||||
appLogger.d(
|
||||
'Profile specifies foreign audio mode (autoSelectSubtitle=1)',
|
||||
);
|
||||
|
||||
// Check if audio language matches user's preferred subtitle language
|
||||
if (selectedAudioTrack != null &&
|
||||
profile.defaultSubtitleLanguage != null) {
|
||||
final audioLang = selectedAudioTrack.language?.toLowerCase();
|
||||
final prefLang = profile.defaultSubtitleLanguage!.toLowerCase();
|
||||
final languageVariations = LanguageCodes.getVariations(prefLang);
|
||||
|
||||
appLogger.d(
|
||||
'Checking if audio is foreign - audio: $audioLang, preferred subtitle lang: $prefLang',
|
||||
);
|
||||
|
||||
// If audio matches preferred language, no subtitles needed
|
||||
if (audioLang != null && languageVariations.contains(audioLang)) {
|
||||
appLogger.d('Audio matches preferred language - Subtitles OFF');
|
||||
return SubtitleTrack.no();
|
||||
}
|
||||
appLogger.d('Foreign audio detected - enabling subtitles');
|
||||
}
|
||||
// Foreign audio detected or cannot determine, enable subtitles
|
||||
}
|
||||
|
||||
// Mode 2: Always enabled (or continuing from mode 1 with foreign audio)
|
||||
appLogger.d('Selecting subtitle track based on preferences');
|
||||
|
||||
// Build list of preferred languages
|
||||
final preferredLanguages = <String>[];
|
||||
if (profile.defaultSubtitleLanguage != null &&
|
||||
profile.defaultSubtitleLanguage!.isNotEmpty) {
|
||||
preferredLanguages.add(profile.defaultSubtitleLanguage!);
|
||||
}
|
||||
if (profile.defaultSubtitleLanguages != null) {
|
||||
preferredLanguages.addAll(profile.defaultSubtitleLanguages!);
|
||||
}
|
||||
|
||||
if (preferredLanguages.isEmpty) {
|
||||
appLogger.d(
|
||||
'Cannot use profile: No defaultSubtitleLanguage(s) specified',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get all possible language code variations (e.g., "en" → ["en", "eng"])
|
||||
final languageVariations = LanguageCodes.getVariations(preferredLanguage);
|
||||
appLogger.d(
|
||||
'Checking language variations: ${languageVariations.join(", ")}',
|
||||
appLogger.d('Preferred languages: ${preferredLanguages.join(", ")}');
|
||||
|
||||
// Apply filtering based on preferences
|
||||
var candidateTracks = availableTracks;
|
||||
|
||||
// Filter by SDH (defaultSubtitleAccessibility: 0-3)
|
||||
candidateTracks = _filterSubtitlesBySDH(
|
||||
candidateTracks,
|
||||
profile.defaultSubtitleAccessibility,
|
||||
);
|
||||
|
||||
// If defaultSubtitleForced is 1, prefer forced subtitles
|
||||
if (profile.preferForcedSubtitles) {
|
||||
appLogger.d('Profile prefers forced subtitles (defaultSubtitleForced=1)');
|
||||
// Try to find forced subtitle in preferred language
|
||||
for (var track in availableTracks) {
|
||||
// Filter by forced subtitle preference (defaultSubtitleForced: 0-3)
|
||||
candidateTracks = _filterSubtitlesByForced(
|
||||
candidateTracks,
|
||||
profile.defaultSubtitleForced,
|
||||
);
|
||||
|
||||
// If no candidates after filtering, relax filters
|
||||
if (candidateTracks.isEmpty) {
|
||||
appLogger.d('No tracks match strict filters, relaxing filters');
|
||||
candidateTracks = availableTracks;
|
||||
}
|
||||
|
||||
// Try to find track matching any preferred language
|
||||
for (final preferredLanguage in preferredLanguages) {
|
||||
final languageVariations = LanguageCodes.getVariations(preferredLanguage);
|
||||
appLogger.d(
|
||||
'Checking language variations for "$preferredLanguage": ${languageVariations.join(", ")}',
|
||||
);
|
||||
|
||||
for (var track in candidateTracks) {
|
||||
final trackLang = track.language?.toLowerCase();
|
||||
if (trackLang != null &&
|
||||
languageVariations.contains(trackLang) &&
|
||||
track.title?.toLowerCase().contains('forced') == true) {
|
||||
if (trackLang != null && languageVariations.contains(trackLang)) {
|
||||
appLogger.d(
|
||||
'Found forced subtitle matching profile language "$preferredLanguage" (matched: "$trackLang"): ${track.title ?? "Track ${track.id}"}',
|
||||
'Found subtitle matching profile language "$preferredLanguage" (matched: "$trackLang"): ${track.title ?? "Track ${track.id}"}',
|
||||
);
|
||||
return track;
|
||||
}
|
||||
}
|
||||
appLogger.d(
|
||||
'No forced subtitle found in "$preferredLanguage" or its variations, trying regular subtitles',
|
||||
);
|
||||
}
|
||||
|
||||
// Try to find regular subtitle in preferred language
|
||||
for (var track in availableTracks) {
|
||||
final trackLang = track.language?.toLowerCase();
|
||||
if (trackLang != null && languageVariations.contains(trackLang)) {
|
||||
appLogger.d(
|
||||
'Found subtitle matching profile language "$preferredLanguage" (matched: "$trackLang"): ${track.title ?? "Track ${track.id}"}',
|
||||
);
|
||||
return track;
|
||||
}
|
||||
}
|
||||
|
||||
appLogger.d(
|
||||
'No subtitle track found matching profile language "$preferredLanguage" or its variations',
|
||||
'No subtitle track found matching profile languages or their variations',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Filters subtitle tracks based on SDH (Subtitles for Deaf or Hard-of-Hearing) preference
|
||||
///
|
||||
/// Values:
|
||||
/// - 0: Prefer non-SDH subtitles
|
||||
/// - 1: Prefer SDH subtitles
|
||||
/// - 2: Only show SDH subtitles
|
||||
/// - 3: Only show non-SDH subtitles
|
||||
List<SubtitleTrack> _filterSubtitlesBySDH(
|
||||
List<SubtitleTrack> tracks,
|
||||
int preference,
|
||||
) {
|
||||
if (preference == 0 || preference == 1) {
|
||||
// Prefer but don't require
|
||||
final preferSDH = preference == 1;
|
||||
final preferred = tracks.where((t) => _isSDH(t) == preferSDH).toList();
|
||||
if (preferred.isNotEmpty) {
|
||||
appLogger.d(
|
||||
'Applying SDH preference: ${preferSDH ? "prefer SDH" : "prefer non-SDH"} (${preferred.length} tracks)',
|
||||
);
|
||||
return preferred;
|
||||
}
|
||||
appLogger.d('No tracks match SDH preference, using all tracks');
|
||||
return tracks;
|
||||
} else if (preference == 2) {
|
||||
// Only SDH
|
||||
final filtered = tracks.where(_isSDH).toList();
|
||||
appLogger.d('Filtering to SDH only (${filtered.length} tracks)');
|
||||
return filtered;
|
||||
} else if (preference == 3) {
|
||||
// Only non-SDH
|
||||
final filtered = tracks.where((t) => !_isSDH(t)).toList();
|
||||
appLogger.d('Filtering to non-SDH only (${filtered.length} tracks)');
|
||||
return filtered;
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
/// Filters subtitle tracks based on forced subtitle preference
|
||||
///
|
||||
/// Values:
|
||||
/// - 0: Prefer non-forced subtitles
|
||||
/// - 1: Prefer forced subtitles
|
||||
/// - 2: Only show forced subtitles
|
||||
/// - 3: Only show non-forced subtitles
|
||||
List<SubtitleTrack> _filterSubtitlesByForced(
|
||||
List<SubtitleTrack> tracks,
|
||||
int preference,
|
||||
) {
|
||||
if (preference == 0 || preference == 1) {
|
||||
// Prefer but don't require
|
||||
final preferForced = preference == 1;
|
||||
final preferred = tracks
|
||||
.where((t) => _isForced(t) == preferForced)
|
||||
.toList();
|
||||
if (preferred.isNotEmpty) {
|
||||
appLogger.d(
|
||||
'Applying forced preference: ${preferForced ? "prefer forced" : "prefer non-forced"} (${preferred.length} tracks)',
|
||||
);
|
||||
return preferred;
|
||||
}
|
||||
appLogger.d('No tracks match forced preference, using all tracks');
|
||||
return tracks;
|
||||
} else if (preference == 2) {
|
||||
// Only forced
|
||||
final filtered = tracks.where(_isForced).toList();
|
||||
appLogger.d('Filtering to forced only (${filtered.length} tracks)');
|
||||
return filtered;
|
||||
} else if (preference == 3) {
|
||||
// Only non-forced
|
||||
final filtered = tracks.where((t) => !_isForced(t)).toList();
|
||||
appLogger.d('Filtering to non-forced only (${filtered.length} tracks)');
|
||||
return filtered;
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
/// Checks if a subtitle track is SDH (Subtitles for Deaf or Hard-of-Hearing)
|
||||
///
|
||||
/// Since media_kit may not expose this directly, we infer from the title
|
||||
bool _isSDH(SubtitleTrack track) {
|
||||
final title = track.title?.toLowerCase() ?? '';
|
||||
|
||||
// Look for common SDH indicators
|
||||
return title.contains('sdh') ||
|
||||
title.contains('cc') ||
|
||||
title.contains('hearing impaired') ||
|
||||
title.contains('deaf');
|
||||
}
|
||||
|
||||
/// Checks if a subtitle track is forced
|
||||
bool _isForced(SubtitleTrack track) {
|
||||
final title = track.title?.toLowerCase() ?? '';
|
||||
return title.contains('forced');
|
||||
}
|
||||
|
||||
void _waitForTracksAndApply() async {
|
||||
// Helper function to process tracks
|
||||
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')
|
||||
@@ -462,11 +742,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');
|
||||
@@ -488,7 +768,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');
|
||||
}
|
||||
@@ -524,12 +804,18 @@ 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');
|
||||
// Get the currently selected audio track
|
||||
final currentAudioTrack = realAudioTracks.firstWhere(
|
||||
(t) => t.id == player!.state.track.audio.id,
|
||||
orElse: () => realAudioTracks.first,
|
||||
);
|
||||
subtitleToSelect = _findSubtitleTrackByProfile(
|
||||
realSubtitleTracks,
|
||||
widget.userProfile!,
|
||||
profileSettings,
|
||||
selectedAudioTrack: currentAudioTrack,
|
||||
);
|
||||
} else if (subtitleToSelect == null && realSubtitleTracks.isNotEmpty) {
|
||||
appLogger.d('Priority 2: No user profile available');
|
||||
@@ -561,21 +847,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!);
|
||||
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;
|
||||
@@ -583,7 +869,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;
|
||||
@@ -603,8 +889,11 @@ 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) {
|
||||
final clientProvider = _cachedClientProvider;
|
||||
@@ -632,6 +921,33 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
void _onPlayerLog(PlayerLog log) {
|
||||
// Map MPV log levels to app logger levels
|
||||
switch (log.level.toLowerCase()) {
|
||||
case 'fatal':
|
||||
case 'error':
|
||||
appLogger.e('[MPV:${log.prefix}] ${log.text}');
|
||||
break;
|
||||
case 'warn':
|
||||
appLogger.w('[MPV:${log.prefix}] ${log.text}');
|
||||
break;
|
||||
case 'info':
|
||||
appLogger.i('[MPV:${log.prefix}] ${log.text}');
|
||||
break;
|
||||
case 'debug':
|
||||
case 'trace':
|
||||
case 'v':
|
||||
appLogger.d('[MPV:${log.prefix}] ${log.text}');
|
||||
break;
|
||||
default:
|
||||
appLogger.d('[MPV:${log.prefix}:${log.level}] ${log.text}');
|
||||
}
|
||||
}
|
||||
|
||||
void _onPlayerError(String error) {
|
||||
appLogger.e('[MPV ERROR] $error');
|
||||
}
|
||||
|
||||
Future<void> _playNext() async {
|
||||
if (_nextEpisode == null || _isLoadingNext) return;
|
||||
|
||||
@@ -650,39 +966,60 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
|
||||
/// 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 episode using pushReplacement to destroy current player
|
||||
if (mounted) {
|
||||
final currentRate = player.state.rate;
|
||||
Navigator.of(context).pushReplacement(
|
||||
PageRouteBuilder(
|
||||
pageBuilder: (context, animation, secondaryAnimation) =>
|
||||
VideoPlayerScreen(
|
||||
metadata: episodeMetadata,
|
||||
preferredAudioTrack: currentAudioTrack,
|
||||
preferredSubtitleTrack: currentSubtitleTrack,
|
||||
preferredPlaybackRate: currentRate,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
transitionDuration: Duration.zero,
|
||||
reverseTransitionDuration: Duration.zero,
|
||||
),
|
||||
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(
|
||||
@@ -690,12 +1027,14 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
// Video player
|
||||
Center(
|
||||
child: Video(
|
||||
controller: controller,
|
||||
controller: controller!,
|
||||
controls: (state) => plexVideoControlsBuilder(
|
||||
player,
|
||||
player!,
|
||||
widget.metadata,
|
||||
onNext: _nextEpisode != null ? _playNext : null,
|
||||
onPrevious: _previousEpisode != null ? _playPrevious : null,
|
||||
availableVersions: _availableVersions,
|
||||
selectedMediaIndex: widget.selectedMediaIndex,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -721,13 +1060,32 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
color: Colors.white,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
const Text(
|
||||
'Up Next',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
Consumer<PlaybackStateProvider>(
|
||||
builder: (context, playbackState, child) {
|
||||
final isShuffleActive =
|
||||
playbackState.isShuffleActive;
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text(
|
||||
'Up Next',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
if (isShuffleActive) ...[
|
||||
const SizedBox(width: 8),
|
||||
const Icon(
|
||||
Icons.shuffle,
|
||||
size: 20,
|
||||
color: Colors.white70,
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
|
||||
@@ -7,8 +7,11 @@ import 'settings_service.dart';
|
||||
class KeyboardShortcutsService {
|
||||
static KeyboardShortcutsService? _instance;
|
||||
late SettingsService _settingsService;
|
||||
Map<String, String> _shortcuts = {}; // Legacy string shortcuts for backward compatibility
|
||||
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._();
|
||||
|
||||
@@ -24,8 +27,11 @@ class KeyboardShortcutsService {
|
||||
_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
|
||||
_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);
|
||||
@@ -59,6 +65,8 @@ class KeyboardShortcutsService {
|
||||
|
||||
Future<void> refreshFromStorage() async {
|
||||
_hotkeys = await _settingsService.getKeyboardHotkeys();
|
||||
_seekTimeSmall = _settingsService.getSeekTimeSmall();
|
||||
_seekTimeLarge = _settingsService.getSeekTimeLarge();
|
||||
}
|
||||
|
||||
Future<void> resetToDefaults() async {
|
||||
@@ -135,8 +143,6 @@ class KeyboardShortcutsService {
|
||||
return modifiers.isEmpty ? keyName : '${modifiers.join(' + ')} + $keyName';
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Handle keyboard input for video player
|
||||
KeyEventResult handleVideoPlayerKeyEvent(
|
||||
KeyEvent event,
|
||||
@@ -207,8 +213,16 @@ class KeyboardShortcutsService {
|
||||
continue;
|
||||
}
|
||||
|
||||
_executeAction(action, player, onToggleFullscreen, onToggleSubtitles,
|
||||
onNextAudioTrack, onNextSubtitleTrack, onNextChapter, onPreviousChapter);
|
||||
_executeAction(
|
||||
action,
|
||||
player,
|
||||
onToggleFullscreen,
|
||||
onToggleSubtitles,
|
||||
onNextAudioTrack,
|
||||
onNextSubtitleTrack,
|
||||
onNextChapter,
|
||||
onPreviousChapter,
|
||||
);
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
}
|
||||
@@ -216,6 +230,21 @@ class KeyboardShortcutsService {
|
||||
return KeyEventResult.ignored;
|
||||
}
|
||||
|
||||
/// Seeks by the given offset (can be positive or negative) while clamping
|
||||
/// the result between 0 and the video duration
|
||||
void _seekWithClamping(Player player, Duration offset) {
|
||||
final currentPosition = player.state.position;
|
||||
final duration = player.state.duration;
|
||||
final newPosition = currentPosition + offset;
|
||||
|
||||
// Clamp between 0 and video duration
|
||||
final clampedPosition = newPosition.isNegative
|
||||
? Duration.zero
|
||||
: (newPosition > duration ? duration : newPosition);
|
||||
|
||||
player.seek(clampedPosition);
|
||||
}
|
||||
|
||||
void _executeAction(
|
||||
String action,
|
||||
Player player,
|
||||
@@ -239,20 +268,16 @@ class KeyboardShortcutsService {
|
||||
player.setVolume(newVolume);
|
||||
break;
|
||||
case 'seek_forward':
|
||||
final newPosition = player.state.position + const Duration(seconds: 10);
|
||||
player.seek(newPosition);
|
||||
_seekWithClamping(player, Duration(seconds: _seekTimeSmall));
|
||||
break;
|
||||
case 'seek_backward':
|
||||
final newPosition = player.state.position - const Duration(seconds: 10);
|
||||
player.seek(newPosition.isNegative ? Duration.zero : newPosition);
|
||||
_seekWithClamping(player, Duration(seconds: -_seekTimeSmall));
|
||||
break;
|
||||
case 'seek_forward_large':
|
||||
final newPosition = player.state.position + const Duration(seconds: 30);
|
||||
player.seek(newPosition);
|
||||
_seekWithClamping(player, Duration(seconds: _seekTimeLarge));
|
||||
break;
|
||||
case 'seek_backward_large':
|
||||
final newPosition = player.state.position - const Duration(seconds: 30);
|
||||
player.seek(newPosition.isNegative ? Duration.zero : newPosition);
|
||||
_seekWithClamping(player, Duration(seconds: -_seekTimeLarge));
|
||||
break;
|
||||
case 'fullscreen_toggle':
|
||||
onToggleFullscreen?.call();
|
||||
@@ -299,13 +324,13 @@ class KeyboardShortcutsService {
|
||||
case 'volume_down':
|
||||
return 'Volume Down';
|
||||
case 'seek_forward':
|
||||
return 'Seek Forward';
|
||||
return 'Seek Forward (${_seekTimeSmall}s)';
|
||||
case 'seek_backward':
|
||||
return 'Seek Backward';
|
||||
return 'Seek Backward (${_seekTimeSmall}s)';
|
||||
case 'seek_forward_large':
|
||||
return 'Seek Forward (Large)';
|
||||
return 'Seek Forward (${_seekTimeLarge}s)';
|
||||
case 'seek_backward_large':
|
||||
return 'Seek Backward (Large)';
|
||||
return 'Seek Backward (${_seekTimeLarge}s)';
|
||||
case 'fullscreen_toggle':
|
||||
return 'Toggle Fullscreen';
|
||||
case 'mute_toggle':
|
||||
@@ -366,6 +391,6 @@ class KeyboardShortcutsService {
|
||||
final bModifiers = Set.from(b.modifiers ?? []);
|
||||
|
||||
return aModifiers.length == bModifiers.length &&
|
||||
aModifiers.every((modifier) => bModifiers.contains(modifier));
|
||||
aModifiers.every((modifier) => bModifiers.contains(modifier));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,8 +179,9 @@ class PlexAuthService {
|
||||
/// Switch to a different user in the home
|
||||
Future<UserSwitchResponse> switchToUser(
|
||||
String userUUID,
|
||||
String currentToken,
|
||||
) async {
|
||||
String currentToken, {
|
||||
String? pin,
|
||||
}) async {
|
||||
final queryParams = {
|
||||
'includeSubscriptions': '1',
|
||||
'includeProviders': '1',
|
||||
@@ -193,6 +194,7 @@ class PlexAuthService {
|
||||
'X-Plex-Platform-Version': '3.8.1',
|
||||
'X-Plex-Token': currentToken,
|
||||
'X-Plex-Language': 'en',
|
||||
if (pin != null) 'pin': pin,
|
||||
};
|
||||
|
||||
final queryString = queryParams.entries
|
||||
@@ -213,6 +215,15 @@ class PlexAuthService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
class PlexServer {
|
||||
final String name;
|
||||
@@ -302,103 +313,156 @@ class PlexServer {
|
||||
return _selectBest(connections);
|
||||
}
|
||||
|
||||
PlexConnection? _findLowestLatency(
|
||||
List<MapEntry<PlexConnection, ConnectionTestResult>> entries,
|
||||
) {
|
||||
if (entries.isEmpty) return null;
|
||||
final bestEntry = entries.reduce(
|
||||
(a, b) => a.value.latencyMs < b.value.latencyMs ? a : b,
|
||||
);
|
||||
return bestEntry.key;
|
||||
}
|
||||
|
||||
PlexConnection? _selectBestWithLatency(
|
||||
Map<PlexConnection, ConnectionTestResult> results,
|
||||
) {
|
||||
final localEntries = results.entries
|
||||
.where((e) => e.key.local && !e.key.relay)
|
||||
.toList();
|
||||
final remoteEntries = results.entries
|
||||
.where((e) => !e.key.local && !e.key.relay)
|
||||
.toList();
|
||||
final relayEntries = results.entries.where((e) => e.key.relay).toList();
|
||||
|
||||
return _findLowestLatency(localEntries) ??
|
||||
_findLowestLatency(remoteEntries) ??
|
||||
_findLowestLatency(relayEntries);
|
||||
}
|
||||
|
||||
/// Find the best working connection by testing them
|
||||
/// 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)
|
||||
/// Tests both plex.direct URI and direct IP for each connection
|
||||
Stream<PlexConnection> findBestWorkingConnection() async* {
|
||||
if (connections.isEmpty) return;
|
||||
|
||||
// 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<PlexConnection?>();
|
||||
PlexConnection? firstConnection;
|
||||
final completer = Completer<_ConnectionCandidate?>();
|
||||
_ConnectionCandidate? firstCandidate;
|
||||
int completedTests = 0;
|
||||
|
||||
// Start testing all connections simultaneously
|
||||
for (final connection in connections) {
|
||||
PlexClient.testConnectionWithLatency(connection.uri, accessToken).then((
|
||||
// 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(connection);
|
||||
completer.complete(candidate);
|
||||
}
|
||||
|
||||
// If all tests complete without success, complete with null
|
||||
if (completedTests == connections.length && !completer.isCompleted) {
|
||||
if (completedTests == candidates.length && !completer.isCompleted) {
|
||||
completer.complete(null);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Wait for and emit the first successful connection
|
||||
firstConnection = await completer.future;
|
||||
if (firstConnection == null) {
|
||||
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 connection 2-3 times and average the latency
|
||||
final connectionResults = <PlexConnection, ConnectionTestResult>{};
|
||||
// Test each candidate 2-3 times and average the latency
|
||||
final candidateResults = <_ConnectionCandidate, ConnectionTestResult>{};
|
||||
|
||||
await Future.wait(
|
||||
connections.map((connection) async {
|
||||
candidates.map((candidate) async {
|
||||
final result = await PlexClient.testConnectionWithAverageLatency(
|
||||
connection.uri,
|
||||
candidate.url,
|
||||
accessToken,
|
||||
attempts: 2,
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
connectionResults[connection] = result;
|
||||
candidateResults[candidate] = result;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// If no connections succeeded, we're done
|
||||
if (connectionResults.isEmpty) {
|
||||
if (candidateResults.isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the best connection considering both priority and latency
|
||||
final bestConnection = _selectBestWithLatency(connectionResults);
|
||||
// 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 (bestConnection != null && bestConnection.uri != firstConnection.uri) {
|
||||
yield bestConnection;
|
||||
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();
|
||||
|
||||
// Find best in each category
|
||||
return _findLowestLatencyCandidate(localCandidates) ??
|
||||
_findLowestLatencyCandidate(remoteCandidates) ??
|
||||
_findLowestLatencyCandidate(relayCandidates);
|
||||
}
|
||||
|
||||
/// Find the candidate with lowest latency, preferring plex.direct URI on tie
|
||||
_ConnectionCandidate? _findLowestLatencyCandidate(
|
||||
List<MapEntry<_ConnectionCandidate, ConnectionTestResult>> entries,
|
||||
) {
|
||||
if (entries.isEmpty) return null;
|
||||
|
||||
// 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;
|
||||
|
||||
// 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;
|
||||
});
|
||||
|
||||
return entries.first.key;
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a connection to a Plex server
|
||||
@@ -445,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';
|
||||
|
||||
@@ -87,7 +87,7 @@ class ServerConnectionService {
|
||||
// Fetch user profile if requested
|
||||
PlexUserProfile? userProfile;
|
||||
if (fetchUserProfile && plexToken != null) {
|
||||
userProfile = await _fetchAndCacheUserProfile(plexToken);
|
||||
userProfile = await _fetchUserProfile(plexToken);
|
||||
}
|
||||
|
||||
// Return success result
|
||||
@@ -123,17 +123,15 @@ class ServerConnectionService {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch user profile from Plex API and cache it locally
|
||||
static Future<PlexUserProfile?> _fetchAndCacheUserProfile(
|
||||
String plexToken,
|
||||
) async {
|
||||
/// 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',
|
||||
'Successfully fetched user profile from API',
|
||||
error: {
|
||||
'autoSelectAudio': profile.autoSelectAudio,
|
||||
'defaultAudioLanguage': profile.defaultAudioLanguage ?? 'not set',
|
||||
@@ -144,40 +142,9 @@ class ServerConnectionService {
|
||||
},
|
||||
);
|
||||
|
||||
// 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',
|
||||
);
|
||||
appLogger.w('Failed to fetch user profile from API', error: e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,19 +2,27 @@ import 'dart:convert';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:hotkey_manager/hotkey_manager.dart';
|
||||
import 'package:plezy/utils/app_logger.dart';
|
||||
|
||||
enum ThemeMode { system, light, dark }
|
||||
|
||||
enum LibraryDensity { compact, normal, comfortable }
|
||||
|
||||
class SettingsService {
|
||||
static const String _keyThemeMode = 'theme_mode';
|
||||
static const String _keyEnableDebugLogging = 'enable_debug_logging';
|
||||
static const String _keyVideoBufferSize = 'video_buffer_size';
|
||||
static const String _keyAudioBufferSize = 'audio_buffer_size';
|
||||
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 const String _keyShowHeroSection = 'show_hero_section';
|
||||
|
||||
static SettingsService? _instance;
|
||||
late SharedPreferences _prefs;
|
||||
@@ -40,36 +48,30 @@ class SettingsService {
|
||||
|
||||
ThemeMode getThemeMode() {
|
||||
final modeString = _prefs.getString(_keyThemeMode);
|
||||
return ThemeMode.values
|
||||
.firstWhere((mode) => mode.name == modeString, orElse: () => ThemeMode.system);
|
||||
return ThemeMode.values.firstWhere(
|
||||
(mode) => mode.name == modeString,
|
||||
orElse: () => ThemeMode.system,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Debug Logging
|
||||
Future<void> setEnableDebugLogging(bool enabled) async {
|
||||
await _prefs.setBool(_keyEnableDebugLogging, enabled);
|
||||
// Update logger level immediately when setting changes
|
||||
setLoggerLevel(enabled);
|
||||
}
|
||||
|
||||
bool getEnableDebugLogging() {
|
||||
return _prefs.getBool(_keyEnableDebugLogging) ?? false;
|
||||
}
|
||||
|
||||
// Video Buffer Size (in MB)
|
||||
Future<void> setVideoBufferSize(int sizeInMB) async {
|
||||
await _prefs.setInt(_keyVideoBufferSize, sizeInMB);
|
||||
// Buffer Size (in MB)
|
||||
Future<void> setBufferSize(int sizeInMB) async {
|
||||
await _prefs.setInt(_keyBufferSize, sizeInMB);
|
||||
}
|
||||
|
||||
int getVideoBufferSize() {
|
||||
return _prefs.getInt(_keyVideoBufferSize) ?? 64; // Default 64MB
|
||||
}
|
||||
|
||||
// Audio Buffer Size (in MB)
|
||||
Future<void> setAudioBufferSize(int sizeInMB) async {
|
||||
await _prefs.setInt(_keyAudioBufferSize, sizeInMB);
|
||||
}
|
||||
|
||||
int getAudioBufferSize() {
|
||||
return _prefs.getInt(_keyAudioBufferSize) ?? 8; // Default 8MB
|
||||
int getBufferSize() {
|
||||
return _prefs.getInt(_keyBufferSize) ?? 128; // Default 128MB
|
||||
}
|
||||
|
||||
// Hardware Decoding
|
||||
@@ -78,7 +80,8 @@ class SettingsService {
|
||||
}
|
||||
|
||||
bool getEnableHardwareDecoding() {
|
||||
return _prefs.getBool(_keyEnableHardwareDecoding) ?? true; // Default enabled
|
||||
return _prefs.getBool(_keyEnableHardwareDecoding) ??
|
||||
true; // Default enabled
|
||||
}
|
||||
|
||||
// Preferred Video Codec
|
||||
@@ -99,6 +102,57 @@ class SettingsService {
|
||||
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)
|
||||
}
|
||||
|
||||
// Show Hero Section
|
||||
Future<void> setShowHeroSection(bool enabled) async {
|
||||
await _prefs.setBool(_keyShowHeroSection, enabled);
|
||||
}
|
||||
|
||||
bool getShowHeroSection() {
|
||||
return _prefs.getBool(_keyShowHeroSection) ??
|
||||
true; // Default: true (show hero section)
|
||||
}
|
||||
|
||||
// Seek Time Small (in seconds)
|
||||
Future<void> setSeekTimeSmall(int seconds) async {
|
||||
await _prefs.setInt(_keySeekTimeSmall, seconds);
|
||||
}
|
||||
|
||||
int getSeekTimeSmall() {
|
||||
return _prefs.getInt(_keySeekTimeSmall) ?? 10; // Default: 10 seconds
|
||||
}
|
||||
|
||||
// Seek Time Large (in seconds)
|
||||
Future<void> setSeekTimeLarge(int seconds) async {
|
||||
await _prefs.setInt(_keySeekTimeLarge, seconds);
|
||||
}
|
||||
|
||||
int getSeekTimeLarge() {
|
||||
return _prefs.getInt(_keySeekTimeLarge) ?? 30; // Default: 30 seconds
|
||||
}
|
||||
|
||||
// Keyboard Shortcuts (Legacy String-based)
|
||||
Map<String, String> getDefaultKeyboardShortcuts() {
|
||||
return {
|
||||
@@ -130,13 +184,22 @@ class SettingsService {
|
||||
'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]),
|
||||
'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]),
|
||||
'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),
|
||||
@@ -156,7 +219,9 @@ class SettingsService {
|
||||
|
||||
try {
|
||||
final decoded = json.decode(jsonString) as Map<String, dynamic>;
|
||||
final shortcuts = decoded.map((key, value) => MapEntry(key, value.toString()));
|
||||
final shortcuts = decoded.map(
|
||||
(key, value) => MapEntry(key, value.toString()),
|
||||
);
|
||||
|
||||
// Merge with defaults to ensure all keys exist
|
||||
final defaults = getDefaultKeyboardShortcuts();
|
||||
@@ -252,28 +317,35 @@ class SettingsService {
|
||||
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 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);
|
||||
return HotKey(
|
||||
key: key,
|
||||
modifiers: modifiers.isNotEmpty ? modifiers : null,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore deserialization errors
|
||||
@@ -283,7 +355,6 @@ class SettingsService {
|
||||
|
||||
// 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,
|
||||
@@ -310,7 +381,9 @@ class SettingsService {
|
||||
// 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);
|
||||
final usbHidMatch = RegExp(
|
||||
r'usbHidUsage: "0x([0-9a-fA-F]+)"',
|
||||
).firstMatch(keyString);
|
||||
if (usbHidMatch != null) {
|
||||
final usbHidCode = usbHidMatch.group(1)!.toLowerCase();
|
||||
|
||||
@@ -434,18 +507,30 @@ class SettingsService {
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -454,35 +539,63 @@ class SettingsService {
|
||||
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;
|
||||
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,
|
||||
'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}')) {
|
||||
if (keyString.contains('key${entry.key}') ||
|
||||
keyString.contains('Key${entry.key}')) {
|
||||
return entry.value;
|
||||
}
|
||||
}
|
||||
@@ -491,19 +604,67 @@ class SettingsService {
|
||||
}
|
||||
}
|
||||
|
||||
// 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(_keyVideoBufferSize),
|
||||
_prefs.remove(_keyAudioBufferSize),
|
||||
_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(_keyShowHeroSection),
|
||||
_prefs.remove(_keySeekTimeSmall),
|
||||
_prefs.remove(_keySeekTimeLarge),
|
||||
_prefs.remove(_keyMediaVersionPreferences),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -522,13 +683,18 @@ class SettingsService {
|
||||
return {
|
||||
'themeMode': getThemeMode().name,
|
||||
'enableDebugLogging': getEnableDebugLogging(),
|
||||
'videoBufferSize': getVideoBufferSize(),
|
||||
'audioBufferSize': getAudioBufferSize(),
|
||||
'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))),
|
||||
'keyboardHotkeys': hotkeys.map(
|
||||
(key, value) => MapEntry(key, _serializeHotKey(value)),
|
||||
),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +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;
|
||||
@@ -135,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);
|
||||
}
|
||||
@@ -144,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);
|
||||
@@ -162,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)
|
||||
@@ -240,10 +306,7 @@ class StorageService {
|
||||
|
||||
// Clear all user-related data (for logout)
|
||||
Future<void> clearUserData() async {
|
||||
await Future.wait([
|
||||
clearCredentials(),
|
||||
clearLibraryPreferences(),
|
||||
]);
|
||||
await Future.wait([clearCredentials(), clearLibraryPreferences()]);
|
||||
}
|
||||
|
||||
// Update current user after switching
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
import '../models/plex_media_info.dart';
|
||||
import '../models/plex_user_profile.dart';
|
||||
|
||||
/// Service for selecting audio and subtitle tracks based on user preferences
|
||||
class TrackSelectionService {
|
||||
/// Selects the best audio track based on user preferences
|
||||
///
|
||||
/// Returns the selected audio track, or null if no suitable track is found
|
||||
static PlexAudioTrack? selectAudioTrack(
|
||||
List<PlexAudioTrack> tracks,
|
||||
PlexUserProfile profile,
|
||||
) {
|
||||
if (tracks.isEmpty) return null;
|
||||
|
||||
// If auto-select is disabled, use Plex's selected track
|
||||
if (!profile.autoSelectAudio) {
|
||||
return tracks.firstWhere(
|
||||
(track) => track.selected,
|
||||
orElse: () => tracks.first,
|
||||
);
|
||||
}
|
||||
|
||||
// Build list of preferred language codes
|
||||
final preferredLanguages = <String>[];
|
||||
if (profile.defaultAudioLanguage != null) {
|
||||
preferredLanguages.add(profile.defaultAudioLanguage!);
|
||||
}
|
||||
if (profile.defaultAudioLanguages != null) {
|
||||
preferredLanguages.addAll(profile.defaultAudioLanguages!);
|
||||
}
|
||||
|
||||
// If no preferred languages, return first track
|
||||
if (preferredLanguages.isEmpty) {
|
||||
return tracks.first;
|
||||
}
|
||||
|
||||
// Try to find a track matching preferred languages
|
||||
for (final language in preferredLanguages) {
|
||||
final matchingTrack = tracks.firstWhere(
|
||||
(track) => _matchesLanguage(track.languageCode, language),
|
||||
orElse: () => tracks.first,
|
||||
);
|
||||
if (matchingTrack != tracks.first ||
|
||||
_matchesLanguage(matchingTrack.languageCode, language)) {
|
||||
return matchingTrack;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to first track
|
||||
return tracks.first;
|
||||
}
|
||||
|
||||
/// Selects the best subtitle track based on user preferences
|
||||
///
|
||||
/// Returns the selected subtitle track, or null if subtitles should be disabled
|
||||
static PlexSubtitleTrack? selectSubtitleTrack(
|
||||
List<PlexSubtitleTrack> tracks,
|
||||
PlexUserProfile profile,
|
||||
PlexAudioTrack? selectedAudioTrack,
|
||||
) {
|
||||
if (tracks.isEmpty) return null;
|
||||
|
||||
// Mode 0: Manually selected - return null to disable subtitles
|
||||
if (profile.autoSelectSubtitle == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Mode 1: Shown with foreign audio
|
||||
if (profile.autoSelectSubtitle == 1) {
|
||||
// Check if audio language matches user's preferred subtitle language
|
||||
if (selectedAudioTrack != null && profile.defaultSubtitleLanguage != null) {
|
||||
final audioLang = selectedAudioTrack.languageCode;
|
||||
final prefLang = profile.defaultSubtitleLanguage;
|
||||
|
||||
// If audio matches preferred language, no subtitles needed
|
||||
if (_matchesLanguage(audioLang, prefLang)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Foreign audio detected, enable subtitles
|
||||
return _findBestSubtitle(tracks, profile);
|
||||
}
|
||||
|
||||
// Mode 2: Always enabled
|
||||
if (profile.autoSelectSubtitle == 2) {
|
||||
return _findBestSubtitle(tracks, profile);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Finds the best subtitle track matching user preferences
|
||||
static PlexSubtitleTrack? _findBestSubtitle(
|
||||
List<PlexSubtitleTrack> tracks,
|
||||
PlexUserProfile profile,
|
||||
) {
|
||||
// Build list of preferred language codes
|
||||
final preferredLanguages = <String>[];
|
||||
if (profile.defaultSubtitleLanguage != null) {
|
||||
preferredLanguages.add(profile.defaultSubtitleLanguage!);
|
||||
}
|
||||
if (profile.defaultSubtitleLanguages != null) {
|
||||
preferredLanguages.addAll(profile.defaultSubtitleLanguages!);
|
||||
}
|
||||
|
||||
// Filter tracks based on preferences
|
||||
var candidateTracks = tracks;
|
||||
|
||||
// Apply SDH (hearing impaired) filtering
|
||||
candidateTracks = _filterBySDH(candidateTracks, profile.defaultSubtitleAccessibility);
|
||||
|
||||
// Apply forced subtitle filtering
|
||||
candidateTracks = _filterByForced(candidateTracks, profile.defaultSubtitleForced);
|
||||
|
||||
// If no candidates after filtering, relax filters
|
||||
if (candidateTracks.isEmpty) {
|
||||
candidateTracks = tracks;
|
||||
}
|
||||
|
||||
// If no preferred languages, return first candidate
|
||||
if (preferredLanguages.isEmpty) {
|
||||
return candidateTracks.firstOrNull;
|
||||
}
|
||||
|
||||
// Try to find a track matching preferred languages
|
||||
for (final language in preferredLanguages) {
|
||||
final matchingTrack = candidateTracks.firstWhere(
|
||||
(track) => _matchesLanguage(track.languageCode, language),
|
||||
orElse: () => candidateTracks.first,
|
||||
);
|
||||
if (matchingTrack != candidateTracks.first ||
|
||||
_matchesLanguage(matchingTrack.languageCode, language)) {
|
||||
return matchingTrack;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to first candidate
|
||||
return candidateTracks.firstOrNull;
|
||||
}
|
||||
|
||||
/// Filters subtitle tracks based on SDH (hearing impaired) preference
|
||||
///
|
||||
/// Values:
|
||||
/// - 0: Prefer non-SDH subtitles
|
||||
/// - 1: Prefer SDH subtitles
|
||||
/// - 2: Only show SDH subtitles
|
||||
/// - 3: Only show non-SDH subtitles
|
||||
static List<PlexSubtitleTrack> _filterBySDH(
|
||||
List<PlexSubtitleTrack> tracks,
|
||||
int preference,
|
||||
) {
|
||||
if (preference == 0 || preference == 1) {
|
||||
// Prefer but don't require
|
||||
final preferSDH = preference == 1;
|
||||
final preferred = tracks.where((t) => _isSDH(t) == preferSDH).toList();
|
||||
return preferred.isNotEmpty ? preferred : tracks;
|
||||
} else if (preference == 2) {
|
||||
// Only SDH
|
||||
return tracks.where(_isSDH).toList();
|
||||
} else if (preference == 3) {
|
||||
// Only non-SDH
|
||||
return tracks.where((t) => !_isSDH(t)).toList();
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
/// Filters subtitle tracks based on forced subtitle preference
|
||||
///
|
||||
/// Values:
|
||||
/// - 0: Prefer non-forced subtitles
|
||||
/// - 1: Prefer forced subtitles
|
||||
/// - 2: Only show forced subtitles
|
||||
/// - 3: Only show non-forced subtitles
|
||||
static List<PlexSubtitleTrack> _filterByForced(
|
||||
List<PlexSubtitleTrack> tracks,
|
||||
int preference,
|
||||
) {
|
||||
if (preference == 0 || preference == 1) {
|
||||
// Prefer but don't require
|
||||
final preferForced = preference == 1;
|
||||
final preferred = tracks.where((t) => t.forced == preferForced).toList();
|
||||
return preferred.isNotEmpty ? preferred : tracks;
|
||||
} else if (preference == 2) {
|
||||
// Only forced
|
||||
return tracks.where((t) => t.forced).toList();
|
||||
} else if (preference == 3) {
|
||||
// Only non-forced
|
||||
return tracks.where((t) => !t.forced).toList();
|
||||
}
|
||||
return tracks;
|
||||
}
|
||||
|
||||
/// Checks if a subtitle track is SDH (Subtitles for Deaf or Hard-of-Hearing)
|
||||
///
|
||||
/// Since Plex API may not expose this directly, we infer from the title/displayTitle
|
||||
static bool _isSDH(PlexSubtitleTrack track) {
|
||||
final title = track.title?.toLowerCase() ?? '';
|
||||
final displayTitle = track.displayTitle?.toLowerCase() ?? '';
|
||||
|
||||
// Look for common SDH indicators
|
||||
return title.contains('sdh') ||
|
||||
displayTitle.contains('sdh') ||
|
||||
title.contains('cc') ||
|
||||
displayTitle.contains('cc') ||
|
||||
title.contains('hearing impaired') ||
|
||||
displayTitle.contains('hearing impaired');
|
||||
}
|
||||
|
||||
/// Checks if a language code matches a preferred language
|
||||
///
|
||||
/// Handles both 2-letter (ISO 639-1) and 3-letter (ISO 639-2) codes
|
||||
static bool _matchesLanguage(String? trackLanguage, String? preferredLanguage) {
|
||||
if (trackLanguage == null || preferredLanguage == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final track = trackLanguage.toLowerCase();
|
||||
final preferred = preferredLanguage.toLowerCase();
|
||||
|
||||
// Direct match
|
||||
if (track == preferred) return true;
|
||||
|
||||
// Handle common 2-letter to 3-letter mappings
|
||||
final languageMap = {
|
||||
'en': 'eng',
|
||||
'es': 'spa',
|
||||
'fr': 'fra',
|
||||
'de': 'deu',
|
||||
'it': 'ita',
|
||||
'pt': 'por',
|
||||
'ja': 'jpn',
|
||||
'ko': 'kor',
|
||||
'zh': 'zho',
|
||||
'ru': 'rus',
|
||||
'ar': 'ara',
|
||||
'hi': 'hin',
|
||||
'nl': 'nld',
|
||||
'pl': 'pol',
|
||||
'tr': 'tur',
|
||||
'sv': 'swe',
|
||||
'no': 'nor',
|
||||
'da': 'dan',
|
||||
'fi': 'fin',
|
||||
'cs': 'ces',
|
||||
'hu': 'hun',
|
||||
'ro': 'ron',
|
||||
'th': 'tha',
|
||||
'vi': 'vie',
|
||||
'id': 'ind',
|
||||
'uk': 'ukr',
|
||||
'el': 'ell',
|
||||
'he': 'heb',
|
||||
};
|
||||
|
||||
// Try mapping preferred to 3-letter and compare
|
||||
if (languageMap[preferred] == track) return true;
|
||||
|
||||
// Try mapping track to 3-letter and compare with preferred 3-letter
|
||||
if (languageMap[track] == preferred) return true;
|
||||
|
||||
// Try reverse mapping (3-letter to 2-letter)
|
||||
final reverseMap = languageMap.map((k, v) => MapEntry(v, k));
|
||||
if (reverseMap[preferred] == track) return true;
|
||||
if (reverseMap[track] == preferred) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:logger/logger.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Service to check for new versions on GitHub
|
||||
/// Only enabled when ENABLE_UPDATE_CHECK build flag is set
|
||||
class UpdateService {
|
||||
static final Logger _logger = Logger();
|
||||
static const String _githubRepo = 'edde746/plezy';
|
||||
|
||||
// SharedPreferences keys
|
||||
static const String _keySkippedVersion = 'update_skipped_version';
|
||||
static const String _keyLastCheckTime = 'update_last_check_time';
|
||||
|
||||
// Check cooldown: 6 hours
|
||||
static const Duration _checkCooldown = Duration(hours: 6);
|
||||
|
||||
/// Check if update checking is enabled via build flag
|
||||
static bool get isUpdateCheckEnabled {
|
||||
const enabled = bool.fromEnvironment('ENABLE_UPDATE_CHECK', defaultValue: false);
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/// Skip a specific version
|
||||
static Future<void> skipVersion(String version) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keySkippedVersion, version);
|
||||
}
|
||||
|
||||
/// Get the skipped version
|
||||
static Future<String?> getSkippedVersion() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keySkippedVersion);
|
||||
}
|
||||
|
||||
/// Clear skipped version
|
||||
static Future<void> clearSkippedVersion() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keySkippedVersion);
|
||||
}
|
||||
|
||||
/// Check if cooldown period has passed since last check
|
||||
static Future<bool> shouldCheckForUpdates() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final lastCheckString = prefs.getString(_keyLastCheckTime);
|
||||
|
||||
if (lastCheckString == null) return true;
|
||||
|
||||
final lastCheck = DateTime.parse(lastCheckString);
|
||||
final now = DateTime.now();
|
||||
final timeSinceLastCheck = now.difference(lastCheck);
|
||||
|
||||
return timeSinceLastCheck >= _checkCooldown;
|
||||
}
|
||||
|
||||
/// Update the last check timestamp
|
||||
static Future<void> _updateLastCheckTime() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_keyLastCheckTime, DateTime.now().toIso8601String());
|
||||
}
|
||||
|
||||
/// Check for updates on GitHub (manual check, ignores cooldown)
|
||||
/// Returns a map with update info, or null if no update or error
|
||||
static Future<Map<String, dynamic>?> checkForUpdates({bool silent = false}) async {
|
||||
if (!isUpdateCheckEnabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
final packageInfo = await PackageInfo.fromPlatform();
|
||||
final currentVersion = packageInfo.version;
|
||||
|
||||
final dio = Dio();
|
||||
final response = await dio.get(
|
||||
'https://api.github.com/repos/$_githubRepo/releases/latest',
|
||||
options: Options(
|
||||
headers: {
|
||||
'Accept': 'application/vnd.github+json',
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = response.data;
|
||||
final latestVersion = data['tag_name'] as String;
|
||||
|
||||
// Remove 'v' prefix if present
|
||||
final cleanVersion = latestVersion.startsWith('v')
|
||||
? latestVersion.substring(1)
|
||||
: latestVersion;
|
||||
|
||||
final hasUpdate = _isNewerVersion(cleanVersion, currentVersion);
|
||||
|
||||
if (hasUpdate) {
|
||||
// Check if this version was skipped (always check, regardless of silent mode)
|
||||
final skippedVersion = await getSkippedVersion();
|
||||
if (skippedVersion == cleanVersion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
'hasUpdate': true,
|
||||
'currentVersion': currentVersion,
|
||||
'latestVersion': cleanVersion,
|
||||
'releaseUrl': data['html_url'] as String,
|
||||
'releaseName': data['name'] as String? ?? 'Version $cleanVersion',
|
||||
'releaseNotes': data['body'] as String? ?? '',
|
||||
'publishedAt': data['published_at'] as String,
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
_logger.e('Failed to check for updates: $e');
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Check for updates on startup (respects cooldown and skipped versions)
|
||||
/// Returns update info if available, null otherwise
|
||||
static Future<Map<String, dynamic>?> checkForUpdatesOnStartup() async {
|
||||
if (!isUpdateCheckEnabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check cooldown
|
||||
if (!await shouldCheckForUpdates()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Perform the check
|
||||
final updateInfo = await checkForUpdates(silent: true);
|
||||
|
||||
// Update last check time
|
||||
await _updateLastCheckTime();
|
||||
|
||||
return updateInfo;
|
||||
}
|
||||
|
||||
/// Compare two version strings
|
||||
/// Returns true if newVersion is newer than currentVersion
|
||||
static bool _isNewerVersion(String newVersion, String currentVersion) {
|
||||
try {
|
||||
// Split by '.' and parse as integers
|
||||
final newParts = newVersion.split('.').map((p) {
|
||||
// Handle versions like "1.2.3+4" by taking only the numeric part
|
||||
final numPart = p.split('+').first.split('-').first;
|
||||
return int.tryParse(numPart) ?? 0;
|
||||
}).toList();
|
||||
|
||||
final currentParts = currentVersion.split('.').map((p) {
|
||||
final numPart = p.split('+').first.split('-').first;
|
||||
return int.tryParse(numPart) ?? 0;
|
||||
}).toList();
|
||||
|
||||
// Compare each part
|
||||
final maxLength = newParts.length > currentParts.length
|
||||
? newParts.length
|
||||
: currentParts.length;
|
||||
|
||||
for (int i = 0; i < maxLength; i++) {
|
||||
final newPart = i < newParts.length ? newParts[i] : 0;
|
||||
final currentPart = i < currentParts.length ? currentParts[i] : 0;
|
||||
|
||||
if (newPart > currentPart) return true;
|
||||
if (newPart < currentPart) return false;
|
||||
}
|
||||
|
||||
return false; // Versions are equal
|
||||
} catch (e) {
|
||||
_logger.e('Error comparing versions: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+222
-9
@@ -1,5 +1,204 @@
|
||||
import 'package:logger/logger.dart';
|
||||
|
||||
/// Redacts sensitive information from log messages
|
||||
String _redactSensitiveData(String message) {
|
||||
String redacted = message;
|
||||
|
||||
// Redact Plex tokens (alphanumeric strings typically 20+ characters)
|
||||
// Pattern: X-Plex-Token=... or token=... or accessToken=... or similar
|
||||
redacted = redacted.replaceAllMapped(
|
||||
RegExp(r'([Tt]oken[=:]\s*)([A-Za-z0-9_-]{10,})', caseSensitive: false),
|
||||
(match) => '${match.group(1)}[REDACTED]',
|
||||
);
|
||||
|
||||
// Redact authorization headers
|
||||
redacted = redacted.replaceAllMapped(
|
||||
RegExp(r'([Aa]uthorization[=:]\s*)([A-Za-z0-9_\-\.]+)', caseSensitive: false),
|
||||
(match) => '${match.group(1)}[REDACTED]',
|
||||
);
|
||||
|
||||
// Redact API keys
|
||||
redacted = redacted.replaceAllMapped(
|
||||
RegExp(r'([Aa]pi[Kk]ey[=:]\s*)([A-Za-z0-9_-]{10,})', caseSensitive: false),
|
||||
(match) => '${match.group(1)}[REDACTED]',
|
||||
);
|
||||
|
||||
// Redact passwords
|
||||
redacted = redacted.replaceAllMapped(
|
||||
RegExp(r'([Pp]assword[=:]\s*)([^\s&,;]+)', caseSensitive: false),
|
||||
(match) => '${match.group(1)}[REDACTED]',
|
||||
);
|
||||
|
||||
// Redact full URLs with tokens in query parameters
|
||||
redacted = redacted.replaceAllMapped(
|
||||
RegExp(r'(https?://[^\s]*[?&])([Xx]-[Pp]lex-[Tt]oken|token)=([A-Za-z0-9_-]+)'),
|
||||
(match) => '${match.group(1)}${match.group(2)}=[REDACTED]',
|
||||
);
|
||||
|
||||
// Redact IP addresses in dot notation (e.g., 192.168.1.100)
|
||||
redacted = redacted.replaceAllMapped(
|
||||
RegExp(r'\b(\d{1,3}\.)(\d{1,3}\.)(\d{1,3}\.)(\d{1,3})\b'),
|
||||
(match) => '${match.group(1)}***.***.${match.group(4)}',
|
||||
);
|
||||
|
||||
// Redact IP addresses in dash notation (e.g., 192-168-1-11)
|
||||
redacted = redacted.replaceAllMapped(
|
||||
RegExp(r'\b(\d{1,3}-)(\d{1,3}-)(\d{1,3}-)(\d{1,3})\b'),
|
||||
(match) => '${match.group(1)}***-***-${match.group(4)}',
|
||||
);
|
||||
|
||||
// Redact standalone token-like strings (20+ alphanumeric characters)
|
||||
// Only if they appear in common token contexts
|
||||
redacted = redacted.replaceAllMapped(
|
||||
RegExp(r'\b([A-Za-z0-9_-]{20,})\b'),
|
||||
(match) {
|
||||
final token = match.group(1)!;
|
||||
// Only redact if it looks like a token (mixed case or contains hyphens/underscores)
|
||||
if (token.contains(RegExp(r'[A-Z]')) && token.contains(RegExp(r'[a-z]')) ||
|
||||
token.contains('_') || token.contains('-')) {
|
||||
return '[REDACTED_TOKEN]';
|
||||
}
|
||||
return token;
|
||||
},
|
||||
);
|
||||
|
||||
return redacted;
|
||||
}
|
||||
|
||||
/// Represents a single log entry stored in memory
|
||||
class LogEntry {
|
||||
final DateTime timestamp;
|
||||
final Level level;
|
||||
final String message;
|
||||
final Object? error;
|
||||
final StackTrace? stackTrace;
|
||||
|
||||
LogEntry({
|
||||
required this.timestamp,
|
||||
required this.level,
|
||||
required this.message,
|
||||
this.error,
|
||||
this.stackTrace,
|
||||
});
|
||||
|
||||
/// Estimate the memory size of this log entry in bytes
|
||||
int get estimatedSize {
|
||||
int size = 0;
|
||||
// DateTime: ~8 bytes
|
||||
size += 8;
|
||||
// Level enum: ~4 bytes
|
||||
size += 4;
|
||||
// Message string: 2 bytes per character (UTF-16)
|
||||
size += message.length * 2;
|
||||
// Error string: 2 bytes per character if present
|
||||
if (error != null) {
|
||||
size += error.toString().length * 2;
|
||||
}
|
||||
// Stack trace string: 2 bytes per character if present
|
||||
if (stackTrace != null) {
|
||||
size += stackTrace.toString().length * 2;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom log output that stores logs in memory with a circular buffer
|
||||
class MemoryLogOutput extends LogOutput {
|
||||
static const int maxLogSizeBytes = 5 * 1024 * 1024; // 5 MB
|
||||
static final List<LogEntry> _logs = [];
|
||||
static int _currentSize = 0;
|
||||
|
||||
/// Get all stored logs (newest first)
|
||||
static List<LogEntry> getLogs() => List.unmodifiable(_logs.reversed);
|
||||
|
||||
/// Clear all stored logs
|
||||
static void clearLogs() {
|
||||
_logs.clear();
|
||||
_currentSize = 0;
|
||||
}
|
||||
|
||||
/// Get current log buffer size in bytes
|
||||
static int getCurrentSize() => _currentSize;
|
||||
|
||||
/// Get current log buffer size in MB
|
||||
static double getCurrentSizeMB() => _currentSize / (1024 * 1024);
|
||||
|
||||
@override
|
||||
void output(OutputEvent event) {
|
||||
// Extract relevant information from the log event
|
||||
for (var line in event.lines) {
|
||||
final logEntry = LogEntry(
|
||||
timestamp: DateTime.now(),
|
||||
level: event.level,
|
||||
message: _redactSensitiveData(line),
|
||||
);
|
||||
|
||||
_logs.add(logEntry);
|
||||
_currentSize += logEntry.estimatedSize;
|
||||
|
||||
// Maintain buffer size limit (remove oldest entries)
|
||||
while (_currentSize > maxLogSizeBytes && _logs.isNotEmpty) {
|
||||
final removed = _logs.removeAt(0);
|
||||
_currentSize -= removed.estimatedSize;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom log printer that also stores error and stack trace information
|
||||
class MemoryAwareLogPrinter extends LogPrinter {
|
||||
final LogPrinter _wrappedPrinter;
|
||||
|
||||
MemoryAwareLogPrinter(this._wrappedPrinter);
|
||||
|
||||
@override
|
||||
List<String> log(LogEvent event) {
|
||||
// Store the log with error and stack trace if available
|
||||
final message = _redactSensitiveData(event.message.toString());
|
||||
final error = event.error != null
|
||||
? _redactSensitiveData(event.error.toString())
|
||||
: null;
|
||||
|
||||
final logEntry = LogEntry(
|
||||
timestamp: DateTime.now(),
|
||||
level: event.level,
|
||||
message: message,
|
||||
error: error,
|
||||
stackTrace: event.stackTrace,
|
||||
);
|
||||
|
||||
MemoryLogOutput._logs.add(logEntry);
|
||||
MemoryLogOutput._currentSize += logEntry.estimatedSize;
|
||||
|
||||
// Maintain buffer size limit (remove oldest entries)
|
||||
while (MemoryLogOutput._currentSize > MemoryLogOutput.maxLogSizeBytes &&
|
||||
MemoryLogOutput._logs.isNotEmpty) {
|
||||
final removed = MemoryLogOutput._logs.removeAt(0);
|
||||
MemoryLogOutput._currentSize -= removed.estimatedSize;
|
||||
}
|
||||
|
||||
// Delegate to wrapped printer for console output
|
||||
return _wrappedPrinter.log(event);
|
||||
}
|
||||
}
|
||||
|
||||
/// Custom production filter that respects our level setting even in release mode
|
||||
class ProductionFilter extends LogFilter {
|
||||
Level _currentLevel = Level.debug;
|
||||
|
||||
void setLevel(Level level) {
|
||||
_currentLevel = level;
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldLog(LogEvent event) {
|
||||
return event.level.value >= _currentLevel.value;
|
||||
}
|
||||
}
|
||||
|
||||
/// Global filter instance
|
||||
final _productionFilter = ProductionFilter();
|
||||
|
||||
/// Centralized logger instance for the application.
|
||||
///
|
||||
/// Usage:
|
||||
@@ -11,14 +210,28 @@ import 'package:logger/logger.dart';
|
||||
/// appLogger.w('Warning message');
|
||||
/// appLogger.e('Error message', error: e, stackTrace: stackTrace);
|
||||
/// ```
|
||||
final appLogger = Logger(
|
||||
printer: PrettyPrinter(
|
||||
methodCount: 2,
|
||||
errorMethodCount: 8,
|
||||
lineLength: 120,
|
||||
colors: true,
|
||||
printEmojis: true,
|
||||
dateTimeFormat: DateTimeFormat.onlyTimeAndSinceStart,
|
||||
),
|
||||
Logger appLogger = Logger(
|
||||
printer: MemoryAwareLogPrinter(SimplePrinter()),
|
||||
filter: _productionFilter,
|
||||
level: Level.debug,
|
||||
);
|
||||
|
||||
/// Update the logger's level dynamically based on debug setting
|
||||
/// Recreates the logger instance to ensure it works in release mode
|
||||
void setLoggerLevel(bool debugEnabled) {
|
||||
final newLevel = debugEnabled ? Level.debug : Level.info;
|
||||
|
||||
// Update the filter level
|
||||
_productionFilter.setLevel(newLevel);
|
||||
|
||||
// Recreate the logger instance with the new level
|
||||
// This ensures it works in release mode where Logger.level might be optimized away
|
||||
appLogger = Logger(
|
||||
printer: MemoryAwareLogPrinter(SimplePrinter()),
|
||||
filter: _productionFilter,
|
||||
level: newLevel,
|
||||
);
|
||||
|
||||
// Also set the static level for consistency
|
||||
Logger.level = newLevel;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'dart:math';
|
||||
|
||||
/// Utility class for platform detection
|
||||
class PlatformDetector {
|
||||
@@ -13,4 +14,24 @@ class PlatformDetector {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@ 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 =>
|
||||
@@ -17,9 +19,18 @@ extension ProviderExtensions on BuildContext {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../utils/platform_detector.dart';
|
||||
|
||||
/// A menu action item for context menus
|
||||
class ContextMenuItem {
|
||||
final String value;
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final bool requiresConfirmation;
|
||||
final String? confirmationTitle;
|
||||
final String? confirmationMessage;
|
||||
final bool isDestructive;
|
||||
|
||||
const ContextMenuItem({
|
||||
required this.value,
|
||||
required this.icon,
|
||||
required this.label,
|
||||
this.requiresConfirmation = false,
|
||||
this.confirmationTitle,
|
||||
this.confirmationMessage,
|
||||
this.isDestructive = false,
|
||||
});
|
||||
}
|
||||
|
||||
/// A wrapper widget that shows context menus differently based on platform.
|
||||
/// On mobile (iOS/Android): Shows a bottom sheet on long-press
|
||||
/// On desktop (Windows/macOS/Linux): Shows a popup menu on right-click or long-press
|
||||
class ContextMenuWrapper extends StatefulWidget {
|
||||
final Widget child;
|
||||
final List<ContextMenuItem> menuItems;
|
||||
final Function(String)? onMenuItemSelected;
|
||||
final VoidCallback? onTap;
|
||||
final String? title;
|
||||
final bool forceBottomSheet;
|
||||
|
||||
const ContextMenuWrapper({
|
||||
super.key,
|
||||
required this.child,
|
||||
required this.menuItems,
|
||||
this.onMenuItemSelected,
|
||||
this.onTap,
|
||||
this.title,
|
||||
this.forceBottomSheet = false,
|
||||
});
|
||||
|
||||
@override
|
||||
State<ContextMenuWrapper> createState() => _ContextMenuWrapperState();
|
||||
}
|
||||
|
||||
class _ContextMenuWrapperState extends State<ContextMenuWrapper> {
|
||||
Offset _tapPosition = Offset.zero;
|
||||
|
||||
void _storeTapPosition(TapDownDetails details) {
|
||||
_tapPosition = details.globalPosition;
|
||||
}
|
||||
|
||||
Future<bool> _showConfirmationDialog({
|
||||
required String title,
|
||||
required String message,
|
||||
required bool isDestructive,
|
||||
}) async {
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(title),
|
||||
content: Text(message),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: isDestructive
|
||||
? TextButton.styleFrom(foregroundColor: Colors.red)
|
||||
: null,
|
||||
child: const Text('Confirm'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
return result ?? false;
|
||||
}
|
||||
|
||||
Future<void> _showContextMenu(BuildContext context) async {
|
||||
final useBottomSheet =
|
||||
widget.forceBottomSheet || PlatformDetector.isMobile(context);
|
||||
String? selected;
|
||||
|
||||
if (useBottomSheet) {
|
||||
// Mobile: Show bottom sheet
|
||||
selected = await showModalBottomSheet<String>(
|
||||
context: context,
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (widget.title != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
widget.title!,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
...widget.menuItems.map(
|
||||
(item) => ListTile(
|
||||
leading: Icon(item.icon),
|
||||
title: Text(item.label),
|
||||
onTap: () => Navigator.pop(context, item.value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Desktop: Show popup menu
|
||||
final RenderBox overlay =
|
||||
Overlay.of(context).context.findRenderObject() as RenderBox;
|
||||
final overlayRect = Rect.fromPoints(
|
||||
_tapPosition,
|
||||
_tapPosition.translate(1, 1),
|
||||
);
|
||||
|
||||
final menuItems = widget.menuItems
|
||||
.map(
|
||||
(item) => PopupMenuItem<String>(
|
||||
value: item.value,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(item.icon, size: 20),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(item.label)),
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
|
||||
selected = await showMenu<String>(
|
||||
context: context,
|
||||
position: RelativeRect.fromRect(
|
||||
overlayRect,
|
||||
Offset.zero & overlay.size,
|
||||
),
|
||||
items: menuItems,
|
||||
elevation: 8,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
popUpAnimationStyle: AnimationStyle(
|
||||
duration: const Duration(milliseconds: 150),
|
||||
reverseDuration: const Duration(milliseconds: 100),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (selected != null && widget.onMenuItemSelected != null) {
|
||||
// Find the selected item to check if confirmation is needed
|
||||
final selectedItem = widget.menuItems.firstWhere(
|
||||
(item) => item.value == selected,
|
||||
);
|
||||
|
||||
if (selectedItem.requiresConfirmation) {
|
||||
final confirmed = await _showConfirmationDialog(
|
||||
title: selectedItem.confirmationTitle ?? 'Confirm Action',
|
||||
message:
|
||||
selectedItem.confirmationMessage ??
|
||||
'Are you sure you want to perform this action?',
|
||||
isDestructive: selectedItem.isDestructive,
|
||||
);
|
||||
|
||||
if (!confirmed) return;
|
||||
}
|
||||
|
||||
widget.onMenuItemSelected!(selected);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onTap: widget.onTap,
|
||||
onTapDown: _storeTapPosition,
|
||||
onLongPress: () => _showContextMenu(context),
|
||||
onSecondaryTapDown: _storeTapPosition,
|
||||
onSecondaryTap: () => _showContextMenu(context),
|
||||
child: widget.child,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,6 @@ class _HotKeyRecorderWidgetState extends State<HotKeyRecorderWidget> {
|
||||
_recordedHotKey = widget.currentHotKey;
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AlertDialog(
|
||||
|
||||
+158
-96
@@ -2,12 +2,12 @@ import 'package:flutter/material.dart';
|
||||
import 'package:cached_network_image/cached_network_image.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';
|
||||
|
||||
@@ -16,7 +16,6 @@ class MediaCard extends StatefulWidget {
|
||||
final double? width;
|
||||
final double? height;
|
||||
final void Function(String ratingKey)? onRefresh;
|
||||
final PlexUserProfile? userProfile;
|
||||
|
||||
const MediaCard({
|
||||
super.key,
|
||||
@@ -24,34 +23,37 @@ class MediaCard extends StatefulWidget {
|
||||
this.width,
|
||||
this.height,
|
||||
this.onRefresh,
|
||||
this.userProfile,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MediaCard> createState() => _MediaCardState();
|
||||
}
|
||||
|
||||
class _MediaCardState extends State<MediaCard>
|
||||
with AutomaticKeepAliveClientMixin {
|
||||
@override
|
||||
bool get wantKeepAlive => true;
|
||||
|
||||
class _MediaCardState extends State<MediaCard> {
|
||||
void _handleTap(BuildContext context) async {
|
||||
final client = context.client;
|
||||
if (client == null) return;
|
||||
|
||||
final itemType = widget.item.type.toLowerCase();
|
||||
|
||||
// Music content is not yet supported
|
||||
if (itemType == 'artist' || itemType == 'album' || itemType == 'track') {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Music playback is not yet supported'),
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// For episodes, start playback directly
|
||||
if (itemType == 'episode') {
|
||||
final result = await Navigator.push<bool>(
|
||||
final result = await navigateToVideoPlayer(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => VideoPlayerScreen(
|
||||
metadata: widget.item,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
),
|
||||
metadata: widget.item,
|
||||
);
|
||||
// Refresh parent screen if result indicates it's needed
|
||||
if (result == true) {
|
||||
@@ -62,10 +64,7 @@ class _MediaCardState extends State<MediaCard>
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => SeasonDetailScreen(
|
||||
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
|
||||
@@ -75,10 +74,7 @@ class _MediaCardState extends State<MediaCard>
|
||||
final result = await Navigator.push<bool>(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MediaDetailScreen(
|
||||
metadata: widget.item,
|
||||
userProfile: widget.userProfile,
|
||||
),
|
||||
builder: (context) => MediaDetailScreen(metadata: widget.item),
|
||||
),
|
||||
);
|
||||
// Refresh parent screen if result indicates it's needed
|
||||
@@ -90,79 +86,86 @@ class _MediaCardState extends State<MediaCard>
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
super.build(context); // Required for AutomaticKeepAliveClientMixin
|
||||
return SizedBox(
|
||||
width: widget.width,
|
||||
child: MediaContextMenu(
|
||||
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: _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.displaySubtitle != null)
|
||||
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.displaySubtitle!,
|
||||
widget.item.displayTitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted,
|
||||
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: tokens(context).textMuted,
|
||||
fontSize: 11,
|
||||
height: 1.1,
|
||||
),
|
||||
)
|
||||
else if (widget.item.year != null)
|
||||
Text(
|
||||
'${widget.item.year}',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: tokens(context).textMuted,
|
||||
fontSize: 11,
|
||||
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: tokens(context).textMuted,
|
||||
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: tokens(context).textMuted,
|
||||
fontSize: 11,
|
||||
height: 1.1,
|
||||
),
|
||||
)
|
||||
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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -183,27 +186,28 @@ class _MediaCardState extends State<MediaCard>
|
||||
}
|
||||
|
||||
Widget _buildPosterImage(BuildContext context) {
|
||||
if (widget.item.posterThumb != null) {
|
||||
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 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),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return CachedNetworkImage(
|
||||
imageUrl: client.getThumbnailUrl(widget.item.posterThumb),
|
||||
imageUrl: client.getThumbnailUrl(posterUrl),
|
||||
fit: BoxFit.cover,
|
||||
width: double.infinity,
|
||||
height: double.infinity,
|
||||
filterQuality: FilterQuality.medium,
|
||||
fadeInDuration: const Duration(milliseconds: 300),
|
||||
placeholder: (context, url) => Container(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
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)),
|
||||
@@ -212,9 +216,10 @@ class _MediaCardState extends State<MediaCard>
|
||||
},
|
||||
);
|
||||
} 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),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -278,3 +283,60 @@ class _PosterOverlay extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.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';
|
||||
import '../providers/playback_state_provider.dart';
|
||||
import '../utils/video_player_navigation.dart';
|
||||
|
||||
/// Helper class to store menu action data
|
||||
class _MenuAction {
|
||||
@@ -99,6 +103,28 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
);
|
||||
}
|
||||
|
||||
// Shuffle Play (for shows and seasons)
|
||||
if (itemType == 'show' || itemType == 'season') {
|
||||
menuActions.add(
|
||||
_MenuAction(
|
||||
value: 'shuffle_play',
|
||||
icon: Icons.shuffle,
|
||||
label: 'Shuffle Play',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
@@ -219,6 +245,14 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
'Error loading season',
|
||||
);
|
||||
break;
|
||||
|
||||
case 'fileinfo':
|
||||
await _showFileInfo(context);
|
||||
break;
|
||||
|
||||
case 'shuffle_play':
|
||||
await _handleShufflePlay(context);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +310,130 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle shuffle play action
|
||||
Future<void> _handleShufflePlay(BuildContext context) async {
|
||||
final client = context.client;
|
||||
if (client == null) return;
|
||||
|
||||
final playbackState = context.read<PlaybackStateProvider>();
|
||||
final itemType = widget.metadata.type.toLowerCase();
|
||||
|
||||
try {
|
||||
// Show loading indicator
|
||||
if (context.mounted) {
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (context) =>
|
||||
const Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
|
||||
// Get unwatched episodes based on type
|
||||
List<PlexMetadata> episodes;
|
||||
if (itemType == 'show') {
|
||||
episodes = await client.getAllUnwatchedEpisodes(
|
||||
widget.metadata.ratingKey,
|
||||
);
|
||||
} else {
|
||||
// season
|
||||
episodes = await client.getUnwatchedEpisodesInSeason(
|
||||
widget.metadata.ratingKey,
|
||||
);
|
||||
}
|
||||
|
||||
// Close loading indicator
|
||||
if (context.mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
if (episodes.isEmpty) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('No unwatched episodes found')),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Shuffle the episodes
|
||||
episodes.shuffle();
|
||||
|
||||
// Store shuffle queue in provider
|
||||
playbackState.setShuffleQueue(episodes, widget.metadata.ratingKey);
|
||||
|
||||
// Navigate to first episode
|
||||
if (context.mounted) {
|
||||
await navigateToVideoPlayer(context, metadata: episodes.first);
|
||||
}
|
||||
} catch (e) {
|
||||
// Close loading indicator if it's still open
|
||||
if (context.mounted && Navigator.canPop(context)) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Error starting shuffle play: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
@@ -7,12 +7,15 @@ import 'package:window_manager/window_manager.dart';
|
||||
import 'package:macos_window_utils/macos_window_utils.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
import '../models/plex_media_info.dart';
|
||||
import '../models/plex_media_version.dart';
|
||||
import '../providers/plex_client_provider.dart';
|
||||
import '../services/fullscreen_state_manager.dart';
|
||||
import '../services/keyboard_shortcuts_service.dart';
|
||||
import '../services/settings_service.dart';
|
||||
import '../utils/desktop_window_padding.dart';
|
||||
import '../utils/platform_detector.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../screens/video_player_screen.dart';
|
||||
import 'app_bar_back_button.dart';
|
||||
|
||||
/// Custom video controls builder for Plex with chapter, audio, and subtitle support
|
||||
@@ -21,12 +24,16 @@ Widget plexVideoControlsBuilder(
|
||||
PlexMetadata metadata, {
|
||||
VoidCallback? onNext,
|
||||
VoidCallback? onPrevious,
|
||||
List<PlexMediaVersion>? availableVersions,
|
||||
int? selectedMediaIndex,
|
||||
}) {
|
||||
return PlexVideoControls(
|
||||
player: player,
|
||||
metadata: metadata,
|
||||
onNext: onNext,
|
||||
onPrevious: onPrevious,
|
||||
availableVersions: availableVersions ?? [],
|
||||
selectedMediaIndex: selectedMediaIndex ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -35,6 +42,8 @@ class PlexVideoControls extends StatefulWidget {
|
||||
final PlexMetadata metadata;
|
||||
final VoidCallback? onNext;
|
||||
final VoidCallback? onPrevious;
|
||||
final List<PlexMediaVersion> availableVersions;
|
||||
final int selectedMediaIndex;
|
||||
|
||||
const PlexVideoControls({
|
||||
super.key,
|
||||
@@ -42,6 +51,8 @@ class PlexVideoControls extends StatefulWidget {
|
||||
required this.metadata,
|
||||
this.onNext,
|
||||
this.onPrevious,
|
||||
this.availableVersions = const [],
|
||||
this.selectedMediaIndex = 0,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -49,7 +60,7 @@ class PlexVideoControls extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
with WindowListener {
|
||||
with WindowListener, WidgetsBindingObserver {
|
||||
bool _showControls = true;
|
||||
List<PlexChapter> _chapters = [];
|
||||
bool _chaptersLoaded = false;
|
||||
@@ -57,14 +68,24 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
bool _isFullscreen = false;
|
||||
late final FocusNode _focusNode;
|
||||
KeyboardShortcutsService? _keyboardService;
|
||||
int _seekTimeSmall = 10; // Default, loaded from settings
|
||||
int _seekTimeLarge = 30; // Default, loaded from settings
|
||||
// Double-tap feedback state
|
||||
bool _showDoubleTapFeedback = false;
|
||||
double _doubleTapFeedbackOpacity = 0.0;
|
||||
bool _lastDoubleTapWasForward = true;
|
||||
Timer? _feedbackTimer;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_focusNode = FocusNode();
|
||||
_loadChapters();
|
||||
_loadSeekTimes();
|
||||
_startHideTimer();
|
||||
_initKeyboardService();
|
||||
// Add lifecycle observer to reload settings when app resumes
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
// Add window listener for tracking fullscreen state (for button icon)
|
||||
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
|
||||
windowManager.addListener(this);
|
||||
@@ -75,6 +96,16 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
_keyboardService = await KeyboardShortcutsService.getInstance();
|
||||
}
|
||||
|
||||
Future<void> _loadSeekTimes() async {
|
||||
final settingsService = await SettingsService.getInstance();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_seekTimeSmall = settingsService.getSeekTimeSmall();
|
||||
_seekTimeLarge = settingsService.getSeekTimeLarge();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _toggleSubtitles() {
|
||||
// Toggle subtitle visibility - this would need to be implemented based on your subtitle system
|
||||
// For now, this is a placeholder
|
||||
@@ -107,7 +138,10 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
@override
|
||||
void dispose() {
|
||||
_hideTimer?.cancel();
|
||||
_feedbackTimer?.cancel();
|
||||
_focusNode.dispose();
|
||||
// Remove lifecycle observer
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
// Remove window listener
|
||||
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
|
||||
windowManager.removeListener(this);
|
||||
@@ -115,6 +149,14 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
// Reload seek times when app resumes (e.g., returning from settings)
|
||||
_loadSeekTimes();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowEnterFullScreen() {
|
||||
if (mounted) {
|
||||
@@ -257,6 +299,11 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
icon: const Icon(Icons.video_library, color: Colors.white),
|
||||
onPressed: _showChapterBottomSheet,
|
||||
),
|
||||
if (widget.availableVersions.length > 1)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.video_file, color: Colors.white),
|
||||
onPressed: _showVersionBottomSheet,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
@@ -265,9 +312,8 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
|
||||
void _seekToPreviousChapter() {
|
||||
if (_chapters.isEmpty) {
|
||||
// No chapters - seek backward 10 seconds
|
||||
final currentPosition = widget.player.state.position;
|
||||
widget.player.seek(currentPosition - const Duration(seconds: 10));
|
||||
// No chapters - seek backward by configured amount
|
||||
_seekWithClamping(Duration(seconds: -_seekTimeSmall));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -289,9 +335,8 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
|
||||
void _seekToNextChapter() {
|
||||
if (_chapters.isEmpty) {
|
||||
// No chapters - seek forward 10 seconds
|
||||
final currentPosition = widget.player.state.position;
|
||||
widget.player.seek(currentPosition + const Duration(seconds: 10));
|
||||
// No chapters - seek forward by configured amount
|
||||
_seekWithClamping(Duration(seconds: _seekTimeSmall));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -307,6 +352,116 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
}
|
||||
}
|
||||
|
||||
/// Seeks by the given offset (can be positive or negative) while clamping
|
||||
/// the result between 0 and the video duration
|
||||
void _seekWithClamping(Duration offset) {
|
||||
final currentPosition = widget.player.state.position;
|
||||
final duration = widget.player.state.duration;
|
||||
final newPosition = currentPosition + offset;
|
||||
|
||||
// Clamp between 0 and video duration
|
||||
final clampedPosition = newPosition.isNegative
|
||||
? Duration.zero
|
||||
: (newPosition > duration ? duration : newPosition);
|
||||
|
||||
widget.player.seek(clampedPosition);
|
||||
}
|
||||
|
||||
/// Get the replay icon based on the duration
|
||||
/// Returns numbered icons (replay_5, replay_10, replay_30) when available,
|
||||
/// otherwise returns generic replay icon
|
||||
IconData _getReplayIcon(int seconds) {
|
||||
switch (seconds) {
|
||||
case 5:
|
||||
return Icons.replay_5;
|
||||
case 10:
|
||||
return Icons.replay_10;
|
||||
case 30:
|
||||
return Icons.replay_30;
|
||||
default:
|
||||
return Icons.replay; // Generic icon for custom durations
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the forward icon based on the duration
|
||||
/// Returns numbered icons (forward_5, forward_10, forward_30) when available,
|
||||
/// otherwise returns generic forward icon
|
||||
IconData _getForwardIcon(int seconds) {
|
||||
switch (seconds) {
|
||||
case 5:
|
||||
return Icons.forward_5;
|
||||
case 10:
|
||||
return Icons.forward_10;
|
||||
case 30:
|
||||
return Icons.forward_30;
|
||||
default:
|
||||
return Icons.forward; // Generic icon for custom durations
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle double-tap skip forward or backward
|
||||
void _handleDoubleTapSkip({required bool isForward}) {
|
||||
// Perform the seek
|
||||
_seekWithClamping(
|
||||
Duration(seconds: isForward ? _seekTimeSmall : -_seekTimeSmall),
|
||||
);
|
||||
|
||||
// Show visual feedback
|
||||
_showSkipFeedback(isForward: isForward);
|
||||
}
|
||||
|
||||
/// Show animated visual feedback for skip gesture
|
||||
void _showSkipFeedback({required bool isForward}) {
|
||||
_feedbackTimer?.cancel();
|
||||
|
||||
setState(() {
|
||||
_lastDoubleTapWasForward = isForward;
|
||||
_showDoubleTapFeedback = true;
|
||||
_doubleTapFeedbackOpacity = 1.0;
|
||||
});
|
||||
|
||||
// Fade out after delay
|
||||
_feedbackTimer = Timer(const Duration(milliseconds: 500), () {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_doubleTapFeedbackOpacity = 0.0;
|
||||
});
|
||||
|
||||
Timer(const Duration(milliseconds: 300), () {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_showDoubleTapFeedback = false;
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Build the visual feedback widget for double-tap skip
|
||||
Widget _buildDoubleTapFeedback() {
|
||||
return Align(
|
||||
alignment: _lastDoubleTapWasForward
|
||||
? Alignment.centerRight
|
||||
: Alignment.centerLeft,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 60),
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.6),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
_lastDoubleTapWasForward
|
||||
? _getForwardIcon(_seekTimeSmall)
|
||||
: _getReplayIcon(_seekTimeSmall),
|
||||
color: Colors.white,
|
||||
size: 48,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _toggleFullscreen() async {
|
||||
if (!PlatformDetector.isMobile(context)) {
|
||||
// Query actual window state to determine what action to take
|
||||
@@ -333,7 +488,6 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isMobile = PlatformDetector.isMobile(context);
|
||||
@@ -447,6 +601,63 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
},
|
||||
),
|
||||
),
|
||||
// Mobile double-tap zones for skip forward/backward
|
||||
if (isMobile)
|
||||
Positioned.fill(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final height = constraints.maxHeight;
|
||||
final width = constraints.maxWidth;
|
||||
final topExclude = height * 0.15; // Exclude top 15% (top bar)
|
||||
final bottomExclude = height * 0.15; // Exclude bottom 15% (seek slider)
|
||||
final leftZoneWidth = width * 0.35; // Left 35%
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
// Left zone - skip backward
|
||||
Positioned(
|
||||
left: 0,
|
||||
top: topExclude,
|
||||
bottom: bottomExclude,
|
||||
width: leftZoneWidth,
|
||||
child: GestureDetector(
|
||||
onTap: _toggleControls,
|
||||
onDoubleTap: () =>
|
||||
_handleDoubleTapSkip(isForward: false),
|
||||
behavior: HitTestBehavior.translucent,
|
||||
child: Container(color: Colors.transparent),
|
||||
),
|
||||
),
|
||||
// Right zone - skip forward
|
||||
Positioned(
|
||||
right: 0,
|
||||
top: topExclude,
|
||||
bottom: bottomExclude,
|
||||
width: leftZoneWidth,
|
||||
child: GestureDetector(
|
||||
onTap: _toggleControls,
|
||||
onDoubleTap: () =>
|
||||
_handleDoubleTapSkip(isForward: true),
|
||||
behavior: HitTestBehavior.translucent,
|
||||
child: Container(color: Colors.transparent),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
// Visual feedback overlay for double-tap
|
||||
if (isMobile && _showDoubleTapFeedback)
|
||||
Positioned.fill(
|
||||
child: IgnorePointer(
|
||||
child: AnimatedOpacity(
|
||||
opacity: _doubleTapFeedbackOpacity,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
child: _buildDoubleTapFeedback(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -548,17 +759,14 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: IconButton(
|
||||
icon: const Icon(
|
||||
Icons.replay_10,
|
||||
icon: Icon(
|
||||
_getReplayIcon(_seekTimeSmall),
|
||||
color: Colors.white,
|
||||
size: 48,
|
||||
),
|
||||
iconSize: 48,
|
||||
onPressed: () {
|
||||
final currentPosition = widget.player.state.position;
|
||||
widget.player.seek(
|
||||
currentPosition - const Duration(seconds: 10),
|
||||
);
|
||||
_seekWithClamping(Duration(seconds: -_seekTimeSmall));
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -593,17 +801,14 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: IconButton(
|
||||
icon: const Icon(
|
||||
Icons.forward_10,
|
||||
icon: Icon(
|
||||
_getForwardIcon(_seekTimeSmall),
|
||||
color: Colors.white,
|
||||
size: 48,
|
||||
),
|
||||
iconSize: 48,
|
||||
onPressed: () {
|
||||
final currentPosition = widget.player.state.position;
|
||||
widget.player.seek(
|
||||
currentPosition + const Duration(seconds: 10),
|
||||
);
|
||||
_seekWithClamping(Duration(seconds: _seekTimeSmall));
|
||||
},
|
||||
),
|
||||
),
|
||||
@@ -688,10 +893,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
final isMacOS = Platform.isMacOS;
|
||||
|
||||
final topBar = Padding(
|
||||
padding: EdgeInsets.only(
|
||||
left: leftPadding,
|
||||
right: 16,
|
||||
),
|
||||
padding: EdgeInsets.only(left: leftPadding, right: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
AppBarBackButton(
|
||||
@@ -828,10 +1030,10 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
),
|
||||
onPressed: widget.onPrevious,
|
||||
),
|
||||
// Previous chapter (or -10s if no chapters)
|
||||
// Previous chapter (or skip backward if no chapters)
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
_chapters.isEmpty ? Icons.replay_10 : Icons.fast_rewind,
|
||||
_chapters.isEmpty ? _getReplayIcon(_seekTimeSmall) : Icons.fast_rewind,
|
||||
color: Colors.white,
|
||||
),
|
||||
onPressed: _seekToPreviousChapter,
|
||||
@@ -860,10 +1062,10 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
);
|
||||
},
|
||||
),
|
||||
// Next chapter (or +10s if no chapters)
|
||||
// Next chapter (or skip forward if no chapters)
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
_chapters.isEmpty ? Icons.forward_10 : Icons.fast_forward,
|
||||
_chapters.isEmpty ? _getForwardIcon(_seekTimeSmall) : Icons.fast_forward,
|
||||
color: Colors.white,
|
||||
),
|
||||
onPressed: _seekToNextChapter,
|
||||
@@ -1100,7 +1302,11 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
stream: widget.player.stream.track,
|
||||
initialData: widget.player.state.track,
|
||||
builder: (context, selectedSnapshot) {
|
||||
final selectedTrack = selectedSnapshot.data?.audio;
|
||||
// Use snapshot data or fall back to current state
|
||||
final currentTrack =
|
||||
selectedSnapshot.data ??
|
||||
widget.player.state.track;
|
||||
final selectedTrack = currentTrack.audio;
|
||||
final selectedId = selectedTrack?.id;
|
||||
|
||||
return ListView.builder(
|
||||
@@ -1222,7 +1428,11 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
stream: widget.player.stream.track,
|
||||
initialData: widget.player.state.track,
|
||||
builder: (context, selectedSnapshot) {
|
||||
final selectedTrack = selectedSnapshot.data?.subtitle;
|
||||
// Use snapshot data or fall back to current state
|
||||
final currentTrack =
|
||||
selectedSnapshot.data ??
|
||||
widget.player.state.track;
|
||||
final selectedTrack = currentTrack.subtitle;
|
||||
final selectedId = selectedTrack?.id;
|
||||
final isOffSelected = selectedId == 'no';
|
||||
|
||||
@@ -1233,9 +1443,13 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
// First item is "Off"
|
||||
if (index == 0) {
|
||||
return ListTile(
|
||||
title: const Text(
|
||||
title: Text(
|
||||
'Off',
|
||||
style: TextStyle(color: Colors.white),
|
||||
style: TextStyle(
|
||||
color: isOffSelected
|
||||
? Colors.blue
|
||||
: Colors.white,
|
||||
),
|
||||
),
|
||||
trailing: isOffSelected
|
||||
? const Icon(
|
||||
@@ -1512,7 +1726,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
final currentRate = snapshot.data ?? 1.0;
|
||||
|
||||
// Define available playback speeds
|
||||
final speeds = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0];
|
||||
final speeds = [0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0];
|
||||
|
||||
return SafeArea(
|
||||
child: SizedBox(
|
||||
@@ -1581,6 +1795,119 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
|
||||
);
|
||||
}
|
||||
|
||||
void _showVersionBottomSheet() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
backgroundColor: Colors.grey[900],
|
||||
isScrollControlled: true,
|
||||
constraints: _getBottomSheetConstraints(),
|
||||
builder: (context) {
|
||||
final versions = widget.availableVersions;
|
||||
final currentIndex = widget.selectedMediaIndex;
|
||||
|
||||
return SafeArea(
|
||||
child: SizedBox(
|
||||
height: MediaQuery.of(context).size.height * 0.75,
|
||||
child: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.video_file, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
const Text(
|
||||
'Video Version',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close, color: Colors.white),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(color: Colors.white24, height: 1),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
itemCount: versions.length,
|
||||
itemBuilder: (context, index) {
|
||||
final version = versions[index];
|
||||
final isSelected = index == currentIndex;
|
||||
|
||||
return ListTile(
|
||||
title: Text(
|
||||
version.displayLabel,
|
||||
style: TextStyle(
|
||||
color: isSelected ? Colors.blue : Colors.white,
|
||||
),
|
||||
),
|
||||
trailing: isSelected
|
||||
? const Icon(Icons.check, color: Colors.blue)
|
||||
: null,
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
_switchMediaVersion(index);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Switch to a different media version
|
||||
Future<void> _switchMediaVersion(int newMediaIndex) async {
|
||||
if (newMediaIndex == widget.selectedMediaIndex) {
|
||||
return; // Already using this version
|
||||
}
|
||||
|
||||
try {
|
||||
// Save current playback position
|
||||
final currentPosition = widget.player.state.position;
|
||||
|
||||
// Save the preference
|
||||
final settingsService = await SettingsService.getInstance();
|
||||
final seriesKey = widget.metadata.grandparentRatingKey ??
|
||||
widget.metadata.ratingKey;
|
||||
await settingsService.setMediaVersionPreference(seriesKey, newMediaIndex);
|
||||
|
||||
// Navigate to new player screen with the selected version
|
||||
// Use PageRouteBuilder with zero-duration transitions to prevent orientation reset
|
||||
if (mounted) {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
PageRouteBuilder<bool>(
|
||||
pageBuilder: (context, animation, secondaryAnimation) => VideoPlayerScreen(
|
||||
metadata: widget.metadata.copyWith(
|
||||
viewOffset: currentPosition.inMilliseconds,
|
||||
),
|
||||
selectedMediaIndex: newMediaIndex,
|
||||
),
|
||||
transitionDuration: Duration.zero,
|
||||
reverseTransitionDuration: Duration.zero,
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Error switching version: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String _formatDuration(Duration duration) {
|
||||
final hours = duration.inHours;
|
||||
final minutes = duration.inMinutes.remainder(60);
|
||||
|
||||
@@ -19,66 +19,84 @@ class ServerListTile extends StatelessWidget {
|
||||
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),
|
||||
),
|
||||
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: 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,
|
||||
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,
|
||||
),
|
||||
),
|
||||
)
|
||||
: (showTrailingIcon ? const Icon(Icons.chevron_right) : null),
|
||||
onTap: isCurrentServer ? null : onTap,
|
||||
enabled: !isCurrentServer,
|
||||
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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/plex_sort.dart';
|
||||
|
||||
class SortBottomSheet extends StatefulWidget {
|
||||
final List<PlexSort> sortOptions;
|
||||
final PlexSort? selectedSort;
|
||||
final bool isSortDescending;
|
||||
final Function(PlexSort, bool) onSortChanged;
|
||||
final VoidCallback? onClear;
|
||||
|
||||
const SortBottomSheet({
|
||||
super.key,
|
||||
required this.sortOptions,
|
||||
required this.selectedSort,
|
||||
required this.isSortDescending,
|
||||
required this.onSortChanged,
|
||||
this.onClear,
|
||||
});
|
||||
|
||||
@override
|
||||
State<SortBottomSheet> createState() => _SortBottomSheetState();
|
||||
}
|
||||
|
||||
class _SortBottomSheetState extends State<SortBottomSheet> {
|
||||
late PlexSort? _currentSort;
|
||||
late bool _currentDescending;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_currentSort = widget.selectedSort;
|
||||
_currentDescending = widget.isSortDescending;
|
||||
}
|
||||
|
||||
void _handleSortChange(PlexSort sort, bool descending) {
|
||||
setState(() {
|
||||
_currentSort = sort;
|
||||
_currentDescending = descending;
|
||||
});
|
||||
widget.onSortChanged(sort, descending);
|
||||
}
|
||||
|
||||
void _handleClear() {
|
||||
setState(() {
|
||||
_currentSort = null;
|
||||
_currentDescending = false;
|
||||
});
|
||||
widget.onClear?.call();
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.6,
|
||||
minChildSize: 0.4,
|
||||
maxChildSize: 0.9,
|
||||
expand: false,
|
||||
builder: (context, scrollController) {
|
||||
return Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
border: Border(
|
||||
bottom: BorderSide(color: Theme.of(context).dividerColor),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Expanded(
|
||||
child: Text(
|
||||
'Sort By',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (widget.onClear != null)
|
||||
TextButton(
|
||||
onPressed: _handleClear,
|
||||
child: const Text('Clear'),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
controller: scrollController,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: widget.sortOptions.length,
|
||||
itemBuilder: (context, index) {
|
||||
final sort = widget.sortOptions[index];
|
||||
final isSelected = _currentSort?.key == sort.key;
|
||||
|
||||
return ListTile(
|
||||
title: Text(sort.title),
|
||||
trailing: isSelected
|
||||
? Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SegmentedButton<bool>(
|
||||
showSelectedIcon: false,
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
value: false,
|
||||
icon: Icon(Icons.arrow_upward, size: 16),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: true,
|
||||
icon: Icon(Icons.arrow_downward, size: 16),
|
||||
),
|
||||
],
|
||||
selected: {_currentDescending},
|
||||
onSelectionChanged: (Set<bool> newSelection) {
|
||||
_handleSortChange(sort, newSelection.first);
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
: null,
|
||||
leading: Radio<PlexSort>(
|
||||
value: sort,
|
||||
groupValue: _currentSort,
|
||||
onChanged: (PlexSort? value) {
|
||||
if (value != null) {
|
||||
_handleSortChange(
|
||||
value,
|
||||
value.defaultDirection == 'desc',
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
onTap: () {
|
||||
_handleSortChange(sort, sort.defaultDirection == 'desc');
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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}
|
||||
@@ -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}"
|
||||
+2
-1
@@ -1,7 +1,7 @@
|
||||
name: plezy
|
||||
description: "A beautiful Plex client for Flutter"
|
||||
publish_to: "none"
|
||||
version: 1.2.0+6
|
||||
version: 1.4.0+11
|
||||
|
||||
environment:
|
||||
sdk: ^3.8.1
|
||||
@@ -44,6 +44,7 @@ flutter:
|
||||
assets:
|
||||
- lib/data/iso_639_codes.json
|
||||
- assets/plezy.png
|
||||
- assets/droid-sans.ttf
|
||||
|
||||
flutter_launcher_icons:
|
||||
android: true
|
||||
|
||||
Executable
+396
@@ -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
|
||||
Executable
+421
@@ -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
|
||||
Executable
+135
@@ -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
|
||||
Executable
+184
@@ -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
|
||||
}
|
||||
Executable
+59
@@ -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"
|
||||
Reference in New Issue
Block a user