Compare commits

..
15 Commits
17 changed files with 248 additions and 66 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "1.30.0"
sha256 "6b72efc1666f2cf0fbc8a29b0bea185d28281d7512fa63a88f37c3c96eff40e1"
version "1.31.2"
sha256 "9d2e403ff8a0449318deab16fe1232accc3959731bb44464dc4609e80a1c04f8"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
+2 -2
View File
@@ -18,7 +18,7 @@ PODS:
- package_info_plus (0.4.5):
- Flutter
- Sentry/HybridSDK (8.58.0)
- sentry_flutter (9.15.0):
- sentry_flutter (9.16.0):
- Flutter
- FlutterMacOS
- Sentry/HybridSDK (= 8.58.0)
@@ -128,7 +128,7 @@ SPEC CHECKSUMS:
os_media_controls: 86dceab6245a5325af90fc0fdebe243c42d789b4
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
Sentry: d587a8fe91ca13503ecd69a1905f3e8a0fcf61be
sentry_flutter: 8939e491bc1511868118c96cae47d945e6f69798
sentry_flutter: 31101687061fb85211ebab09ce6eb8db4e9ba74f
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
sqlite3: a51c07cf16e023d6c48abd5e5791a61a47354921
+4 -3
View File
@@ -396,9 +396,10 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
}
case AppLifecycleState.paused:
case AppLifecycleState.detached:
if (Platform.isAndroid || Platform.isIOS) {
unawaited(_appDatabase.close());
}
// Database is session-scoped and must survive suspend/resume.
// Closing here would kill the Drift isolate channel while services
// (sync, downloads, cache) still hold references to the executor.
// SQLite WAL mode handles process death; desktop uses onExitRequested.
InAppReviewService.instance.endSession();
if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
if (ProcessInfo.currentRss > 1024 * 1024 * 1024) { // 1GB
@@ -1310,7 +1310,7 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<PlexMetadata, LibraryBr
maxHeight: memHeight,
),
context,
);
).ignore();
}
}
+1 -1
View File
@@ -133,7 +133,7 @@ class _LogsScreenState extends State<LogsScreen> {
);
try {
final response = await createHttpClient().post(
final response = await httpClient.post(
'https://ice.plezy.app/logs',
data: logText,
options: Options(contentType: 'text/plain'),
+2 -3
View File
@@ -300,8 +300,7 @@ class DiscordRPCService {
if (imageUrl.isEmpty) return null;
// Fetch image data
final dio = createHttpClient();
final imageResponse = await dio.get<List<int>>(
final imageResponse = await httpClient.get<List<int>>(
imageUrl,
options: Options(responseType: ResponseType.bytes, receiveTimeout: const Duration(seconds: 10)),
);
@@ -316,7 +315,7 @@ class DiscordRPCService {
'fileToUpload': MultipartFile.fromBytes(Uint8List.fromList(imageBytes), filename: 'thumbnail.jpg'),
});
final uploadResponse = await dio.post<String>(
final uploadResponse = await httpClient.post<String>(
_litterboxUrl,
data: formData,
options: Options(receiveTimeout: const Duration(seconds: 15)),
+1 -1
View File
@@ -122,7 +122,7 @@ class DownloadManagerService {
DownloadManagerService({required AppDatabase database, required DownloadStorageService storageService, Dio? dio})
: _database = database,
_storageService = storageService,
_dio = dio ?? createHttpClient();
_dio = dio ?? httpClient;
/// Initialize background_downloader with callbacks, notifications, and concurrency config.
Future<void> _initializeFileDownloader() async {
+81 -9
View File
@@ -1,13 +1,15 @@
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:http/io_client.dart';
/// Custom cache manager for Plex image transcoding with connection limiting.
import '../utils/http_client.dart';
/// Custom cache manager for Plex image transcoding with HTTP/2 multiplexing.
///
/// Limits concurrent HTTP connections to 6 per host (matching browser HTTP/1.1
/// behavior) to prevent overwhelming the Plex server's transcode pipeline when
/// many posters are visible simultaneously.
/// Uses Dio with [Http2Adapter] so all platforms benefit from HTTP/2 connection
/// multiplexing — many concurrent image downloads over a single connection
/// instead of being limited to a handful of HTTP/1.1 connections.
class PlexImageCacheManager extends CacheManager with ImageCacheManager {
static const _key = 'plexImageCache';
@@ -19,11 +21,81 @@ class PlexImageCacheManager extends CacheManager with ImageCacheManager {
_key,
stalePeriod: const Duration(days: 14),
maxNrOfCacheObjects: 3000,
fileService: HttpFileService(
httpClient: IOClient(
HttpClient()..maxConnectionsPerHost = 6,
),
fileService: _DioFileService(
Dio()..httpClientAdapter = createHttp2Adapter(),
),
),
);
}
class _DioFileService extends FileService {
final Dio _dio;
_DioFileService(this._dio);
@override
Future<FileServiceResponse> get(
String url, {
Map<String, String>? headers,
}) async {
final response = await _dio.get<ResponseBody>(
url,
options: Options(
headers: headers,
responseType: ResponseType.stream,
),
);
return _DioGetResponse(response);
}
}
class _DioGetResponse implements FileServiceResponse {
final Response<ResponseBody> _response;
final DateTime _receivedTime = DateTime.now();
_DioGetResponse(this._response);
@override
Stream<List<int>> get content => _response.data!.stream;
@override
int? get contentLength {
final value = _header(HttpHeaders.contentLengthHeader);
return value != null ? int.tryParse(value) : null;
}
@override
int get statusCode => _response.statusCode ?? 200;
@override
DateTime get validTill {
var ageDuration = const Duration(days: 7);
final controlHeader = _header(HttpHeaders.cacheControlHeader);
if (controlHeader != null) {
for (final setting in controlHeader.split(',')) {
final s = setting.trim().toLowerCase();
if (s == 'no-cache') ageDuration = Duration.zero;
if (s.startsWith('max-age=')) {
final secs = int.tryParse(s.split('=')[1]) ?? 0;
if (secs > 0) ageDuration = Duration(seconds: secs);
}
}
}
return _receivedTime.add(ageDuration);
}
@override
String? get eTag => _header(HttpHeaders.etagHeader);
@override
String get fileExtension {
final contentTypeHeader = _header(HttpHeaders.contentTypeHeader);
if (contentTypeHeader != null) {
final ct = ContentType.parse(contentTypeHeader);
return '.${ct.subType}';
}
return '';
}
String? _header(String name) => _response.headers.value(name);
}
@@ -25,6 +25,7 @@ class OfflineWatchSyncService extends ChangeNotifier {
VoidCallback? _offlineModeListener;
bool _isSyncing = false;
bool _isBidirectionalSyncing = false;
bool _isShutDown = false;
DateTime? _lastSyncTime;
bool _hasPerformedStartupSync = false;
@@ -82,6 +83,8 @@ class OfflineWatchSyncService extends ChangeNotifier {
///
/// Push always happens immediately. Pull respects [minSyncInterval] unless [force] is true.
Future<void> _performBidirectionalSync({bool force = false}) async {
if (_isShutDown) return;
// Prevent overlapping bidirectional syncs
if (_isBidirectionalSyncing) {
appLogger.d('Bidirectional sync already in progress, skipping');
@@ -121,6 +124,7 @@ class OfflineWatchSyncService extends ChangeNotifier {
/// On mobile, always syncs immediately (device-switching scenario).
/// On desktop, respects the throttle interval.
void onAppResumed() {
if (_isShutDown) return;
if (_offlineModeProvider?.isOffline != true) {
final isMobile = Platform.isIOS || Platform.isAndroid;
appLogger.d('App resumed - ${isMobile ? "forcing" : "checking"} sync');
@@ -133,6 +137,7 @@ class OfflineWatchSyncService extends ChangeNotifier {
/// Triggers the initial sync now that PlexClients are available.
/// Only runs once per app session.
void onServersConnected() {
if (_isShutDown) return;
if (_hasPerformedStartupSync) return;
_hasPerformedStartupSync = true;
@@ -558,6 +563,7 @@ class OfflineWatchSyncService extends ChangeNotifier {
@override
void dispose() {
_isShutDown = true;
if (_offlineModeProvider != null && _offlineModeListener != null) {
_offlineModeProvider!.removeListener(_offlineModeListener!);
}
+10 -8
View File
@@ -8,6 +8,7 @@ import '../models/plex_home.dart';
import '../models/user_switch_response.dart';
import '../utils/app_logger.dart';
import '../utils/connection_constants.dart';
import '../utils/http_client.dart';
/// Redacts the middle of an IP address or hostname for safe logging.
/// E.g. `192.168.1.50` → `192.***.***.50`, `my.server.example.com` → `my.***.***. com`.
@@ -53,7 +54,7 @@ class PlexAuthService {
final storage = await StorageService.getInstance();
final dio = Dio(
BaseOptions(connectTimeout: ConnectionTimeouts.plexTvConnect, receiveTimeout: ConnectionTimeouts.plexTvReceive),
);
)..httpClientAdapter = createHttp2Adapter();
// Get or create client identifier
String? clientIdentifier = storage.getClientIdentifier();
@@ -720,7 +721,7 @@ class PlexServer {
);
if (!result.success) {
appLogger.w('HTTPS upgrade failed, staying on HTTP candidate', error: {'url': currentUrl});
appLogger.w('HTTPS upgrade failed, staying on HTTP candidate', error: {'url': currentUrl, 'reason': result.error});
return null;
}
@@ -794,18 +795,19 @@ class PlexServer {
) {
if (entries.isEmpty) return null;
// Sort by latency first, then by protocol (HTTPS > HTTP), then by URL type (prefer plex.direct)
// Sort by protocol first (HTTPS enables H2 multiplexing), then latency, then URL type
entries.sort((a, b) {
final latencyCompare = a.value.latencyMs.compareTo(b.value.latencyMs);
if (latencyCompare != 0) return latencyCompare;
// If latencies are equal, prefer HTTPS over HTTP
// Prefer HTTPS over HTTP
final aIsHttps = a.key.isHttps;
final bIsHttps = b.key.isHttps;
if (aIsHttps && !bIsHttps) return -1;
if (!aIsHttps && bIsHttps) return 1;
// If latencies and protocols are equal, prefer plex.direct URI (isPlexDirectUri = true)
// Within same protocol, sort by latency
final latencyCompare = a.value.latencyMs.compareTo(b.value.latencyMs);
if (latencyCompare != 0) return latencyCompare;
// Prefer plex.direct URI on tie
if (a.key.isPlexDirectUri && !b.key.isPlexDirectUri) return -1;
if (!a.key.isPlexDirectUri && b.key.isPlexDirectUri) return 1;
return 0;
+2
View File
@@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart';
import 'package:dio/dio.dart';
import '../utils/http_client.dart';
import '../models/livetv_capture_buffer.dart';
import '../models/livetv_channel.dart';
import '../models/livetv_dvr.dart';
@@ -198,6 +199,7 @@ class PlexClient {
responseDecoder: _lenientUtf8Decoder,
),
);
_dio.httpClientAdapter = createHttp2Adapter();
_dio.transformer = BackgroundTransformer();
// Add interceptor for logging (optional, can be disabled in production)
+13 -4
View File
@@ -224,11 +224,20 @@ class SettingsService extends BaseSharedPreferencesService {
}
int getLibraryDensity() {
// New int format
final intVal = prefs.getInt(_keyLibraryDensity);
if (intVal != null) return intVal.clamp(LibraryDensity.min, LibraryDensity.max);
// New int format — getInt throws if the stored value is a different type
try {
final intVal = prefs.getInt(_keyLibraryDensity);
if (intVal != null) return intVal.clamp(LibraryDensity.min, LibraryDensity.max);
} on TypeError {
// Stored value is a String from old enum format — fall through to migration
}
// Migrate from old enum string format
final strVal = prefs.getString(_keyLibraryDensity);
String? strVal;
try {
strVal = prefs.getString(_keyLibraryDensity);
} on TypeError {
// Value exists but isn't a String either
}
final result = switch (strVal) {
'compact' => 2,
'comfortable' => 4,
+1 -2
View File
@@ -155,8 +155,7 @@ class UpdateService {
final packageInfo = await PackageInfo.fromPlatform();
final currentVersion = packageInfo.version;
final dio = createHttpClient();
final response = await dio.get(
final response = await httpClient.get(
'https://api.github.com/repos/$_githubRepo/releases/latest',
options: Options(headers: {'Accept': 'application/vnd.github+json'}),
);
+58 -16
View File
@@ -1,18 +1,60 @@
import 'package:dio/dio.dart';
import 'dart:io';
import 'dart:typed_data';
/// Creates a plain [Dio] instance with sensible default timeouts for ad-hoc
/// HTTP requests that don't go through [PlexClient].
///
/// Use this instead of bare `Dio()` so every call site gets consistent timeout
/// behaviour without duplicating configuration.
Dio createHttpClient({
Duration connectTimeout = const Duration(seconds: 10),
Duration receiveTimeout = const Duration(seconds: 30),
}) {
return Dio(
BaseOptions(
connectTimeout: connectTimeout,
receiveTimeout: receiveTimeout,
),
);
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:dio_http2_adapter/dio_http2_adapter.dart';
import 'app_logger.dart';
/// Shared HTTP/2 connection pool. All Dio instances that go through
/// [createHttp2Adapter] reuse the same pool, so connections to the same
/// host are multiplexed instead of duplicated.
final _connectionManager = ConnectionManager(idleTimeout: const Duration(seconds: 15));
final _http1Fallback = IOHttpClientAdapter();
/// Returns an [HttpClientAdapter] that tries HTTP/2 first and falls back
/// to HTTP/1.1 when the server rejects h2 ALPN negotiation.
HttpClientAdapter createHttp2Adapter() => _Http2WithFallbackAdapter(Http2Adapter(_connectionManager));
/// Shared [Dio] instance for ad-hoc HTTP requests that don't go through
/// [PlexClient]. Reuses the global HTTP/2 connection pool.
final httpClient = Dio()..httpClientAdapter = createHttp2Adapter();
class _Http2WithFallbackAdapter implements HttpClientAdapter {
_Http2WithFallbackAdapter(this._h2);
final Http2Adapter _h2;
static final _http1Hosts = <String>{'plex.tv'};
@override
Future<ResponseBody> fetch(
RequestOptions options,
Stream<Uint8List>? requestStream,
Future<void>? cancelFuture,
) async {
if (_http1Hosts.contains(options.uri.host)) {
return _http1Fallback.fetch(options, requestStream, cancelFuture);
}
try {
return await _h2.fetch(options, requestStream, cancelFuture);
} on HandshakeException {
appLogger.d('H2 handshake failed for ${options.uri.host}, falling back to HTTP/1.1');
_http1Hosts.add(options.uri.host);
return _http1Fallback.fetch(options, requestStream, cancelFuture);
} catch (e) {
if (e.toString().contains('HTTP/2')) {
appLogger.d('H2 connection error for ${options.uri.host}, falling back to HTTP/1.1');
_http1Hosts.add(options.uri.host);
return _http1Fallback.fetch(options, requestStream, cancelFuture);
}
rethrow;
}
}
@override
void close({bool force = false}) {
_h2.close(force: force);
}
}
+18 -1
View File
@@ -6,8 +6,16 @@ import 'package:material_symbols_icons/symbols.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../services/image_cache_service.dart';
import '../../services/plex_client.dart';
import '../utils/app_logger.dart';
import '../utils/plex_image_helper.dart';
/// Tracks recent image load failures to log a periodic summary instead of
/// spamming per-image. Resets after [_logInterval] so recurring issues
/// remain visible.
int _imageFailureCount = 0;
DateTime _lastFailureLog = DateTime.now();
const _logInterval = Duration(seconds: 10);
/// Set to `true` to blur all artwork (for store screenshots).
const kBlurArtwork = false;
@@ -348,7 +356,16 @@ class PlexOptimizedImage extends StatelessWidget {
fit: fit,
filterQuality: filterQuality,
alignment: alignment,
errorBuilder: (context, error, stackTrace) => _buildErrorWidget(context, error),
errorBuilder: (context, error, stackTrace) {
_imageFailureCount++;
final now = DateTime.now();
if (now.difference(_lastFailureLog) >= _logInterval) {
appLogger.w('Image load failed ($_imageFailureCount since last log): $error');
_imageFailureCount = 0;
_lastFailureLog = now;
}
return _buildErrorWidget(context, error);
},
frameBuilder: (context, child, frame, wasSynchronouslyLoaded) {
if (wasSynchronouslyLoaded) return child;
return AnimatedSwitcher(
+29 -11
View File
@@ -349,6 +349,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.9.2"
dio_http2_adapter:
dependency: "direct main"
description:
name: dio_http2_adapter
sha256: "79f3d69b155b92a786c8734bd11860390b986210d4e07cbb6a5c8c806a7187b2"
url: "https://pub.dev"
source: hosted
version: "2.7.0"
dio_web_adapter:
dependency: transitive
description:
@@ -529,6 +537,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.6.0"
http2:
dependency: transitive
description:
name: http2
sha256: "382d3aefc5bd6dc68c6b892d7664f29b5beb3251611ae946a98d35158a82bbfa"
url: "https://pub.dev"
source: hosted
version: "2.3.1"
http_multi_server:
dependency: transitive
description:
@@ -1004,21 +1020,23 @@ packages:
source: hosted
version: "0.2.0"
sentry:
dependency: transitive
dependency: "direct overridden"
description:
name: sentry
sha256: a49b4fb1cba576fe216347dc2a0e6d76076fb998e6012857db96f991c23b7b3c
url: "https://pub.dev"
source: hosted
version: "9.15.0"
path: "packages/dart"
ref: "build/fetch-native-zip"
resolved-ref: "711f54f34d6cda9cccfb57519b9e3b72dd116b69"
url: "https://github.com/edde746/sentry-dart"
source: git
version: "9.16.0"
sentry_flutter:
dependency: "direct main"
description:
name: sentry_flutter
sha256: "25150030c93bd1d4b727ab61cfb09e99121c69ce90fa820bb9ca16dab433e43a"
url: "https://pub.dev"
source: hosted
version: "9.15.0"
path: "packages/flutter"
ref: "build/fetch-native-zip"
resolved-ref: "711f54f34d6cda9cccfb57519b9e3b72dd116b69"
url: "https://github.com/edde746/sentry-dart"
source: git
version: "9.16.0"
serial_csv:
dependency: transitive
description:
+17 -2
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 1.31.0+63
version: 1.31.3+67
environment:
sdk: ^3.8.1
@@ -54,7 +54,12 @@ dependencies:
flutter_svg: ^2.2.3
mobile_scanner: ^7.2.0
background_downloader: ^9.5.2
sentry_flutter: ^9.15.0
sentry_flutter:
git:
url: https://github.com/edde746/sentry-dart
path: packages/flutter
ref: build/fetch-native-zip
dio_http2_adapter: ^2.7.0
auto_updater:
git:
url: https://github.com/edde746/auto_updater
@@ -87,6 +92,16 @@ dependency_overrides:
url: https://github.com/edde746/auto_updater
ref: 9e150f7
path: packages/auto_updater_windows
sentry:
git:
url: https://github.com/edde746/sentry-dart
path: packages/dart
ref: build/fetch-native-zip
sentry_flutter:
git:
url: https://github.com/edde746/sentry-dart
path: packages/flutter
ref: build/fetch-native-zip
material_symbols_icons:
git:
url: https://github.com/edde746/material_symbols_icons