Compare commits

..
33 Commits
Author SHA1 Message Date
edde746 36c6adb50c chore: bump version 2025-11-05 08:26:28 +01:00
edde746 4180ab6248 feat: log viewer 2025-11-05 08:25:28 +01:00
edde746 597640ece5 ci: remove appimage 2025-11-05 08:10:41 +01:00
edde746 4031b6043c ci: appimage fixes 2025-11-05 08:05:07 +01:00
edde746 57676178e2 ci(linux): fix missing icon 2025-11-05 07:47:26 +01:00
edde746 4430581806 ci: optimize appimage build 2025-11-05 07:42:13 +01:00
edde746 7236702818 ci: replace flatpak with appimage 2025-11-05 07:36:55 +01:00
edde746 0774263d83 feat: hero section toggle 2025-11-05 07:35:04 +01:00
edde746 6243195b21 feat: shuffle play 2025-11-05 07:28:23 +01:00
edde746 8d8423d136 refactor: move library actions to context menu 2025-11-05 07:09:58 +01:00
Sam Matthews 2f7c1084cb Add library management features: scan, refresh metadata, empty trash, and analyze #38 2025-11-04 20:10:59 +00:00
edde746 03495b1ea3 refactor: deduplicate sort widget 2025-11-04 20:49:25 +01:00
edde746andGitHub a48032c706 Merge pull request #36 from TheLidlMan/plex-recommendation-on-discover-screen-28
Plex recommendation on Home screen
2025-11-04 20:39:12 +01:00
edde746 357a4a5590 ci(flatpak): correct container 2025-11-04 20:09:05 +01:00
Sam Matthews 81adf86769 formatting issues 2025-11-04 19:00:44 +00:00
Sam Matthews 50264d52f3 Merge branch 'main' into plex-recommendation-on-discover-screen-28 2025-11-04 18:59:31 +00:00
Sam Matthews 2603a3992c - Add PlexHub model to represent recommendation sections (trending, top in genre, etc.)
- Add getLibraryHubs() and getPlaylist() API methods to PlexClient
- Display library hubs below Recently Added on Discover screen
- Filter out duplicate hubs (Continue Watching, Recently Added) that are already shown
- Add dynamic context-aware icons based on hub titles (trending, genres, ratings, etc.)
- Support 20+ hub types with matching icons: trending, popular, seasonal, genres, top rated, playlists, and more
- Support for custom collections from Kometa/Pulsarr

Implements feature request #28
2025-11-04 18:57:46 +00:00
edde746 3f95b4d822 ci(flatpak): hardcode flutter version
ts garbage
2025-11-04 19:56:14 +01:00
edde746 3b8c944512 ci(flatpak): fix 2025-11-04 19:41:21 +01:00
edde746 d646adca89 docs: update google group 2025-11-04 19:21:56 +01:00
edde746 3e7a9231b7 ci(flatpak): fix 2025-11-04 19:18:26 +01:00
edde746 dd76e59bf1 fix: properly get sorts 2025-11-04 19:09:54 +01:00
Sam Matthews bc54a2230b feat: Add support for Plex recommendation hubs on Discover screen
- Add PlexHub model to represent recommendation sections (trending, top in genre, etc.)
- Add getLibraryHubs() and getPlaylist() API methods to PlexClient
- Display library hubs below Recently Added on Discover screen
- Filter out duplicate hubs (Continue Watching, Recently Added) that are already shown
- Add dynamic context-aware icons based on hub titles (trending, genres, ratings, etc.)
- Support 20+ hub types with matching icons: trending, popular, seasonal, genres, top rated, playlists, and more
- Support for custom collections from Kometa/Pulsarr

Implements feature request #28
2025-11-04 18:04:43 +00:00
Sam Matthews 4b972b0992 feat: Add 'Latest Episode Air Date' sort option for TV show libraries
- Add conditional sort option for TV show libraries that sorts by the most recent episode's original air date
- Uses 'episode.originallyAvailableAt' field to track when the latest episode aired
- Only appears for TV show libraries, not movies or other media types
- Defaults to descending order to show recently aired episodes first
- Perfect for tracking seasonal anime/shows with new episodes

Fixes #31
2025-11-04 17:15:21 +00:00
Sam Matthews 1cab790570 fix 2025-11-04 17:09:32 +00:00
edde746 feb9254aea ci(flatpak): fix
but actually this time
2025-11-04 17:38:44 +01:00
edde746andGitHub 9a2e5e5358 Merge pull request #32 from TheLidlMan/issue-20-hide-music-libraries
Hide music libraries from app (Issue #20)
2025-11-04 17:17:00 +01:00
edde746 e260f801d6 ci(flatpak): fix 2025-11-04 17:16:13 +01:00
Sam Matthews 2ac3555567 Merge main into issue-20: Combine music filtering with library ordering 2025-11-04 16:04:31 +00:00
edde746 dafdea282e fix: library management sheet scrolling 2025-11-04 16:55:52 +01:00
edde746 aa1efdff64 ci: flatpak build 2025-11-04 16:51:14 +01:00
edde746 3d5c7f7e3b feat: update checks 2025-11-04 16:50:46 +01:00
Sam Matthews 1ec9fbcc02 Hide music libraries from app (Issue #20)
- Filter out artist-type libraries in libraries_screen.dart
- Add safety check in media_card.dart to prevent music playback attempts
- Filter music content from getOnDeck() and getRecentlyAdded() in plex_client.dart

Music libraries are now hidden throughout the app since music playback
is not yet supported. This focuses the app on video content (movies and TV shows).
2025-11-04 15:49:00 +00:00
21 changed files with 2836 additions and 205 deletions
+13 -6
View File
@@ -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,7 +176,7 @@ 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:
@@ -298,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
@@ -361,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: |
@@ -380,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
+1 -1
View File
@@ -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)
+219 -30
View File
@@ -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
@@ -339,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 [];
}
@@ -366,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 '';
@@ -434,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);
@@ -538,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();
}
@@ -685,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',
@@ -723,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',
@@ -818,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');
}
}
+87 -1
View File
@@ -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,
+57
View File
@@ -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;
}
+11
View File
@@ -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:
+251 -56
View File
@@ -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),
),
);
}
});
}(),
],
),
+362
View File
@@ -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;
}
}
}
+424 -77
View File
@@ -14,6 +14,7 @@ import '../utils/app_logger.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
import '../widgets/context_menu_wrapper.dart';
import '../services/storage_service.dart';
import '../services/settings_service.dart';
import '../mixins/refreshable.dart';
@@ -97,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;
});
@@ -121,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;
}
@@ -211,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;
@@ -404,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();
@@ -434,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);
@@ -448,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) {
@@ -458,7 +474,6 @@ class _LibrariesScreenState extends State<LibrariesScreen>
}
}
void _showFiltersBottomSheet() {
showModalBottomSheet(
context: context,
@@ -498,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,
@@ -517,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) {
@@ -547,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)
@@ -625,48 +872,54 @@ class _LibrariesScreenState extends State<LibrariesScreen>
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,
),
),
),
);
}),
),
),
),
),
@@ -1256,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> {
@@ -1289,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':
@@ -1359,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',
),
],
),
),
);
+318
View File
@@ -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',
),
),
),
],
],
],
),
),
),
);
}
}
+171 -1
View File
@@ -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(
+122 -24
View File
@@ -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');
@@ -387,7 +418,8 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Build list of preferred languages
final preferredLanguages = <String>[];
if (profile.defaultAudioLanguage != null && profile.defaultAudioLanguage!.isNotEmpty) {
if (profile.defaultAudioLanguage != null &&
profile.defaultAudioLanguage!.isNotEmpty) {
preferredLanguages.add(profile.defaultAudioLanguage!);
}
if (profile.defaultAudioLanguages != null) {
@@ -469,15 +501,20 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Mode 1: Shown with foreign audio
if (profile.autoSelectSubtitle == 1) {
appLogger.d('Profile specifies foreign audio mode (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) {
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');
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)) {
@@ -494,7 +531,8 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Build list of preferred languages
final preferredLanguages = <String>[];
if (profile.defaultSubtitleLanguage != null && profile.defaultSubtitleLanguage!.isNotEmpty) {
if (profile.defaultSubtitleLanguage != null &&
profile.defaultSubtitleLanguage!.isNotEmpty) {
preferredLanguages.add(profile.defaultSubtitleLanguage!);
}
if (profile.defaultSubtitleLanguages != null) {
@@ -502,7 +540,9 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
if (preferredLanguages.isEmpty) {
appLogger.d('Cannot use profile: No defaultSubtitleLanguage(s) specified');
appLogger.d(
'Cannot use profile: No defaultSubtitleLanguage(s) specified',
);
return null;
}
@@ -512,10 +552,16 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
var candidateTracks = availableTracks;
// Filter by SDH (defaultSubtitleAccessibility: 0-3)
candidateTracks = _filterSubtitlesBySDH(candidateTracks, profile.defaultSubtitleAccessibility);
candidateTracks = _filterSubtitlesBySDH(
candidateTracks,
profile.defaultSubtitleAccessibility,
);
// Filter by forced subtitle preference (defaultSubtitleForced: 0-3)
candidateTracks = _filterSubtitlesByForced(candidateTracks, profile.defaultSubtitleForced);
candidateTracks = _filterSubtitlesByForced(
candidateTracks,
profile.defaultSubtitleForced,
);
// If no candidates after filtering, relax filters
if (candidateTracks.isEmpty) {
@@ -563,7 +609,9 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
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)');
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');
@@ -596,9 +644,13 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
if (preference == 0 || preference == 1) {
// Prefer but don't require
final preferForced = preference == 1;
final preferred = tracks.where((t) => _isForced(t) == preferForced).toList();
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)');
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');
@@ -625,9 +677,9 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
// Look for common SDH indicators
return title.contains('sdh') ||
title.contains('cc') ||
title.contains('hearing impaired') ||
title.contains('deaf');
title.contains('cc') ||
title.contains('hearing impaired') ||
title.contains('deaf');
}
/// Checks if a subtitle track is forced
@@ -869,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;
@@ -981,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(
+21 -2
View File
@@ -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),
+177
View File
@@ -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
View File
@@ -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;
}
+57 -1
View File
@@ -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);
}
}
+13
View File
@@ -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(
+91 -4
View File
@@ -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')),
);
}
}
+151
View File
@@ -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
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 1.3.1+10
version: 1.4.0+11
environment:
sdk: ^3.8.1