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 |
@@ -58,7 +58,7 @@ jobs:
|
||||
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()
|
||||
@@ -118,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: |
|
||||
@@ -176,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
|
||||
@@ -222,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
|
||||
@@ -285,7 +361,7 @@ jobs:
|
||||
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: |
|
||||
@@ -304,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
|
||||
|
||||
@@ -17,7 +17,7 @@ Plezy is a modern Plex media client that provides a seamless streaming experienc
|
||||
<a href='https://apps.apple.com/us/app/id6754315964'><img height='60' alt='Download on the App Store' src='./assets/app-store-badge.png'/></a>
|
||||
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
|
||||
|
||||
> Google Play version is in closed testing ([required by Google](https://support.google.com/googleplay/android-developer/answer/14151465#overview)). Join the [Google Group](https://groups.google.com/g/plezy-testers) to get access.
|
||||
> 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)
|
||||
|
||||
+223
-30
@@ -7,6 +7,7 @@ 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
|
||||
@@ -29,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',
|
||||
),
|
||||
);
|
||||
|
||||
@@ -77,6 +80,8 @@ class PlexClient {
|
||||
connectTimeout: timeout,
|
||||
receiveTimeout: timeout,
|
||||
validateStatus: (status) => status != null && status < 500,
|
||||
responseType: ResponseType.json,
|
||||
contentType: 'application/json; charset=utf-8',
|
||||
),
|
||||
);
|
||||
|
||||
@@ -335,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 [];
|
||||
}
|
||||
@@ -362,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 '';
|
||||
@@ -430,7 +485,10 @@ class PlexClient {
|
||||
|
||||
/// Get detailed media info including chapters and tracks
|
||||
/// [mediaIndex] specifies which Media item to use (defaults to 0 - first version)
|
||||
Future<PlexMediaInfo?> getMediaInfo(String ratingKey, {int mediaIndex = 0}) async {
|
||||
Future<PlexMediaInfo?> getMediaInfo(
|
||||
String ratingKey, {
|
||||
int mediaIndex = 0,
|
||||
}) async {
|
||||
final response = await _dio.get('/library/metadata/$ratingKey');
|
||||
final metadataJson = _getFirstMetadataJson(response);
|
||||
|
||||
@@ -534,7 +592,9 @@ class PlexClient {
|
||||
(metadataJson['Media'] as List).isNotEmpty) {
|
||||
final mediaList = metadataJson['Media'] as List;
|
||||
return mediaList
|
||||
.map((media) => PlexMediaVersion.fromJson(media as Map<String, dynamic>))
|
||||
.map(
|
||||
(media) => PlexMediaVersion.fromJson(media as Map<String, dynamic>),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@@ -681,32 +741,61 @@ class PlexClient {
|
||||
/// Get available sort options for a library section
|
||||
Future<List<PlexSort>> getLibrarySorts(String sectionId) async {
|
||||
try {
|
||||
// Fetch library content with minimal data to get Sort metadata
|
||||
final response = await _dio.get(
|
||||
'/library/sections/$sectionId/all',
|
||||
queryParameters: {'X-Plex-Container-Size': 0},
|
||||
);
|
||||
// Use the dedicated sorts endpoint
|
||||
final response = await _dio.get('/library/sections/$sectionId/sorts');
|
||||
|
||||
final container = _getMediaContainer(response);
|
||||
if (container != null && container['Sort'] != null) {
|
||||
return (container['Sort'] as List)
|
||||
.map((json) => PlexSort.fromJson(json as Map<String, dynamic>))
|
||||
.toList();
|
||||
// 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 [
|
||||
PlexSort(
|
||||
key: 'titleSort',
|
||||
title: 'Title',
|
||||
defaultDirection: 'asc',
|
||||
),
|
||||
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',
|
||||
@@ -719,16 +808,14 @@ class PlexClient {
|
||||
title: 'Rating',
|
||||
defaultDirection: 'desc',
|
||||
),
|
||||
];
|
||||
]);
|
||||
|
||||
return fallbackSorts;
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to get library sorts: $e');
|
||||
// Return fallback sort options on error
|
||||
appLogger.e('Failed to get fallback sorts: $e');
|
||||
// Return minimal fallback options
|
||||
return [
|
||||
PlexSort(
|
||||
key: 'titleSort',
|
||||
title: 'Title',
|
||||
defaultDirection: 'asc',
|
||||
),
|
||||
PlexSort(key: 'titleSort', title: 'Title', defaultDirection: 'asc'),
|
||||
PlexSort(
|
||||
key: 'addedAt',
|
||||
descKey: 'addedAt:desc',
|
||||
@@ -814,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) {
|
||||
|
||||
+87
-1
@@ -3,6 +3,7 @@ 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';
|
||||
@@ -10,11 +11,14 @@ 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';
|
||||
@@ -45,6 +49,11 @@ void main() async {
|
||||
// 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();
|
||||
|
||||
@@ -70,6 +79,7 @@ class MainApp extends StatelessWidget {
|
||||
ChangeNotifierProvider(create: (context) => ThemeProvider()),
|
||||
ChangeNotifierProvider(create: (context) => SettingsProvider()),
|
||||
ChangeNotifierProvider(create: (context) => HiddenLibrariesProvider()),
|
||||
ChangeNotifierProvider(create: (context) => PlaybackStateProvider()),
|
||||
],
|
||||
child: Consumer<ThemeProvider>(
|
||||
builder: (context, themeProvider, child) {
|
||||
@@ -126,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();
|
||||
|
||||
@@ -173,10 +255,14 @@ 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!);
|
||||
|
||||
// Check for updates BEFORE navigation to keep context valid
|
||||
_checkForUpdatesOnStartup();
|
||||
|
||||
// Navigate to main screen after update check is initiated
|
||||
if (mounted) {
|
||||
Navigator.pushReplacement(
|
||||
context,
|
||||
|
||||
@@ -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,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;
|
||||
}
|
||||
@@ -5,6 +5,7 @@ class SettingsProvider extends ChangeNotifier {
|
||||
late SettingsService _settingsService;
|
||||
LibraryDensity _libraryDensity = LibraryDensity.normal;
|
||||
bool _useSeasonPoster = false;
|
||||
bool _showHeroSection = true;
|
||||
|
||||
SettingsProvider() {
|
||||
_initializeSettings();
|
||||
@@ -14,11 +15,13 @@ class SettingsProvider extends ChangeNotifier {
|
||||
_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) {
|
||||
@@ -36,6 +39,14 @@ class SettingsProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setShowHeroSection(bool value) async {
|
||||
if (_showHeroSection != value) {
|
||||
_showHeroSection = value;
|
||||
await _settingsService.setShowHeroSection(value);
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
String get libraryDensityDisplayName {
|
||||
switch (_libraryDensity) {
|
||||
case LibraryDensity.compact:
|
||||
|
||||
@@ -4,6 +4,7 @@ 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_hub.dart';
|
||||
import '../providers/plex_client_provider.dart';
|
||||
import '../services/storage_service.dart';
|
||||
import '../services/plex_auth_service.dart';
|
||||
@@ -13,7 +14,9 @@ import '../widgets/user_avatar_widget.dart';
|
||||
import '../widgets/horizontal_scroll_with_arrows.dart';
|
||||
import 'profile_switch_screen.dart';
|
||||
import 'server_selection_screen.dart';
|
||||
import 'hub_detail_screen.dart';
|
||||
import '../providers/user_profile_provider.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../mixins/refreshable.dart';
|
||||
import '../mixins/item_updatable.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
@@ -40,6 +43,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
|
||||
List<PlexMetadata> _onDeck = [];
|
||||
List<PlexMetadata> _recentlyAdded = [];
|
||||
List<PlexHub> _hubs = [];
|
||||
bool _isLoading = true;
|
||||
String? _errorMessage;
|
||||
final PageController _heroController = PageController();
|
||||
@@ -74,8 +78,11 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
|
||||
_indicatorAnimationController.forward(from: 0.0);
|
||||
_autoScrollTimer = Timer.periodic(_heroAutoScrollDuration, (timer) {
|
||||
if (_onDeck.isEmpty || !_heroController.hasClients || _isAutoScrollPaused)
|
||||
if (_onDeck.isEmpty ||
|
||||
!_heroController.hasClients ||
|
||||
_isAutoScrollPaused) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate current index is within bounds before calculating next page
|
||||
if (_currentHeroIndex >= _onDeck.length) {
|
||||
@@ -170,12 +177,47 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
final onDeck = await client.getOnDeck();
|
||||
final recentlyAdded = await client.getRecentlyAdded(limit: 20);
|
||||
|
||||
// Load hubs from all libraries
|
||||
final libraries = await client.getLibraries();
|
||||
final allHubs = <PlexHub>[];
|
||||
|
||||
for (final library in libraries) {
|
||||
// Only fetch hubs for movie and show libraries
|
||||
if (library.type == 'movie' || library.type == 'show') {
|
||||
try {
|
||||
final libraryHubs = await client.getLibraryHubs(
|
||||
library.key,
|
||||
limit: 12,
|
||||
);
|
||||
// Filter out duplicate hubs that we already fetch separately
|
||||
final filteredHubs = libraryHubs.where((hub) {
|
||||
final hubId = hub.hubIdentifier?.toLowerCase() ?? '';
|
||||
final title = hub.title.toLowerCase();
|
||||
// Skip "Continue Watching", "On Deck", and "Recently Added" hubs
|
||||
return !hubId.contains('ondeck') &&
|
||||
!hubId.contains('continue') &&
|
||||
!hubId.contains('recentlyadded') &&
|
||||
!title.contains('continue watching') &&
|
||||
!title.contains('on deck') &&
|
||||
!title.contains('recently added');
|
||||
}).toList();
|
||||
allHubs.addAll(filteredHubs);
|
||||
} catch (e) {
|
||||
appLogger.w(
|
||||
'Failed to load hubs for library ${library.title}',
|
||||
error: e,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
appLogger.d(
|
||||
'Received ${onDeck.length} on deck items and ${recentlyAdded.length} recently added items',
|
||||
'Received ${onDeck.length} on deck items, ${recentlyAdded.length} recently added items, and ${allHubs.length} hubs',
|
||||
);
|
||||
setState(() {
|
||||
_onDeck = onDeck;
|
||||
_recentlyAdded = recentlyAdded;
|
||||
_hubs = allHubs;
|
||||
_isLoading = false;
|
||||
|
||||
// Reset hero index to avoid sync issues
|
||||
@@ -204,6 +246,106 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
_loadContent();
|
||||
}
|
||||
|
||||
/// Get icon for hub based on its title
|
||||
IconData _getHubIcon(String title) {
|
||||
final lowerTitle = title.toLowerCase();
|
||||
|
||||
// Trending/Popular content
|
||||
if (lowerTitle.contains('trending')) {
|
||||
return Icons.trending_up;
|
||||
}
|
||||
if (lowerTitle.contains('popular') || lowerTitle.contains('imdb')) {
|
||||
return Icons.whatshot;
|
||||
}
|
||||
|
||||
// Seasonal/Time-based
|
||||
if (lowerTitle.contains('seasonal')) {
|
||||
return Icons.calendar_month;
|
||||
}
|
||||
if (lowerTitle.contains('newly') || lowerTitle.contains('new release')) {
|
||||
return Icons.new_releases;
|
||||
}
|
||||
if (lowerTitle.contains('recently released') ||
|
||||
lowerTitle.contains('recent')) {
|
||||
return Icons.schedule;
|
||||
}
|
||||
|
||||
// Top/Rated content
|
||||
if (lowerTitle.contains('top rated') ||
|
||||
lowerTitle.contains('highest rated')) {
|
||||
return Icons.star;
|
||||
}
|
||||
if (lowerTitle.contains('top ')) {
|
||||
return Icons.military_tech;
|
||||
}
|
||||
|
||||
// Genre-specific
|
||||
if (lowerTitle.contains('thriller')) {
|
||||
return Icons.warning_amber_rounded;
|
||||
}
|
||||
if (lowerTitle.contains('comedy') || lowerTitle.contains('comedier')) {
|
||||
return Icons.mood;
|
||||
}
|
||||
if (lowerTitle.contains('action')) {
|
||||
return Icons.flash_on;
|
||||
}
|
||||
if (lowerTitle.contains('drama')) {
|
||||
return Icons.theater_comedy;
|
||||
}
|
||||
if (lowerTitle.contains('fantasy')) {
|
||||
return Icons.auto_fix_high;
|
||||
}
|
||||
if (lowerTitle.contains('science') || lowerTitle.contains('sci-fi')) {
|
||||
return Icons.rocket_launch;
|
||||
}
|
||||
if (lowerTitle.contains('horror') || lowerTitle.contains('skräck')) {
|
||||
return Icons.nights_stay;
|
||||
}
|
||||
if (lowerTitle.contains('romance') || lowerTitle.contains('romantic')) {
|
||||
return Icons.favorite_border;
|
||||
}
|
||||
if (lowerTitle.contains('adventure') || lowerTitle.contains('äventyr')) {
|
||||
return Icons.explore;
|
||||
}
|
||||
|
||||
// Watchlist/Playlists
|
||||
if (lowerTitle.contains('playlist') || lowerTitle.contains('watchlist')) {
|
||||
return Icons.playlist_play;
|
||||
}
|
||||
if (lowerTitle.contains('unwatched') || lowerTitle.contains('unplayed')) {
|
||||
return Icons.visibility_off;
|
||||
}
|
||||
if (lowerTitle.contains('watched') || lowerTitle.contains('played')) {
|
||||
return Icons.visibility;
|
||||
}
|
||||
|
||||
// Network/Studio
|
||||
if (lowerTitle.contains('network') || lowerTitle.contains('more from')) {
|
||||
return Icons.tv;
|
||||
}
|
||||
|
||||
// Actor/Director
|
||||
if (lowerTitle.contains('actor') || lowerTitle.contains('director')) {
|
||||
return Icons.person;
|
||||
}
|
||||
|
||||
// Year-based (80s, 90s, etc.)
|
||||
if (lowerTitle.contains('80') ||
|
||||
lowerTitle.contains('90') ||
|
||||
lowerTitle.contains('00')) {
|
||||
return Icons.history;
|
||||
}
|
||||
|
||||
// Rediscover/Start Watching
|
||||
if (lowerTitle.contains('rediscover') ||
|
||||
lowerTitle.contains('start watching')) {
|
||||
return Icons.play_arrow;
|
||||
}
|
||||
|
||||
// Default icon for other hubs
|
||||
return Icons.auto_awesome;
|
||||
}
|
||||
|
||||
@override
|
||||
void updateItemInLists(String ratingKey, PlexMetadata updatedMetadata) {
|
||||
// Check and update in _onDeck list
|
||||
@@ -418,7 +560,14 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
),
|
||||
if (!_isLoading && _errorMessage == null) ...[
|
||||
// Hero Section (Continue Watching)
|
||||
if (_onDeck.isNotEmpty) _buildHeroSection(),
|
||||
Consumer<SettingsProvider>(
|
||||
builder: (context, settingsProvider, child) {
|
||||
if (_onDeck.isNotEmpty && settingsProvider.showHeroSection) {
|
||||
return _buildHeroSection();
|
||||
}
|
||||
return const SliverToBoxAdapter(child: SizedBox.shrink());
|
||||
},
|
||||
),
|
||||
|
||||
// On Deck / Continue Watching
|
||||
if (_onDeck.isNotEmpty) ...[
|
||||
@@ -460,7 +609,46 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
_buildHorizontalList(_recentlyAdded, isLarge: false),
|
||||
],
|
||||
|
||||
if (_onDeck.isEmpty && _recentlyAdded.isEmpty)
|
||||
// Recommendation Hubs (Trending, Top in Genre, etc.)
|
||||
for (final hub in _hubs) ...[
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 24, 16, 8),
|
||||
child: InkWell(
|
||||
onTap: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => HubDetailScreen(hub: hub),
|
||||
),
|
||||
);
|
||||
},
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 4,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(_getHubIcon(hub.title)),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
hub.title,
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
const Icon(Icons.chevron_right, size: 20),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
_buildHorizontalList(hub.items, isLarge: false),
|
||||
],
|
||||
|
||||
if (_onDeck.isEmpty && _recentlyAdded.isEmpty && _hubs.isEmpty)
|
||||
const SliverFillRemaining(
|
||||
child: Center(
|
||||
child: Column(
|
||||
@@ -543,63 +731,70 @@ class _DiscoverScreenState extends State<DiscoverScreen>
|
||||
// Page indicators (limited to 5 dots)
|
||||
...() {
|
||||
final range = _getVisibleDotRange();
|
||||
return List.generate(
|
||||
range.end - range.start + 1,
|
||||
(i) {
|
||||
final index = range.start + i;
|
||||
final isActive = _currentHeroIndex == index;
|
||||
final dotSize = _getDotSize(index, range.start, range.end);
|
||||
return List.generate(range.end - range.start + 1, (i) {
|
||||
final index = range.start + i;
|
||||
final isActive = _currentHeroIndex == index;
|
||||
final dotSize = _getDotSize(
|
||||
index,
|
||||
range.start,
|
||||
range.end,
|
||||
);
|
||||
|
||||
if (isActive) {
|
||||
// Animated progress indicator for active page
|
||||
return AnimatedBuilder(
|
||||
animation: _indicatorAnimationController,
|
||||
builder: (context, child) {
|
||||
// Fill width animates based on dot size
|
||||
final maxWidth = dotSize * 3; // 24px for normal, 15px for small
|
||||
final fillWidth =
|
||||
dotSize +
|
||||
((maxWidth - dotSize) * _indicatorAnimationController.value);
|
||||
return AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeInOut,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||
width: maxWidth,
|
||||
height: dotSize,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(dotSize / 2),
|
||||
if (isActive) {
|
||||
// Animated progress indicator for active page
|
||||
return AnimatedBuilder(
|
||||
animation: _indicatorAnimationController,
|
||||
builder: (context, child) {
|
||||
// Fill width animates based on dot size
|
||||
final maxWidth =
|
||||
dotSize * 3; // 24px for normal, 15px for small
|
||||
final fillWidth =
|
||||
dotSize +
|
||||
((maxWidth - dotSize) *
|
||||
_indicatorAnimationController.value);
|
||||
return AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeInOut,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||
width: maxWidth,
|
||||
height: dotSize,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(
|
||||
dotSize / 2,
|
||||
),
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Container(
|
||||
width: fillWidth,
|
||||
height: dotSize,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(dotSize / 2),
|
||||
),
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Container(
|
||||
width: fillWidth,
|
||||
height: dotSize,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(
|
||||
dotSize / 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
} else {
|
||||
// Static indicator for inactive pages
|
||||
return AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeInOut,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||
width: dotSize,
|
||||
height: dotSize,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(dotSize / 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
} else {
|
||||
// Static indicator for inactive pages
|
||||
return AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeInOut,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 4),
|
||||
width: dotSize,
|
||||
height: dotSize,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withValues(alpha: 0.4),
|
||||
borderRadius: BorderRadius.circular(dotSize / 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}(),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import '../client/plex_client.dart';
|
||||
import '../models/plex_library.dart';
|
||||
import '../models/plex_metadata.dart';
|
||||
@@ -9,6 +10,7 @@ import '../providers/plex_client_provider.dart';
|
||||
import '../providers/settings_provider.dart';
|
||||
import '../providers/hidden_libraries_provider.dart';
|
||||
import '../utils/provider_extensions.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../widgets/media_card.dart';
|
||||
import '../widgets/desktop_app_bar.dart';
|
||||
import '../widgets/app_bar_back_button.dart';
|
||||
@@ -50,6 +52,27 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
_loadLibraries();
|
||||
}
|
||||
|
||||
/// Helper method to get user-friendly error message from exception
|
||||
String _getErrorMessage(dynamic error, String context) {
|
||||
if (error is DioException) {
|
||||
// Other Dio errors
|
||||
switch (error.type) {
|
||||
case DioExceptionType.connectionTimeout:
|
||||
case DioExceptionType.receiveTimeout:
|
||||
return 'Connection timeout while loading $context';
|
||||
case DioExceptionType.connectionError:
|
||||
return 'Unable to connect to Plex server';
|
||||
default:
|
||||
appLogger.e('Error loading $context', error: error);
|
||||
return 'Failed to load $context: ${error.message}';
|
||||
}
|
||||
}
|
||||
|
||||
// Generic error
|
||||
appLogger.e('Unexpected error in $context', error: error);
|
||||
return 'Failed to load $context: $error';
|
||||
}
|
||||
|
||||
Future<void> _loadLibraries() async {
|
||||
// Extract context dependencies before async gap
|
||||
final clientProvider = Provider.of<PlexClientProvider>(
|
||||
@@ -75,12 +98,22 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
final storage = await StorageService.getInstance();
|
||||
final allLibraries = await client.getLibraries();
|
||||
|
||||
// Filter out music libraries (type: 'artist') since music playback is not yet supported
|
||||
// Only show movie and TV show libraries
|
||||
final filteredLibraries = allLibraries
|
||||
.where((lib) => lib.type.toLowerCase() != 'artist')
|
||||
.toList();
|
||||
|
||||
// Load saved library order and apply it
|
||||
final savedOrder = storage.getLibraryOrder();
|
||||
final orderedLibraries = _applyLibraryOrder(allLibraries, savedOrder);
|
||||
final orderedLibraries = _applyLibraryOrder(
|
||||
filteredLibraries,
|
||||
savedOrder,
|
||||
);
|
||||
|
||||
setState(() {
|
||||
_allLibraries = orderedLibraries; // Store all libraries with ordering applied
|
||||
_allLibraries =
|
||||
orderedLibraries; // Store all libraries with ordering applied
|
||||
_isLoadingLibraries = false;
|
||||
});
|
||||
|
||||
@@ -99,8 +132,9 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
String? libraryKeyToLoad;
|
||||
if (savedLibraryKey != null) {
|
||||
// Check if saved library exists and is visible
|
||||
final libraryExists = visibleLibraries
|
||||
.any((lib) => lib.key == savedLibraryKey);
|
||||
final libraryExists = visibleLibraries.any(
|
||||
(lib) => lib.key == savedLibraryKey,
|
||||
);
|
||||
if (libraryExists) {
|
||||
libraryKeyToLoad = savedLibraryKey;
|
||||
}
|
||||
@@ -122,7 +156,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
}
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_errorMessage = 'Failed to load libraries: $e';
|
||||
_errorMessage = _getErrorMessage(e, 'libraries');
|
||||
_isLoadingLibraries = false;
|
||||
});
|
||||
}
|
||||
@@ -189,12 +223,14 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
.where((lib) => !hiddenKeys.contains(lib.key))
|
||||
.toList();
|
||||
|
||||
|
||||
// Find the library by key
|
||||
final libraryIndex = visibleLibraries.indexWhere((lib) => lib.key == libraryKey);
|
||||
final libraryIndex = visibleLibraries.indexWhere(
|
||||
(lib) => lib.key == libraryKey,
|
||||
);
|
||||
if (libraryIndex == -1) return; // Library not found or hidden
|
||||
|
||||
final isChangingLibrary = !_isInitialLoad && _selectedLibraryKey != libraryKey;
|
||||
final isChangingLibrary =
|
||||
!_isInitialLoad && _selectedLibraryKey != libraryKey;
|
||||
|
||||
// Extract context dependencies before async operations
|
||||
final clientProvider = context.plexClient;
|
||||
@@ -234,7 +270,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
try {
|
||||
// Load filters and sort options for the new library
|
||||
_loadFilters(libraryKey);
|
||||
_loadSortOptions(libraryKey);
|
||||
await _loadSortOptions(libraryKey);
|
||||
|
||||
// Add sort parameter to filters if selected
|
||||
final filtersWithSort = Map<String, String>.from(_selectedFilters);
|
||||
@@ -255,7 +291,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_errorMessage = 'Failed to load library content: $e';
|
||||
_errorMessage = _getErrorMessage(e, 'library content');
|
||||
_isLoadingItems = false;
|
||||
});
|
||||
}
|
||||
@@ -277,6 +313,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
_filters = filters;
|
||||
});
|
||||
} catch (e) {
|
||||
appLogger.w('Failed to load filters', error: e);
|
||||
setState(() {
|
||||
_filters = [];
|
||||
});
|
||||
@@ -381,10 +418,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
// Save sort preference for this library
|
||||
final storage = await StorageService.getInstance();
|
||||
final sortKey = sort.getSortKey(descending: descending);
|
||||
await storage.saveLibrarySort(
|
||||
_selectedLibraryKey!,
|
||||
sortKey,
|
||||
);
|
||||
await storage.saveLibrarySort(_selectedLibraryKey!, sortKey);
|
||||
|
||||
// Reload content with new sort
|
||||
_applyFilters();
|
||||
@@ -411,7 +445,9 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
context,
|
||||
listen: false,
|
||||
);
|
||||
final isHidden = hiddenLibrariesProvider.hiddenLibraryKeys.contains(library.key);
|
||||
final isHidden = hiddenLibrariesProvider.hiddenLibraryKeys.contains(
|
||||
library.key,
|
||||
);
|
||||
|
||||
if (isHidden) {
|
||||
await hiddenLibrariesProvider.unhideLibrary(library.key);
|
||||
@@ -425,7 +461,10 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
if (isCurrentlySelected) {
|
||||
// Compute visible libraries after hiding
|
||||
final visibleLibraries = _allLibraries
|
||||
.where((lib) => !hiddenLibrariesProvider.hiddenLibraryKeys.contains(lib.key))
|
||||
.where(
|
||||
(lib) =>
|
||||
!hiddenLibrariesProvider.hiddenLibraryKeys.contains(lib.key),
|
||||
)
|
||||
.toList();
|
||||
|
||||
if (visibleLibraries.isNotEmpty) {
|
||||
@@ -435,7 +474,6 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void _showFiltersBottomSheet() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
@@ -475,6 +513,66 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
);
|
||||
}
|
||||
|
||||
List<ContextMenuItem> _getLibraryMenuItems(PlexLibrary library) {
|
||||
return [
|
||||
ContextMenuItem(
|
||||
value: 'scan',
|
||||
icon: Icons.refresh,
|
||||
label: 'Scan Library Files',
|
||||
requiresConfirmation: true,
|
||||
confirmationTitle: 'Scan Library',
|
||||
confirmationMessage:
|
||||
'This will scan "${library.title}" for new files. Continue?',
|
||||
),
|
||||
ContextMenuItem(
|
||||
value: 'analyze',
|
||||
icon: Icons.analytics_outlined,
|
||||
label: 'Analyze',
|
||||
requiresConfirmation: true,
|
||||
confirmationTitle: 'Analyze Library',
|
||||
confirmationMessage:
|
||||
'This will analyze "${library.title}" for intro markers and other metadata. This may take some time. Continue?',
|
||||
),
|
||||
ContextMenuItem(
|
||||
value: 'refresh',
|
||||
icon: Icons.sync,
|
||||
label: 'Refresh Metadata',
|
||||
requiresConfirmation: true,
|
||||
confirmationTitle: 'Refresh Metadata',
|
||||
confirmationMessage:
|
||||
'This will refresh metadata for all items in "${library.title}". This may take some time. Continue?',
|
||||
isDestructive: true,
|
||||
),
|
||||
ContextMenuItem(
|
||||
value: 'empty_trash',
|
||||
icon: Icons.delete_outline,
|
||||
label: 'Empty Trash',
|
||||
requiresConfirmation: true,
|
||||
confirmationTitle: 'Empty Trash',
|
||||
confirmationMessage:
|
||||
'This will permanently delete all trashed items in "${library.title}". This action cannot be undone. Continue?',
|
||||
isDestructive: true,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
void _handleLibraryMenuAction(String action, PlexLibrary library) {
|
||||
switch (action) {
|
||||
case 'scan':
|
||||
_scanLibrary(library);
|
||||
break;
|
||||
case 'analyze':
|
||||
_analyzeLibrary(library);
|
||||
break;
|
||||
case 'refresh':
|
||||
_refreshLibraryMetadata(library);
|
||||
break;
|
||||
case 'empty_trash':
|
||||
_emptyLibraryTrash(library);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _showLibraryManagementSheet() {
|
||||
final hiddenLibrariesProvider = Provider.of<HiddenLibrariesProvider>(
|
||||
context,
|
||||
@@ -494,10 +592,179 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
_saveLibraryOrder();
|
||||
},
|
||||
onToggleVisibility: _toggleLibraryVisibility,
|
||||
getLibraryMenuItems: _getLibraryMenuItems,
|
||||
onLibraryMenuAction: _handleLibraryMenuAction,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _scanLibrary(PlexLibrary library) async {
|
||||
try {
|
||||
final clientProvider = context.plexClient;
|
||||
final client = clientProvider.client;
|
||||
if (client == null) {
|
||||
throw Exception('No client available');
|
||||
}
|
||||
|
||||
// Show progress indicator
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Scanning "${library.title}"...'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await client.scanLibrary(library.key);
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Library scan started for "${library.title}"'),
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to scan library', error: e);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Failed to scan library: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _refreshLibraryMetadata(PlexLibrary library) async {
|
||||
try {
|
||||
final clientProvider = context.plexClient;
|
||||
final client = clientProvider.client;
|
||||
if (client == null) {
|
||||
throw Exception('No client available');
|
||||
}
|
||||
|
||||
// Show progress indicator
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Refreshing metadata for "${library.title}"...'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await client.refreshLibraryMetadata(library.key);
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Metadata refresh started for "${library.title}"'),
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to refresh library metadata', error: e);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Failed to refresh metadata: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _emptyLibraryTrash(PlexLibrary library) async {
|
||||
try {
|
||||
final clientProvider = context.plexClient;
|
||||
final client = clientProvider.client;
|
||||
if (client == null) {
|
||||
throw Exception('No client available');
|
||||
}
|
||||
|
||||
// Show progress indicator
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Emptying trash for "${library.title}"...'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await client.emptyLibraryTrash(library.key);
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Trash emptied for "${library.title}"'),
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to empty library trash', error: e);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Failed to empty trash: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _analyzeLibrary(PlexLibrary library) async {
|
||||
try {
|
||||
final clientProvider = context.plexClient;
|
||||
final client = clientProvider.client;
|
||||
if (client == null) {
|
||||
throw Exception('No client available');
|
||||
}
|
||||
|
||||
// Show progress indicator
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Analyzing "${library.title}"...'),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await client.analyzeLibrary(library.key);
|
||||
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Analysis started for "${library.title}"'),
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
appLogger.e('Failed to analyze library', error: e);
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Failed to analyze library: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
duration: const Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -524,7 +791,10 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
actions: [
|
||||
if (_allLibraries.isNotEmpty)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.edit, semanticLabel: 'Manage Libraries'),
|
||||
icon: const Icon(
|
||||
Icons.edit,
|
||||
semanticLabel: 'Manage Libraries',
|
||||
),
|
||||
onPressed: _showLibraryManagementSheet,
|
||||
),
|
||||
if (_sortOptions.isNotEmpty)
|
||||
@@ -597,54 +867,59 @@ class _LibrariesScreenState extends State<LibrariesScreen>
|
||||
// Library selector chips
|
||||
SliverToBoxAdapter(
|
||||
child: Container(
|
||||
height: 48,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 8,
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: List.generate(visibleLibraries.length, (index) {
|
||||
final library = visibleLibraries[index];
|
||||
final isSelected = library.key == _selectedLibraryKey;
|
||||
final t = tokens(context);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: ChoiceChip(
|
||||
label: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
_getLibraryIcon(library.type),
|
||||
size: 16,
|
||||
color: isSelected ? t.bg : t.text,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Text(library.title),
|
||||
],
|
||||
),
|
||||
selected: isSelected,
|
||||
onSelected: (selected) {
|
||||
if (selected) {
|
||||
_loadLibraryContent(library.key);
|
||||
}
|
||||
},
|
||||
backgroundColor: t.surface,
|
||||
selectedColor: t.text,
|
||||
side: BorderSide(color: t.outline),
|
||||
labelStyle: TextStyle(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: List.generate(visibleLibraries.length, (index) {
|
||||
final library = visibleLibraries[index];
|
||||
final isSelected = library.key == _selectedLibraryKey;
|
||||
final t = tokens(context);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: ContextMenuWrapper(
|
||||
menuItems: _getLibraryMenuItems(library),
|
||||
onMenuItemSelected: (value) =>
|
||||
_handleLibraryMenuAction(value, library),
|
||||
onTap: () => _loadLibraryContent(library.key),
|
||||
child: ChoiceChip(
|
||||
label: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
_getLibraryIcon(library.type),
|
||||
size: 16,
|
||||
color: isSelected ? t.bg : t.text,
|
||||
fontWeight: isSelected
|
||||
? FontWeight.w600
|
||||
: FontWeight.w400,
|
||||
),
|
||||
showCheckmark: false,
|
||||
),
|
||||
);
|
||||
}),
|
||||
const SizedBox(width: 6),
|
||||
Text(library.title),
|
||||
],
|
||||
),
|
||||
selected: isSelected,
|
||||
onSelected: (selected) {
|
||||
if (selected) {
|
||||
_loadLibraryContent(library.key);
|
||||
}
|
||||
},
|
||||
backgroundColor: t.surface,
|
||||
selectedColor: t.text,
|
||||
side: BorderSide(color: t.outline),
|
||||
labelStyle: TextStyle(
|
||||
color: isSelected ? t.bg : t.text,
|
||||
fontWeight: isSelected
|
||||
? FontWeight.w600
|
||||
: FontWeight.w400,
|
||||
),
|
||||
showCheckmark: false,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1234,16 +1509,21 @@ class _LibraryManagementSheet extends StatefulWidget {
|
||||
final Set<String> hiddenLibraryKeys;
|
||||
final Function(List<PlexLibrary>) onReorder;
|
||||
final Function(PlexLibrary) onToggleVisibility;
|
||||
final List<ContextMenuItem> Function(PlexLibrary) getLibraryMenuItems;
|
||||
final void Function(String action, PlexLibrary library) onLibraryMenuAction;
|
||||
|
||||
const _LibraryManagementSheet({
|
||||
required this.allLibraries,
|
||||
required this.hiddenLibraryKeys,
|
||||
required this.onReorder,
|
||||
required this.onToggleVisibility,
|
||||
required this.getLibraryMenuItems,
|
||||
required this.onLibraryMenuAction,
|
||||
});
|
||||
|
||||
@override
|
||||
State<_LibraryManagementSheet> createState() => _LibraryManagementSheetState();
|
||||
State<_LibraryManagementSheet> createState() =>
|
||||
_LibraryManagementSheetState();
|
||||
}
|
||||
|
||||
class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
@@ -1267,6 +1547,77 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
widget.onReorder(_tempLibraries);
|
||||
}
|
||||
|
||||
Future<void> _showLibraryMenuBottomSheet(
|
||||
BuildContext context,
|
||||
PlexLibrary library,
|
||||
) async {
|
||||
final menuItems = widget.getLibraryMenuItems(library);
|
||||
final selected = await showModalBottomSheet<String>(
|
||||
context: context,
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(
|
||||
library.title,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
...menuItems.map(
|
||||
(item) => ListTile(
|
||||
leading: Icon(item.icon),
|
||||
title: Text(item.label),
|
||||
onTap: () => Navigator.pop(context, item.value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (selected != null && mounted) {
|
||||
// Find the selected item to check if confirmation is needed
|
||||
final selectedItem = menuItems.firstWhere(
|
||||
(item) => item.value == selected,
|
||||
);
|
||||
|
||||
if (selectedItem.requiresConfirmation) {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(selectedItem.confirmationTitle ?? 'Confirm Action'),
|
||||
content: Text(
|
||||
selectedItem.confirmationMessage ??
|
||||
'Are you sure you want to perform this action?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: selectedItem.isDestructive
|
||||
? TextButton.styleFrom(foregroundColor: Colors.red)
|
||||
: null,
|
||||
child: const Text('Confirm'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed != true) return;
|
||||
}
|
||||
|
||||
widget.onLibraryMenuAction(selected, library);
|
||||
}
|
||||
}
|
||||
|
||||
IconData _getLibraryIcon(String type) {
|
||||
switch (type.toLowerCase()) {
|
||||
case 'movie':
|
||||
@@ -1337,31 +1688,49 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
|
||||
final library = _tempLibraries[index];
|
||||
final isHidden = hiddenLibraryKeys.contains(library.key);
|
||||
|
||||
return ReorderableDragStartListener(
|
||||
return Opacity(
|
||||
key: ValueKey(library.key),
|
||||
index: index,
|
||||
child: Opacity(
|
||||
opacity: isHidden ? 0.5 : 1.0,
|
||||
child: ListTile(
|
||||
leading: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.drag_indicator,
|
||||
color: Theme.of(context).textTheme.bodyMedium?.color?.withOpacity(0.5),
|
||||
opacity: isHidden ? 0.5 : 1.0,
|
||||
child: ListTile(
|
||||
leading: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ReorderableDragStartListener(
|
||||
index: index,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: 12),
|
||||
child: Icon(
|
||||
Icons.drag_indicator,
|
||||
color: Theme.of(
|
||||
context,
|
||||
).textTheme.bodyMedium?.color?.withOpacity(0.5),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Icon(_getLibraryIcon(library.type)),
|
||||
],
|
||||
),
|
||||
title: Text(library.title),
|
||||
trailing: IconButton(
|
||||
icon: Icon(
|
||||
isHidden ? Icons.visibility_off : Icons.visibility,
|
||||
),
|
||||
onPressed: () => widget.onToggleVisibility(library),
|
||||
tooltip: isHidden ? 'Show library' : 'Hide library',
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Icon(_getLibraryIcon(library.type)),
|
||||
],
|
||||
),
|
||||
title: Text(library.title),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: Icon(
|
||||
isHidden
|
||||
? Icons.visibility_off
|
||||
: Icons.visibility,
|
||||
),
|
||||
onPressed: () => widget.onToggleVisibility(library),
|
||||
tooltip: isHidden ? 'Show library' : 'Hide library',
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.more_vert),
|
||||
onPressed: () =>
|
||||
_showLibraryMenuBottomSheet(context, library),
|
||||
tooltip: 'Library options',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -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,13 +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});
|
||||
@@ -27,6 +30,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
int _seekTimeSmall = 10;
|
||||
int _seekTimeLarge = 30;
|
||||
|
||||
// Update checking state
|
||||
bool _isCheckingForUpdate = false;
|
||||
Map<String, dynamic>? _updateInfo;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -47,7 +54,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_isLoading) {
|
||||
@@ -70,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),
|
||||
]),
|
||||
@@ -131,6 +141,21 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
);
|
||||
},
|
||||
),
|
||||
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);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -240,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'),
|
||||
@@ -259,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(
|
||||
@@ -585,6 +671,90 @@ 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(
|
||||
|
||||
@@ -3,9 +3,11 @@ 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';
|
||||
@@ -48,6 +50,8 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
PlexClientProvider? _cachedClientProvider;
|
||||
bool _isPhone = false;
|
||||
List<PlexMediaVersion> _availableVersions = [];
|
||||
StreamSubscription<PlayerLog>? _logSubscription;
|
||||
StreamSubscription<String>? _errorSubscription;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -101,7 +105,9 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
final settingsService = await SettingsService.getInstance();
|
||||
final bufferSizeMB = settingsService.getBufferSize();
|
||||
final bufferSizeBytes = bufferSizeMB * 1024 * 1024;
|
||||
final enableHardwareDecoding = settingsService.getEnableHardwareDecoding();
|
||||
final enableHardwareDecoding = settingsService
|
||||
.getEnableHardwareDecoding();
|
||||
final debugLoggingEnabled = settingsService.getEnableDebugLogging();
|
||||
|
||||
// Create player with configuration
|
||||
player = Player(
|
||||
@@ -110,6 +116,7 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
libassAndroidFont: 'assets/droid-sans.ttf',
|
||||
libassAndroidFontName: 'Droid Sans Fallback',
|
||||
bufferSize: bufferSizeBytes,
|
||||
logLevel: debugLoggingEnabled ? MPVLogLevel.debug : MPVLogLevel.error,
|
||||
),
|
||||
);
|
||||
controller = VideoController(
|
||||
@@ -148,6 +155,12 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
// 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();
|
||||
|
||||
@@ -173,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(() {
|
||||
@@ -265,6 +292,10 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
// Stop progress tracking
|
||||
_progressTimer?.cancel();
|
||||
|
||||
// Cancel stream subscriptions
|
||||
_logSubscription?.cancel();
|
||||
_errorSubscription?.cancel();
|
||||
|
||||
// Send final stopped state
|
||||
_sendProgress('stopped');
|
||||
|
||||
@@ -375,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) {
|
||||
@@ -385,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;
|
||||
}
|
||||
@@ -434,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) {
|
||||
@@ -446,63 +491,203 @@ 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 {
|
||||
@@ -622,9 +807,15 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
|
||||
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,
|
||||
profileSettings,
|
||||
selectedAudioTrack: currentAudioTrack,
|
||||
);
|
||||
} else if (subtitleToSelect == null && realSubtitleTracks.isNotEmpty) {
|
||||
appLogger.d('Priority 2: No user profile available');
|
||||
@@ -730,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;
|
||||
|
||||
@@ -842,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(
|
||||
|
||||
@@ -2,6 +2,7 @@ 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 }
|
||||
|
||||
@@ -21,6 +22,7 @@ class SettingsService {
|
||||
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;
|
||||
@@ -55,6 +57,8 @@ class SettingsService {
|
||||
// Debug Logging
|
||||
Future<void> setEnableDebugLogging(bool enabled) async {
|
||||
await _prefs.setBool(_keyEnableDebugLogging, enabled);
|
||||
// Update logger level immediately when setting changes
|
||||
setLoggerLevel(enabled);
|
||||
}
|
||||
|
||||
bool getEnableDebugLogging() {
|
||||
@@ -117,7 +121,18 @@ class SettingsService {
|
||||
}
|
||||
|
||||
bool getUseSeasonPoster() {
|
||||
return _prefs.getBool(_keyUseSeasonPoster) ?? false; // Default: false (use series poster)
|
||||
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)
|
||||
@@ -593,7 +608,10 @@ class SettingsService {
|
||||
/// 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 {
|
||||
Future<void> setMediaVersionPreference(
|
||||
String seriesRatingKey,
|
||||
int mediaIndex,
|
||||
) async {
|
||||
final preferences = _getMediaVersionPreferences();
|
||||
preferences[seriesRatingKey] = mediaIndex;
|
||||
|
||||
@@ -643,6 +661,7 @@ class SettingsService {
|
||||
_prefs.remove(_keyPreferredAudioCodec),
|
||||
_prefs.remove(_keyLibraryDensity),
|
||||
_prefs.remove(_keyUseSeasonPoster),
|
||||
_prefs.remove(_keyShowHeroSection),
|
||||
_prefs.remove(_keySeekTimeSmall),
|
||||
_prefs.remove(_keySeekTimeLarge),
|
||||
_prefs.remove(_keyMediaVersionPreferences),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+224
-1
@@ -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,4 +210,28 @@ import 'package:logger/logger.dart';
|
||||
/// appLogger.w('Warning message');
|
||||
/// appLogger.e('Error message', error: e, stackTrace: stackTrace);
|
||||
/// ```
|
||||
final appLogger = Logger(printer: SimplePrinter(), level: Level.debug);
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -6,11 +6,19 @@ 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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -23,6 +31,7 @@ class ContextMenuWrapper extends StatefulWidget {
|
||||
final Function(String)? onMenuItemSelected;
|
||||
final VoidCallback? onTap;
|
||||
final String? title;
|
||||
final bool forceBottomSheet;
|
||||
|
||||
const ContextMenuWrapper({
|
||||
super.key,
|
||||
@@ -31,6 +40,7 @@ class ContextMenuWrapper extends StatefulWidget {
|
||||
this.onMenuItemSelected,
|
||||
this.onTap,
|
||||
this.title,
|
||||
this.forceBottomSheet = false,
|
||||
});
|
||||
|
||||
@override
|
||||
@@ -44,8 +54,37 @@ class _ContextMenuWrapperState extends State<ContextMenuWrapper> {
|
||||
_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 = PlatformDetector.isMobile(context);
|
||||
final useBottomSheet =
|
||||
widget.forceBottomSheet || PlatformDetector.isMobile(context);
|
||||
String? selected;
|
||||
|
||||
if (useBottomSheet) {
|
||||
@@ -119,6 +158,23 @@ class _ContextMenuWrapperState extends State<ContextMenuWrapper> {
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,19 @@ class _MediaCardState extends State<MediaCard> {
|
||||
|
||||
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 navigateToVideoPlayer(
|
||||
|
||||
@@ -1,10 +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 {
|
||||
@@ -100,6 +103,17 @@ 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(
|
||||
@@ -235,6 +249,10 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
case 'fileinfo':
|
||||
await _showFileInfo(context);
|
||||
break;
|
||||
|
||||
case 'shuffle_play':
|
||||
await _handleShufflePlay(context);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,9 +321,8 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (context) => const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
builder: (context) =>
|
||||
const Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -339,9 +356,79 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
|
||||
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 loading file info: $e')),
|
||||
SnackBar(content: Text('Error starting shuffle play: $e')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
name: plezy
|
||||
description: "A beautiful Plex client for Flutter"
|
||||
publish_to: "none"
|
||||
version: 1.3.0+9
|
||||
version: 1.4.0+11
|
||||
|
||||
environment:
|
||||
sdk: ^3.8.1
|
||||
|
||||
Reference in New Issue
Block a user