Compare commits

..
6 Commits
9 changed files with 148 additions and 56 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "1.33.1"
sha256 "155722eb653c0efa939e47c38d1fb340c693f9039424effcb9c2bf4aea80720e"
version "1.34.1"
sha256 "9e230f1c7522e85c9b1ee039b92cb331e92625732f6b2059c5ea5cfe85f77869"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
+1 -1
View File
@@ -23,7 +23,7 @@ val downloadLibmpv by tasks.registering {
}
}
val assVersion = "fp-2"
val assVersion = "fp-3"
val assDir = layout.buildDirectory.dir("libass").get().asFile
val assAars = listOf("lib_ass-release.aar", "lib_ass_kt-release.aar", "lib_ass_media-release.aar")
@@ -476,12 +476,17 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
// SurfaceFlinger-layer-backed overlay that eglPresentationTimeANDROID can
// vsync-pin. Z-order: default video SurfaceView < this MediaOverlay-flagged
// SurfaceView < Flutter TextureView in the window.
//
// Inserted at child index 0 so the SurfaceView's transparent punch runs BEFORE
// SubtitleView's built-in CanvasSubtitleOutput child renders non-ASS cues.
// Appending would punch away already-drawn SRT/VTT text.
var assSubtitleSurfaceView: AssSubtitleSurfaceView? = null
subtitleView?.let { sv ->
val assView = AssSubtitleSurfaceView(sv.context, handler)
assSubtitleSurfaceView = assView
sv.addView(
assView,
0,
FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
@@ -1408,22 +1413,69 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
}
fun addSubtitleTrack(uri: String, title: String?, language: String?, mimeType: String?, select: Boolean) {
val index = externalSubtitles.size
val subtitleConfig = MediaItem.SubtitleConfiguration.Builder(Uri.parse(uri))
.setId("external_$index")
.setLabel(title ?: "External")
.setLanguage(language)
.setMimeType(mimeType ?: detectSubtitleMimeType(uri))
.build()
val existingIndex = externalSubtitleUris.indexOf(uri)
val isNew = existingIndex < 0
val index = if (isNew) externalSubtitles.size else existingIndex
val formatId = "external_$index"
externalSubtitles.add(subtitleConfig)
externalSubtitleUris.add(uri)
if (isNew) {
// SELECTION_FLAG_DEFAULT marks this as the preferred text track so ExoPlayer's
// natural selection picks it on prepare. Avoids pinning the selector to a
// specific TrackGroup override — if the URL 404s (e.g. stale Plex stream key),
// ExoPlayer falls back to another available track (e.g. embedded SRT) instead
// of leaving text disabled.
val selectionFlags = if (select) C.SELECTION_FLAG_DEFAULT else 0
val subtitleConfig = MediaItem.SubtitleConfiguration.Builder(Uri.parse(uri))
.setId(formatId)
.setLabel(title ?: "External")
.setLanguage(language)
.setMimeType(mimeType ?: detectSubtitleMimeType(uri))
.setSelectionFlags(selectionFlags)
.build()
externalSubtitles.add(subtitleConfig)
externalSubtitleUris.add(uri)
}
// Note: ExoPlayer won't see these until the media is reloaded.
// On Android, external subs are normally passed at open() time.
// This path is only reached if the Flutter layer calls addSubtitleTrack
// while ExoPlayer (not MPV fallback) is active.
emitTrackList()
// Media3 only picks up MediaItem.SubtitleConfiguration at prepare() time
// (tracking issue androidx/media #1649). When the caller wants this subtitle
// activated immediately (e.g. after OpenSubtitles download), rebuild the
// MediaItem and re-prepare with the position preserved.
val player = exoPlayer
val mediaUri = currentMediaUri
if (select && player != null && mediaUri != null && !currentMediaIsLive) {
if (isNew) {
val savedPosition = player.currentPosition
val savedPlayWhenReady = player.playWhenReady
// Clear any stale text-type override (pointing at a pre-reload TrackGroup)
// and re-enable the text type — mirrors the reset done in open(). Without
// this, a previously-selected sub's override would either block the new
// DEFAULT-flagged sub from winning or, if the new sub fails to load, keep
// the text renderer stuck with no selection.
trackSelector?.let { selector ->
selector.parameters = selector.buildUponParameters()
.clearOverridesOfType(C.TRACK_TYPE_TEXT)
.setTrackTypeDisabled(C.TRACK_TYPE_TEXT, false)
.build()
}
selectedSubtitleTrackId = null
val mediaItem = buildMediaItem(mediaUri)
player.setMediaItem(mediaItem, savedPosition)
player.prepare()
player.playWhenReady = savedPlayWhenReady
} else {
// Already attached — select the existing track via override.
val trackId = subtitleTrackGroupMap.entries
.firstOrNull { (_, group) -> group.getFormat(0).id == formatId }
?.key
if (trackId != null) {
selectSubtitleTrack(trackId)
}
}
}
if (isNew) emitTrackList()
}
private fun detectSubtitleMimeType(uri: String): String {
+6 -2
View File
@@ -551,8 +551,12 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
: const Duration(minutes: 2);
if (now.difference(_lastResumeProbe) >= cooldown) {
_lastResumeProbe = now;
_serverManager.checkServerHealth();
_serverManager.reconnectOfflineServers();
// Await health check before reconnecting so stale "online" servers
// get marked offline and included in the reconnection sweep.
unawaited(() async {
await _serverManager.checkServerHealth();
await _serverManager.reconnectOfflineServers();
}());
}
case AppLifecycleState.paused:
case AppLifecycleState.detached:
+10 -6
View File
@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:io' show Platform, exit;
import 'package:flutter/material.dart';
@@ -589,13 +590,16 @@ class _MainScreenState extends State<MainScreen> with RouteAware, WindowListener
setState(() => _isReconnecting = true);
final serverManager = context.read<MultiServerProvider>().serverManager;
serverManager.checkServerHealth();
serverManager.reconnectOfflineServers().whenComplete(() {
// Give a moment for status updates to propagate
Future.delayed(const Duration(seconds: 1), () {
unawaited(() async {
try {
// Health check first so stale "online" servers get marked offline before
// we snapshot the offline list for reconnection.
await serverManager.checkServerHealth();
await serverManager.reconnectOfflineServers(forceRediscovery: true);
} finally {
if (mounted) setState(() => _isReconnecting = false);
});
});
}
}());
}
void _handleLiveTvChanged() {
+14 -4
View File
@@ -492,12 +492,17 @@ class MultiServerManager {
}
}
/// Attempt reconnection for all offline servers
Future<void> reconnectOfflineServers() async {
/// Attempt reconnection for all offline servers.
///
/// When [forceRediscovery] is true, the cached endpoint is cleared before
/// reconnecting so the fast-path is skipped and a full candidate race runs.
/// Used by the manual reconnect button when the cached URL may be stale
/// (e.g. after a network change while the app was backgrounded).
Future<void> reconnectOfflineServers({bool forceRediscovery = false}) async {
// Coalesce concurrent calls — return the in-flight future if one exists
if (_activeReconnect != null) return _activeReconnect!;
_activeReconnect = _doReconnectOfflineServers();
_activeReconnect = _doReconnectOfflineServers(forceRediscovery: forceRediscovery);
try {
await _activeReconnect;
} finally {
@@ -505,13 +510,18 @@ class MultiServerManager {
}
}
Future<void> _doReconnectOfflineServers() async {
Future<void> _doReconnectOfflineServers({required bool forceRediscovery}) async {
final offline = offlineServerIds;
if (offline.isEmpty) return;
appLogger.d('Attempting reconnection for ${offline.length} offline servers');
Sentry.addBreadcrumb(Breadcrumb(message: 'Reconnecting ${offline.length} offline server(s)', category: 'servers'));
if (forceRediscovery) {
final storage = await StorageService.getInstance();
await Future.wait(offline.map(storage.clearServerEndpoint));
}
final futures = offline.map((serverId) {
final server = _servers[serverId];
if (server == null) return Future<void>.value();
+4 -3
View File
@@ -238,7 +238,7 @@ class PlexClient {
'Switching Plex endpoint after GET failure',
error: {'from': failedEndpoint, 'to': nextBaseUrl, 'path': path},
);
await _handleEndpointSwitch(nextBaseUrl);
await _handleEndpointSwitch(nextBaseUrl, persist: false);
final response = await _http.get(
path,
queryParameters: queryParameters,
@@ -247,6 +247,7 @@ class PlexClient {
abort: abort,
);
appLogger.i('Endpoint failover retry succeeded', error: {'newEndpoint': nextBaseUrl});
await _onEndpointChanged?.call(nextBaseUrl);
return response;
} finally {
_failoverSwitching = false;
@@ -2887,7 +2888,7 @@ class PlexClient {
}
}
Future<void> _handleEndpointSwitch(String newBaseUrl) async {
Future<void> _handleEndpointSwitch(String newBaseUrl, {bool persist = true}) async {
if (config.baseUrl == newBaseUrl) {
return;
}
@@ -2897,7 +2898,7 @@ class PlexClient {
config = config.copyWith(baseUrl: newBaseUrl);
LogRedactionManager.registerServerUrl(newBaseUrl);
if (_onEndpointChanged != null) {
if (persist && _onEndpointChanged != null) {
await _onEndpointChanged(newBaseUrl);
}
}
+44 -23
View File
@@ -2471,41 +2471,62 @@ class _PlexVideoControlsState extends State<PlexVideoControls> with WindowListen
Future<void> _onSubtitleDownloaded() async {
if (!mounted) return;
// Wait for the server to finish downloading the subtitle file
await Future.delayed(const Duration(seconds: 2));
if (!mounted) return;
try {
final client = _getClientForMetadata();
final data = await client.getVideoPlaybackData(widget.metadata.ratingKey);
if (!mounted || data.mediaInfo == null) return;
final token = client.config.token;
if (token == null) return;
// Find external subtitle tracks from the refreshed metadata
// Plex's OpenSubtitles download is asynchronous: the PUT returns immediately
// but the new stream entry shows up in metadata seconds later. Poll until it
// appears. Up to 15s matches what Plex-web tolerates before giving up.
// Snapshot what's already attached so we can identify the new download.
final existingUris = widget.player.state.tracks.subtitle.where((t) => t.uri != null).map((t) => t.uri!).toSet();
for (final plexTrack in data.mediaInfo!.subtitleTracks) {
if (!plexTrack.isExternal) continue;
final url = plexTrack.getSubtitleUrl(client.config.baseUrl, token);
if (url == null) continue;
// Skip tracks already loaded in the player
if (existingUris.any((uri) => uri.contains(plexTrack.key!))) continue;
final deadline = DateTime.now().add(const Duration(seconds: 15));
PlexSubtitleTrack? newTrack;
String? newUrl;
PlexMediaInfo? latestInfo;
await widget.player.addSubtitleTrack(
uri: url,
title: plexTrack.displayTitle ?? plexTrack.language ?? 'Downloaded',
language: plexTrack.languageCode,
select: true,
);
while (mounted && DateTime.now().isBefore(deadline)) {
await Future.delayed(const Duration(seconds: 2));
if (!mounted) return;
// Save the selection on the server so it persists across sessions
final partId = data.mediaInfo!.partId;
if (partId != null) {
await client.selectStreams(partId, subtitleStreamID: plexTrack.id);
try {
final data = await client.getVideoPlaybackData(widget.metadata.ratingKey);
if (!mounted) return;
if (data.mediaInfo == null) continue;
latestInfo = data.mediaInfo;
for (final plexTrack in data.mediaInfo!.subtitleTracks) {
if (!plexTrack.isExternal) continue;
final url = plexTrack.getSubtitleUrl(client.config.baseUrl, token);
if (url == null) continue;
if (existingUris.any((uri) => uri.contains(plexTrack.key!))) continue;
newTrack = plexTrack;
newUrl = url;
break;
}
if (newTrack != null) break;
} catch (e) {
appLogger.w('Subtitle download poll iteration failed', error: e);
}
}
if (!mounted || newTrack == null || newUrl == null) return;
await widget.player.addSubtitleTrack(
uri: newUrl,
title: newTrack.displayTitle ?? newTrack.language ?? 'Downloaded',
language: newTrack.languageCode,
select: true,
);
final partId = latestInfo?.partId;
if (partId != null) {
await client.selectStreams(partId, subtitleStreamID: newTrack.id);
}
} catch (e) {
appLogger.w('Failed to refresh subtitles after download', error: e);
}
+1 -1
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex client for Flutter"
publish_to: "none"
version: 1.34.0+71
version: 1.34.2+73
environment:
sdk: ^3.8.1