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
254 lines
8.8 KiB
Dart
254 lines
8.8 KiB
Dart
import 'package:flutter/foundation.dart';
|
|
import '../media/ids.dart';
|
|
|
|
import '../i18n/strings.g.dart';
|
|
import '../media/episode_collection.dart';
|
|
import '../media/media_item.dart';
|
|
import '../media/media_item_types.dart';
|
|
import '../mixins/disposable_change_notifier_mixin.dart';
|
|
import '../models/download_models.dart';
|
|
import '../services/offline_watch_sync_service.dart';
|
|
import '../services/settings_service.dart';
|
|
import '../utils/app_logger.dart';
|
|
import '../utils/snackbar_helper.dart';
|
|
import '../utils/watch_state_notifier.dart';
|
|
import 'download_provider.dart';
|
|
import '../utils/global_key_utils.dart';
|
|
|
|
/// Provider for offline watch status UI state.
|
|
///
|
|
/// Provides:
|
|
/// - Effective watch status (local changes + cached server data)
|
|
/// - Offline "OnDeck" calculation for shows
|
|
/// - Manual mark watched/unwatched while offline
|
|
class OfflineWatchProvider extends ChangeNotifier with DisposableChangeNotifierMixin {
|
|
final OfflineWatchSyncService _syncService;
|
|
final DownloadProvider _downloadProvider;
|
|
|
|
OfflineWatchProvider({required this._syncService, required this._downloadProvider}) {
|
|
// Listen to sync service changes to update UI
|
|
_syncService.addListener(_onSyncServiceChanged);
|
|
}
|
|
|
|
void _onSyncServiceChanged() {
|
|
safeNotifyListeners();
|
|
}
|
|
|
|
/// Whether a sync is in progress
|
|
bool get isSyncing => _syncService.isSyncing;
|
|
|
|
/// Get count of pending sync items
|
|
Future<int> getPendingSyncCount() => _syncService.getPendingSyncCount();
|
|
|
|
/// Get the effective watch status for a media item.
|
|
///
|
|
/// Priority:
|
|
/// 1. Local offline action (if exists)
|
|
/// 2. Cached server data from API cache
|
|
/// 3. Metadata from download provider
|
|
///
|
|
/// Returns true if watched, false otherwise.
|
|
Future<bool> isWatched(String globalKey) async {
|
|
// First check local offline action
|
|
final localStatus = await _syncService.getLocalWatchStatus(globalKey);
|
|
if (localStatus != null) {
|
|
return localStatus;
|
|
}
|
|
|
|
// Fall back to cached metadata
|
|
final metadata = _downloadProvider.getMetadata(globalKey);
|
|
if (metadata != null) {
|
|
return metadata.isWatched;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/// Get the effective view offset (resume position) for a media item.
|
|
///
|
|
/// Priority:
|
|
/// 1. Local offline progress (if exists)
|
|
/// 2. Metadata from download provider
|
|
///
|
|
/// Returns null if no position is available.
|
|
@visibleForTesting
|
|
Future<int?> getViewOffset(String globalKey) async {
|
|
// First check local offline progress
|
|
final localOffset = await _syncService.getLocalViewOffset(globalKey);
|
|
if (localOffset != null) {
|
|
return localOffset;
|
|
}
|
|
|
|
final localStatus = await _syncService.getLocalWatchStatus(globalKey);
|
|
if (localStatus == true) return null;
|
|
|
|
// Fall back to cached metadata
|
|
final metadata = _downloadProvider.getMetadata(globalKey);
|
|
return metadata?.viewOffsetMs;
|
|
}
|
|
|
|
/// Get sorted episodes for a show: regular seasons first, Specials last,
|
|
/// then season then episode — the shared [sortEpisodesByWatchOrder] order,
|
|
/// so the offline watch order matches what "download next N" selects (#1414).
|
|
List<MediaItem> _getSortedEpisodes(String showId) {
|
|
final episodes = _downloadProvider.getDownloadedEpisodesForShow(showId);
|
|
if (episodes.isEmpty) return episodes;
|
|
sortEpisodesByWatchOrder(episodes);
|
|
return episodes;
|
|
}
|
|
|
|
/// Batch resolve watch statuses for a list of episodes.
|
|
///
|
|
/// Returns a map of globalKey -> isWatched for each episode.
|
|
Future<Map<String, bool>> _resolveEpisodeWatchStatuses(List<MediaItem> episodes) async {
|
|
if (episodes.isEmpty) return {};
|
|
|
|
final globalKeys = episodes.map((e) => e.globalKey).toSet();
|
|
final localStatuses = await _syncService.getLocalWatchStatusesBatched(globalKeys);
|
|
|
|
return {
|
|
for (final episode in episodes)
|
|
episode.globalKey:
|
|
localStatuses[episode.globalKey] ?? _downloadProvider.getMetadata(episode.globalKey)?.isWatched ?? false,
|
|
};
|
|
}
|
|
|
|
/// Find the next unwatched downloaded episode for a show.
|
|
///
|
|
/// This is the "offline OnDeck" calculation - finds the first
|
|
/// episode that hasn't been watched (or is in progress).
|
|
///
|
|
/// Episodes are sorted by season number, then episode number.
|
|
///
|
|
/// Returns the next unwatched episode, or the first episode if all watched.
|
|
Future<MediaItem?> getNextUnwatchedEpisode(String showId) async {
|
|
final episodes = _getSortedEpisodes(showId);
|
|
if (episodes.isEmpty) return null;
|
|
|
|
final watchStatuses = await _resolveEpisodeWatchStatuses(episodes);
|
|
|
|
// Find first unwatched episode
|
|
for (final episode in episodes) {
|
|
if (!watchStatuses[episode.globalKey]!) {
|
|
return episode;
|
|
}
|
|
}
|
|
|
|
// All episodes watched - return first episode for replay
|
|
return episodes.firstOrNull;
|
|
}
|
|
|
|
/// Emit a watch state change event for immediate UI update.
|
|
void _emitWatchStateChange({
|
|
required ServerId serverId,
|
|
required String itemId,
|
|
required bool isNowWatched,
|
|
required WatchStateChangeType changeType,
|
|
required WatchPatchId patchId,
|
|
String? cacheServerId,
|
|
}) {
|
|
final globalKey = buildGlobalKey(ServerId(serverId), itemId);
|
|
final metadata = _downloadProvider.getMetadata(globalKey);
|
|
if (metadata != null) {
|
|
WatchStateNotifier().notifyWatched(
|
|
item: metadata,
|
|
isNowWatched: isNowWatched,
|
|
cacheServerId: cacheServerId,
|
|
patchId: patchId,
|
|
);
|
|
} else {
|
|
// Fallback: emit minimal event without parent chain.
|
|
WatchStateNotifier().notify(
|
|
WatchStateEvent(
|
|
itemId: itemId,
|
|
serverId: serverId,
|
|
cacheServerId: cacheServerId,
|
|
changeType: changeType,
|
|
parentChain: [],
|
|
mediaType: 'unknown',
|
|
isNowWatched: isNowWatched,
|
|
patchId: patchId,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Mark an item as watched while offline.
|
|
///
|
|
/// This queues the action for sync when online and emits a [WatchStateEvent].
|
|
Future<void> markAsWatched({required ServerId serverId, required String itemId}) async {
|
|
final queued = await _syncService.queueMarkWatched(serverId: serverId, itemId: itemId);
|
|
_emitWatchStateChange(
|
|
serverId: serverId,
|
|
itemId: itemId,
|
|
isNowWatched: true,
|
|
changeType: WatchStateChangeType.watched,
|
|
cacheServerId: queued.clientScopeId,
|
|
patchId: WatchPatchId.offlineAction(profileId: queued.profileId, rowId: queued.rowId, revision: queued.revision),
|
|
);
|
|
safeNotifyListeners();
|
|
_autoDeleteIfWatched(serverId, itemId);
|
|
}
|
|
|
|
/// Auto-delete a download if the auto-remove setting is enabled.
|
|
void _autoDeleteIfWatched(ServerId serverId, String itemId) {
|
|
final settings = SettingsService.instanceOrNull;
|
|
if (settings == null || !settings.read(SettingsService.autoRemoveWatchedDownloads)) return;
|
|
|
|
final globalKey = buildGlobalKey(ServerId(serverId), itemId);
|
|
final meta = _downloadProvider.getMetadata(globalKey);
|
|
if (meta == null) return;
|
|
if (!meta.isEpisode && !meta.isMovie) return;
|
|
|
|
final progress = _downloadProvider.downloads[globalKey];
|
|
if (progress?.status != DownloadStatus.completed) return;
|
|
|
|
appLogger.i('Auto-deleting locally-watched download: ${meta.title} ($globalKey)');
|
|
_downloadProvider
|
|
.deleteDownload(globalKey)
|
|
.then(
|
|
(_) {
|
|
showMainSnackBar(t.messages.autoRemovedWatchedDownload(title: meta.title ?? 'Unknown'));
|
|
},
|
|
onError: (e) {
|
|
appLogger.w('Failed to auto-delete locally-watched download $globalKey: $e');
|
|
},
|
|
);
|
|
}
|
|
|
|
/// Mark an item as unwatched while offline.
|
|
///
|
|
/// This queues the action for sync when online and emits a [WatchStateEvent].
|
|
Future<void> markAsUnwatched({required ServerId serverId, required String itemId}) async {
|
|
final queued = await _syncService.queueMarkUnwatched(serverId: serverId, itemId: itemId);
|
|
_emitWatchStateChange(
|
|
serverId: serverId,
|
|
itemId: itemId,
|
|
isNowWatched: false,
|
|
changeType: WatchStateChangeType.unwatched,
|
|
cacheServerId: queued.clientScopeId,
|
|
patchId: WatchPatchId.offlineAction(profileId: queued.profileId, rowId: queued.rowId, revision: queued.revision),
|
|
);
|
|
safeNotifyListeners();
|
|
}
|
|
|
|
/// Get downloaded episodes for a show with their watch status.
|
|
///
|
|
/// Returns a list of (episode, isWatched) pairs.
|
|
/// Uses batched database query for efficiency.
|
|
Future<List<(MediaItem episode, bool isWatched)>> getEpisodesWithWatchStatus(String showId) async {
|
|
final episodes = _downloadProvider.getDownloadedEpisodesForShow(showId);
|
|
if (episodes.isEmpty) return [];
|
|
|
|
final watchStatuses = await _resolveEpisodeWatchStatuses(episodes);
|
|
|
|
return [for (final episode in episodes) (episode, watchStatuses[episode.globalKey]!)];
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_syncService.removeListener(_onSyncServiceChanged);
|
|
super.dispose();
|
|
}
|
|
}
|