Pausing an episode on one device, finishing it on another and pressing Refresh left the first device showing the old "minutes left". Restarting the app showed the right value. Two independent defects produce that, and either alone reproduces the report. The first is the watch-state overlay. Every local watch event lands in WatchStateStore as a patch, and WatchStateSnapshot.apply overwrites viewOffsetMs unconditionally; isNewerThan only ever orders one patch against another, never against the server row underneath. Nothing expires a patch and nothing clears the map except a profile switch, so the Mac's own paused position kept winning over every subsequent fetch until the process died. A patch exists to bridge the gap between a local action and the next server read of that item, so it should stop applying once that read happens. The store now records the watermark at which a successful authoritative response returned each key, and suppresses an acknowledged session patch at or below it. Only a watermark is stored, never the observed state: WatchStateSnapshot cannot hold a container's leaf counts, and keeping max() per key makes the order two concurrent responses complete irrelevant. Suppression is a read-time predicate, so nothing mutates during build. The barrier covers the parentChain too. patchForItem picks the newest of the item's own entry and its ancestors', so retiring only the item's entry would let an older season mark win and render watched/0 -- worse than either the stale value or the fresh one. An authoritative read of a child already reflects any container mark that preceded it, so the child's observation judges its ancestors as well; a newer container action still wins. Provenance decides what may be suppressed at all. WatchStateEvent now carries serverAcknowledged, defaulting to false so an unclassified emit site degrades to today's behaviour rather than silently becoming retireable. An offline write is owed to the server and a read must never retire it, so it stays until a WatchPatchPromotionNotifier promotion says the queue replayed it. That channel is deliberately not a WatchStateEvent: OfflineWatchSyncService reacts to watched/unwatched by purging queued progress, so replaying one there would delete a newer rewatch. Promotion matches an exact WatchPatchId -- session minted for live crossings, derived from the persisted (profile, row, revision) for queued ones so it still joins after a restart. Report acceptance is not delivery: PlaybackReportSession resolves true for a same-state startup heartbeat it drops, so acknowledgement now keys on onDelivered. A MediaBrowser Started saves play count and last-played date but not the position, so it cannot acknowledge an offset. No report-derived watched crossing is acknowledged on any backend -- Jellyfin hard-codes its threshold and Plex never loads the server pref that would tell it the real one -- so only an awaited explicit markWatched settles one. The second defect is that a failed Refresh reported success. Plex _fetchHubs and the Jellyfin hub legs both degrade a failure to an empty list, and the library prefetch discarded its failures, so a server whose every hub request failed was recorded as succeeded; DiscoverProvider then kept the previous rows, set loaded and surfaced nothing. Worse, the background Continue Watching refresh wiped the row outright on zero success. Hub legs now report what they degraded through a HubFetchDiagnostics sink, which keeps partial rows alongside the failure and leaves every existing caller untouched. Failures ride through the aggregation results, a leg that could not run because discovery failed contributes that failure rather than a successful no-op, and loaded-server ids became succeeded - failed - cancelled so one bad leg no longer caches a server as covered and blocks its retry. The toolbar awaits a DiscoverRefreshOutcome and shows the existing unableToLoad snackbar on failure while the retained rows stay on screen. Rollback after a mid-pass exception is version-guarded, refilters against the current hidden libraries and no longer publishes a system shelf the pass never committed. Observations are staged with the pass and flushed only once the same disposal, generation and exception checks that authorise committing those rows have passed, so a discarded or rolled-back response can never suppress a patch. Also fixes a live data-loss race the promotion work would have built on: upsertProgressAction stamped a millisecond timestamp and updated the row in place, so a rewatch queued during an in-flight replay was deleted by id. Revisions are now strictly monotonic per row, replay deletes and retry updates compare against them, and the upsert resets the retry fields because a new revision is a new logical action. close #1829
284 lines
9.9 KiB
Dart
284 lines
9.9 KiB
Dart
import 'dart:async';
|
|
import '../media/ids.dart';
|
|
import 'dart:io';
|
|
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/services.dart';
|
|
|
|
import '../media/media_item.dart';
|
|
import '../media/media_server_client.dart';
|
|
import '../media/watch_progress.dart';
|
|
import '../models/external_player_models.dart';
|
|
import '../utils/app_logger.dart';
|
|
import '../utils/platform_detector.dart';
|
|
import '../utils/snackbar_helper.dart';
|
|
import '../utils/watch_state_notifier.dart';
|
|
import '../i18n/strings.g.dart';
|
|
import 'settings_service.dart';
|
|
import 'offline_watch_sync_service.dart';
|
|
import 'trackers/tracker_coordinator.dart';
|
|
|
|
const _externalPlayerChannel = MethodChannel('com.plezy/external_player');
|
|
|
|
class _ExternalPlayerLaunchResult {
|
|
const _ExternalPlayerLaunchResult({
|
|
required this.launched,
|
|
this.positionMs,
|
|
this.durationMs,
|
|
this.playbackCompleted = false,
|
|
this.playbackError = false,
|
|
});
|
|
|
|
final bool launched;
|
|
final int? positionMs;
|
|
final int? durationMs;
|
|
final bool playbackCompleted;
|
|
final bool playbackError;
|
|
|
|
factory _ExternalPlayerLaunchResult.fromMap(Map<String, Object?>? map) {
|
|
if (map == null) return const _ExternalPlayerLaunchResult(launched: true);
|
|
return _ExternalPlayerLaunchResult(
|
|
launched: map['launched'] == true,
|
|
positionMs: _asInt(map['positionMs']),
|
|
durationMs: _asInt(map['durationMs']),
|
|
playbackCompleted: map['playbackCompleted'] == true,
|
|
playbackError: map['playbackError'] == true,
|
|
);
|
|
}
|
|
|
|
static int? _asInt(Object? value) {
|
|
if (value is int) return value;
|
|
if (value is double) return value.round();
|
|
if (value is String) return int.tryParse(value);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
class ExternalPlayerService {
|
|
/// Launch an external player with either a pre-resolved [videoUrl] (e.g.
|
|
/// a local file path for downloaded content) or by asking [client] to
|
|
/// resolve the streaming URL for [metadata]. Each backend implements
|
|
/// `resolveExternalPlaybackUrl` for the right shape (Plex part URL,
|
|
/// Jellyfin `/Videos/{id}/stream?Static=true`).
|
|
static Future<bool> launch({
|
|
required BuildContext context,
|
|
MediaItem? metadata,
|
|
MediaServerClient? client,
|
|
OfflineWatchSyncService? offlineWatchService,
|
|
int mediaIndex = 0,
|
|
String? mediaSourceId,
|
|
String? videoUrl,
|
|
}) async {
|
|
if (!PlatformDetector.supportsExternalPlayers()) return false;
|
|
|
|
try {
|
|
String resolvedUrl;
|
|
|
|
if (videoUrl != null) {
|
|
resolvedUrl = videoUrl;
|
|
} else if (client != null && metadata != null) {
|
|
final url = await client.resolveExternalPlaybackUrl(
|
|
metadata,
|
|
mediaIndex: mediaIndex,
|
|
mediaSourceId: mediaSourceId,
|
|
);
|
|
if (url == null || url.isEmpty) {
|
|
if (context.mounted) {
|
|
showErrorSnackBar(context, t.messages.fileInfoNotAvailable);
|
|
}
|
|
return false;
|
|
}
|
|
resolvedUrl = url;
|
|
} else {
|
|
appLogger.e('ExternalPlayerService.launch requires either videoUrl or client+metadata');
|
|
return false;
|
|
}
|
|
|
|
final settings = await SettingsService.getInstance();
|
|
final player = settings.read(SettingsService.selectedExternalPlayer);
|
|
|
|
// On Android, always use native intent to avoid url_launcher opening in browser
|
|
if (Platform.isAndroid && context.mounted) {
|
|
final launchResult = await _launchAndroidNative(resolvedUrl, player, context, metadata: metadata);
|
|
if (launchResult.launched && metadata != null) {
|
|
await _reportAndroidExternalProgress(
|
|
launchResult,
|
|
metadata: metadata,
|
|
client: client,
|
|
offlineWatchService: offlineWatchService,
|
|
mediaSourceId: mediaSourceId,
|
|
);
|
|
}
|
|
return launchResult.launched;
|
|
}
|
|
|
|
final launched = await player.launch(resolvedUrl);
|
|
if (!launched && context.mounted) {
|
|
showErrorSnackBar(context, t.externalPlayer.appNotInstalled(name: player.name));
|
|
}
|
|
return launched;
|
|
} catch (e) {
|
|
appLogger.e('Failed to launch external player', error: e);
|
|
if (context.mounted) {
|
|
showErrorSnackBar(context, t.externalPlayer.launchFailed);
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// Launch a video on Android using native ACTION_VIEW intent.
|
|
/// Handles local files (file://, content://, absolute paths) and remote URLs.
|
|
static Future<_ExternalPlayerLaunchResult> _launchAndroidNative(
|
|
String url,
|
|
ExternalPlayer player,
|
|
BuildContext context, {
|
|
MediaItem? metadata,
|
|
}) async {
|
|
try {
|
|
final packages = player.id == 'system_default' ? const <String>[] : KnownPlayers.androidPackageCandidates(player);
|
|
final result = await _externalPlayerChannel.invokeMapMethod<String, Object?>('openVideo', {
|
|
'filePath': url,
|
|
if (metadata?.title?.trim().isNotEmpty == true) 'title': metadata!.title!.trim(),
|
|
if ((metadata?.viewOffsetMs ?? 0) > 0) 'startPositionMs': metadata!.viewOffsetMs,
|
|
if (packages.isNotEmpty) 'packages': packages,
|
|
});
|
|
return _ExternalPlayerLaunchResult.fromMap(result);
|
|
} on PlatformException catch (e) {
|
|
if (e.code == 'APP_NOT_FOUND' && context.mounted) {
|
|
showErrorSnackBar(context, t.externalPlayer.appNotInstalled(name: player.name));
|
|
} else if (context.mounted) {
|
|
showErrorSnackBar(context, t.externalPlayer.launchFailed);
|
|
}
|
|
return const _ExternalPlayerLaunchResult(launched: false);
|
|
}
|
|
}
|
|
|
|
static Future<void> _reportAndroidExternalProgress(
|
|
_ExternalPlayerLaunchResult result, {
|
|
required MediaItem metadata,
|
|
required MediaServerClient? client,
|
|
OfflineWatchSyncService? offlineWatchService,
|
|
String? mediaSourceId,
|
|
}) async {
|
|
if (result.playbackError) {
|
|
appLogger.d('External player returned an error result for ${metadata.id}; skipping progress sync');
|
|
return;
|
|
}
|
|
|
|
final durationMs = _positive(result.durationMs) ?? _positive(metadata.durationMs);
|
|
final reportedPositionMs = _positive(result.positionMs) ?? (result.playbackCompleted ? durationMs : null);
|
|
if (reportedPositionMs == null) return;
|
|
|
|
final positionMs = durationMs == null ? reportedPositionMs : reportedPositionMs.clamp(0, durationMs).toInt();
|
|
final position = Duration(milliseconds: positionMs);
|
|
final duration = durationMs == null ? null : Duration(milliseconds: durationMs);
|
|
if (client == null) {
|
|
await _queueExternalProgress(metadata, offlineWatchService, position: position, duration: duration);
|
|
return;
|
|
}
|
|
|
|
var startedSucceeded = false;
|
|
try {
|
|
await client.reportPlaybackStarted(
|
|
itemId: metadata.id,
|
|
position: position,
|
|
duration: duration,
|
|
playMethod: 'DirectPlay',
|
|
mediaSourceId: mediaSourceId,
|
|
);
|
|
startedSucceeded = true;
|
|
} catch (e) {
|
|
appLogger.d('External player progress: started call failed (continuing)', error: e);
|
|
}
|
|
|
|
try {
|
|
await client.reportPlaybackStopped(
|
|
itemId: metadata.id,
|
|
position: position,
|
|
duration: duration,
|
|
mediaSourceId: mediaSourceId,
|
|
);
|
|
} catch (e) {
|
|
appLogger.w('Failed to sync external player progress for ${metadata.id}', error: e);
|
|
await _queueExternalProgress(metadata, offlineWatchService, position: position, duration: duration);
|
|
return;
|
|
}
|
|
|
|
if (duration == null) return;
|
|
|
|
WatchStateNotifier().notifyProgress(
|
|
item: metadata,
|
|
cacheServerId: client.cacheServerId,
|
|
viewOffset: position.inMilliseconds,
|
|
duration: duration.inMilliseconds,
|
|
watchedThreshold: client.watchedThreshold,
|
|
// MediaBrowser persists stopped progress only for a session opened by
|
|
// Started; Plex persists every timeline report independently.
|
|
serverAcknowledged: !metadata.backend.usesMediaBrowserApi || startedSucceeded,
|
|
);
|
|
|
|
if (isWatchedProgress(
|
|
positionMs: position.inMilliseconds,
|
|
durationMs: duration.inMilliseconds,
|
|
threshold: client.watchedThreshold,
|
|
)) {
|
|
try {
|
|
// reportPlaybackStopped above marks the item played on backends that
|
|
// support it (Jellyfin); markWatchedFromPlaybackStop then only emits the
|
|
// local watch event there to avoid double-scrobbling via the Trakt
|
|
// plugin (#1287). Plex still issues the explicit server call.
|
|
await client.markWatchedFromPlaybackStop(metadata);
|
|
unawaited(TrackerCoordinator.instance.markWatched(metadata, client));
|
|
} catch (e) {
|
|
appLogger.w('Failed to mark external playback watched for ${metadata.id}', error: e);
|
|
}
|
|
}
|
|
}
|
|
|
|
@visibleForTesting
|
|
static Future<void> reportAndroidExternalProgressForTesting({
|
|
required int? positionMs,
|
|
required int? durationMs,
|
|
bool playbackCompleted = false,
|
|
bool playbackError = false,
|
|
required MediaItem metadata,
|
|
required MediaServerClient? client,
|
|
OfflineWatchSyncService? offlineWatchService,
|
|
String? mediaSourceId,
|
|
}) {
|
|
return _reportAndroidExternalProgress(
|
|
_ExternalPlayerLaunchResult(
|
|
launched: true,
|
|
positionMs: positionMs,
|
|
durationMs: durationMs,
|
|
playbackCompleted: playbackCompleted,
|
|
playbackError: playbackError,
|
|
),
|
|
metadata: metadata,
|
|
client: client,
|
|
offlineWatchService: offlineWatchService,
|
|
mediaSourceId: mediaSourceId,
|
|
);
|
|
}
|
|
|
|
static Future<void> _queueExternalProgress(
|
|
MediaItem metadata,
|
|
OfflineWatchSyncService? offlineWatchService, {
|
|
required Duration position,
|
|
required Duration? duration,
|
|
}) async {
|
|
final serverId = metadata.serverId;
|
|
if (offlineWatchService == null || serverId == null) return;
|
|
await offlineWatchService.queueProgressUpdate(
|
|
serverId: ServerId(serverId),
|
|
itemId: metadata.id,
|
|
viewOffset: duration == null
|
|
? position.inMilliseconds
|
|
: position.inMilliseconds.clamp(0, duration.inMilliseconds).toInt(),
|
|
duration: duration?.inMilliseconds,
|
|
);
|
|
}
|
|
|
|
static int? _positive(int? value) => value != null && value > 0 ? value : null;
|
|
}
|