Compare commits

..
10 Commits
Author SHA1 Message Date
edde746 5c418395b1 chore: bump version
also update screenshots
2025-10-31 05:17:30 +01:00
edde746 90ec76b661 fix: clear all data on logout 2025-10-31 05:12:52 +01:00
edde746 5f1251d82b refactor: fix warnings 2025-10-31 04:27:32 +01:00
edde746 19ab6a21b9 feat: settings page 2025-10-31 03:55:01 +01:00
edde746 e0fc990b0e refactor: back button unification 2025-10-31 00:51:45 +01:00
edde746 36b897f963 feat: profiles 2025-10-30 19:50:50 +01:00
edde746 17dba97dbb fix: no redundant search queries 2025-10-30 13:08:31 +01:00
edde746 564746d6a7 refactor: mobile hero section improvements 2025-10-30 10:29:03 +01:00
edde746 a5063a662e refactor: remove dead code 2025-10-29 14:04:39 +01:00
edde746 8d086d282c chore: update screenshots 2025-10-29 11:01:20 +01:00
67 changed files with 4921 additions and 1151 deletions
+6
View File
@@ -43,3 +43,9 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release
# Code duplication reports
duplication-report/
# Test credentials (do not commit!)
.env.test
+21
View File
@@ -0,0 +1,21 @@
{
"threshold": 5,
"reporters": ["html", "console"],
"ignore": [
"**/*.g.dart",
"**/*.freezed.dart",
"**/*.mocks.dart",
"**/generated/**",
"**/*.config.dart"
],
"absolute": true,
"gitignore": true,
"format": ["dart"],
"minLines": 5,
"minTokens": 50,
"output": "./duplication-report",
"mode": "strict",
"formatsExts": {
"dart": ["dart"]
}
}
+2 -2
View File
@@ -6,10 +6,10 @@
Plezy is a modern Plex media client that provides a seamless streaming experience across desktop and mobile platforms. Built with Flutter, it offers native performance and a clean, intuitive interface for browsing and playing your Plex media library.
<p align="center">
<img src="screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
<img src="assets/screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
</p>
*See more screenshots in the [screenshots folder](screenshots/#readme)*
*See more screenshots in the [screenshots folder](assets/screenshots/#readme)*
## Download
@@ -1,8 +1,8 @@
## iOS
| Home | Library | Media Card |
|------|---------|------------|
| ![iOS Home - Content discovery and recommendations](ios-home.png) | ![iOS Library - Media collection view](ios-library.png) | ![iOS Media Card - Playback controls](ios-media-card.png) |
| Home | Library | Media Card | Season |
|------|---------|------------|--------|
| ![iOS Home - Content discovery and recommendations](ios-home.png) | ![iOS Library - Media collection view](ios-library.png) | ![iOS Media Card](ios-media-card.png) | ![iOS Season View](ios-season.png) |
## macOS
@@ -10,4 +10,6 @@
![macOS Library - Media collection view](macos-library.png)
![macOS Media Card - Playback controls](macos-media-card.png)
![macOS Media Card](macos-media-card.png)
![macOS Season View](macos-season.png)
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

-111
View File
@@ -1,111 +0,0 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
class PlexAuth {
static const String authUrl = 'https://plex.tv/api/v2';
static const String clientsUrl = 'https://clients.plex.tv/api/v2';
final String clientIdentifier;
final String product;
PlexAuth({
required this.clientIdentifier,
this.product = 'Plex Flutter Client',
});
Map<String, String> get _headers => {
'Accept': 'application/json',
'X-Plex-Client-Identifier': clientIdentifier,
'X-Plex-Product': product,
};
/// Generate a PIN for authentication
Future<Map<String, dynamic>> generatePin({bool strong = true}) async {
final response = await http.post(
Uri.parse('$authUrl/pins?strong=$strong'),
headers: _headers,
);
if (response.statusCode == 201) {
return json.decode(response.body);
} else {
throw Exception('Failed to generate PIN: ${response.body}');
}
}
/// Check PIN status
Future<Map<String, dynamic>> checkPin(int pinId) async {
final response = await http.get(
Uri.parse('$authUrl/pins/$pinId'),
headers: _headers,
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to check PIN: ${response.body}');
}
}
/// Get auth app URL for user to authenticate
String getAuthAppUrl(String code, {String? forwardUrl}) {
final params = {
'clientID': clientIdentifier,
'code': code,
'context[device][product]': product,
if (forwardUrl != null) 'forwardUrl': forwardUrl,
};
final queryString = params.entries
.map(
(e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}',
)
.join('&');
return 'https://app.plex.tv/auth#?$queryString';
}
/// Verify token validity
Future<bool> verifyToken(String token) async {
try {
final response = await http.get(
Uri.parse('$authUrl/user'),
headers: {..._headers, 'X-Plex-Token': token},
);
return response.statusCode == 200;
} catch (e) {
return false;
}
}
/// Get user info
Future<Map<String, dynamic>> getUserInfo(String token) async {
final response = await http.get(
Uri.parse('$authUrl/user'),
headers: {..._headers, 'X-Plex-Token': token},
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to get user info: ${response.body}');
}
}
/// Get available resources (servers)
Future<List<dynamic>> getResources(String token) async {
final response = await http.get(
Uri.parse(
'$clientsUrl/resources?includeHttps=1&includeRelay=1&includeIPv6=1',
),
headers: {..._headers, 'X-Plex-Token': token},
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception('Failed to get resources: ${response.body}');
}
}
}
+9 -15
View File
@@ -15,7 +15,7 @@ class ConnectionTestResult {
}
class PlexClient {
final PlexConfig config;
PlexConfig config;
late final Dio _dio;
PlexClient(this.config) {
@@ -41,6 +41,14 @@ class PlexClient {
);
}
/// Update the token used by this client
void updateToken(String newToken) {
// Update both the Dio headers and the config to ensure consistency
_dio.options.headers['X-Plex-Token'] = newToken;
config = config.copyWith(token: newToken);
appLogger.d('PlexClient token updated (headers and config)');
}
/// Test connection to server
Future<bool> testConnection() async {
try {
@@ -51,20 +59,6 @@ class PlexClient {
}
}
/// Test connection to a specific URL with token (legacy method)
static Future<bool> testConnectionUrl(
String baseUrl,
String token, {
Duration timeout = const Duration(seconds: 5),
}) async {
final result = await testConnectionWithLatency(
baseUrl,
token,
timeout: timeout,
);
return result.success;
}
/// Test connection to a specific URL with token and measure latency
static Future<ConnectionTestResult> testConnectionWithLatency(
String baseUrl,
+54 -11
View File
@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
import 'dart:io' show Platform;
import 'package:media_kit/media_kit.dart';
import 'package:window_manager/window_manager.dart';
import 'package:provider/provider.dart';
import 'screens/main_screen.dart';
import 'screens/auth_screen.dart';
import 'services/storage_service.dart';
@@ -10,9 +11,12 @@ 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 'providers/user_profile_provider.dart';
import 'providers/plex_client_provider.dart';
import 'providers/theme_provider.dart';
import 'utils/language_codes.dart';
import 'utils/app_logger.dart';
import 'theme/mono_theme.dart';
import 'utils/provider_extensions.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
@@ -55,13 +59,27 @@ class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Plezy',
debugShowCheckedModeBanner: false,
theme: monoTheme(dark: false),
darkTheme: monoTheme(dark: true),
navigatorObservers: [routeObserver],
home: const SetupScreen(),
return MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => PlexClientProvider()),
ChangeNotifierProvider(
create: (context) => UserProfileProvider()..initialize(),
),
ChangeNotifierProvider(create: (context) => ThemeProvider()),
],
child: Consumer<ThemeProvider>(
builder: (context, themeProvider, child) {
return MaterialApp(
title: 'Plezy',
debugShowCheckedModeBanner: false,
theme: themeProvider.lightTheme,
darkTheme: themeProvider.darkTheme,
themeMode: themeProvider.materialThemeMode,
navigatorObservers: [routeObserver],
home: const SetupScreen(),
);
},
),
);
}
}
@@ -88,14 +106,37 @@ class _SetupScreenState extends State<SetupScreen> {
final clientId = storage.getClientIdentifier();
final plexToken = storage.getPlexToken();
// Get current user's server token (prioritize over original server token)
final currentUserToken = storage.getToken();
if (serverData != null && clientId != null) {
try {
// Recreate PlexServer from stored data
final server = PlexServer.fromJson(serverData);
// Connect using the optimized service
// Use current user's token if available, fallback to server's original token
final tokenToUse = currentUserToken ?? server.accessToken;
appLogger.d(
'App startup token selection: currentUserToken=${currentUserToken != null ? 'present' : 'null'}, using=${currentUserToken != null ? 'current user' : 'original server'} token',
);
// Create updated server with correct token for current user
final serverWithCurrentToken = PlexServer(
name: server.name,
clientIdentifier: server.clientIdentifier,
accessToken: tokenToUse,
connections: server.connections,
owned: server.owned,
product: server.product,
platform: server.platform,
lastSeenAt: server.lastSeenAt,
presence: server.presence,
);
// Connect using the optimized service with current user's token
final result = await ServerConnectionService.connectToServer(
server,
serverWithCurrentToken,
clientIdentifier: clientId,
verifyServer: true,
fetchUserProfile: plexToken != null,
@@ -104,8 +145,10 @@ class _SetupScreenState extends State<SetupScreen> {
// Handle result
if (result.isSuccess) {
// Success! Navigate to main screen
// Success! Set client in provider and navigate to main screen
if (mounted) {
context.plexClient.setClient(result.client!);
Navigator.pushReplacement(
context,
MaterialPageRoute(
+70
View File
@@ -0,0 +1,70 @@
import 'plex_home_user.dart';
class PlexHome {
final int id;
final String name;
final int guestUserID;
final String guestUserUUID;
final bool guestEnabled;
final bool subscription;
final List<PlexHomeUser> users;
PlexHome({
required this.id,
required this.name,
required this.guestUserID,
required this.guestUserUUID,
required this.guestEnabled,
required this.subscription,
required this.users,
});
factory PlexHome.fromJson(Map<String, dynamic> json) {
final List<dynamic> usersJson = json['users'] as List<dynamic>;
final users = usersJson
.map(
(userJson) => PlexHomeUser.fromJson(userJson as Map<String, dynamic>),
)
.toList();
return PlexHome(
id: json['id'] as int,
name: json['name'] as String,
guestUserID: json['guestUserID'] as int,
guestUserUUID: json['guestUserUUID'] as String,
guestEnabled: json['guestEnabled'] as bool,
subscription: json['subscription'] as bool,
users: users,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'guestUserID': guestUserID,
'guestUserUUID': guestUserUUID,
'guestEnabled': guestEnabled,
'subscription': subscription,
'users': users.map((user) => user.toJson()).toList(),
};
}
PlexHomeUser? get adminUser => users.where((user) => user.admin).firstOrNull;
List<PlexHomeUser> get managedUsers =>
users.where((user) => !user.admin).toList();
List<PlexHomeUser> get restrictedUsers =>
users.where((user) => user.restricted).toList();
PlexHomeUser? getUserByUUID(String uuid) {
try {
return users.firstWhere((user) => user.uuid == uuid);
} catch (e) {
return null;
}
}
bool get hasMultipleUsers => users.length > 1;
}
+74
View File
@@ -0,0 +1,74 @@
class PlexHomeUser {
final int id;
final String uuid;
final String title;
final String? username;
final String? email;
final String? friendlyName;
final String thumb;
final bool hasPassword;
final bool restricted;
final int updatedAt;
final bool admin;
final bool guest;
final bool protected;
PlexHomeUser({
required this.id,
required this.uuid,
required this.title,
this.username,
this.email,
this.friendlyName,
required this.thumb,
required this.hasPassword,
required this.restricted,
required this.updatedAt,
required this.admin,
required this.guest,
required this.protected,
});
factory PlexHomeUser.fromJson(Map<String, dynamic> json) {
return PlexHomeUser(
id: json['id'] as int,
uuid: json['uuid'] as String,
title: json['title'] as String,
username: json['username'] as String?,
email: json['email'] as String?,
friendlyName: json['friendlyName'] as String?,
thumb: json['thumb'] as String,
hasPassword: json['hasPassword'] as bool,
restricted: json['restricted'] as bool,
updatedAt: json['updatedAt'] as int,
admin: json['admin'] as bool,
guest: json['guest'] as bool,
protected: json['protected'] as bool,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'uuid': uuid,
'title': title,
'username': username,
'email': email,
'friendlyName': friendlyName,
'thumb': thumb,
'hasPassword': hasPassword,
'restricted': restricted,
'updatedAt': updatedAt,
'admin': admin,
'guest': guest,
'protected': protected,
};
}
String get displayName => friendlyName ?? title;
bool get isAdminUser => admin;
bool get isRestrictedUser => restricted;
bool get isGuestUser => guest;
bool get requiresPassword => hasPassword;
}
+137
View File
@@ -0,0 +1,137 @@
import 'plex_user_profile.dart';
class UserSwitchResponse {
final int id;
final String uuid;
final String username;
final String title;
final String email;
final String? friendlyName;
final String? locale;
final bool confirmed;
final int joinedAt;
final bool emailOnlyAuth;
final bool hasPassword;
final bool protected;
final String thumb;
final String authToken;
final bool? mailingListActive;
final String scrobbleTypes;
final String country;
final bool restricted;
final bool? anonymous;
final bool home;
final bool guest;
final int homeSize;
final bool homeAdmin;
final int maxHomeSize;
final PlexUserProfile profile;
final bool twoFactorEnabled;
final bool backupCodesCreated;
final String? attributionPartner;
UserSwitchResponse({
required this.id,
required this.uuid,
required this.username,
required this.title,
required this.email,
this.friendlyName,
this.locale,
required this.confirmed,
required this.joinedAt,
required this.emailOnlyAuth,
required this.hasPassword,
required this.protected,
required this.thumb,
required this.authToken,
this.mailingListActive,
required this.scrobbleTypes,
required this.country,
required this.restricted,
this.anonymous,
required this.home,
required this.guest,
required this.homeSize,
required this.homeAdmin,
required this.maxHomeSize,
required this.profile,
required this.twoFactorEnabled,
required this.backupCodesCreated,
this.attributionPartner,
});
factory UserSwitchResponse.fromJson(Map<String, dynamic> json) {
return UserSwitchResponse(
id: json['id'] as int,
uuid: json['uuid'] as String,
username: json['username'] as String? ?? '',
title: json['title'] as String,
email: json['email'] as String? ?? '',
friendlyName: json['friendlyName'] as String?,
locale: json['locale'] as String?,
confirmed: json['confirmed'] as bool,
joinedAt: json['joinedAt'] as int,
emailOnlyAuth: json['emailOnlyAuth'] as bool,
hasPassword: json['hasPassword'] as bool,
protected: json['protected'] as bool,
thumb: json['thumb'] as String,
authToken: json['authToken'] as String,
mailingListActive: json['mailingListActive'] as bool?,
scrobbleTypes: json['scrobbleTypes'] as String? ?? '',
country: json['country'] as String? ?? '',
restricted: json['restricted'] as bool,
anonymous: json['anonymous'] as bool?,
home: json['home'] as bool,
guest: json['guest'] as bool,
homeSize: json['homeSize'] as int,
homeAdmin: json['homeAdmin'] as bool,
maxHomeSize: json['maxHomeSize'] as int,
profile: PlexUserProfile.fromJson(json),
twoFactorEnabled: json['twoFactorEnabled'] as bool,
backupCodesCreated: json['backupCodesCreated'] as bool,
attributionPartner: json['attributionPartner'] as String?,
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'uuid': uuid,
'username': username,
'title': title,
'email': email,
'friendlyName': friendlyName,
'locale': locale,
'confirmed': confirmed,
'joinedAt': joinedAt,
'emailOnlyAuth': emailOnlyAuth,
'hasPassword': hasPassword,
'protected': protected,
'thumb': thumb,
'authToken': authToken,
'mailingListActive': mailingListActive,
'scrobbleTypes': scrobbleTypes,
'country': country,
'restricted': restricted,
'anonymous': anonymous,
'home': home,
'guest': guest,
'homeSize': homeSize,
'homeAdmin': homeAdmin,
'maxHomeSize': maxHomeSize,
'profile': profile.toJson()['profile'],
'twoFactorEnabled': twoFactorEnabled,
'backupCodesCreated': backupCodesCreated,
'attributionPartner': attributionPartner,
};
}
String get displayName => friendlyName ?? title;
bool get isAdminUser => homeAdmin;
bool get isRestrictedUser => restricted;
bool get isGuestUser => guest;
bool get requiresPassword => hasPassword;
bool get isSecureUser => twoFactorEnabled || backupCodesCreated;
}
+31
View File
@@ -0,0 +1,31 @@
import 'package:flutter/foundation.dart';
import '../client/plex_client.dart';
import '../utils/app_logger.dart';
class PlexClientProvider extends ChangeNotifier {
PlexClient? _client;
PlexClient? get client => _client;
void setClient(PlexClient client) {
_client = client;
appLogger.d('PlexClientProvider: Client set');
notifyListeners();
}
void updateToken(String newToken) {
if (_client != null) {
_client!.updateToken(newToken);
appLogger.d('PlexClientProvider: Token updated');
notifyListeners();
} else {
appLogger.w('PlexClientProvider: Cannot update token - no client set');
}
}
void clearClient() {
_client = null;
appLogger.d('PlexClientProvider: Client cleared');
notifyListeners();
}
}
+99
View File
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
import '../services/settings_service.dart' as settings;
import '../theme/mono_theme.dart';
class ThemeProvider extends ChangeNotifier {
late settings.SettingsService _settingsService;
settings.ThemeMode _themeMode = settings.ThemeMode.system;
late Brightness _systemBrightness;
ThemeProvider() {
_systemBrightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;
_initializeSettings();
// Listen to system theme changes
WidgetsBinding.instance.platformDispatcher.onPlatformBrightnessChanged = () {
_systemBrightness = WidgetsBinding.instance.platformDispatcher.platformBrightness;
if (_themeMode == settings.ThemeMode.system) {
notifyListeners();
}
};
}
Future<void> _initializeSettings() async {
_settingsService = await settings.SettingsService.getInstance();
_themeMode = _settingsService.getThemeMode();
notifyListeners();
}
settings.ThemeMode get themeMode => _themeMode;
ThemeData get lightTheme => monoTheme(dark: false);
ThemeData get darkTheme => monoTheme(dark: true);
ThemeMode get materialThemeMode {
switch (_themeMode) {
case settings.ThemeMode.light:
return ThemeMode.light;
case settings.ThemeMode.dark:
return ThemeMode.dark;
case settings.ThemeMode.system:
return ThemeMode.system;
}
}
bool get isDarkMode {
switch (_themeMode) {
case settings.ThemeMode.light:
return false;
case settings.ThemeMode.dark:
return true;
case settings.ThemeMode.system:
return _systemBrightness == Brightness.dark;
}
}
Future<void> setThemeMode(settings.ThemeMode mode) async {
if (_themeMode != mode) {
_themeMode = mode;
await _settingsService.setThemeMode(mode);
notifyListeners();
}
}
String get themeModeDisplayName {
switch (_themeMode) {
case settings.ThemeMode.light:
return 'Light';
case settings.ThemeMode.dark:
return 'Dark';
case settings.ThemeMode.system:
return 'System';
}
}
IconData get themeModeIcon {
switch (_themeMode) {
case settings.ThemeMode.light:
return Icons.light_mode;
case settings.ThemeMode.dark:
return Icons.dark_mode;
case settings.ThemeMode.system:
return Icons.brightness_auto;
}
}
void toggleTheme() {
switch (_themeMode) {
case settings.ThemeMode.system:
setThemeMode(settings.ThemeMode.light);
break;
case settings.ThemeMode.light:
setThemeMode(settings.ThemeMode.dark);
break;
case settings.ThemeMode.dark:
setThemeMode(settings.ThemeMode.system);
break;
}
}
}
+438
View File
@@ -0,0 +1,438 @@
import 'package:flutter/material.dart';
import '../models/plex_home.dart';
import '../models/plex_home_user.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import 'plex_client_provider.dart';
class UserProfileProvider extends ChangeNotifier {
PlexHome? _home;
PlexHomeUser? _currentUser;
bool _isLoading = false;
String? _error;
PlexHome? get home => _home;
PlexHomeUser? get currentUser => _currentUser;
bool get isLoading => _isLoading;
String? get error => _error;
bool get hasMultipleUsers {
final result = _home?.hasMultipleUsers ?? false;
appLogger.d(
'hasMultipleUsers: _home=${_home != null}, users count=${_home?.users.length ?? 0}, result=$result',
);
return result;
}
PlexAuthService? _authService;
StorageService? _storageService;
// Callback for data invalidation when switching profiles
VoidCallback? _onDataInvalidationRequested;
/// Set a callback to be called when profile switching requires data invalidation
void setDataInvalidationCallback(VoidCallback? callback) {
_onDataInvalidationRequested = callback;
}
/// Trigger data invalidation for all screens
void _invalidateAllData() {
if (_onDataInvalidationRequested != null) {
_onDataInvalidationRequested!();
appLogger.d('Data invalidation triggered for profile switch');
}
}
Future<void> initialize() async {
appLogger.d('UserProfileProvider: Initializing...');
try {
_authService = await PlexAuthService.create();
_storageService = await StorageService.getInstance();
await _loadCachedData();
// If no cached home data or it's expired, try to load from API
if (_home == null) {
appLogger.d(
'UserProfileProvider: No cached home data, attempting to load from API',
);
try {
await loadHomeUsers();
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to load home users during initialization',
error: e,
);
// Don't set error here as it's not critical for app startup
}
}
appLogger.d('UserProfileProvider: Initialization complete');
} catch (e) {
appLogger.e(
'UserProfileProvider: Critical initialization failure',
error: e,
);
_setError('Failed to initialize profile services');
// Ensure services are null on failure
_authService = null;
_storageService = null;
}
}
Future<void> _loadCachedData() async {
if (_storageService == null) return;
// Load cached home users
final cachedHomeData = _storageService!.getHomeUsersCache();
if (cachedHomeData != null) {
try {
_home = PlexHome.fromJson(cachedHomeData);
} catch (e) {
appLogger.w('Failed to load cached home data', error: e);
}
}
// Load current user UUID
final currentUserUUID = _storageService!.getCurrentUserUUID();
if (currentUserUUID != null && _home != null) {
_currentUser = _home!.getUserByUUID(currentUserUUID);
}
notifyListeners();
}
Future<void> loadHomeUsers({bool forceRefresh = false}) async {
appLogger.d('loadHomeUsers called - forceRefresh: $forceRefresh');
// Auto-initialize services if not ready
if (_authService == null || _storageService == null) {
appLogger.d(
'loadHomeUsers: Services not initialized, initializing services...',
);
_authService = await PlexAuthService.create();
_storageService = await StorageService.getInstance();
await _loadCachedData();
// Double-check after initialization
if (_authService == null || _storageService == null) {
appLogger.e('loadHomeUsers: Failed to initialize services');
_setError('Failed to initialize services');
return;
}
}
// Use cached data if available and not forcing refresh
if (!forceRefresh && _home != null) {
appLogger.d(
'loadHomeUsers: Using cached data, users count: ${_home!.users.length}',
);
return;
}
_setLoading(true);
_clearError();
try {
final currentToken = _storageService!.getPlexToken();
if (currentToken == null) {
throw Exception('No Plex.tv authentication token available');
}
appLogger.d('loadHomeUsers: Using Plex.tv token');
appLogger.d('loadHomeUsers: Fetching home users from API');
final home = await _authService!.getHomeUsers(currentToken);
_home = home;
appLogger.i(
'loadHomeUsers: Success! Home users count: ${home.users.length}',
);
appLogger.d(
'loadHomeUsers: Users: ${home.users.map((u) => u.displayName).join(', ')}',
);
// Cache the home data
await _storageService!.saveHomeUsersCache(home.toJson());
// Set current user if not already set
if (_currentUser == null) {
final currentUserUUID = _storageService!.getCurrentUserUUID();
if (currentUserUUID != null) {
_currentUser = home.getUserByUUID(currentUserUUID);
appLogger.d(
'loadHomeUsers: Set current user from UUID: ${_currentUser?.displayName}',
);
} else {
// Default to admin user if no current user set
_currentUser = home.adminUser;
if (_currentUser != null) {
await _storageService!.saveCurrentUserUUID(_currentUser!.uuid);
appLogger.d(
'loadHomeUsers: Set current user to admin: ${_currentUser?.displayName}',
);
}
}
}
notifyListeners();
} catch (e) {
_setError('Failed to load home users: $e');
appLogger.e('Failed to load home users', error: e);
} finally {
_setLoading(false);
}
}
Future<bool> switchToUser(PlexHomeUser user, BuildContext? context) async {
if (_authService == null || _storageService == null) {
_setError('Services not initialized');
return false;
}
if (user.uuid == _currentUser?.uuid) {
// Already on this user
return true;
}
// Extract client provider before async operations
PlexClientProvider? clientProvider;
if (context != null) {
try {
clientProvider = context.plexClient;
} catch (e) {
appLogger.w('Failed to get PlexClientProvider', error: e);
}
}
_setLoading(true);
_clearError();
try {
final currentToken = _storageService!.getPlexToken();
if (currentToken == null) {
throw Exception('No Plex.tv authentication token available');
}
final switchResponse = await _authService!.switchToUser(
user.uuid,
currentToken,
);
// switchResponse.authToken is the new user's Plex.tv token
// We need to fetch servers with this token to get the proper server access token
appLogger.d('Got new user Plex.tv token, fetching servers...');
final servers = await _authService!.fetchServers(
switchResponse.authToken,
);
if (servers.isEmpty) {
throw Exception('No servers available for this user');
}
// Find the current server from storage
final currentServerData = _storageService!.getServerData();
if (currentServerData == null) {
throw Exception('No current server data found');
}
// Find matching server by name or client identifier
final currentServerName = currentServerData['name'] as String?;
final currentServerClientId =
currentServerData['clientIdentifier'] as String?;
final matchingServer = servers.firstWhere(
(server) =>
server.name == currentServerName ||
server.clientIdentifier == currentServerClientId,
orElse: () => servers.first, // Fallback to first server
);
appLogger.d(
'Found matching server: ${matchingServer.name}, getting access token',
);
// Update storage with new tokens
await _storageService!.updateCurrentUser(
user.uuid,
matchingServer
.accessToken, // Use server access token, not Plex.tv token
);
// Also save the new Plex.tv token for future profile operations
await _storageService!.savePlexToken(switchResponse.authToken);
// Update current user
_currentUser = user;
// Save user profile
await _storageService!.saveUserProfile(switchResponse.profile.toJson());
// Update PlexClient with proper server access token
if (clientProvider != null) {
try {
clientProvider.updateToken(matchingServer.accessToken);
appLogger.d(
'Updated PlexClient with server access token for user: ${user.displayName}',
);
} catch (e) {
appLogger.w('Failed to update PlexClient token', error: e);
}
}
notifyListeners();
// Invalidate all cached data for the new profile
// This will cause screens to refresh and rebuild widgets with the new token
_invalidateAllData();
appLogger.d(
'Profile switch complete, all data and images should refresh with new token',
);
appLogger.i('Successfully switched to user: ${user.displayName}');
return true;
} catch (e) {
_setError('Failed to switch user: $e');
appLogger.e('Failed to switch to user: ${user.displayName}', error: e);
return false;
} finally {
_setLoading(false);
}
}
Future<void> refreshCurrentUser() async {
if (_currentUser != null) {
await loadHomeUsers(forceRefresh: true);
// Update current user from refreshed data
if (_home != null) {
_currentUser = _home!.getUserByUUID(_currentUser!.uuid);
notifyListeners();
}
}
}
Future<void> logout() async {
if (_storageService == null) return;
_setLoading(true);
try {
await _storageService!.clearUserData();
// Clear user-specific provider state but keep services for future sign-ins
_home = null;
_currentUser = null;
_onDataInvalidationRequested = null;
_clearError();
notifyListeners();
appLogger.i('User logged out successfully');
} catch (e) {
appLogger.e('Error during logout', error: e);
} finally {
_setLoading(false);
}
}
/// Refresh provider for new server context
/// Call this when switching servers to ensure provider state is synchronized
Future<void> refreshForNewServer([BuildContext? context]) async {
appLogger.d('UserProfileProvider: Refreshing for new server context');
_setLoading(true);
try {
// Clear cached data from previous server (both memory and storage)
_home = null;
_currentUser = null;
_clearError();
// Re-initialize services with current storage state
_authService = await PlexAuthService.create();
_storageService = await StorageService.getInstance();
// Clear storage state that's specific to the previous server context
await Future.wait([
// Clear home users cache (server-specific)
_storageService!.clearHomeUsersCache(),
// Clear current user UUID (profile-specific, should not persist across servers)
_storageService!.clearCurrentUserUUID(),
]);
appLogger.d('UserProfileProvider: Cleared previous server storage state');
// Load fresh data for the new server (should be empty after clearing cache)
await _loadCachedData();
// Load from API since we cleared the cache
appLogger.d(
'UserProfileProvider: Loading fresh home users for new server',
);
// Store context reference before async operations to avoid build context warnings
final contextForSwitch = context;
try {
await loadHomeUsers();
// After loading home users, if a current user was set (admin user),
// perform a complete profile switch to ensure tokens are properly updated
if (_currentUser != null && contextForSwitch != null) {
appLogger.d(
'UserProfileProvider: Performing complete profile switch to ${_currentUser!.displayName} for new server',
);
// Perform full profile switch which includes API calls and token updates
final userToSwitchTo = _currentUser!;
// ignore: use_build_context_synchronously
final success = await switchToUser(userToSwitchTo, contextForSwitch);
if (success) {
appLogger.d(
'UserProfileProvider: Successfully switched to admin user for new server',
);
} else {
appLogger.w(
'UserProfileProvider: Failed to complete profile switch for new server',
);
}
} else if (_currentUser != null && contextForSwitch == null) {
appLogger.w(
'UserProfileProvider: Cannot perform complete profile switch - no context provided',
);
}
} catch (e) {
appLogger.w(
'UserProfileProvider: Failed to load home users for new server',
error: e,
);
// Don't set error as it's not critical
}
appLogger.d('UserProfileProvider: Refresh for new server complete');
} catch (e) {
appLogger.e(
'UserProfileProvider: Failed to refresh for new server',
error: e,
);
_setError('Failed to refresh for new server');
} finally {
_setLoading(false);
}
}
void _setLoading(bool loading) {
_isLoading = loading;
notifyListeners();
}
void _setError(String error) {
_error = error;
notifyListeners();
}
void _clearError() {
_error = null;
}
}
+6 -83
View File
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
import 'licenses_screen.dart';
class AboutScreen extends StatefulWidget {
const AboutScreen({super.key});
@@ -36,11 +36,7 @@ class _AboutScreenState extends State<AboutScreen> {
return Scaffold(
body: CustomScrollView(
slivers: [
DesktopSliverAppBar(
title: const Text('About'),
pinned: true,
leading: const AppBarBackButton(style: BackButtonStyle.circular),
),
CustomAppBar(title: const Text('About'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
@@ -86,61 +82,16 @@ class _AboutScreenState extends State<AboutScreen> {
),
trailing: const Icon(Icons.chevron_right),
onTap: () {
showLicensePage(
context: context,
applicationName: appName,
applicationVersion: appVersion,
applicationIcon: Image.asset(
'assets/plezy.png',
width: 48,
height: 48,
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const LicensesScreen(),
),
);
},
),
),
const SizedBox(height: 16),
// Key Dependencies
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Key Dependencies',
style: Theme.of(context).textTheme.titleMedium
?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 12),
_buildDependencyItem('http', 'HTTP networking'),
_buildDependencyItem('dio', 'Advanced HTTP client'),
_buildDependencyItem(
'cached_network_image',
'Image caching',
),
_buildDependencyItem('media_kit', 'Video playback'),
_buildDependencyItem(
'shared_preferences',
'Local storage',
),
_buildDependencyItem('xml', 'XML parsing'),
_buildDependencyItem('url_launcher', 'External links'),
_buildDependencyItem(
'window_manager',
'Desktop window management',
),
_buildDependencyItem(
'macos_window_utils',
'macOS window controls',
),
_buildDependencyItem('logger', 'Logging'),
],
),
),
),
const SizedBox(height: 24),
]),
@@ -151,32 +102,4 @@ class _AboutScreenState extends State<AboutScreen> {
);
}
Widget _buildDependencyItem(String name, String description) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
children: [
const Icon(Icons.circle, size: 6),
const SizedBox(width: 8),
Expanded(
child: RichText(
text: TextSpan(
children: [
TextSpan(
text: name,
style: const TextStyle(fontWeight: FontWeight.w600),
),
TextSpan(
text: ' - $description',
style: const TextStyle(color: Colors.grey),
),
],
style: const TextStyle(fontSize: 13, color: Colors.white),
),
),
),
],
),
);
}
}
+247 -283
View File
@@ -1,34 +1,31 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../services/storage_service.dart';
import '../services/plex_auth_service.dart';
import '../services/server_connection_service.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/server_list_tile.dart';
import '../widgets/user_avatar_widget.dart';
import 'profile_switch_screen.dart';
import 'server_selection_screen.dart';
import '../providers/user_profile_provider.dart';
import '../mixins/refreshable.dart';
import '../mixins/item_updatable.dart';
import '../utils/app_logger.dart';
import '../utils/platform_detector.dart';
import '../utils/provider_extensions.dart';
import 'video_player_screen.dart';
import 'main_screen.dart';
import 'about_screen.dart';
import 'auth_screen.dart';
class DiscoverScreen extends StatefulWidget {
final PlexClient client;
final PlexUserProfile? userProfile;
final VoidCallback? onBecameVisible;
const DiscoverScreen({
super.key,
required this.client,
this.userProfile,
this.onBecameVisible,
});
const DiscoverScreen({super.key, this.userProfile, this.onBecameVisible});
@override
State<DiscoverScreen> createState() => _DiscoverScreenState();
@@ -37,7 +34,7 @@ class DiscoverScreen extends StatefulWidget {
class _DiscoverScreenState extends State<DiscoverScreen>
with Refreshable, ItemUpdatable, SingleTickerProviderStateMixin {
@override
PlexClient get client => widget.client;
PlexClient get client => context.clientSafe;
List<PlexMetadata> _onDeck = [];
List<PlexMetadata> _recentlyAdded = [];
@@ -101,8 +98,14 @@ class _DiscoverScreenState extends State<DiscoverScreen>
try {
appLogger.d('Fetching onDeck and recentlyAdded from Plex');
final onDeck = await widget.client.getOnDeck();
final recentlyAdded = await widget.client.getRecentlyAdded(limit: 20);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final onDeck = await client.getOnDeck();
final recentlyAdded = await client.getRecentlyAdded(limit: 20);
appLogger.d(
'Received ${onDeck.length} on deck items and ${recentlyAdded.length} recently added items',
@@ -163,155 +166,25 @@ class _DiscoverScreenState extends State<DiscoverScreen>
return;
}
// Show loading dialog
if (mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text('Loading servers...'),
],
),
),
);
}
try {
// Fetch available servers
final authService = await PlexAuthService.create();
final servers = await authService.fetchServers(plexToken);
// Close loading dialog
// Navigate to server selection screen
if (mounted) {
Navigator.pop(context);
}
if (servers.isEmpty) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('No servers found')));
}
return;
}
// Show server selection dialog
if (mounted) {
final selectedServer = await showDialog<PlexServer>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Switch Server'),
content: SizedBox(
width: double.maxFinite,
child: ListView.builder(
shrinkWrap: true,
itemCount: servers.length,
itemBuilder: (context, index) {
final server = servers[index];
return ServerListTile(
server: server,
onTap: () => Navigator.pop(context, server),
showTrailingIcon: false,
);
},
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
],
),
);
if (selectedServer != null) {
await _connectToServer(selectedServer);
}
}
} catch (e) {
// Close loading dialog if still open
if (mounted) {
Navigator.pop(context);
}
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text('Failed to load servers: $e')));
}
}
}
Future<void> _connectToServer(PlexServer server) async {
// Show loading dialog
if (mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text('Testing connections...'),
],
),
),
);
}
// Get client identifier
final storage = await StorageService.getInstance();
final clientId = storage.getClientIdentifier();
if (clientId == null) {
// Close loading dialog
if (mounted) {
Navigator.pop(context);
}
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Client identifier not found')),
);
}
return;
}
// Connect using the optimized service
final result = await ServerConnectionService.connectToServer(
server,
clientIdentifier: clientId,
);
// Close loading dialog
if (mounted) {
Navigator.pop(context);
}
// Handle result
if (result.isSuccess) {
// Replace current screen with main screen (includes bottom nav)
if (mounted) {
Navigator.pushReplacement(
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: result.client!),
builder: (context) => ServerSelectionScreen(
authService: authService,
plexToken: plexToken,
),
),
);
}
} else {
// Show error
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(result.error ?? 'Connection failed')),
SnackBar(content: Text('Failed to initialize server selection: $e')),
);
}
}
@@ -337,15 +210,30 @@ class _DiscoverScreenState extends State<DiscoverScreen>
);
if (confirm == true && mounted) {
final storage = await StorageService.getInstance();
await storage.clearCredentials();
// Use comprehensive logout through UserProfileProvider
final userProfileProvider = Provider.of<UserProfileProvider>(context, listen: false);
final plexClientProvider = Provider.of<PlexClientProvider>(context, listen: false);
// Clear all user data and provider states
await userProfileProvider.logout();
plexClientProvider.clearClient();
if (mounted) {
Navigator.of(context).pushNamedAndRemoveUntil('/', (route) => false);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => const AuthScreen()),
(route) => false,
);
}
}
}
void _handleSwitchProfile(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ProfileSwitchScreen()),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -366,54 +254,61 @@ class _DiscoverScreenState extends State<DiscoverScreen>
icon: const Icon(Icons.refresh),
onPressed: _loadContent,
),
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
onSelected: (value) {
if (value == 'switch_server') {
_handleSwitchServer();
} else if (value == 'logout') {
_handleLogout();
} else if (value == 'about') {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const AboutScreen(),
Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
return PopupMenuButton<String>(
icon: userProvider.currentUser?.thumb != null
? UserAvatarWidget(
user: userProvider.currentUser!,
size: 32,
showIndicators: false,
)
: const Icon(Icons.account_circle, size: 32),
onSelected: (value) {
if (value == 'switch_profile') {
_handleSwitchProfile(context);
} else if (value == 'switch_server') {
_handleSwitchServer();
} else if (value == 'logout') {
_handleLogout();
}
},
itemBuilder: (context) => [
// Only show Switch Profile if multiple users available
if (userProvider.hasMultipleUsers)
const PopupMenuItem(
value: 'switch_profile',
child: Row(
children: [
Icon(Icons.people),
SizedBox(width: 8),
Text('Switch Profile'),
],
),
),
const PopupMenuItem(
value: 'switch_server',
child: Row(
children: [
Icon(Icons.swap_horiz),
SizedBox(width: 8),
Text('Switch Server'),
],
),
),
);
}
const PopupMenuItem(
value: 'logout',
child: Row(
children: [
Icon(Icons.logout),
SizedBox(width: 8),
Text('Logout'),
],
),
),
],
);
},
itemBuilder: (context) => [
const PopupMenuItem(
value: 'switch_server',
child: Row(
children: [
Icon(Icons.swap_horiz),
SizedBox(width: 8),
Text('Switch Server'),
],
),
),
const PopupMenuItem(
value: 'about',
child: Row(
children: [
Icon(Icons.info_outline),
SizedBox(width: 8),
Text('About'),
],
),
),
const PopupMenuItem(
value: 'logout',
child: Row(
children: [
Icon(Icons.logout),
SizedBox(width: 8),
Text('Logout'),
],
),
),
],
),
],
),
@@ -604,15 +499,25 @@ class _DiscoverScreenState extends State<DiscoverScreen>
Widget _buildHeroItem(PlexMetadata heroItem) {
final isEpisode = heroItem.type.toLowerCase() == 'episode';
final showName = heroItem.grandparentTitle ?? heroItem.title;
final screenWidth = MediaQuery.of(context).size.width;
final isLargeScreen = screenWidth > 800;
// Determine content type label for chip
final contentTypeLabel = heroItem.type.toLowerCase() == 'movie'
? 'Movie'
: 'TV Show';
return GestureDetector(
onTap: () {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Navigating to VideoPlayerScreen for: ${heroItem.title}');
Navigator.push<bool>(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: heroItem,
userProfile: widget.userProfile,
),
@@ -659,21 +564,33 @@ class _DiscoverScreenState extends State<DiscoverScreen>
child: Opacity(opacity: value, child: child),
);
},
child: CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(
heroItem.art ?? heroItem.grandparentArt,
),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
heroItem.art ?? heroItem.grandparentArt,
),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
);
},
),
),
)
@@ -700,15 +617,17 @@ class _DiscoverScreenState extends State<DiscoverScreen>
// Content with responsive alignment
Positioned(
bottom: PlatformDetector.isDesktop(context) ? 80 : 70,
bottom: isLargeScreen ? 80 : 50,
left: 0,
right: PlatformDetector.isDesktop(context) ? 200 : 0,
right: isLargeScreen ? 200 : 0,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: PlatformDetector.isDesktop(context) ? 40 : 16,
horizontal: isLargeScreen ? 40 : 16,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: isLargeScreen
? CrossAxisAlignment.start
: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
// Show logo or name/title
@@ -716,60 +635,82 @@ class _DiscoverScreenState extends State<DiscoverScreen>
SizedBox(
height: 120,
width: 400,
child: CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(
heroItem.clearLogo,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
placeholder: (context, url) => Align(
alignment: Alignment.centerLeft,
child: Text(
showName,
style: Theme.of(context).textTheme.displaySmall
?.copyWith(
color: Colors.white.withValues(
alpha: 0.3,
),
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
errorWidget: (context, url, error) {
// Fallback to text if logo fails to load
return Align(
alignment: Alignment.centerLeft,
child: Text(
showName,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container();
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
heroItem.clearLogo,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
alignment: isLargeScreen
? Alignment.bottomLeft
: Alignment.bottomCenter,
placeholder: (context, url) => Align(
alignment: isLargeScreen
? Alignment.centerLeft
: Alignment.center,
child: Text(
showName,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white.withValues(
alpha: 0.3,
),
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
),
),
errorWidget: (context, url, error) {
// Fallback to text if logo fails to load
return Align(
alignment: isLargeScreen
? Alignment.centerLeft
: Alignment.center,
child: Text(
showName,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
),
);
},
);
},
),
@@ -790,15 +731,19 @@ class _DiscoverScreenState extends State<DiscoverScreen>
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
),
// Metadata as dot-separated text
// Metadata as dot-separated text with content type
if (heroItem.year != null ||
heroItem.contentRating != null ||
heroItem.rating != null) ...[
const SizedBox(height: 16),
Text(
[
contentTypeLabel,
if (heroItem.rating != null)
'★ ${(heroItem.rating! / 10).toStringAsFixed(1)}',
if (heroItem.contentRating != null)
@@ -810,15 +755,27 @@ class _DiscoverScreenState extends State<DiscoverScreen>
fontSize: 14,
fontWeight: FontWeight.w500,
),
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
),
],
// On small screens: show button before summary
if (!isLargeScreen) ...[
const SizedBox(height: 20),
_buildSmartPlayButton(heroItem),
],
// Summary with episode info (Apple TV style)
if (heroItem.summary != null) ...[
const SizedBox(height: 12),
RichText(
maxLines: 2,
overflow: TextOverflow.ellipsis,
textAlign: isLargeScreen
? TextAlign.left
: TextAlign.center,
text: TextSpan(
style: const TextStyle(
color: Colors.white70,
@@ -837,16 +794,21 @@ class _DiscoverScreenState extends State<DiscoverScreen>
color: Colors.white,
),
),
TextSpan(text: heroItem.summary!),
TextSpan(
text: heroItem.summary?.isNotEmpty == true
? heroItem.summary!
: 'No description available',
),
],
),
),
],
const SizedBox(height: 20),
// Smart Play Button with progress
_buildSmartPlayButton(heroItem),
// On large screens: show button after summary
if (isLargeScreen) ...[
const SizedBox(height: 20),
_buildSmartPlayButton(heroItem),
],
],
),
),
@@ -875,12 +837,15 @@ class _DiscoverScreenState extends State<DiscoverScreen>
return InkWell(
onTap: () {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Playing: ${heroItem.title}');
Navigator.push<bool>(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: heroItem,
userProfile: widget.userProfile,
),
@@ -978,7 +943,6 @@ class _DiscoverScreenState extends State<DiscoverScreen>
padding: const EdgeInsets.symmetric(horizontal: 2),
child: MediaCard(
key: Key(item.ratingKey),
client: widget.client,
item: item,
width: cardWidth,
height: cardHeight,
+56 -13
View File
@@ -1,9 +1,12 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_library.dart';
import '../models/plex_metadata.dart';
import '../models/plex_filter.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
@@ -13,10 +16,9 @@ import '../mixins/item_updatable.dart';
import '../theme/theme_helper.dart';
class LibrariesScreen extends StatefulWidget {
final PlexClient client;
final PlexUserProfile? userProfile;
const LibrariesScreen({super.key, required this.client, this.userProfile});
const LibrariesScreen({super.key, this.userProfile});
@override
State<LibrariesScreen> createState() => _LibrariesScreenState();
@@ -25,7 +27,7 @@ class LibrariesScreen extends StatefulWidget {
class _LibrariesScreenState extends State<LibrariesScreen>
with Refreshable, ItemUpdatable {
@override
PlexClient get client => widget.client;
PlexClient get client => context.clientSafe;
List<PlexLibrary> _libraries = [];
List<PlexMetadata> _items = [];
@@ -50,7 +52,16 @@ class _LibrariesScreenState extends State<LibrariesScreen>
});
try {
final libraries = await widget.client.getLibraries();
final clientProvider = Provider.of<PlexClientProvider>(
context,
listen: false,
);
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final libraries = await client.getLibraries();
setState(() {
_libraries = libraries;
_isLoadingLibraries = false;
@@ -88,6 +99,17 @@ class _LibrariesScreenState extends State<LibrariesScreen>
final isChangingLibrary = !_isInitialLoad && _selectedLibraryIndex != index;
// Extract context dependencies before async operations
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
setState(() {
_errorMessage = 'No client available';
_isLoadingItems = false;
});
return;
}
setState(() {
_selectedLibraryIndex = index;
_isLoadingItems = true;
@@ -117,7 +139,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
_loadFilters(index);
// Load content
final items = await widget.client.getLibraryContent(
final items = await client.getLibraryContent(
_libraries[index].key,
filters: _selectedFilters,
);
@@ -137,9 +159,16 @@ class _LibrariesScreenState extends State<LibrariesScreen>
if (index < 0 || index >= _libraries.length) return;
try {
final filters = await widget.client.getLibraryFilters(
_libraries[index].key,
final clientProvider = Provider.of<PlexClientProvider>(
context,
listen: false,
);
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final filters = await client.getLibraryFilters(_libraries[index].key);
setState(() {
_filters = filters;
});
@@ -157,7 +186,16 @@ class _LibrariesScreenState extends State<LibrariesScreen>
});
try {
final items = await widget.client.getLibraryContent(
final clientProvider = Provider.of<PlexClientProvider>(
context,
listen: false,
);
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final items = await client.getLibraryContent(
_libraries[_selectedLibraryIndex].key,
filters: _selectedFilters,
);
@@ -196,7 +234,6 @@ class _LibrariesScreenState extends State<LibrariesScreen>
builder: (context) => _FiltersBottomSheet(
filters: _filters,
selectedFilters: _selectedFilters,
client: widget.client,
onFiltersChanged: (filters) async {
setState(() {
_selectedFilters.clear();
@@ -394,7 +431,6 @@ class _LibrariesScreenState extends State<LibrariesScreen>
final item = _items[index];
return MediaCard(
key: Key(item.ratingKey),
client: widget.client,
item: item,
onRefresh: updateItem,
userProfile: widget.userProfile,
@@ -427,13 +463,11 @@ class _LibrariesScreenState extends State<LibrariesScreen>
class _FiltersBottomSheet extends StatefulWidget {
final List<PlexFilter> filters;
final Map<String, String> selectedFilters;
final PlexClient client;
final Function(Map<String, String>) onFiltersChanged;
const _FiltersBottomSheet({
required this.filters,
required this.selectedFilters,
required this.client,
required this.onFiltersChanged,
});
@@ -480,7 +514,16 @@ class _FiltersBottomSheetState extends State<_FiltersBottomSheet> {
});
try {
final values = await widget.client.getFilterValues(filter.key);
final clientProvider = Provider.of<PlexClientProvider>(
context,
listen: false,
);
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final values = await client.getFilterValues(filter.key);
setState(() {
_filterValues = values;
_isLoadingValues = false;
+223
View File
@@ -0,0 +1,223 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../widgets/desktop_app_bar.dart';
class MergedLicenseEntry {
final String packageName;
final List<LicenseEntry> licenseEntries;
final Set<String> allPackageNames;
MergedLicenseEntry({
required this.packageName,
required this.licenseEntries,
required this.allPackageNames,
});
}
class LicensesScreen extends StatefulWidget {
const LicensesScreen({super.key});
@override
State<LicensesScreen> createState() => _LicensesScreenState();
}
class _LicensesScreenState extends State<LicensesScreen> {
List<MergedLicenseEntry> _mergedLicenses = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadLicenses();
}
Future<void> _loadLicenses() async {
final licenseMap = <String, List<LicenseEntry>>{};
final allPackageNames = <String, Set<String>>{};
await for (final license in LicenseRegistry.licenses) {
for (final packageName in license.packages) {
if (!licenseMap.containsKey(packageName)) {
licenseMap[packageName] = [];
allPackageNames[packageName] = <String>{};
}
licenseMap[packageName]!.add(license);
allPackageNames[packageName]!.addAll(license.packages);
}
}
final mergedLicenses = licenseMap.entries.map((entry) {
return MergedLicenseEntry(
packageName: entry.key,
licenseEntries: entry.value,
allPackageNames: allPackageNames[entry.key]!,
);
}).toList();
mergedLicenses.sort((a, b) => a.packageName.compareTo(b.packageName));
if (mounted) {
setState(() {
_mergedLicenses = mergedLicenses;
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Licenses'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final mergedLicense = _mergedLicenses[index];
final packageName = mergedLicense.packageName;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
title: Text(
packageName,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
subtitle: mergedLicense.licenseEntries.length > 1
? Text('${mergedLicense.licenseEntries.length} licenses')
: null,
trailing: const Icon(Icons.chevron_right),
onTap: () => _showLicenseDetail(mergedLicense),
),
);
},
childCount: _mergedLicenses.length,
),
),
),
],
),
);
}
void _showLicenseDetail(MergedLicenseEntry mergedLicense) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => _LicenseDetailScreen(
mergedLicense: mergedLicense,
),
),
);
}
}
class _LicenseDetailScreen extends StatelessWidget {
final MergedLicenseEntry mergedLicense;
const _LicenseDetailScreen({
required this.mergedLicense,
});
@override
Widget build(BuildContext context) {
final packageName = mergedLicense.packageName;
final licenseEntries = mergedLicense.licenseEntries;
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: Text(packageName),
pinned: true,
),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
// Package info card
if (mergedLicense.allPackageNames.length > 1)
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Related Packages',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
mergedLicense.allPackageNames.join(', '),
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
),
if (mergedLicense.allPackageNames.length > 1)
const SizedBox(height: 16),
// License cards
...licenseEntries.asMap().entries.map((entry) {
final index = entry.key;
final license = entry.value;
final isMultipleLicenses = licenseEntries.length > 1;
return Column(
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isMultipleLicenses ? 'License ${index + 1}' : 'License',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 16),
...license.paragraphs.map((paragraph) {
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: SelectableText(
paragraph.text,
style: TextStyle(
fontFamily: paragraph.indent > 0 ? 'monospace' : null,
fontSize: 14,
),
),
);
}),
],
),
),
),
if (index < licenseEntries.length - 1)
const SizedBox(height: 16),
],
);
}),
]),
),
),
],
),
);
}
}
+46 -3
View File
@@ -2,11 +2,13 @@ import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_user_profile.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../main.dart';
import '../mixins/refreshable.dart';
import 'discover_screen.dart';
import 'libraries_screen.dart';
import 'search_screen.dart';
import 'settings_screen.dart';
class MainScreen extends StatefulWidget {
final PlexClient client;
@@ -23,6 +25,9 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
late final List<Widget> _screens;
final GlobalKey<State<DiscoverScreen>> _discoverKey = GlobalKey();
final GlobalKey<State<LibrariesScreen>> _librariesKey = GlobalKey();
final GlobalKey<State<SearchScreen>> _searchKey = GlobalKey();
final GlobalKey<State<SettingsScreen>> _settingsKey = GlobalKey();
@override
void initState() {
@@ -31,13 +36,23 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
_screens = [
DiscoverScreen(
key: _discoverKey,
client: widget.client,
userProfile: widget.userProfile,
onBecameVisible: _onDiscoverBecameVisible,
),
LibrariesScreen(client: widget.client, userProfile: widget.userProfile),
SearchScreen(client: widget.client, userProfile: widget.userProfile),
LibrariesScreen(key: _librariesKey, userProfile: widget.userProfile),
SearchScreen(key: _searchKey, userProfile: widget.userProfile),
SettingsScreen(key: _settingsKey),
];
// Set up data invalidation callback for profile switching
WidgetsBinding.instance.addPostFrameCallback((_) async {
// Initialize UserProfileProvider to ensure it's ready after sign-in
final userProfileProvider = context.userProfile;
await userProfileProvider.initialize();
// Set up data invalidation callback for profile switching
userProfileProvider.setDataInvalidationCallback(_invalidateAllScreens);
});
}
@override
@@ -77,6 +92,29 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
}
}
/// Invalidate all cached data across all screens when profile is switched
void _invalidateAllScreens() {
appLogger.d('Invalidating all screen data due to profile switch');
// Refresh discover screen
final discoverState = _discoverKey.currentState;
if (discoverState != null && discoverState is Refreshable) {
(discoverState as Refreshable).refresh();
}
// Refresh libraries screen
final librariesState = _librariesKey.currentState;
if (librariesState != null && librariesState is Refreshable) {
(librariesState as Refreshable).refresh();
}
// Refresh search screen
final searchState = _searchKey.currentState;
if (searchState != null && searchState is Refreshable) {
(searchState as Refreshable).refresh();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -108,6 +146,11 @@ class _MainScreenState extends State<MainScreen> with RouteAware {
selectedIcon: Icon(Icons.search),
label: 'Search',
),
NavigationDestination(
icon: Icon(Icons.settings_outlined),
selectedIcon: Icon(Icons.settings),
label: 'Settings',
),
],
),
);
+181 -103
View File
@@ -1,24 +1,24 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../client/plex_client.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
import '../widgets/media_context_menu.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import '../theme/theme_helper.dart';
import 'season_detail_screen.dart';
import 'video_player_screen.dart';
class MediaDetailScreen extends StatefulWidget {
final PlexClient client;
final PlexMetadata metadata;
final PlexUserProfile? userProfile;
const MediaDetailScreen({
super.key,
required this.client,
required this.metadata,
this.userProfile,
});
@@ -55,8 +55,14 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
});
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// Fetch full metadata with clearLogo and OnDeck episode
final result = await widget.client.getMetadataWithImagesAndOnDeck(
final result = await client.getMetadataWithImagesAndOnDeck(
widget.metadata.ratingKey,
);
final metadata = result['metadata'] as PlexMetadata?;
@@ -104,9 +110,13 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
});
try {
final seasons = await widget.client.getChildren(
widget.metadata.ratingKey,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final seasons = await client.getChildren(widget.metadata.ratingKey);
setState(() {
_seasons = seasons;
_isLoadingSeasons = false;
@@ -122,7 +132,13 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
/// This preserves scroll position and only updates watch-related data
Future<void> _updateWatchState() async {
try {
final metadata = await widget.client.getMetadataWithImages(
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final metadata = await client.getMetadataWithImages(
widget.metadata.ratingKey,
);
@@ -130,9 +146,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
// For shows, also refetch seasons to update their watch counts
List<PlexMetadata>? updatedSeasons;
if (metadata.type.toLowerCase() == 'show') {
updatedSeasons = await widget.client.getChildren(
widget.metadata.ratingKey,
);
updatedSeasons = await client.getChildren(widget.metadata.ratingKey);
}
// Single setState to minimize rebuilds - scroll position is preserved by controller
@@ -151,6 +165,13 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
Future<void> _playFirstEpisode() async {
try {
// Extract context dependencies before async operations
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// If seasons aren't loaded yet, wait for them or load them
if (_seasons.isEmpty && !_isLoadingSeasons) {
await _loadSeasons();
@@ -174,7 +195,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
final firstSeason = _seasons.first;
// Get episodes of the first season
final episodes = await widget.client.getChildren(firstSeason.ratingKey);
final episodes = await client.getChildren(firstSeason.ratingKey);
if (episodes.isEmpty) {
if (mounted) {
@@ -188,12 +209,15 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
// Play the first episode
final firstEpisode = episodes.first;
if (mounted) {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Playing first episode: ${firstEpisode.title}');
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: firstEpisode,
userProfile: widget.userProfile,
),
@@ -249,19 +273,31 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
children: [
// Background Art
if (metadata.art != null)
CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(metadata.art),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(metadata.art),
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
);
},
)
else
Container(
@@ -303,42 +339,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
SizedBox(
height: 120,
width: 400,
child: CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(
metadata.clearLogo,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
placeholder: (context, url) => Align(
alignment: Alignment.centerLeft,
child: Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white.withValues(
alpha: 0.3,
),
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
errorWidget: (context, url, error) {
return Align(
alignment: Alignment.centerLeft,
child: Text(
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Text(
metadata.title,
style: Theme.of(context)
.textTheme
@@ -346,17 +351,66 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(alpha: 0.5),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
metadata.clearLogo,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
placeholder: (context, url) => Align(
alignment: Alignment.centerLeft,
child: Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white.withValues(
alpha: 0.3,
),
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(alpha: 0.5),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
errorWidget: (context, url, error) {
return Align(
alignment: Alignment.centerLeft,
child: Text(
metadata.title,
style: Theme.of(context)
.textTheme
.displaySmall
?.copyWith(
color: Colors.white,
fontWeight: FontWeight.bold,
shadows: [
Shadow(
color: Colors.black
.withValues(
alpha: 0.5,
),
blurRadius: 8,
),
],
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
);
},
);
},
),
@@ -481,6 +535,10 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
// Otherwise, play the first episode of the first season
if (metadata.type.toLowerCase() == 'show') {
if (_onDeckEpisode != null) {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d(
'Playing on deck episode: ${_onDeckEpisode!.title}',
);
@@ -488,7 +546,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: _onDeckEpisode!,
userProfile: widget.userProfile,
),
@@ -504,13 +561,16 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
await _playFirstEpisode();
}
} else {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
appLogger.d('Playing: ${metadata.title}');
// For movies or episodes, play directly
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: metadata,
userProfile: widget.userProfile,
),
@@ -540,9 +600,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
IconButton.filledTonal(
onPressed: () async {
try {
await widget.client.markAsWatched(
metadata.ratingKey,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
await client.markAsWatched(metadata.ratingKey);
if (context.mounted) {
_watchStateChanged = true;
ScaffoldMessenger.of(context).showSnackBar(
@@ -573,9 +635,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
IconButton.filledTonal(
onPressed: () async {
try {
await widget.client.markAsUnwatched(
metadata.ratingKey,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
await client.markAsUnwatched(metadata.ratingKey);
if (context.mounted) {
_watchStateChanged = true;
ScaffoldMessenger.of(context).showSnackBar(
@@ -691,7 +755,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
return Card(
clipBehavior: Clip.antiAlias,
child: MediaContextMenu(
client: widget.client,
metadata: season,
onRefresh: (ratingKey) {
_watchStateChanged = true;
@@ -701,8 +764,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
final watchStateChanged = await Navigator.push<bool>(
context,
MaterialPageRoute(
builder: (context) =>
SeasonDetailScreen(client: widget.client, season: season),
builder: (context) => SeasonDetailScreen(season: season),
),
);
if (watchStateChanged == true) {
@@ -719,26 +781,41 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
if (season.thumb != null)
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(season.thumb),
width: 80,
height: 120,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
child: Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(season.thumb),
width: 80,
height: 120,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
width: 80,
height: 120,
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
);
},
),
)
else
@@ -785,7 +862,8 @@ class _MediaDetailScreenState extends State<MediaDetailScreen> {
borderRadius: BorderRadius.circular(4),
child: LinearProgressIndicator(
value:
season.viewedLeafCount! / season.leafCount!,
season.viewedLeafCount! /
season.leafCount!,
backgroundColor: tokens(context).outline,
valueColor: AlwaysStoppedAnimation<Color>(
Theme.of(context).colorScheme.primary,
+124
View File
@@ -0,0 +1,124 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/profile_list_tile.dart';
import '../widgets/desktop_app_bar.dart';
class ProfileSwitchScreen extends StatelessWidget {
const ProfileSwitchScreen({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Switch Profile')),
SliverFillRemaining(
child: Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
final users = userProvider.home?.users ?? [];
if (userProvider.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (userProvider.error != null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
userProvider.error!,
style: TextStyle(color: theme.colorScheme.error),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
userProvider.refreshCurrentUser();
},
child: const Text('Retry'),
),
],
),
);
}
if (users.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.person_off,
size: 64,
color: theme.colorScheme.onSurfaceVariant,
),
const SizedBox(height: 16),
Text(
'No profiles available',
style: theme.textTheme.titleMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 8),
Text(
'Contact your Plex administrator to add profiles',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
],
),
);
}
return ListView.builder(
itemCount: users.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
final user = users[index];
final isCurrentUser =
user.uuid == userProvider.currentUser?.uuid;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Card(
child: ProfileListTile(
user: user,
isCurrentUser: isCurrentUser,
onTap: () => _switchToUser(context, user),
),
),
);
},
);
},
),
),
],
),
);
}
void _switchToUser(BuildContext context, PlexHomeUser user) async {
final userProvider = context.userProfile;
final success = await userProvider.switchToUser(user, context);
if (success && context.mounted) {
Navigator.of(context).pop();
} else if (!success && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to switch to ${user.displayName}'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
}
}
+18 -5
View File
@@ -3,16 +3,16 @@ import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../utils/provider_extensions.dart';
import '../widgets/media_card.dart';
import '../widgets/desktop_app_bar.dart';
import '../mixins/refreshable.dart';
import '../mixins/item_updatable.dart';
class SearchScreen extends StatefulWidget {
final PlexClient client;
final PlexUserProfile? userProfile;
const SearchScreen({super.key, required this.client, this.userProfile});
const SearchScreen({super.key, this.userProfile});
@override
State<SearchScreen> createState() => _SearchScreenState();
@@ -21,13 +21,14 @@ class SearchScreen extends StatefulWidget {
class _SearchScreenState extends State<SearchScreen>
with Refreshable, ItemUpdatable {
@override
PlexClient get client => widget.client;
PlexClient get client => context.clientSafe;
final _searchController = TextEditingController();
List<PlexMetadata> _searchResults = [];
bool _isSearching = false;
bool _hasSearched = false;
Timer? _debounceTimer;
String _lastSearchedQuery = '';
@override
void initState() {
@@ -54,10 +55,16 @@ class _SearchScreenState extends State<SearchScreen>
_searchResults = [];
_hasSearched = false;
_isSearching = false;
_lastSearchedQuery = '';
});
return;
}
// Only search if the query has actually changed
if (query.trim() == _lastSearchedQuery.trim()) {
return;
}
// Start new timer
_debounceTimer = Timer(const Duration(milliseconds: 500), () {
_performSearch(query);
@@ -79,11 +86,18 @@ class _SearchScreenState extends State<SearchScreen>
});
try {
final results = await widget.client.search(query);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final results = await client.search(query);
if (mounted) {
setState(() {
_searchResults = results;
_isSearching = false;
_lastSearchedQuery = query.trim();
});
}
} catch (e) {
@@ -212,7 +226,6 @@ class _SearchScreenState extends State<SearchScreen>
final item = _searchResults[index];
return MediaCard(
key: Key(item.ratingKey),
client: widget.client,
item: item,
onRefresh: updateItem,
userProfile: widget.userProfile,
+70 -54
View File
@@ -1,26 +1,22 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/app_bar_back_button.dart';
import '../widgets/media_context_menu.dart';
import '../mixins/item_updatable.dart';
import '../theme/theme_helper.dart';
import 'video_player_screen.dart';
class SeasonDetailScreen extends StatefulWidget {
final PlexClient client;
final PlexMetadata season;
final PlexUserProfile? userProfile;
const SeasonDetailScreen({
super.key,
required this.client,
required this.season,
this.userProfile,
});
const SeasonDetailScreen({super.key, required this.season, this.userProfile});
@override
State<SeasonDetailScreen> createState() => _SeasonDetailScreenState();
@@ -29,7 +25,7 @@ class SeasonDetailScreen extends StatefulWidget {
class _SeasonDetailScreenState extends State<SeasonDetailScreen>
with ItemUpdatable {
@override
PlexClient get client => widget.client;
PlexClient get client => context.clientSafe;
List<PlexMetadata> _episodes = [];
bool _isLoadingEpisodes = false;
@@ -47,7 +43,13 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
});
try {
final episodes = await widget.client.getChildren(widget.season.ratingKey);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
final episodes = await client.getChildren(widget.season.ratingKey);
setState(() {
_episodes = episodes;
_isLoadingEpisodes = false;
@@ -78,13 +80,10 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
return Scaffold(
body: CustomScrollView(
slivers: [
DesktopSliverAppBar(
CustomAppBar(
title: Text(widget.season.title),
pinned: true,
leading: AppBarBackButton(
style: BackButtonStyle.circular,
onPressed: () => Navigator.pop(context, _watchStateChanged),
),
onBackPressed: () => Navigator.pop(context, _watchStateChanged),
),
if (_isLoadingEpisodes)
const SliverFillRemaining(
@@ -104,9 +103,7 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
const SizedBox(height: 16),
Text(
'No episodes found',
style: Theme.of(
context,
).textTheme.titleLarge?.copyWith(
style: Theme.of(context).textTheme.titleLarge?.copyWith(
color: tokens(context).textMuted,
),
),
@@ -136,7 +133,6 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
: 0.0;
return MediaContextMenu(
client: widget.client,
metadata: episode,
onRefresh: updateItem,
onTap: () async {
@@ -144,7 +140,6 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: episode,
userProfile: widget.userProfile,
),
@@ -155,14 +150,13 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
},
child: InkWell(
key: Key(episode.ratingKey),
hoverColor: Theme.of(context).colorScheme.surface.withValues(alpha: 0.05),
hoverColor: Theme.of(
context,
).colorScheme.surface.withValues(alpha: 0.05),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: tokens(context).outline,
width: 0.5,
),
bottom: BorderSide(color: tokens(context).outline, width: 0.5),
),
),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
@@ -179,23 +173,42 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
child: AspectRatio(
aspectRatio: 16 / 9,
child: episode.thumb != null
? CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(
episode.thumb,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(Icons.movie, size: 32),
),
? Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Center(
child: Icon(Icons.movie, size: 40),
),
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(
episode.thumb,
),
filterQuality: FilterQuality.medium,
fit: BoxFit.cover,
placeholder: (context, url) => Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) =>
Container(
color: Theme.of(
context,
).colorScheme.surfaceContainerHighest,
child: const Icon(
Icons.movie,
size: 32,
),
),
);
},
)
: Container(
color: Theme.of(
@@ -327,28 +340,31 @@ class _SeasonDetailScreenState extends State<SeasonDetailScreen>
if (episode.duration != null)
Text(
_formatDuration(episode.duration!),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
if (episode.duration != null && episode.isWatched) ...[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 6),
child: Text(
'•',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
),
Text(
'Watched ✓',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
style: Theme.of(context).textTheme.bodySmall
?.copyWith(
color: tokens(context).textMuted,
fontSize: 12,
),
),
],
],
+157 -64
View File
@@ -4,6 +4,8 @@ import '../services/storage_service.dart';
import '../services/server_connection_service.dart';
import '../widgets/server_list_tile.dart';
import '../widgets/desktop_app_bar.dart';
import '../utils/app_logger.dart';
import '../utils/provider_extensions.dart';
import 'main_screen.dart';
class ServerSelectionScreen extends StatefulWidget {
@@ -24,13 +26,26 @@ class _ServerSelectionScreenState extends State<ServerSelectionScreen> {
List<PlexServer>? _servers;
bool _isLoading = true;
String? _errorMessage;
String? _currentServerUrl;
@override
void initState() {
super.initState();
_loadCurrentServerUrl();
_loadServers();
}
Future<void> _loadCurrentServerUrl() async {
try {
final storage = await StorageService.getInstance();
setState(() {
_currentServerUrl = storage.getServerUrl();
});
} catch (e) {
appLogger.w('Failed to load current server URL', error: e);
}
}
Future<void> _loadServers() async {
try {
final servers = await widget.authService.fetchServers(widget.plexToken);
@@ -58,92 +73,170 @@ class _ServerSelectionScreenState extends State<ServerSelectionScreen> {
children: [
CircularProgressIndicator(),
SizedBox(height: 16),
Text('Testing connections...'),
Text('Connecting to server...'),
],
),
),
);
}
// Get client identifier
final storage = await StorageService.getInstance();
final clientId =
storage.getClientIdentifier() ?? widget.authService.clientIdentifier;
try {
// Get client identifier and storage
final storage = await StorageService.getInstance();
final clientId =
storage.getClientIdentifier() ?? widget.authService.clientIdentifier;
// Connect using the optimized service
final result = await ServerConnectionService.connectToServer(
server,
clientIdentifier: clientId,
plexToken: widget.plexToken,
);
// Get current profile context to maintain profile across server switch
final currentUserUUID = storage.getCurrentUserUUID();
// Close loading dialog
if (mounted) {
Navigator.pop(context);
}
PlexServer serverWithCorrectToken = server;
// Handle result
if (result.isSuccess) {
// Navigate to main app
if (mounted) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: result.client!),
),
);
// If we have a current profile, get a profile-specific token for this server
if (currentUserUUID != null) {
try {
// Switch to the current profile on the new server to get the correct token
final switchResponse = await widget.authService.switchToUser(
currentUserUUID,
widget.plexToken,
);
// Get servers with the profile's Plex.tv token to get profile-specific server tokens
final servers = await widget.authService.fetchServers(
switchResponse.authToken,
);
// Find the matching server with the profile-specific token
final matchingServer = servers.firstWhere(
(s) =>
s.name == server.name ||
s.clientIdentifier == server.clientIdentifier,
orElse: () => server, // Fallback to original server
);
serverWithCorrectToken = matchingServer;
appLogger.d(
'Got profile-specific token for server ${server.name} and user UUID $currentUserUUID',
);
} catch (e) {
appLogger.w(
'Failed to get profile-specific token, using default server token',
error: e,
);
// Continue with original server token as fallback
}
}
} else {
// Show error
// Connect using the server with the correct token
final result = await ServerConnectionService.connectToServer(
serverWithCorrectToken,
clientIdentifier: clientId,
plexToken: widget.plexToken,
);
// Close loading dialog
if (mounted) {
Navigator.pop(context);
}
// Handle result
if (result.isSuccess) {
// Set client in provider before navigation (same pattern as auto-login)
if (mounted) {
context.plexClient.setClient(result.client!);
// Navigate to main app and clear navigation stack
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(
builder: (context) => MainScreen(client: result.client!),
),
(route) => false, // Remove all routes
);
}
} else {
// Show error
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(result.error ?? 'Connection failed')),
);
}
}
} catch (e) {
// Close loading dialog on error
if (mounted) {
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(result.error ?? 'Connection failed')),
SnackBar(content: Text('Failed to connect to server: $e')),
);
}
appLogger.e('Server selection failed', error: e);
}
}
bool _isCurrentServer(PlexServer server) {
if (_currentServerUrl == null) return false;
// Check all server connections to see if any match the current server URL
for (final connection in server.connections) {
if (connection.uri == _currentServerUrl) {
return true;
}
}
return false;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: const DesktopAppBar(title: Text('Select Server')),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_errorMessage!,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Select Server')),
SliverFillRemaining(
child: _isLoading
? const Center(child: CircularProgressIndicator())
: _errorMessage != null
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_errorMessage!,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadServers,
child: const Text('Retry'),
),
],
),
textAlign: TextAlign.center,
)
: _servers == null || _servers!.isEmpty
? const Center(child: Text('No servers found'))
: ListView.builder(
itemCount: _servers!.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
final server = _servers![index];
final isCurrentServer = _isCurrentServer(server);
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Card(
child: ServerListTile(
server: server,
isCurrentServer: isCurrentServer,
onTap: () => _selectServer(server),
),
),
);
},
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _loadServers,
child: const Text('Retry'),
),
],
),
)
: _servers == null || _servers!.isEmpty
? const Center(child: Text('No servers found'))
: ListView.builder(
itemCount: _servers!.length,
padding: const EdgeInsets.all(16),
itemBuilder: (context, index) {
final server = _servers![index];
return Card(
child: ServerListTile(
server: server,
onTap: () => _selectServer(server),
),
);
},
),
),
],
),
);
}
}
+577
View File
@@ -0,0 +1,577 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import '../providers/theme_provider.dart';
import '../services/settings_service.dart' as settings;
import '../services/keyboard_shortcuts_service.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/hotkey_recorder_widget.dart';
import 'about_screen.dart';
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@override
State<SettingsScreen> createState() => _SettingsScreenState();
}
class _SettingsScreenState extends State<SettingsScreen> {
late settings.SettingsService _settingsService;
late KeyboardShortcutsService _keyboardService;
bool _isLoading = true;
bool _enableDebugLogging = false;
bool _enableHardwareDecoding = true;
int _videoBufferSize = 64;
int _audioBufferSize = 8;
@override
void initState() {
super.initState();
_loadSettings();
}
Future<void> _loadSettings() async {
_settingsService = await settings.SettingsService.getInstance();
_keyboardService = await KeyboardShortcutsService.getInstance();
setState(() {
_enableDebugLogging = _settingsService.getEnableDebugLogging();
_enableHardwareDecoding = _settingsService.getEnableHardwareDecoding();
_videoBufferSize = _settingsService.getVideoBufferSize();
_audioBufferSize = _settingsService.getAudioBufferSize();
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
body: CustomScrollView(
slivers: [
const CustomAppBar(title: Text('Settings'), pinned: true),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate([
_buildAppearanceSection(),
const SizedBox(height: 24),
_buildVideoPlaybackSection(),
const SizedBox(height: 24),
_buildKeyboardShortcutsSection(),
const SizedBox(height: 24),
_buildAdvancedSection(),
const SizedBox(height: 24),
_buildAboutSection(),
const SizedBox(height: 24),
]),
),
),
],
),
);
}
Widget _buildAppearanceSection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Appearance',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
Consumer<ThemeProvider>(
builder: (context, themeProvider, child) {
return ListTile(
leading: Icon(themeProvider.themeModeIcon),
title: const Text('Theme'),
subtitle: Text(themeProvider.themeModeDisplayName),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showThemeDialog(themeProvider),
);
},
),
],
),
);
}
Widget _buildVideoPlaybackSection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Video Playback',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
SwitchListTile(
secondary: const Icon(Icons.hardware),
title: const Text('Hardware Decoding'),
subtitle: const Text('Use hardware acceleration when available'),
value: _enableHardwareDecoding,
onChanged: (value) async {
setState(() {
_enableHardwareDecoding = value;
});
await _settingsService.setEnableHardwareDecoding(value);
},
),
ListTile(
leading: const Icon(Icons.memory),
title: const Text('Video Buffer Size'),
subtitle: Text('${_videoBufferSize}MB'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showBufferSizeDialog(true),
),
ListTile(
leading: const Icon(Icons.audiotrack),
title: const Text('Audio Buffer Size'),
subtitle: Text('${_audioBufferSize}MB'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showBufferSizeDialog(false),
),
],
),
);
}
Widget _buildKeyboardShortcutsSection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Keyboard Shortcuts',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
ListTile(
leading: const Icon(Icons.keyboard),
title: const Text('Video Player Controls'),
subtitle: const Text('Customize keyboard shortcuts'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showKeyboardShortcutsDialog(),
),
],
),
);
}
Widget _buildAdvancedSection() {
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Advanced',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
),
SwitchListTile(
secondary: const Icon(Icons.bug_report),
title: const Text('Debug Logging'),
subtitle: const Text('Enable detailed logging for troubleshooting'),
value: _enableDebugLogging,
onChanged: (value) async {
setState(() {
_enableDebugLogging = value;
});
await _settingsService.setEnableDebugLogging(value);
},
),
ListTile(
leading: const Icon(Icons.cleaning_services),
title: const Text('Clear Cache'),
subtitle: const Text('Free up storage space'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showClearCacheDialog(),
),
ListTile(
leading: const Icon(Icons.restore),
title: const Text('Reset Settings'),
subtitle: const Text('Reset all settings to defaults'),
trailing: const Icon(Icons.chevron_right),
onTap: () => _showResetSettingsDialog(),
),
],
),
);
}
Widget _buildAboutSection() {
return Card(
child: ListTile(
leading: const Icon(Icons.info),
title: const Text('About'),
subtitle: const Text('App information and licenses'),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const AboutScreen()),
);
},
),
);
}
void _showThemeDialog(ThemeProvider themeProvider) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Theme'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: Icon(
themeProvider.themeMode == settings.ThemeMode.system
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('System'),
subtitle: const Text('Follow system settings'),
onTap: () {
themeProvider.setThemeMode(settings.ThemeMode.system);
Navigator.pop(context);
},
),
ListTile(
leading: Icon(
themeProvider.themeMode == settings.ThemeMode.light
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('Light'),
onTap: () {
themeProvider.setThemeMode(settings.ThemeMode.light);
Navigator.pop(context);
},
),
ListTile(
leading: Icon(
themeProvider.themeMode == settings.ThemeMode.dark
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: const Text('Dark'),
onTap: () {
themeProvider.setThemeMode(settings.ThemeMode.dark);
Navigator.pop(context);
},
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
],
);
},
);
}
void _showBufferSizeDialog(bool isVideo) {
final currentSize = isVideo ? _videoBufferSize : _audioBufferSize;
final title = isVideo ? 'Video Buffer Size' : 'Audio Buffer Size';
final options = isVideo ? [16, 32, 64, 128, 256] : [2, 4, 8, 16, 32];
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
content: Column(
mainAxisSize: MainAxisSize.min,
children: options.map((size) {
return ListTile(
leading: Icon(
currentSize == size
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
),
title: Text('${size}MB'),
onTap: () {
setState(() {
if (isVideo) {
_videoBufferSize = size;
_settingsService.setVideoBufferSize(size);
} else {
_audioBufferSize = size;
_settingsService.setAudioBufferSize(size);
}
});
Navigator.pop(context);
},
);
}).toList(),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
],
);
},
);
}
void _showKeyboardShortcutsDialog() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => _KeyboardShortcutsScreen(
keyboardService: _keyboardService,
),
),
);
}
void _showClearCacheDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Clear Cache'),
content: const Text(
'This will clear all cached images and data. The app may take longer to load content after clearing the cache.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
TextButton(
onPressed: () async {
final navigator = Navigator.of(context);
final messenger = ScaffoldMessenger.of(context);
await _settingsService.clearCache();
if (mounted) {
navigator.pop();
messenger.showSnackBar(
const SnackBar(content: Text('Cache cleared successfully')),
);
}
},
child: const Text('Clear'),
),
],
);
},
);
}
void _showResetSettingsDialog() {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Reset Settings'),
content: const Text(
'This will reset all settings to their default values. This action cannot be undone.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
TextButton(
onPressed: () async {
final navigator = Navigator.of(context);
final messenger = ScaffoldMessenger.of(context);
await _settingsService.resetAllSettings();
await _keyboardService.resetToDefaults();
if (mounted) {
navigator.pop();
messenger.showSnackBar(
const SnackBar(content: Text('Settings reset successfully')),
);
// Reload settings
_loadSettings();
}
},
child: const Text('Reset'),
),
],
);
},
);
}
}
class _KeyboardShortcutsScreen extends StatefulWidget {
final KeyboardShortcutsService keyboardService;
const _KeyboardShortcutsScreen({required this.keyboardService});
@override
State<_KeyboardShortcutsScreen> createState() => _KeyboardShortcutsScreenState();
}
class _KeyboardShortcutsScreenState extends State<_KeyboardShortcutsScreen> {
Map<String, HotKey> _hotkeys = {};
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadHotkeys();
}
Future<void> _loadHotkeys() async {
await widget.keyboardService.refreshFromStorage();
setState(() {
_hotkeys = widget.keyboardService.hotkeys;
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
return Scaffold(
body: CustomScrollView(
slivers: [
CustomAppBar(
title: const Text('Keyboard Shortcuts'),
pinned: true,
actions: [
TextButton(
onPressed: () async {
final messenger = ScaffoldMessenger.of(context);
await widget.keyboardService.resetToDefaults();
await _loadHotkeys();
if (mounted) {
messenger.showSnackBar(
const SnackBar(content: Text('Shortcuts reset to defaults')),
);
}
},
child: const Text('Reset'),
),
],
),
SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
final actions = _hotkeys.keys.toList();
final action = actions[index];
final hotkey = _hotkeys[action]!;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
title: Text(widget.keyboardService.getActionDisplayName(action)),
subtitle: Text(action),
trailing: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
border: Border.all(color: Theme.of(context).dividerColor),
borderRadius: BorderRadius.circular(6),
),
child: Text(
widget.keyboardService.formatHotkey(hotkey),
style: const TextStyle(fontFamily: 'monospace'),
),
),
onTap: () => _editHotkey(action, hotkey),
),
);
},
childCount: _hotkeys.length,
),
),
),
],
),
);
}
void _editHotkey(String action, HotKey currentHotkey) {
showDialog(
context: context,
builder: (BuildContext context) {
return HotKeyRecorderWidget(
actionName: widget.keyboardService.getActionDisplayName(action),
currentHotKey: currentHotkey,
onHotKeyRecorded: (newHotkey) async {
final navigator = Navigator.of(context);
final messenger = ScaffoldMessenger.of(context);
// Check for conflicts
final existingAction = widget.keyboardService.getActionForHotkey(newHotkey);
if (existingAction != null && existingAction != action) {
navigator.pop();
messenger.showSnackBar(
SnackBar(
content: Text('Shortcut already assigned to ${widget.keyboardService.getActionDisplayName(existingAction)}'),
),
);
return;
}
// Save the new hotkey
await widget.keyboardService.setHotkey(action, newHotkey);
if (mounted) {
// Update UI directly instead of reloading from storage
setState(() {
_hotkeys[action] = newHotkey;
});
navigator.pop();
messenger.showSnackBar(
SnackBar(
content: Text('Shortcut updated for ${widget.keyboardService.getActionDisplayName(action)}'),
),
);
}
},
onCancel: () => Navigator.pop(context),
);
},
);
}
}
+30 -14
View File
@@ -3,15 +3,15 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../utils/provider_extensions.dart';
import '../widgets/plex_video_controls.dart';
import '../utils/language_codes.dart';
import '../utils/app_logger.dart';
class VideoPlayerScreen extends StatefulWidget {
final PlexClient client;
final PlexMetadata metadata;
final AudioTrack? preferredAudioTrack;
final SubtitleTrack? preferredSubtitleTrack;
@@ -20,7 +20,6 @@ class VideoPlayerScreen extends StatefulWidget {
const VideoPlayerScreen({
super.key,
required this.client,
required this.metadata,
this.preferredAudioTrack,
this.preferredSubtitleTrack,
@@ -40,6 +39,7 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
PlexMetadata? _previousEpisode;
bool _isLoadingNext = false;
bool _showPlayNextDialog = false;
PlexClientProvider? _cachedClientProvider;
@override
void initState() {
@@ -87,6 +87,15 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Cache provider reference for safe access in dispose()
try {
_cachedClientProvider = context.plexClient;
} catch (e) {
appLogger.w('Failed to cache PlexClientProvider', error: e);
_cachedClientProvider = null;
}
// Ensure landscape orientation is set even after navigation
_setLandscapeOrientation();
}
@@ -105,11 +114,12 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
}
try {
final next = await widget.client.findAdjacentEpisode(widget.metadata, 1);
final previous = await widget.client.findAdjacentEpisode(
widget.metadata,
-1,
);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final next = await client.findAdjacentEpisode(widget.metadata, 1);
final previous = await client.findAdjacentEpisode(widget.metadata, -1);
if (mounted) {
setState(() {
@@ -124,10 +134,14 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
Future<void> _startPlayback() async {
try {
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) {
throw Exception('No client available');
}
// Get the direct file URL from the server
final videoUrl = await widget.client.getVideoUrl(
widget.metadata.ratingKey,
);
final videoUrl = await client.getVideoUrl(widget.metadata.ratingKey);
if (videoUrl != null) {
// Open video without auto-playing
@@ -593,7 +607,11 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
final duration = player.state.duration.inMilliseconds;
if (duration > 0) {
widget.client
final clientProvider = _cachedClientProvider;
final client = clientProvider?.client;
if (client == null) return;
client
.updateProgress(
widget.metadata.ratingKey,
time: position,
@@ -648,7 +666,6 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) =>
VideoPlayerScreen(
client: widget.client,
metadata: episodeMetadata,
preferredAudioTrack: currentAudioTrack,
preferredSubtitleTrack: currentSubtitleTrack,
@@ -676,7 +693,6 @@ class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
controller: controller,
controls: (state) => plexVideoControlsBuilder(
player,
widget.client,
widget.metadata,
onNext: _nextEpisode != null ? _playNext : null,
onPrevious: _previousEpisode != null ? _playPrevious : null,
@@ -0,0 +1,371 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
import 'settings_service.dart';
class KeyboardShortcutsService {
static KeyboardShortcutsService? _instance;
late SettingsService _settingsService;
Map<String, String> _shortcuts = {}; // Legacy string shortcuts for backward compatibility
Map<String, HotKey> _hotkeys = {}; // New HotKey objects
KeyboardShortcutsService._();
static Future<KeyboardShortcutsService> getInstance() async {
if (_instance == null) {
_instance = KeyboardShortcutsService._();
await _instance!._init();
}
return _instance!;
}
Future<void> _init() async {
_settingsService = await SettingsService.getInstance();
// Ensure settings service is fully initialized before loading data
await Future.delayed(Duration.zero); // Allow event loop to complete
_shortcuts = _settingsService.getKeyboardShortcuts(); // Keep for legacy compatibility
_hotkeys = await _settingsService.getKeyboardHotkeys(); // Primary method
}
Map<String, String> get shortcuts => Map.from(_shortcuts);
Map<String, HotKey> get hotkeys => Map.from(_hotkeys);
String getShortcut(String action) {
return _shortcuts[action] ?? '';
}
HotKey? getHotkey(String action) {
return _hotkeys[action];
}
Future<void> setShortcut(String action, String key) async {
_shortcuts[action] = key;
await _settingsService.setKeyboardShortcuts(_shortcuts);
}
Future<void> setHotkey(String action, HotKey hotkey) async {
// Update local cache first
_hotkeys[action] = hotkey;
// Save to persistent storage
await _settingsService.setKeyboardHotkey(action, hotkey);
// Verify local cache is still correct
if (_hotkeys[action] != hotkey) {
_hotkeys[action] = hotkey; // Restore correct value
}
}
Future<void> refreshFromStorage() async {
_hotkeys = await _settingsService.getKeyboardHotkeys();
}
Future<void> resetToDefaults() async {
_shortcuts = _settingsService.getDefaultKeyboardShortcuts();
_hotkeys = _settingsService.getDefaultKeyboardHotkeys();
await _settingsService.setKeyboardShortcuts(_shortcuts);
await _settingsService.setKeyboardHotkeys(_hotkeys);
// Refresh cache to ensure consistency
await refreshFromStorage();
}
// Format HotKey for display
String formatHotkey(HotKey? hotKey) {
if (hotKey == null) return 'No shortcut set';
final modifiers = <String>[];
for (final modifier in hotKey.modifiers ?? []) {
switch (modifier) {
case HotKeyModifier.alt:
modifiers.add('Alt');
break;
case HotKeyModifier.control:
modifiers.add('Ctrl');
break;
case HotKeyModifier.shift:
modifiers.add('Shift');
break;
case HotKeyModifier.meta:
modifiers.add('Meta');
break;
case HotKeyModifier.capsLock:
modifiers.add('CapsLock');
break;
case HotKeyModifier.fn:
modifiers.add('Fn');
break;
}
}
// Format the key name
String keyName = hotKey.key.keyLabel;
if (keyName.startsWith('PhysicalKeyboardKey#')) {
keyName = keyName.substring(20, keyName.length - 1);
}
if (keyName.startsWith('key')) {
keyName = keyName.substring(3).toUpperCase();
}
// Special cases for common keys
switch (keyName.toLowerCase()) {
case 'space':
keyName = 'Space';
break;
case 'arrowup':
keyName = 'Arrow Up';
break;
case 'arrowdown':
keyName = 'Arrow Down';
break;
case 'arrowleft':
keyName = 'Arrow Left';
break;
case 'arrowright':
keyName = 'Arrow Right';
break;
case 'equal':
keyName = 'Plus';
break;
case 'minus':
keyName = 'Minus';
break;
}
return modifiers.isEmpty ? keyName : '${modifiers.join(' + ')} + $keyName';
}
// Handle keyboard input for video player
KeyEventResult handleVideoPlayerKeyEvent(
KeyEvent event,
Player player,
VoidCallback? onToggleFullscreen,
VoidCallback? onToggleSubtitles,
VoidCallback? onNextAudioTrack,
VoidCallback? onNextSubtitleTrack,
VoidCallback? onNextChapter,
VoidCallback? onPreviousChapter,
) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
final physicalKey = event.physicalKey;
final isShiftPressed = HardwareKeyboard.instance.isShiftPressed;
final isControlPressed = HardwareKeyboard.instance.isControlPressed;
final isAltPressed = HardwareKeyboard.instance.isAltPressed;
final isMetaPressed = HardwareKeyboard.instance.isMetaPressed;
// Check each hotkey
for (final entry in _hotkeys.entries) {
final action = entry.key;
final hotkey = entry.value;
// Check if the physical key matches
if (physicalKey != hotkey.key) continue;
// Check if modifiers match
final requiredModifiers = hotkey.modifiers ?? [];
bool modifiersMatch = true;
// Check each required modifier
for (final modifier in requiredModifiers) {
switch (modifier) {
case HotKeyModifier.shift:
if (!isShiftPressed) modifiersMatch = false;
break;
case HotKeyModifier.control:
if (!isControlPressed) modifiersMatch = false;
break;
case HotKeyModifier.alt:
if (!isAltPressed) modifiersMatch = false;
break;
case HotKeyModifier.meta:
if (!isMetaPressed) modifiersMatch = false;
break;
case HotKeyModifier.capsLock:
// CapsLock is typically not used for shortcuts, ignore for now
break;
case HotKeyModifier.fn:
// Fn key is typically not used for shortcuts, ignore for now
break;
}
if (!modifiersMatch) break;
}
// Check that no extra modifiers are pressed
if (modifiersMatch) {
final hasShift = requiredModifiers.contains(HotKeyModifier.shift);
final hasControl = requiredModifiers.contains(HotKeyModifier.control);
final hasAlt = requiredModifiers.contains(HotKeyModifier.alt);
final hasMeta = requiredModifiers.contains(HotKeyModifier.meta);
if (isShiftPressed != hasShift ||
isControlPressed != hasControl ||
isAltPressed != hasAlt ||
isMetaPressed != hasMeta) {
continue;
}
_executeAction(action, player, onToggleFullscreen, onToggleSubtitles,
onNextAudioTrack, onNextSubtitleTrack, onNextChapter, onPreviousChapter);
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
void _executeAction(
String action,
Player player,
VoidCallback? onToggleFullscreen,
VoidCallback? onToggleSubtitles,
VoidCallback? onNextAudioTrack,
VoidCallback? onNextSubtitleTrack,
VoidCallback? onNextChapter,
VoidCallback? onPreviousChapter,
) {
switch (action) {
case 'play_pause':
player.playOrPause();
break;
case 'volume_up':
final newVolume = (player.state.volume + 10).clamp(0.0, 100.0);
player.setVolume(newVolume);
break;
case 'volume_down':
final newVolume = (player.state.volume - 10).clamp(0.0, 100.0);
player.setVolume(newVolume);
break;
case 'seek_forward':
final newPosition = player.state.position + const Duration(seconds: 10);
player.seek(newPosition);
break;
case 'seek_backward':
final newPosition = player.state.position - const Duration(seconds: 10);
player.seek(newPosition.isNegative ? Duration.zero : newPosition);
break;
case 'seek_forward_large':
final newPosition = player.state.position + const Duration(seconds: 30);
player.seek(newPosition);
break;
case 'seek_backward_large':
final newPosition = player.state.position - const Duration(seconds: 30);
player.seek(newPosition.isNegative ? Duration.zero : newPosition);
break;
case 'fullscreen_toggle':
onToggleFullscreen?.call();
break;
case 'mute_toggle':
player.setVolume(player.state.volume > 0 ? 0.0 : 100.0);
break;
case 'subtitle_toggle':
onToggleSubtitles?.call();
break;
case 'audio_track_next':
onNextAudioTrack?.call();
break;
case 'subtitle_track_next':
onNextSubtitleTrack?.call();
break;
case 'chapter_next':
onNextChapter?.call();
break;
case 'chapter_previous':
onPreviousChapter?.call();
break;
case 'speed_increase':
final newRate = (player.state.rate + 0.1).clamp(0.1, 3.0);
player.setRate(newRate);
break;
case 'speed_decrease':
final newRate = (player.state.rate - 0.1).clamp(0.1, 3.0);
player.setRate(newRate);
break;
case 'speed_reset':
player.setRate(1.0);
break;
}
}
// Get human-readable action names
String getActionDisplayName(String action) {
switch (action) {
case 'play_pause':
return 'Play/Pause';
case 'volume_up':
return 'Volume Up';
case 'volume_down':
return 'Volume Down';
case 'seek_forward':
return 'Seek Forward';
case 'seek_backward':
return 'Seek Backward';
case 'seek_forward_large':
return 'Seek Forward (Large)';
case 'seek_backward_large':
return 'Seek Backward (Large)';
case 'fullscreen_toggle':
return 'Toggle Fullscreen';
case 'mute_toggle':
return 'Toggle Mute';
case 'subtitle_toggle':
return 'Toggle Subtitles';
case 'audio_track_next':
return 'Next Audio Track';
case 'subtitle_track_next':
return 'Next Subtitle Track';
case 'chapter_next':
return 'Next Chapter';
case 'chapter_previous':
return 'Previous Chapter';
case 'speed_increase':
return 'Increase Speed';
case 'speed_decrease':
return 'Decrease Speed';
case 'speed_reset':
return 'Reset Speed';
default:
return action;
}
}
// Validate if a key combination is valid (legacy method for backward compatibility)
bool isValidKeyShortcut(String keyString) {
// For backward compatibility, assume all non-empty strings are valid
// The new system will use HotKey objects for validation
return keyString.isNotEmpty;
}
// Check if a shortcut is already assigned to another action
String? getActionForShortcut(String keyString) {
for (final entry in _shortcuts.entries) {
if (entry.value == keyString) {
return entry.key;
}
}
return null;
}
// Check if a hotkey is already assigned to another action
String? getActionForHotkey(HotKey hotkey) {
for (final entry in _hotkeys.entries) {
if (_hotkeyEquals(entry.value, hotkey)) {
return entry.key;
}
}
return null;
}
// Helper method to compare two HotKey objects
bool _hotkeyEquals(HotKey a, HotKey b) {
if (a.key != b.key) return false;
final aModifiers = Set.from(a.modifiers ?? []);
final bModifiers = Set.from(b.modifiers ?? []);
return aModifiers.length == bModifiers.length &&
aModifiers.every((modifier) => bModifiers.contains(modifier));
}
}
+48 -23
View File
@@ -4,6 +4,8 @@ import 'package:uuid/uuid.dart';
import 'storage_service.dart';
import '../client/plex_client.dart';
import '../models/plex_user_profile.dart';
import '../models/plex_home.dart';
import '../models/user_switch_response.dart';
class PlexAuthService {
static const String _appName = 'Plezy';
@@ -163,6 +165,52 @@ class PlexAuthService {
return PlexUserProfile.fromJson(response.data as Map<String, dynamic>);
}
/// Get home users for the authenticated user
Future<PlexHome> getHomeUsers(String authToken) async {
final response = await _dio.get(
'$_clientsApi/home/users',
options: _getCommonOptions(authToken: authToken),
);
return PlexHome.fromJson(response.data as Map<String, dynamic>);
}
/// Switch to a different user in the home
Future<UserSwitchResponse> switchToUser(
String userUUID,
String currentToken,
) async {
final queryParams = {
'includeSubscriptions': '1',
'includeProviders': '1',
'includeSettings': '1',
'includeSharedSettings': '1',
'X-Plex-Product': _appName,
'X-Plex-Version': '1.1.0',
'X-Plex-Client-Identifier': _clientIdentifier,
'X-Plex-Platform': 'Flutter',
'X-Plex-Platform-Version': '3.8.1',
'X-Plex-Token': currentToken,
'X-Plex-Language': 'en',
};
final queryString = queryParams.entries
.map(
(e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}',
)
.join('&');
final response = await _dio.post(
'$_clientsApi/home/users/$userUUID/switch?$queryString',
options: Options(
headers: {'Accept': 'application/json', 'Content-Length': '0'},
),
);
return UserSwitchResponse.fromJson(response.data as Map<String, dynamic>);
}
}
/// Represents a Plex Media Server
@@ -351,29 +399,6 @@ class PlexServer {
yield bestConnection;
}
}
/// Legacy method for backward compatibility - returns first working connection
/// For optimal performance, use findBestWorkingConnection() stream instead
@Deprecated('Use findBestWorkingConnection() stream for optimized connection')
Future<PlexConnection?> findBestWorkingConnectionLegacy() async {
if (connections.isEmpty) return null;
// Test all connections simultaneously
final working = <PlexConnection>[];
await Future.wait(
connections.map((connection) async {
final works = await PlexClient.testConnectionUrl(
connection.uri,
accessToken,
);
if (works) {
working.add(connection);
}
}),
);
return _selectBest(working);
}
}
/// Represents a connection to a Plex server
+534
View File
@@ -0,0 +1,534 @@
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
enum ThemeMode { system, light, dark }
class SettingsService {
static const String _keyThemeMode = 'theme_mode';
static const String _keyEnableDebugLogging = 'enable_debug_logging';
static const String _keyVideoBufferSize = 'video_buffer_size';
static const String _keyAudioBufferSize = 'audio_buffer_size';
static const String _keyKeyboardShortcuts = 'keyboard_shortcuts';
static const String _keyKeyboardHotkeys = 'keyboard_hotkeys';
static const String _keyEnableHardwareDecoding = 'enable_hardware_decoding';
static const String _keyPreferredVideoCodec = 'preferred_video_codec';
static const String _keyPreferredAudioCodec = 'preferred_audio_codec';
static SettingsService? _instance;
late SharedPreferences _prefs;
SettingsService._();
static Future<SettingsService> getInstance() async {
if (_instance == null) {
_instance = SettingsService._();
await _instance!._init();
}
return _instance!;
}
Future<void> _init() async {
_prefs = await SharedPreferences.getInstance();
}
// Theme Mode
Future<void> setThemeMode(ThemeMode mode) async {
await _prefs.setString(_keyThemeMode, mode.name);
}
ThemeMode getThemeMode() {
final modeString = _prefs.getString(_keyThemeMode);
return ThemeMode.values
.firstWhere((mode) => mode.name == modeString, orElse: () => ThemeMode.system);
}
// Debug Logging
Future<void> setEnableDebugLogging(bool enabled) async {
await _prefs.setBool(_keyEnableDebugLogging, enabled);
}
bool getEnableDebugLogging() {
return _prefs.getBool(_keyEnableDebugLogging) ?? false;
}
// Video Buffer Size (in MB)
Future<void> setVideoBufferSize(int sizeInMB) async {
await _prefs.setInt(_keyVideoBufferSize, sizeInMB);
}
int getVideoBufferSize() {
return _prefs.getInt(_keyVideoBufferSize) ?? 64; // Default 64MB
}
// Audio Buffer Size (in MB)
Future<void> setAudioBufferSize(int sizeInMB) async {
await _prefs.setInt(_keyAudioBufferSize, sizeInMB);
}
int getAudioBufferSize() {
return _prefs.getInt(_keyAudioBufferSize) ?? 8; // Default 8MB
}
// Hardware Decoding
Future<void> setEnableHardwareDecoding(bool enabled) async {
await _prefs.setBool(_keyEnableHardwareDecoding, enabled);
}
bool getEnableHardwareDecoding() {
return _prefs.getBool(_keyEnableHardwareDecoding) ?? true; // Default enabled
}
// Preferred Video Codec
Future<void> setPreferredVideoCodec(String codec) async {
await _prefs.setString(_keyPreferredVideoCodec, codec);
}
String getPreferredVideoCodec() {
return _prefs.getString(_keyPreferredVideoCodec) ?? 'auto';
}
// Preferred Audio Codec
Future<void> setPreferredAudioCodec(String codec) async {
await _prefs.setString(_keyPreferredAudioCodec, codec);
}
String getPreferredAudioCodec() {
return _prefs.getString(_keyPreferredAudioCodec) ?? 'auto';
}
// Keyboard Shortcuts (Legacy String-based)
Map<String, String> getDefaultKeyboardShortcuts() {
return {
'play_pause': 'Space',
'volume_up': 'Arrow Up',
'volume_down': 'Arrow Down',
'seek_forward': 'Arrow Right',
'seek_backward': 'Arrow Left',
'seek_forward_large': 'Shift+Arrow Right',
'seek_backward_large': 'Shift+Arrow Left',
'fullscreen_toggle': 'F',
'mute_toggle': 'M',
'subtitle_toggle': 'S',
'audio_track_next': 'A',
'subtitle_track_next': 'Shift+S',
'chapter_next': 'N',
'chapter_previous': 'P',
'speed_increase': 'Plus',
'speed_decrease': 'Minus',
'speed_reset': 'R',
};
}
// HotKey Objects (New implementation)
Map<String, HotKey> getDefaultKeyboardHotkeys() {
return {
'play_pause': HotKey(key: PhysicalKeyboardKey.space),
'volume_up': HotKey(key: PhysicalKeyboardKey.arrowUp),
'volume_down': HotKey(key: PhysicalKeyboardKey.arrowDown),
'seek_forward': HotKey(key: PhysicalKeyboardKey.arrowRight),
'seek_backward': HotKey(key: PhysicalKeyboardKey.arrowLeft),
'seek_forward_large': HotKey(key: PhysicalKeyboardKey.arrowRight, modifiers: [HotKeyModifier.shift]),
'seek_backward_large': HotKey(key: PhysicalKeyboardKey.arrowLeft, modifiers: [HotKeyModifier.shift]),
'fullscreen_toggle': HotKey(key: PhysicalKeyboardKey.keyF),
'mute_toggle': HotKey(key: PhysicalKeyboardKey.keyM),
'subtitle_toggle': HotKey(key: PhysicalKeyboardKey.keyS),
'audio_track_next': HotKey(key: PhysicalKeyboardKey.keyA),
'subtitle_track_next': HotKey(key: PhysicalKeyboardKey.keyS, modifiers: [HotKeyModifier.shift]),
'chapter_next': HotKey(key: PhysicalKeyboardKey.keyN),
'chapter_previous': HotKey(key: PhysicalKeyboardKey.keyP),
'speed_increase': HotKey(key: PhysicalKeyboardKey.equal),
'speed_decrease': HotKey(key: PhysicalKeyboardKey.minus),
'speed_reset': HotKey(key: PhysicalKeyboardKey.keyR),
};
}
Future<void> setKeyboardShortcuts(Map<String, String> shortcuts) async {
final jsonString = json.encode(shortcuts);
await _prefs.setString(_keyKeyboardShortcuts, jsonString);
}
Map<String, String> getKeyboardShortcuts() {
final jsonString = _prefs.getString(_keyKeyboardShortcuts);
if (jsonString == null) return getDefaultKeyboardShortcuts();
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
final shortcuts = decoded.map((key, value) => MapEntry(key, value.toString()));
// Merge with defaults to ensure all keys exist
final defaults = getDefaultKeyboardShortcuts();
defaults.addAll(shortcuts);
return defaults;
} catch (e) {
return getDefaultKeyboardShortcuts();
}
}
Future<void> setKeyboardShortcut(String action, String key) async {
final shortcuts = getKeyboardShortcuts();
shortcuts[action] = key;
await setKeyboardShortcuts(shortcuts);
}
String getKeyboardShortcut(String action) {
final shortcuts = getKeyboardShortcuts();
return shortcuts[action] ?? '';
}
Future<void> resetKeyboardShortcuts() async {
await setKeyboardShortcuts(getDefaultKeyboardShortcuts());
}
// HotKey Objects Methods
Future<void> setKeyboardHotkeys(Map<String, HotKey> hotkeys) async {
final Map<String, Map<String, dynamic>> serializedHotkeys = {};
for (final entry in hotkeys.entries) {
serializedHotkeys[entry.key] = _serializeHotKey(entry.value);
}
final jsonString = json.encode(serializedHotkeys);
await _prefs.setString(_keyKeyboardHotkeys, jsonString);
}
Future<Map<String, HotKey>> getKeyboardHotkeys() async {
final jsonString = _prefs.getString(_keyKeyboardHotkeys);
if (jsonString == null) {
return getDefaultKeyboardHotkeys();
}
try {
final decoded = json.decode(jsonString) as Map<String, dynamic>;
final Map<String, HotKey> hotkeys = {};
for (final entry in decoded.entries) {
final hotKey = _deserializeHotKey(entry.value as Map<String, dynamic>);
if (hotKey != null) {
hotkeys[entry.key] = hotKey;
}
}
// Merge with defaults to ensure all keys exist, but keep saved hotkeys priority
final defaults = getDefaultKeyboardHotkeys();
final result = <String, HotKey>{};
// Start with defaults
result.addAll(defaults);
// Override with saved hotkeys (this preserves user customizations)
result.addAll(hotkeys);
return result;
} catch (e) {
return getDefaultKeyboardHotkeys();
}
}
Future<void> setKeyboardHotkey(String action, HotKey hotKey) async {
final hotkeys = await getKeyboardHotkeys();
hotkeys[action] = hotKey;
await setKeyboardHotkeys(hotkeys);
}
Future<HotKey?> getKeyboardHotkey(String action) async {
final hotkeys = await getKeyboardHotkeys();
return hotkeys[action];
}
Future<void> resetKeyboardHotkeys() async {
await setKeyboardHotkeys(getDefaultKeyboardHotkeys());
}
// Helper methods for HotKey serialization
Map<String, dynamic> _serializeHotKey(HotKey hotKey) {
return {
'key': hotKey.key.toString(),
'modifiers': hotKey.modifiers?.map((m) => m.name).toList() ?? [],
};
}
HotKey? _deserializeHotKey(Map<String, dynamic> data) {
try {
final keyString = data['key'] as String;
final modifierNames = (data['modifiers'] as List<dynamic>).cast<String>();
final modifiers = modifierNames.map((name) {
switch (name) {
case 'alt':
return HotKeyModifier.alt;
case 'control':
return HotKeyModifier.control;
case 'shift':
return HotKeyModifier.shift;
case 'meta':
return HotKeyModifier.meta;
case 'capsLock':
return HotKeyModifier.capsLock;
case 'fn':
return HotKeyModifier.fn;
default:
return null;
}
}).where((m) => m != null).cast<HotKeyModifier>().toList();
final key = _findKeyByString(keyString);
if (key != null) {
return HotKey(key: key, modifiers: modifiers.isNotEmpty ? modifiers : null);
}
} catch (e) {
// Ignore deserialization errors
}
return null;
}
// Helper method to find PhysicalKeyboardKey by string representation
PhysicalKeyboardKey? _findKeyByString(String keyString) {
// Handle exact string matches first for better performance
const keyMap = {
'PhysicalKeyboardKey#0002c': PhysicalKeyboardKey.space,
'PhysicalKeyboardKey#7002a': PhysicalKeyboardKey.backspace,
'PhysicalKeyboardKey#7004c': PhysicalKeyboardKey.delete,
'PhysicalKeyboardKey#70028': PhysicalKeyboardKey.enter,
'PhysicalKeyboardKey#70029': PhysicalKeyboardKey.escape,
'PhysicalKeyboardKey#7002b': PhysicalKeyboardKey.tab,
'PhysicalKeyboardKey#7004a': PhysicalKeyboardKey.home,
'PhysicalKeyboardKey#7004d': PhysicalKeyboardKey.end,
'PhysicalKeyboardKey#7004b': PhysicalKeyboardKey.pageUp,
'PhysicalKeyboardKey#7004e': PhysicalKeyboardKey.pageDown,
'PhysicalKeyboardKey#70050': PhysicalKeyboardKey.arrowLeft,
'PhysicalKeyboardKey#70052': PhysicalKeyboardKey.arrowUp,
'PhysicalKeyboardKey#7004f': PhysicalKeyboardKey.arrowRight,
'PhysicalKeyboardKey#70051': PhysicalKeyboardKey.arrowDown,
};
// Check exact matches first
if (keyMap.containsKey(keyString)) {
return keyMap[keyString];
}
// Alternative approach: extract USB HID usage code from the toString() output
// Format: PhysicalKeyboardKey#ec9ed(usbHidUsage: "0x0007002c", debugName: "Space")
try {
final usbHidMatch = RegExp(r'usbHidUsage: "0x([0-9a-fA-F]+)"').firstMatch(keyString);
if (usbHidMatch != null) {
final usbHidCode = usbHidMatch.group(1)!.toLowerCase();
// Map USB HID codes to PhysicalKeyboardKey objects
const usbHidMap = {
'0007002c': PhysicalKeyboardKey.space,
'0007002a': PhysicalKeyboardKey.backspace,
'0007004c': PhysicalKeyboardKey.delete,
'00070028': PhysicalKeyboardKey.enter,
'00070029': PhysicalKeyboardKey.escape,
'0007002b': PhysicalKeyboardKey.tab,
'00070039': PhysicalKeyboardKey.capsLock,
// Function keys
'0007003a': PhysicalKeyboardKey.f1,
'0007003b': PhysicalKeyboardKey.f2,
'0007003c': PhysicalKeyboardKey.f3,
'0007003d': PhysicalKeyboardKey.f4,
'0007003e': PhysicalKeyboardKey.f5,
'0007003f': PhysicalKeyboardKey.f6,
'00070040': PhysicalKeyboardKey.f7,
'00070041': PhysicalKeyboardKey.f8,
'00070042': PhysicalKeyboardKey.f9,
'00070043': PhysicalKeyboardKey.f10,
'00070044': PhysicalKeyboardKey.f11,
'00070045': PhysicalKeyboardKey.f12,
// Number keys
'00070027': PhysicalKeyboardKey.digit0,
'0007001e': PhysicalKeyboardKey.digit1,
'0007001f': PhysicalKeyboardKey.digit2,
'00070020': PhysicalKeyboardKey.digit3,
'00070021': PhysicalKeyboardKey.digit4,
'00070022': PhysicalKeyboardKey.digit5,
'00070023': PhysicalKeyboardKey.digit6,
'00070024': PhysicalKeyboardKey.digit7,
'00070025': PhysicalKeyboardKey.digit8,
'00070026': PhysicalKeyboardKey.digit9,
// Letter keys
'00070004': PhysicalKeyboardKey.keyA,
'00070005': PhysicalKeyboardKey.keyB,
'00070006': PhysicalKeyboardKey.keyC,
'00070007': PhysicalKeyboardKey.keyD,
'00070008': PhysicalKeyboardKey.keyE,
'00070009': PhysicalKeyboardKey.keyF,
'0007000a': PhysicalKeyboardKey.keyG,
'0007000b': PhysicalKeyboardKey.keyH,
'0007000c': PhysicalKeyboardKey.keyI,
'0007000d': PhysicalKeyboardKey.keyJ,
'0007000e': PhysicalKeyboardKey.keyK,
'0007000f': PhysicalKeyboardKey.keyL,
'00070010': PhysicalKeyboardKey.keyM,
'00070011': PhysicalKeyboardKey.keyN,
'00070012': PhysicalKeyboardKey.keyO,
'00070013': PhysicalKeyboardKey.keyP,
'00070014': PhysicalKeyboardKey.keyQ,
'00070015': PhysicalKeyboardKey.keyR,
'00070016': PhysicalKeyboardKey.keyS,
'00070017': PhysicalKeyboardKey.keyT,
'00070018': PhysicalKeyboardKey.keyU,
'00070019': PhysicalKeyboardKey.keyV,
'0007001a': PhysicalKeyboardKey.keyW,
'0007001b': PhysicalKeyboardKey.keyX,
'0007001c': PhysicalKeyboardKey.keyY,
'0007001d': PhysicalKeyboardKey.keyZ,
// Arrow keys
'00070050': PhysicalKeyboardKey.arrowLeft,
'00070052': PhysicalKeyboardKey.arrowUp,
'0007004f': PhysicalKeyboardKey.arrowRight,
'00070051': PhysicalKeyboardKey.arrowDown,
// Other common keys
'0007002d': PhysicalKeyboardKey.equal,
'0007002e': PhysicalKeyboardKey.minus,
'0007004a': PhysicalKeyboardKey.home,
'0007004d': PhysicalKeyboardKey.end,
'0007004b': PhysicalKeyboardKey.pageUp,
'0007004e': PhysicalKeyboardKey.pageDown,
};
if (usbHidMap.containsKey(usbHidCode)) {
return usbHidMap[usbHidCode];
}
}
} catch (e) {
// Ignore parsing errors
}
// Fall back to contains() checks for partial matches
if (keyString.contains('space')) {
return PhysicalKeyboardKey.space;
} else if (keyString.contains('arrowUp')) {
return PhysicalKeyboardKey.arrowUp;
} else if (keyString.contains('arrowDown')) {
return PhysicalKeyboardKey.arrowDown;
} else if (keyString.contains('arrowLeft')) {
return PhysicalKeyboardKey.arrowLeft;
} else if (keyString.contains('arrowRight')) {
return PhysicalKeyboardKey.arrowRight;
} else if (keyString.contains('equal')) {
return PhysicalKeyboardKey.equal;
} else if (keyString.contains('minus')) {
return PhysicalKeyboardKey.minus;
} else if (keyString.contains('escape')) {
return PhysicalKeyboardKey.escape;
} else if (keyString.contains('enter')) {
return PhysicalKeyboardKey.enter;
} else if (keyString.contains('tab')) {
return PhysicalKeyboardKey.tab;
} else if (keyString.contains('backspace')) {
return PhysicalKeyboardKey.backspace;
} else if (keyString.contains('delete')) {
return PhysicalKeyboardKey.delete;
} else if (keyString.contains('home')) {
return PhysicalKeyboardKey.home;
} else if (keyString.contains('end')) {
return PhysicalKeyboardKey.end;
} else if (keyString.contains('pageUp')) {
return PhysicalKeyboardKey.pageUp;
} else if (keyString.contains('pageDown')) {
return PhysicalKeyboardKey.pageDown;
} else {
// Try function keys F1-F12
for (int i = 1; i <= 12; i++) {
if (keyString.contains('f$i') || keyString.contains('F$i')) {
switch (i) {
case 1: return PhysicalKeyboardKey.f1;
case 2: return PhysicalKeyboardKey.f2;
case 3: return PhysicalKeyboardKey.f3;
case 4: return PhysicalKeyboardKey.f4;
case 5: return PhysicalKeyboardKey.f5;
case 6: return PhysicalKeyboardKey.f6;
case 7: return PhysicalKeyboardKey.f7;
case 8: return PhysicalKeyboardKey.f8;
case 9: return PhysicalKeyboardKey.f9;
case 10: return PhysicalKeyboardKey.f10;
case 11: return PhysicalKeyboardKey.f11;
case 12: return PhysicalKeyboardKey.f12;
}
}
}
// Try number keys 0-9
for (int i = 0; i <= 9; i++) {
if (keyString.contains('digit$i') || keyString.contains('Digit$i')) {
switch (i) {
case 0: return PhysicalKeyboardKey.digit0;
case 1: return PhysicalKeyboardKey.digit1;
case 2: return PhysicalKeyboardKey.digit2;
case 3: return PhysicalKeyboardKey.digit3;
case 4: return PhysicalKeyboardKey.digit4;
case 5: return PhysicalKeyboardKey.digit5;
case 6: return PhysicalKeyboardKey.digit6;
case 7: return PhysicalKeyboardKey.digit7;
case 8: return PhysicalKeyboardKey.digit8;
case 9: return PhysicalKeyboardKey.digit9;
}
}
}
// Try letter keys A-Z (both upper and lower case patterns)
const letterKeys = {
'A': PhysicalKeyboardKey.keyA, 'B': PhysicalKeyboardKey.keyB, 'C': PhysicalKeyboardKey.keyC,
'D': PhysicalKeyboardKey.keyD, 'E': PhysicalKeyboardKey.keyE, 'F': PhysicalKeyboardKey.keyF,
'G': PhysicalKeyboardKey.keyG, 'H': PhysicalKeyboardKey.keyH, 'I': PhysicalKeyboardKey.keyI,
'J': PhysicalKeyboardKey.keyJ, 'K': PhysicalKeyboardKey.keyK, 'L': PhysicalKeyboardKey.keyL,
'M': PhysicalKeyboardKey.keyM, 'N': PhysicalKeyboardKey.keyN, 'O': PhysicalKeyboardKey.keyO,
'P': PhysicalKeyboardKey.keyP, 'Q': PhysicalKeyboardKey.keyQ, 'R': PhysicalKeyboardKey.keyR,
'S': PhysicalKeyboardKey.keyS, 'T': PhysicalKeyboardKey.keyT, 'U': PhysicalKeyboardKey.keyU,
'V': PhysicalKeyboardKey.keyV, 'W': PhysicalKeyboardKey.keyW, 'X': PhysicalKeyboardKey.keyX,
'Y': PhysicalKeyboardKey.keyY, 'Z': PhysicalKeyboardKey.keyZ,
};
for (final entry in letterKeys.entries) {
if (keyString.contains('key${entry.key}') || keyString.contains('Key${entry.key}')) {
return entry.value;
}
}
return null;
}
}
// Reset all settings to defaults
Future<void> resetAllSettings() async {
await Future.wait([
_prefs.remove(_keyThemeMode),
_prefs.remove(_keyEnableDebugLogging),
_prefs.remove(_keyVideoBufferSize),
_prefs.remove(_keyAudioBufferSize),
_prefs.remove(_keyKeyboardShortcuts),
_prefs.remove(_keyKeyboardHotkeys),
_prefs.remove(_keyEnableHardwareDecoding),
_prefs.remove(_keyPreferredVideoCodec),
_prefs.remove(_keyPreferredAudioCodec),
]);
}
// Clear cache (for storage cleanup)
Future<void> clearCache() async {
// This would be expanded to clear various cache directories
// For now, we'll just clear any cache-related preferences
await Future.wait([
// Add cache clearing logic here
]);
}
// Get all settings as a map for debugging/export
Future<Map<String, dynamic>> getAllSettings() async {
final hotkeys = await getKeyboardHotkeys();
return {
'themeMode': getThemeMode().name,
'enableDebugLogging': getEnableDebugLogging(),
'videoBufferSize': getVideoBufferSize(),
'audioBufferSize': getAudioBufferSize(),
'enableHardwareDecoding': getEnableHardwareDecoding(),
'preferredVideoCodec': getPreferredVideoCodec(),
'preferredAudioCodec': getPreferredAudioCodec(),
'keyboardShortcuts': getKeyboardShortcuts(),
'keyboardHotkeys': hotkeys.map((key, value) => MapEntry(key, _serializeHotKey(value))),
};
}
}
+73
View File
@@ -10,6 +10,9 @@ class StorageService {
static const String _keySelectedLibraryIndex = 'selected_library_index';
static const String _keyLibraryFilters = 'library_filters';
static const String _keyUserProfile = 'user_profile';
static const String _keyCurrentUserUUID = 'current_user_uuid';
static const String _keyHomeUsersCache = 'home_users_cache';
static const String _keyHomeUsersCacheExpiry = 'home_users_cache_expiry';
static StorageService? _instance;
late SharedPreferences _prefs;
@@ -117,6 +120,9 @@ class StorageService {
_prefs.remove(_keyServerData),
_prefs.remove(_keyClientId),
_prefs.remove(_keyUserProfile),
_prefs.remove(_keyCurrentUserUUID),
_prefs.remove(_keyHomeUsersCache),
_prefs.remove(_keyHomeUsersCacheExpiry),
]);
}
@@ -180,4 +186,71 @@ class StorageService {
return null;
}
}
// Current User UUID
Future<void> saveCurrentUserUUID(String uuid) async {
await _prefs.setString(_keyCurrentUserUUID, uuid);
}
String? getCurrentUserUUID() {
return _prefs.getString(_keyCurrentUserUUID);
}
// Home Users Cache (stored as JSON string with expiry)
Future<void> saveHomeUsersCache(Map<String, dynamic> homeData) async {
final jsonString = json.encode(homeData);
await _prefs.setString(_keyHomeUsersCache, jsonString);
// Set cache expiry to 1 hour from now
final expiry = DateTime.now()
.add(const Duration(hours: 1))
.millisecondsSinceEpoch;
await _prefs.setInt(_keyHomeUsersCacheExpiry, expiry);
}
Map<String, dynamic>? getHomeUsersCache() {
final expiry = _prefs.getInt(_keyHomeUsersCacheExpiry);
if (expiry == null || DateTime.now().millisecondsSinceEpoch > expiry) {
// Cache expired, clear it
clearHomeUsersCache();
return null;
}
final jsonString = _prefs.getString(_keyHomeUsersCache);
if (jsonString == null) return null;
try {
return json.decode(jsonString) as Map<String, dynamic>;
} catch (e) {
return null;
}
}
Future<void> clearHomeUsersCache() async {
await Future.wait([
_prefs.remove(_keyHomeUsersCache),
_prefs.remove(_keyHomeUsersCacheExpiry),
]);
}
// Clear current user UUID (for server switching)
Future<void> clearCurrentUserUUID() async {
await _prefs.remove(_keyCurrentUserUUID);
}
// Clear all user-related data (for logout)
Future<void> clearUserData() async {
await Future.wait([
clearCredentials(),
clearLibraryPreferences(),
]);
}
// Update current user after switching
Future<void> updateCurrentUser(String userUUID, String authToken) async {
await Future.wait([
saveCurrentUserUUID(userUUID),
saveToken(authToken), // Update the main token
]);
}
}
+11 -2
View File
@@ -111,9 +111,18 @@ ThemeData monoTheme({required bool dark}) {
elevation: const WidgetStatePropertyAll(0),
backgroundColor: WidgetStatePropertyAll(c.text),
foregroundColor: WidgetStatePropertyAll(dark ? c.bg : Colors.white),
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
shape: const WidgetStatePropertyAll(StadiumBorder()),
),
),
filledButtonTheme: FilledButtonThemeData(
style: ButtonStyle(
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 18, vertical: 14),
),
elevation: const WidgetStatePropertyAll(0),
backgroundColor: WidgetStatePropertyAll(c.text),
foregroundColor: WidgetStatePropertyAll(dark ? c.bg : Colors.white),
shape: const WidgetStatePropertyAll(StadiumBorder()),
),
),
dividerTheme: DividerThemeData(space: 0, thickness: 1, color: c.outline),
+17 -5
View File
@@ -12,21 +12,33 @@ class DesktopWindowPadding {
/// Right padding for macOS to prevent actions from being too close to edge
static const double macOSRight = 16.0;
/// Right padding for mobile devices to prevent actions from being too close to edge
static const double mobileRight = 6.0;
}
/// Helper class for adjusting app bar widgets to account for desktop window controls
class DesktopAppBarHelper {
/// Builds actions list with appropriate right padding for macOS
/// Builds actions list with appropriate right padding for macOS and mobile
static List<Widget>? buildAdjustedActions(List<Widget>? actions) {
if (!Platform.isMacOS) {
double? rightPadding;
if (Platform.isMacOS) {
rightPadding = DesktopWindowPadding.macOSRight;
} else if (Platform.isIOS || Platform.isAndroid) {
rightPadding = DesktopWindowPadding.mobileRight;
}
// If no platform-specific padding needed, return original actions
if (rightPadding == null) {
return actions;
}
// macOS: Add padding to keep actions away from edge
// Add padding to keep actions away from edge
if (actions != null) {
return [...actions, SizedBox(width: DesktopWindowPadding.macOSRight)];
return [...actions, SizedBox(width: rightPadding)];
} else {
return [SizedBox(width: DesktopWindowPadding.macOSRight)];
return [SizedBox(width: rightPadding)];
}
}
-37
View File
@@ -1,37 +0,0 @@
/// Utility class for building Plex API headers
class PlexHeaders {
/// Standard Plex headers required for API requests
static const String plexClientIdentifier = 'X-Plex-Client-Identifier';
static const String plexProduct = 'X-Plex-Product';
static const String plexVersion = 'X-Plex-Version';
static const String plexToken = 'X-Plex-Token';
static const String plexPlatform = 'X-Plex-Platform';
static const String plexPlatformVersion = 'X-Plex-Platform-Version';
static const String plexDevice = 'X-Plex-Device';
/// Builds standard Plex headers with optional token
static Map<String, String> buildHeaders({
required String clientIdentifier,
String? token,
String product = 'Plezy',
String version = '1.0',
String platform = 'Flutter',
String platformVersion = '1.0',
String device = 'Mobile',
}) {
final headers = {
plexClientIdentifier: clientIdentifier,
plexProduct: product,
plexVersion: version,
plexPlatform: platform,
plexPlatformVersion: platformVersion,
plexDevice: device,
};
if (token != null) {
headers[plexToken] = token;
}
return headers;
}
}
+25
View File
@@ -0,0 +1,25 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/plex_client_provider.dart';
import '../providers/user_profile_provider.dart';
import '../client/plex_client.dart';
extension ProviderExtensions on BuildContext {
PlexClientProvider get plexClient =>
Provider.of<PlexClientProvider>(this, listen: false);
UserProfileProvider get userProfile =>
Provider.of<UserProfileProvider>(this, listen: false);
PlexClientProvider watchPlexClient() =>
Provider.of<PlexClientProvider>(this, listen: true);
UserProfileProvider watchUserProfile() =>
Provider.of<UserProfileProvider>(this, listen: true);
// Direct client access (nullable)
PlexClient? get client => plexClient.client;
// Null-safe client access
PlexClient get clientSafe => plexClient.client!;
}
+28
View File
@@ -0,0 +1,28 @@
import 'package:flutter/material.dart';
import '../models/plex_home_user.dart';
import 'provider_extensions.dart';
class UserSwitchingUtils {
static Future<bool> switchToUser(
BuildContext context,
PlexHomeUser user, {
bool popOnSuccess = false,
}) async {
final userProvider = context.userProfile;
final success = await userProvider.switchToUser(user, context);
if (success && context.mounted && popOnSuccess) {
Navigator.of(context).pop();
} else if (!success && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to switch to ${user.displayName}'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
}
return success;
}
}
+98 -44
View File
@@ -23,7 +23,7 @@ enum BackButtonStyle {
/// ```dart
/// AppBarBackButton(style: BackButtonStyle.circular)
/// ```
class AppBarBackButton extends StatelessWidget {
class AppBarBackButton extends StatefulWidget {
/// Creates a back button with the specified style.
///
/// [style] determines the visual appearance of the back button.
@@ -45,9 +45,44 @@ class AppBarBackButton extends StatelessWidget {
/// The color of the back arrow icon. If null, uses style-appropriate default.
final Color? color;
void _handlePressed(BuildContext context) {
if (onPressed != null) {
onPressed!();
@override
State<AppBarBackButton> createState() => _AppBarBackButtonState();
}
class _AppBarBackButtonState extends State<AppBarBackButton>
with TickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _backgroundAnimation;
@override
void initState() {
super.initState();
_animationController = AnimationController(
duration: const Duration(milliseconds: 150),
vsync: this,
);
_backgroundAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _onHoverChange(bool isHovered) {
if (isHovered) {
_animationController.forward();
} else {
_animationController.reverse();
}
}
void _handlePressed() {
if (widget.onPressed != null) {
widget.onPressed!();
} else {
Navigator.of(context).pop();
}
@@ -55,53 +90,72 @@ class AppBarBackButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
switch (style) {
case BackButtonStyle.circular:
return _buildCircularBackButton(context);
final theme = Theme.of(context);
final isDarkTheme = theme.brightness == Brightness.dark;
final Color effectiveColor;
switch (widget.style) {
case BackButtonStyle.plain:
return _buildPlainBackButton(context);
effectiveColor =
widget.color ?? (isDarkTheme ? Colors.white : Colors.black);
break;
case BackButtonStyle.circular:
case BackButtonStyle.video:
return _buildVideoBackButton(context);
effectiveColor = widget.color ?? Colors.white;
break;
}
}
/// Builds a back button with circular semi-transparent background
Widget _buildCircularBackButton(BuildContext context) {
return SafeArea(
child: Container(
margin: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
child: IconButton(
icon: Icon(Icons.arrow_back, color: color ?? Colors.white),
onPressed: () => _handlePressed(context),
padding: EdgeInsets.zero,
tooltip: 'Back',
final Color baseColor;
final Color hoverColor;
switch (widget.style) {
case BackButtonStyle.circular:
baseColor = Colors.black.withValues(alpha: 0.3);
hoverColor = Colors.black.withValues(alpha: 0.5);
break;
case BackButtonStyle.plain:
hoverColor = (isDarkTheme ? Colors.white : Colors.black).withValues(
alpha: 0.2,
);
baseColor = Colors.transparent;
break;
case BackButtonStyle.video:
baseColor = Colors.transparent;
hoverColor = Colors.black.withValues(alpha: 0.3);
break;
}
final button = MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) => _onHoverChange(true),
onExit: (_) => _onHoverChange(false),
child: GestureDetector(
onTap: _handlePressed,
child: AnimatedBuilder(
animation: _backgroundAnimation,
builder: (context, child) {
final currentColor = Color.lerp(
baseColor,
hoverColor,
_backgroundAnimation.value,
);
return Container(
margin: const EdgeInsets.all(8),
width: 40,
height: 40,
decoration: BoxDecoration(
color: currentColor,
shape: BoxShape.circle,
),
child: Icon(Icons.arrow_back, color: effectiveColor, size: 20),
);
},
),
),
);
}
/// Builds a plain back button without background
Widget _buildPlainBackButton(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back, color: color),
onPressed: () => _handlePressed(context),
tooltip: 'Back',
);
}
/// Builds a back button styled for video player overlay
Widget _buildVideoBackButton(BuildContext context) {
return Container(
margin: const EdgeInsets.only(left: 8),
child: IconButton(
icon: Icon(Icons.arrow_back, color: color ?? Colors.white),
onPressed: () => _handlePressed(context),
tooltip: 'Back',
),
);
return widget.style == BackButtonStyle.circular
? SafeArea(child: button)
: button;
}
}
+157 -4
View File
@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
import '../utils/desktop_window_padding.dart';
import '../services/fullscreen_state_manager.dart';
import 'app_bar_back_button.dart';
/// A custom app bar that automatically handles desktop window controls spacing.
/// Use this instead of AppBar for consistent desktop platform behavior.
@@ -91,20 +93,39 @@ class DesktopSliverAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Determine the effective leading widget
Widget? effectiveLeading = leading;
// If no leading is provided but automaticallyImplyLeading is true,
// create a back button manually so it goes through our padding logic
if (leading == null && automaticallyImplyLeading) {
final parentRoute = ModalRoute.of(context);
final canPop = parentRoute?.canPop ?? false;
if (canPop) {
effectiveLeading = IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(),
tooltip: MaterialLocalizations.of(context).backButtonTooltip,
);
}
}
return SliverAppBar(
title: title != null
? DesktopTitleBarPadding(
leftPadding: leading != null ? 0 : null,
leftPadding: effectiveLeading != null ? 0 : null,
child: title!,
)
: null,
actions: DesktopAppBarHelper.buildAdjustedActions(actions),
leading: DesktopAppBarHelper.buildAdjustedLeading(
leading,
effectiveLeading,
includeGestureDetector: true,
),
leadingWidth: DesktopAppBarHelper.calculateLeadingWidth(leading),
automaticallyImplyLeading: automaticallyImplyLeading,
leadingWidth: DesktopAppBarHelper.calculateLeadingWidth(effectiveLeading),
automaticallyImplyLeading:
false, // Always false since we handle it manually
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
@@ -120,3 +141,135 @@ class DesktopSliverAppBar extends StatelessWidget {
);
}
}
/// Convenient wrapper for DesktopAppBar with built-in back button handling
class PlexAppBar extends StatelessWidget implements PreferredSizeWidget {
final Widget? title;
final List<Widget>? actions;
final VoidCallback? onBackPressed;
final double? elevation;
final Color? backgroundColor;
final Color? surfaceTintColor;
final Color? shadowColor;
final double? scrolledUnderElevation;
const PlexAppBar({
super.key,
this.title,
this.actions,
this.onBackPressed,
this.elevation,
this.backgroundColor,
this.surfaceTintColor,
this.shadowColor,
this.scrolledUnderElevation,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
return DesktopAppBar(
key: ValueKey('plex_app_bar_$isFullscreen'),
title: title,
actions: actions,
leading: _shouldShowBackButton(context)
? AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: onBackPressed,
)
: null,
automaticallyImplyLeading: false,
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
scrolledUnderElevation: scrolledUnderElevation,
);
},
);
}
bool _shouldShowBackButton(BuildContext context) {
final parentRoute = ModalRoute.of(context);
return parentRoute?.canPop ?? false;
}
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
/// Convenient wrapper for DesktopSliverAppBar with built-in back button handling
class CustomAppBar extends StatelessWidget {
final Widget? title;
final List<Widget>? actions;
final VoidCallback? onBackPressed;
final double? elevation;
final Color? backgroundColor;
final Color? surfaceTintColor;
final Color? shadowColor;
final double? scrolledUnderElevation;
final bool floating;
final bool pinned;
final double? expandedHeight;
final Widget? flexibleSpace;
final PreferredSizeWidget? bottom;
const CustomAppBar({
super.key,
this.title,
this.actions,
this.onBackPressed,
this.elevation,
this.backgroundColor,
this.surfaceTintColor,
this.shadowColor,
this.scrolledUnderElevation,
this.floating = false,
this.pinned = false,
this.expandedHeight,
this.flexibleSpace,
this.bottom,
});
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: FullscreenStateManager(),
builder: (context, _) {
final isFullscreen = FullscreenStateManager().isFullscreen;
return DesktopSliverAppBar(
key: ValueKey('plex_sliver_app_bar_$isFullscreen'),
title: title,
actions: actions,
leading: _shouldShowBackButton(context)
? AppBarBackButton(
style: BackButtonStyle.plain,
onPressed: onBackPressed,
)
: null,
automaticallyImplyLeading: false,
elevation: elevation,
backgroundColor: backgroundColor,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
scrolledUnderElevation: scrolledUnderElevation,
floating: floating,
pinned: pinned,
expandedHeight: expandedHeight,
flexibleSpace: flexibleSpace,
bottom: bottom,
);
},
);
}
bool _shouldShowBackButton(BuildContext context) {
final parentRoute = ModalRoute.of(context);
return parentRoute?.canPop ?? false;
}
}
+115
View File
@@ -0,0 +1,115 @@
import 'package:flutter/material.dart';
import 'package:hotkey_manager/hotkey_manager.dart';
class HotKeyRecorderWidget extends StatefulWidget {
final String actionName;
final HotKey? currentHotKey;
final Function(HotKey) onHotKeyRecorded;
final VoidCallback onCancel;
const HotKeyRecorderWidget({
super.key,
required this.actionName,
this.currentHotKey,
required this.onHotKeyRecorded,
required this.onCancel,
});
@override
State<HotKeyRecorderWidget> createState() => _HotKeyRecorderWidgetState();
}
class _HotKeyRecorderWidgetState extends State<HotKeyRecorderWidget> {
HotKey? _recordedHotKey;
@override
void initState() {
super.initState();
_recordedHotKey = widget.currentHotKey;
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text('Set Shortcut for ${widget.actionName}'),
content: SizedBox(
width: double.maxFinite,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Current shortcut:',
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 6),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 6,
),
decoration: BoxDecoration(
border: Border.all(color: Theme.of(context).dividerColor),
borderRadius: BorderRadius.circular(6),
),
child: Row(
children: [
Expanded(
child: HotKeyRecorder(
initalHotKey: _recordedHotKey,
onHotKeyRecorded: (hotKey) {
setState(() {
_recordedHotKey = hotKey;
});
},
),
),
if (_recordedHotKey != null)
IconButton(
icon: const Icon(Icons.backspace, size: 18),
onPressed: () {
setState(() {
_recordedHotKey = null;
});
},
padding: EdgeInsets.zero,
constraints: const BoxConstraints(
minWidth: 24,
minHeight: 24,
),
tooltip: 'Clear shortcut',
),
],
),
),
const SizedBox(height: 8),
Text(
'Press any key combination to set a new shortcut',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(
context,
).colorScheme.onSurface.withValues(alpha: 0.7),
),
textAlign: TextAlign.center,
),
],
),
),
),
actions: [
TextButton(onPressed: widget.onCancel, child: const Text('Cancel')),
TextButton(
onPressed: _recordedHotKey != null
? () => widget.onHotKeyRecorded(_recordedHotKey!)
: null,
child: const Text('Save'),
),
],
);
}
}
+32 -21
View File
@@ -1,8 +1,10 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../client/plex_client.dart';
import 'package:provider/provider.dart';
import '../models/plex_metadata.dart';
import '../models/plex_user_profile.dart';
import '../providers/plex_client_provider.dart';
import '../utils/provider_extensions.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
import '../screens/video_player_screen.dart';
@@ -10,7 +12,6 @@ import '../theme/theme_helper.dart';
import 'media_context_menu.dart';
class MediaCard extends StatefulWidget {
final PlexClient client;
final PlexMetadata item;
final double? width;
final double? height;
@@ -19,7 +20,6 @@ class MediaCard extends StatefulWidget {
const MediaCard({
super.key,
required this.client,
required this.item,
this.width,
this.height,
@@ -37,6 +37,9 @@ class _MediaCardState extends State<MediaCard>
bool get wantKeepAlive => true;
void _handleTap(BuildContext context) async {
final client = context.client;
if (client == null) return;
final itemType = widget.item.type.toLowerCase();
// For episodes, start playback directly
@@ -45,7 +48,6 @@ class _MediaCardState extends State<MediaCard>
context,
MaterialPageRoute(
builder: (context) => VideoPlayerScreen(
client: widget.client,
metadata: widget.item,
userProfile: widget.userProfile,
),
@@ -61,7 +63,6 @@ class _MediaCardState extends State<MediaCard>
context,
MaterialPageRoute(
builder: (context) => SeasonDetailScreen(
client: widget.client,
season: widget.item,
userProfile: widget.userProfile,
),
@@ -75,7 +76,6 @@ class _MediaCardState extends State<MediaCard>
context,
MaterialPageRoute(
builder: (context) => MediaDetailScreen(
client: widget.client,
metadata: widget.item,
userProfile: widget.userProfile,
),
@@ -94,7 +94,6 @@ class _MediaCardState extends State<MediaCard>
return SizedBox(
width: widget.width,
child: MediaContextMenu(
client: widget.client,
metadata: widget.item,
onRefresh: widget.onRefresh,
onTap: () => _handleTap(context),
@@ -185,20 +184,32 @@ class _MediaCardState extends State<MediaCard>
Widget _buildPosterImage(BuildContext context) {
if (widget.item.posterThumb != null) {
return CachedNetworkImage(
imageUrl: widget.client.getThumbnailUrl(widget.item.posterThumb),
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
filterQuality: FilterQuality.medium,
fadeInDuration: const Duration(milliseconds: 300),
placeholder: (context, url) => Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: const Center(child: Icon(Icons.broken_image, size: 40)),
),
return Consumer<PlexClientProvider>(
builder: (context, clientProvider, child) {
final client = clientProvider.client;
if (client == null) {
return Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: const Center(child: Icon(Icons.movie, size: 40)),
);
}
return CachedNetworkImage(
imageUrl: client.getThumbnailUrl(widget.item.posterThumb),
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity,
filterQuality: FilterQuality.medium,
fadeInDuration: const Duration(milliseconds: 300),
placeholder: (context, url) => Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
),
errorWidget: (context, url, error) => Container(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: const Center(child: Icon(Icons.broken_image, size: 40)),
),
);
},
);
} else {
return Container(
+13 -10
View File
@@ -1,7 +1,7 @@
import 'dart:io';
import 'package:flutter/material.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../utils/provider_extensions.dart';
import '../screens/media_detail_screen.dart';
import '../screens/season_detail_screen.dart';
@@ -17,7 +17,6 @@ class _MenuAction {
/// A reusable wrapper widget that adds a context menu (long press / right click)
/// to any media item with appropriate actions based on the item type.
class MediaContextMenu extends StatefulWidget {
final PlexClient client;
final PlexMetadata metadata;
final void Function(String ratingKey)? onRefresh;
final VoidCallback? onTap;
@@ -25,7 +24,6 @@ class MediaContextMenu extends StatefulWidget {
const MediaContextMenu({
super.key,
required this.client,
required this.metadata,
this.onRefresh,
this.onTap,
@@ -44,6 +42,9 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
}
void _showContextMenu(BuildContext context) async {
final client = context.client;
if (client == null) return;
final itemType = widget.metadata.type.toLowerCase();
final isPartiallyWatched =
widget.metadata.viewedLeafCount != null &&
@@ -188,7 +189,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
case 'watch':
await _executeAction(
context,
() => widget.client.markAsWatched(widget.metadata.ratingKey),
() => client.markAsWatched(widget.metadata.ratingKey),
'Marked as watched',
);
break;
@@ -196,7 +197,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
case 'unwatch':
await _executeAction(
context,
() => widget.client.markAsUnwatched(widget.metadata.ratingKey),
() => client.markAsUnwatched(widget.metadata.ratingKey),
'Marked as unwatched',
);
break;
@@ -205,8 +206,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
await _navigateToRelated(
context,
widget.metadata.grandparentRatingKey,
(metadata) =>
MediaDetailScreen(client: widget.client, metadata: metadata),
(metadata) => MediaDetailScreen(metadata: metadata),
'Error loading series',
);
break;
@@ -215,8 +215,7 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
await _navigateToRelated(
context,
widget.metadata.parentRatingKey,
(metadata) =>
SeasonDetailScreen(client: widget.client, season: metadata),
(metadata) => SeasonDetailScreen(season: metadata),
'Error loading season',
);
break;
@@ -255,8 +254,12 @@ class _MediaContextMenuState extends State<MediaContextMenu> {
) async {
if (ratingKey == null) return;
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
try {
final metadata = await widget.client.getMetadata(ratingKey);
final metadata = await client.getMetadata(ratingKey);
if (metadata != null && context.mounted) {
await Navigator.push(
context,
+82 -163
View File
@@ -1,29 +1,29 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:media_kit/media_kit.dart';
import 'package:provider/provider.dart';
import 'package:window_manager/window_manager.dart';
import 'package:macos_window_utils/macos_window_utils.dart';
import '../client/plex_client.dart';
import '../models/plex_metadata.dart';
import '../models/plex_media_info.dart';
import '../providers/plex_client_provider.dart';
import '../services/fullscreen_state_manager.dart';
import '../services/keyboard_shortcuts_service.dart';
import '../utils/desktop_window_padding.dart';
import '../utils/platform_detector.dart';
import '../utils/provider_extensions.dart';
import 'app_bar_back_button.dart';
/// Custom video controls builder for Plex with chapter, audio, and subtitle support
Widget plexVideoControlsBuilder(
Player player,
PlexClient client,
PlexMetadata metadata, {
VoidCallback? onNext,
VoidCallback? onPrevious,
}) {
return PlexVideoControls(
player: player,
client: client,
metadata: metadata,
onNext: onNext,
onPrevious: onPrevious,
@@ -32,7 +32,6 @@ Widget plexVideoControlsBuilder(
class PlexVideoControls extends StatefulWidget {
final Player player;
final PlexClient client;
final PlexMetadata metadata;
final VoidCallback? onNext;
final VoidCallback? onPrevious;
@@ -40,7 +39,6 @@ class PlexVideoControls extends StatefulWidget {
const PlexVideoControls({
super.key,
required this.player,
required this.client,
required this.metadata,
this.onNext,
this.onPrevious,
@@ -58,6 +56,7 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
Timer? _hideTimer;
bool _isFullscreen = false;
late final FocusNode _focusNode;
KeyboardShortcutsService? _keyboardService;
@override
void initState() {
@@ -65,12 +64,46 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
_focusNode = FocusNode();
_loadChapters();
_startHideTimer();
_initKeyboardService();
// Add window listener for tracking fullscreen state (for button icon)
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
windowManager.addListener(this);
}
}
Future<void> _initKeyboardService() async {
_keyboardService = await KeyboardShortcutsService.getInstance();
}
void _toggleSubtitles() {
// Toggle subtitle visibility - this would need to be implemented based on your subtitle system
// For now, this is a placeholder
}
void _nextAudioTrack() {
// Switch to next audio track - this would need to be implemented based on your track system
// For now, this is a placeholder
}
void _nextSubtitleTrack() {
// Switch to next subtitle track - this would need to be implemented based on your subtitle system
// For now, this is a placeholder
}
void _nextChapter() {
// Go to next chapter - this would use your existing chapter navigation
if (widget.onNext != null) {
widget.onNext!();
}
}
void _previousChapter() {
// Go to previous chapter - this would use your existing chapter navigation
if (widget.onPrevious != null) {
widget.onPrevious!();
}
}
@override
void dispose() {
_hideTimer?.cancel();
@@ -167,7 +200,11 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
}
Future<void> _loadChapters() async {
final chapters = await widget.client.getChapters(widget.metadata.ratingKey);
final clientProvider = context.plexClient;
final client = clientProvider.client;
if (client == null) return;
final chapters = await client.getChapters(widget.metadata.ratingKey);
if (mounted) {
setState(() {
_chapters = chapters;
@@ -296,47 +333,6 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
}
}
void _togglePlayPause() {
final isPlaying = widget.player.state.playing;
if (isPlaying) {
widget.player.pause();
_hideTimer?.cancel(); // Cancel auto-hide when paused
} else {
widget.player.play();
_startHideTimer(); // Start auto-hide when playing
}
}
void _adjustVolume(double delta) {
final currentVolume = widget.player.state.volume;
final newVolume = (currentVolume + delta).clamp(0.0, 100.0);
widget.player.setVolume(newVolume);
}
void _toggleMute() {
final currentVolume = widget.player.state.volume;
if (currentVolume == 0) {
// Unmute to 100%
widget.player.setVolume(100.0);
} else {
// Mute
widget.player.setVolume(0.0);
}
}
void _seek(Duration offset) {
final currentPosition = widget.player.state.position;
final newPosition = currentPosition + offset;
// Clamp to valid range
final duration = widget.player.state.duration;
if (newPosition < Duration.zero) {
widget.player.seek(Duration.zero);
} else if (newPosition > duration) {
widget.player.seek(duration);
} else {
widget.player.seek(newPosition);
}
}
@override
Widget build(BuildContext context) {
@@ -346,110 +342,18 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (node, event) {
// Only respond to key down events (not key up)
if (event is KeyDownEvent) {
final isShiftPressed = HardwareKeyboard.instance.isShiftPressed;
final isCtrlPressed = HardwareKeyboard.instance.isControlPressed;
if (_keyboardService == null) return KeyEventResult.ignored;
// Play/Pause shortcuts
if (event.logicalKey == LogicalKeyboardKey.space ||
event.logicalKey == LogicalKeyboardKey.keyK) {
_togglePlayPause();
return KeyEventResult.handled;
}
// Arrow key handling - check for modifiers first
if (event.logicalKey == LogicalKeyboardKey.arrowLeft) {
if (isCtrlPressed) {
// Ctrl+Left: Seek backward 1 minute
_seek(const Duration(minutes: -1));
} else if (isShiftPressed) {
// Shift+Left: Seek backward 5 seconds
_seek(const Duration(seconds: -5));
} else {
// Left: Seek backward 10 seconds
_seek(const Duration(seconds: -10));
}
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.arrowRight) {
if (isCtrlPressed) {
// Ctrl+Right: Seek forward 1 minute
_seek(const Duration(minutes: 1));
} else if (isShiftPressed) {
// Shift+Right: Seek forward 5 seconds
_seek(const Duration(seconds: 5));
} else {
// Right: Seek forward 10 seconds
_seek(const Duration(seconds: 10));
}
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
// Up: Volume up 5%
_adjustVolume(5.0);
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
// Down: Volume down 5%
_adjustVolume(-5.0);
return KeyEventResult.handled;
}
// J/L keys for seeking (alternative to arrows)
if (event.logicalKey == LogicalKeyboardKey.keyJ) {
// J: Seek backward 10 seconds
_seek(const Duration(seconds: -10));
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.keyL) {
// L: Seek forward 10 seconds
_seek(const Duration(seconds: 10));
return KeyEventResult.handled;
}
// Fullscreen shortcuts
if (event.logicalKey == LogicalKeyboardKey.keyF) {
_toggleFullscreen();
return KeyEventResult.handled;
}
if (event.logicalKey == LogicalKeyboardKey.escape) {
// Escape: Exit fullscreen (only if currently fullscreen)
if (_isFullscreen) {
_toggleFullscreen();
return KeyEventResult.handled;
}
}
// Mute shortcut
if (event.logicalKey == LogicalKeyboardKey.keyM) {
_toggleMute();
return KeyEventResult.handled;
}
// Episode navigation shortcuts
if (event.logicalKey == LogicalKeyboardKey.keyN) {
// N: Next episode
if (widget.onNext != null) {
widget.onNext!();
return KeyEventResult.handled;
}
}
if (event.logicalKey == LogicalKeyboardKey.keyP) {
// P: Previous episode
if (widget.onPrevious != null) {
widget.onPrevious!();
return KeyEventResult.handled;
}
}
}
return KeyEventResult.ignored;
return _keyboardService!.handleVideoPlayerKeyEvent(
event,
widget.player,
_toggleFullscreen,
_toggleSubtitles,
_nextAudioTrack,
_nextSubtitleTrack,
_nextChapter,
_previousChapter,
);
},
child: MouseRegion(
cursor: _showControls
@@ -787,8 +691,6 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
padding: EdgeInsets.only(
left: leftPadding,
right: 16,
top: isMacOS ? 8 : 16,
bottom: isMacOS ? 8 : 16,
),
child: Row(
children: [
@@ -1505,20 +1407,37 @@ class _PlexVideoControlsState extends State<PlexVideoControls>
children: [
ClipRRect(
borderRadius: BorderRadius.circular(4),
child: Image.network(
widget.client.getThumbnailUrl(
chapter.thumb,
),
width: 60,
height: 34,
fit: BoxFit.cover,
errorBuilder:
(context, error, stackTrace) =>
const Icon(
child: Consumer<PlexClientProvider>(
builder:
(context, clientProvider, child) {
final client =
clientProvider.client;
if (client == null) {
return const Icon(
Icons.image,
color: Colors.white54,
size: 34,
);
}
return Image.network(
client.getThumbnailUrl(
chapter.thumb,
),
width: 60,
height: 34,
fit: BoxFit.cover,
errorBuilder:
(
context,
error,
stackTrace,
) => const Icon(
Icons.image,
color: Colors.white54,
size: 34,
),
);
},
),
),
if (isCurrentChapter)
+114
View File
@@ -0,0 +1,114 @@
import 'package:flutter/material.dart';
import '../models/plex_home_user.dart';
import 'user_avatar_widget.dart';
class ProfileListTile extends StatelessWidget {
final PlexHomeUser user;
final VoidCallback onTap;
final bool isCurrentUser;
final bool showTrailingIcon;
const ProfileListTile({
super.key,
required this.user,
required this.onTap,
this.isCurrentUser = false,
this.showTrailingIcon = true,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return ListTile(
leading: UserAvatarWidget(user: user, size: 40, showIndicators: false),
title: Text(user.displayName),
subtitle: _hasUserAttributes()
? Row(children: _buildUserAttributes(theme))
: null,
trailing: isCurrentUser
? Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: theme.colorScheme.primary,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'CURRENT',
style: TextStyle(
fontSize: 10,
color: theme.colorScheme.onPrimary,
fontWeight: FontWeight.bold,
letterSpacing: 0.5,
),
),
)
: (showTrailingIcon ? const Icon(Icons.chevron_right) : null),
onTap: isCurrentUser ? null : onTap,
enabled: !isCurrentUser,
);
}
bool _hasUserAttributes() {
return user.isAdminUser || user.isRestrictedUser || user.requiresPassword;
}
List<Widget> _buildUserAttributes(ThemeData theme) {
final attributes = <Widget>[];
final labels = <String>[];
if (user.isAdminUser) {
labels.add('Admin');
}
if (user.isRestrictedUser && !user.isAdminUser) {
labels.add('Restricted');
}
if (user.requiresPassword) {
labels.add('Protected');
}
for (int i = 0; i < labels.length; i++) {
if (i > 0) {
attributes.addAll([
const SizedBox(width: 8),
Text(
'•',
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.onSurface.withValues(alpha: 0.5),
),
),
const SizedBox(width: 8),
]);
}
attributes.add(
Text(
labels[i],
style: TextStyle(
fontSize: 12,
color: _getAttributeColor(labels[i], theme),
fontWeight: FontWeight.w500,
),
),
);
}
return attributes;
}
Color _getAttributeColor(String attribute, ThemeData theme) {
switch (attribute) {
case 'Admin':
return theme.colorScheme.primary;
case 'Restricted':
return theme.colorScheme.warning ?? Colors.orange;
case 'Protected':
return theme.colorScheme.secondary;
default:
return theme.colorScheme.onSurface;
}
}
}
+88
View File
@@ -0,0 +1,88 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/user_switching_utils.dart';
import 'user_avatar_widget.dart';
import '../screens/profile_switch_screen.dart';
class ProfileSelector extends StatelessWidget {
final double avatarSize;
final bool showCurrentUserOnly;
const ProfileSelector({
super.key,
this.avatarSize = 32,
this.showCurrentUserOnly = false,
});
@override
Widget build(BuildContext context) {
return Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
if (userProvider.currentUser == null) {
return const SizedBox.shrink();
}
if (showCurrentUserOnly || !userProvider.hasMultipleUsers) {
// Show only current user avatar
return UserAvatarWidget(
user: userProvider.currentUser!,
size: avatarSize,
onTap: userProvider.hasMultipleUsers
? () => _showProfileSwitchDialog(context)
: null,
);
}
// Show horizontal list of users
return SizedBox(
height: avatarSize + 8,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: userProvider.home?.users.length ?? 0,
separatorBuilder: (context, index) => const SizedBox(width: 8),
itemBuilder: (context, index) {
final users = userProvider.home!.users;
final user = users[index];
final isCurrentUser = user.uuid == userProvider.currentUser?.uuid;
return Container(
decoration: isCurrentUser
? BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Theme.of(context).colorScheme.primary,
width: 2,
),
)
: null,
child: Padding(
padding: EdgeInsets.all(isCurrentUser ? 2 : 0),
child: UserAvatarWidget(
user: user,
size: avatarSize - (isCurrentUser ? 4 : 0),
onTap: isCurrentUser
? () => _showProfileSwitchDialog(context)
: () => _switchToUser(context, user),
),
),
);
},
),
);
},
);
}
void _showProfileSwitchDialog(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ProfileSwitchScreen()),
);
}
void _switchToUser(BuildContext context, PlexHomeUser user) async {
await UserSwitchingUtils.switchToUser(context, user);
}
}
+87
View File
@@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/plex_home_user.dart';
import '../providers/user_profile_provider.dart';
import '../utils/user_switching_utils.dart';
import 'profile_list_tile.dart';
class ProfileSwitchDialog extends StatelessWidget {
const ProfileSwitchDialog({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Consumer<UserProfileProvider>(
builder: (context, userProvider, child) {
final users = userProvider.home?.users ?? [];
return AlertDialog(
content: SizedBox(
width: double.maxFinite,
height: users.isEmpty ? 100 : (users.length * 72.0).clamp(100, 400),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (userProvider.isLoading)
const Expanded(
child: Center(child: CircularProgressIndicator()),
)
else if (users.isEmpty)
const Expanded(
child: Center(child: Text('No users available')),
)
else
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
final isCurrentUser =
user.uuid == userProvider.currentUser?.uuid;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Card(
child: ProfileListTile(
user: user,
isCurrentUser: isCurrentUser,
onTap: () => _switchToUser(context, user),
),
),
);
},
),
),
if (userProvider.error != null)
Padding(
padding: const EdgeInsets.only(top: 16),
child: Text(
userProvider.error!,
style: TextStyle(
color: theme.colorScheme.error,
fontSize: 12,
),
textAlign: TextAlign.center,
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
],
);
},
);
}
void _switchToUser(BuildContext context, PlexHomeUser user) async {
await UserSwitchingUtils.switchToUser(context, user, popOnSuccess: true);
}
}
+22 -2
View File
@@ -5,12 +5,14 @@ class ServerListTile extends StatelessWidget {
final PlexServer server;
final VoidCallback onTap;
final bool showTrailingIcon;
final bool isCurrentServer;
const ServerListTile({
super.key,
required this.server,
required this.onTap,
this.showTrailingIcon = true,
this.isCurrentServer = false,
});
@override
@@ -57,8 +59,26 @@ class ServerListTile extends StatelessWidget {
),
],
),
trailing: showTrailingIcon ? const Icon(Icons.chevron_right) : null,
onTap: onTap,
trailing: isCurrentServer
? Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'CURRENT',
style: TextStyle(
fontSize: 10,
color: Theme.of(context).colorScheme.onPrimary,
fontWeight: FontWeight.bold,
letterSpacing: 0.5,
),
),
)
: (showTrailingIcon ? const Icon(Icons.chevron_right) : null),
onTap: isCurrentServer ? null : onTap,
enabled: !isCurrentServer,
);
}
}
+235
View File
@@ -0,0 +1,235 @@
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../models/plex_home_user.dart';
class UserAvatarWidget extends StatelessWidget {
final PlexHomeUser user;
final double size;
final bool showIndicators;
final bool useTextLabels;
final VoidCallback? onTap;
const UserAvatarWidget({
super.key,
required this.user,
this.size = 40,
this.showIndicators = true,
this.useTextLabels = false,
this.onTap,
});
Widget _buildPlaceholderAvatar(ThemeData theme) {
return Container(
width: size,
height: size,
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
shape: BoxShape.circle,
),
child: Icon(
Icons.person,
size: size * 0.6,
color: theme.colorScheme.onSurfaceVariant,
),
);
}
List<Widget> _buildTextLabels(ThemeData theme) {
if (!useTextLabels || !showIndicators) return [];
final labels = <Widget>[];
if (user.isAdminUser) {
labels.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.primary,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Admin',
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
);
}
if (user.isRestrictedUser && !user.isAdminUser) {
labels.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.warning ?? Colors.orange,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Restricted',
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onPrimary,
fontWeight: FontWeight.bold,
),
),
),
);
}
if (user.requiresPassword) {
labels.add(
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: theme.colorScheme.secondary,
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Protected',
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSecondary,
fontWeight: FontWeight.bold,
),
),
),
);
}
if (labels.isEmpty) return [];
return [
const SizedBox(height: 4),
Wrap(
spacing: 4,
runSpacing: 2,
alignment: WrapAlignment.center,
children: labels,
),
];
}
Widget _buildAvatar(ThemeData theme) {
return SizedBox(
width: size,
height: size,
child: Stack(
children: [
// Avatar image
ClipOval(
child: CachedNetworkImage(
imageUrl: user.thumb,
width: size,
height: size,
fit: BoxFit.cover,
placeholder: (context, url) => _buildPlaceholderAvatar(theme),
errorWidget: (context, url, error) =>
_buildPlaceholderAvatar(theme),
),
),
// Indicators (only show icon indicators when not using text labels)
if (showIndicators && !useTextLabels) ...[
// Admin badge
if (user.isAdminUser)
Positioned(
top: 0,
right: 0,
child: Container(
width: size * 0.3,
height: size * 0.3,
decoration: BoxDecoration(
color: theme.colorScheme.primary,
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.surface,
width: 1,
),
),
child: Icon(
Icons.admin_panel_settings,
size: size * 0.2,
color: theme.colorScheme.onPrimary,
),
),
),
// Restricted badge
if (user.isRestrictedUser && !user.isAdminUser)
Positioned(
top: 0,
right: 0,
child: Container(
width: size * 0.3,
height: size * 0.3,
decoration: BoxDecoration(
color: theme.colorScheme.warning ?? Colors.orange,
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.surface,
width: 1,
),
),
child: Icon(
Icons.security,
size: size * 0.2,
color: theme.colorScheme.onPrimary,
),
),
),
// Password indicator
if (user.requiresPassword)
Positioned(
bottom: 0,
right: 0,
child: Container(
width: size * 0.25,
height: size * 0.25,
decoration: BoxDecoration(
color: theme.colorScheme.secondary,
shape: BoxShape.circle,
border: Border.all(
color: theme.colorScheme.surface,
width: 1,
),
),
child: Icon(
Icons.lock,
size: size * 0.15,
color: theme.colorScheme.onSecondary,
),
),
),
],
],
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
if (useTextLabels) {
// Return avatar with text labels below
return GestureDetector(
onTap: onTap,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [_buildAvatar(theme), ..._buildTextLabels(theme)],
),
);
} else {
// Return just the avatar (original behavior)
return GestureDetector(onTap: onTap, child: _buildAvatar(theme));
}
}
}
// Extension to add warning color to ColorScheme if not available
extension ColorSchemeExtension on ColorScheme {
Color? get warning => brightness == Brightness.light
? Colors.orange.shade600
: Colors.orange.shade400;
}
@@ -6,6 +6,7 @@
#include "generated_plugin_registrant.h"
#include <hotkey_manager_linux/hotkey_manager_linux_plugin.h>
#include <media_kit_libs_linux/media_kit_libs_linux_plugin.h>
#include <media_kit_video/media_kit_video_plugin.h>
#include <screen_retriever_linux/screen_retriever_linux_plugin.h>
@@ -14,6 +15,9 @@
#include <window_manager/window_manager_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) hotkey_manager_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "HotkeyManagerLinuxPlugin");
hotkey_manager_linux_plugin_register_with_registrar(hotkey_manager_linux_registrar);
g_autoptr(FlPluginRegistrar) media_kit_libs_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "MediaKitLibsLinuxPlugin");
media_kit_libs_linux_plugin_register_with_registrar(media_kit_libs_linux_registrar);
+1
View File
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
hotkey_manager_linux
media_kit_libs_linux
media_kit_video
screen_retriever_linux
@@ -5,6 +5,7 @@
import FlutterMacOS
import Foundation
import hotkey_manager_macos
import macos_window_utils
import media_kit_libs_macos_video
import media_kit_video
@@ -19,6 +20,7 @@ import wakelock_plus
import window_manager
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
HotkeyManagerMacosPlugin.register(with: registry.registrar(forPlugin: "HotkeyManagerMacosPlugin"))
MacOSWindowUtilsPlugin.register(with: registry.registrar(forPlugin: "MacOSWindowUtilsPlugin"))
MediaKitLibsMacosVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitLibsMacosVideoPlugin"))
MediaKitVideoPlugin.register(with: registry.registrar(forPlugin: "MediaKitVideoPlugin"))
+13
View File
@@ -1,5 +1,9 @@
PODS:
- FlutterMacOS (1.0.0)
- HotKey (0.2.1)
- hotkey_manager_macos (0.0.1):
- FlutterMacOS
- HotKey
- macos_window_utils (1.0.0):
- FlutterMacOS
- media_kit_libs_macos_video (1.0.4):
@@ -30,6 +34,7 @@ PODS:
DEPENDENCIES:
- FlutterMacOS (from `Flutter/ephemeral`)
- hotkey_manager_macos (from `Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos`)
- macos_window_utils (from `Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos`)
- media_kit_libs_macos_video (from `Flutter/ephemeral/.symlinks/plugins/media_kit_libs_macos_video/macos`)
- media_kit_video (from `Flutter/ephemeral/.symlinks/plugins/media_kit_video/macos`)
@@ -43,9 +48,15 @@ DEPENDENCIES:
- wakelock_plus (from `Flutter/ephemeral/.symlinks/plugins/wakelock_plus/macos`)
- window_manager (from `Flutter/ephemeral/.symlinks/plugins/window_manager/macos`)
SPEC REPOS:
trunk:
- HotKey
EXTERNAL SOURCES:
FlutterMacOS:
:path: Flutter/ephemeral
hotkey_manager_macos:
:path: Flutter/ephemeral/.symlinks/plugins/hotkey_manager_macos/macos
macos_window_utils:
:path: Flutter/ephemeral/.symlinks/plugins/macos_window_utils/macos
media_kit_libs_macos_video:
@@ -73,6 +84,8 @@ EXTERNAL SOURCES:
SPEC CHECKSUMS:
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
HotKey: 400beb7caa29054ea8d864c96f5ba7e5b4852277
hotkey_manager_macos: a4317849af96d2430fa89944d3c58977ca089fbe
macos_window_utils: 23f54331a0fd51eea9e0ed347253bf48fd379d1d
media_kit_libs_macos_video: 85a23e549b5f480e72cae3e5634b5514bc692f65
media_kit_video: fa6564e3799a0a28bff39442334817088b7ca758
+62 -70
View File
@@ -185,14 +185,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.6"
dart_service_protocol_shared:
dependency: transitive
description:
name: dart_service_protocol_shared
sha256: "1737875c176d7e3d87bb3a359182828b542fe20a0b34198b8d31a81af5c7a76d"
url: "https://pub.dev"
source: hosted
version: "0.0.3"
dart_style:
dependency: transitive
description:
@@ -225,14 +217,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.1"
dtd:
dependency: "direct main"
description:
name: dtd
sha256: "09ddb228b3d1478a093556357692a4c203ff4f9d5f8cda05dfdca0ff3fb7c5d3"
url: "https://pub.dev"
source: hosted
version: "4.0.0"
fake_async:
dependency: transitive
description:
@@ -294,14 +278,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.0"
flutter_svg:
dependency: "direct main"
description:
name: flutter_svg
sha256: b9c2ad5872518a27507ab432d1fb97e8813b05f0fc693f9d40fad06d073e0678
url: "https://pub.dev"
source: hosted
version: "2.2.1"
flutter_test:
dependency: "direct dev"
description: flutter
@@ -328,8 +304,48 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.3.2"
http:
hotkey_manager:
dependency: "direct main"
description:
name: hotkey_manager
sha256: "06f0655b76c8dd322fb7101dc615afbdbf39c3d3414df9e059c33892104479cd"
url: "https://pub.dev"
source: hosted
version: "0.2.3"
hotkey_manager_linux:
dependency: transitive
description:
name: hotkey_manager_linux
sha256: "83676bda8210a3377bc6f1977f193bc1dbdd4c46f1bdd02875f44b6eff9a8473"
url: "https://pub.dev"
source: hosted
version: "0.2.0"
hotkey_manager_macos:
dependency: transitive
description:
name: hotkey_manager_macos
sha256: "03b5967e64357b9ac05188ea4a5df6fe4ed4205762cb80aaccf8916ee1713c96"
url: "https://pub.dev"
source: hosted
version: "0.2.0"
hotkey_manager_platform_interface:
dependency: transitive
description:
name: hotkey_manager_platform_interface
sha256: "98ffca25b8cc9081552902747b2942e3bc37855389a4218c9d50ca316b653b13"
url: "https://pub.dev"
source: hosted
version: "0.2.0"
hotkey_manager_windows:
dependency: transitive
description:
name: hotkey_manager_windows
sha256: "0d03ced9fe563ed0b68f0a0e1b22c9ffe26eb8053cb960e401f68a4f070e0117"
url: "https://pub.dev"
source: hosted
version: "0.2.0"
http:
dependency: transitive
description:
name: http
sha256: bb2ce4590bc2667c96f318d68cac1b5a7987ec819351d32b1c987239a815e007
@@ -376,14 +392,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.9.0"
json_rpc_2:
dependency: transitive
description:
name: json_rpc_2
sha256: "3c46c2633aec07810c3d6a2eb08d575b5b4072980db08f1344e66aeb53d6e4a7"
url: "https://pub.dev"
source: hosted
version: "4.0.0"
json_serializable:
dependency: "direct dev"
description:
@@ -545,6 +553,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
octo_image:
dependency: transitive
description:
@@ -585,14 +601,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_parsing:
dependency: transitive
description:
name: path_parsing
sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
path_provider:
dependency: transitive
description:
@@ -681,6 +689,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.0.3"
provider:
dependency: "direct main"
description:
name: provider
sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272"
url: "https://pub.dev"
source: hosted
version: "6.1.5+1"
pub_semver:
dependency: transitive
description:
@@ -982,14 +998,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
unified_analytics:
uni_platform:
dependency: transitive
description:
name: unified_analytics
sha256: "8d1429a4b27320a9c4fc854287d18c8fde1549bf622165c5837202a9f370b53d"
name: uni_platform
sha256: e02213a7ee5352212412ca026afd41d269eb00d982faa552f419ffc2debfad84
url: "https://pub.dev"
source: hosted
version: "8.0.5"
version: "0.1.3"
universal_platform:
dependency: transitive
description:
@@ -1078,30 +1094,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.5.1"
vector_graphics:
dependency: transitive
description:
name: vector_graphics
sha256: a4f059dc26fc8295b5921376600a194c4ec7d55e72f2fe4c7d2831e103d461e6
url: "https://pub.dev"
source: hosted
version: "1.1.19"
vector_graphics_codec:
dependency: transitive
description:
name: vector_graphics_codec
sha256: "99fd9fbd34d9f9a32efd7b6a6aae14125d8237b10403b422a6a6dfeac2806146"
url: "https://pub.dev"
source: hosted
version: "1.1.13"
vector_graphics_compiler:
dependency: transitive
description:
name: vector_graphics_compiler
sha256: d354a7ec6931e6047785f4db12a1f61ec3d43b207fc0790f863818543f8ff0dc
url: "https://pub.dev"
source: hosted
version: "1.1.19"
vector_math:
dependency: transitive
description:
@@ -1199,7 +1191,7 @@ packages:
source: hosted
version: "1.1.0"
xml:
dependency: "direct main"
dependency: transitive
description:
name: xml
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
+3 -5
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 1.1.0+5
version: 1.2.0+6
environment:
sdk: ^3.8.1
@@ -9,12 +9,9 @@ environment:
dependencies:
flutter:
sdk: flutter
http: ^1.2.0
dio: ^5.4.0
json_annotation: ^4.8.1
xml: ^6.5.0
shared_preferences: ^2.2.2
dtd: ^4.0.0
cached_network_image: ^3.4.1
media_kit: ^1.1.10+1
media_kit_video: ^1.2.4
@@ -24,8 +21,9 @@ dependencies:
uuid: ^4.4.0
window_manager: ^0.4.3
logger: ^2.0.2
flutter_svg: ^2.0.10
package_info_plus: ^9.0.0
provider: ^6.1.2
hotkey_manager: ^0.2.3
dependency_overrides:
media_kit:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 MiB

@@ -6,6 +6,7 @@
#include "generated_plugin_registrant.h"
#include <hotkey_manager_windows/hotkey_manager_windows_plugin_c_api.h>
#include <media_kit_libs_windows_video/media_kit_libs_windows_video_plugin_c_api.h>
#include <media_kit_video/media_kit_video_plugin_c_api.h>
#include <screen_retriever_windows/screen_retriever_windows_plugin_c_api.h>
@@ -14,6 +15,8 @@
#include <window_manager/window_manager_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
HotkeyManagerWindowsPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("HotkeyManagerWindowsPluginCApi"));
MediaKitLibsWindowsVideoPluginCApiRegisterWithRegistrar(
registry->GetRegistrarForPlugin("MediaKitLibsWindowsVideoPluginCApi"));
MediaKitVideoPluginCApiRegisterWithRegistrar(
+1
View File
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
hotkey_manager_windows
media_kit_libs_windows_video
media_kit_video
screen_retriever_windows