Skip to content

Commit 04fb276

Browse files
RXWatcherclaudezZebrahz
committed
Polish cast pairing and TV navigation UI across Android clients (#63)
* Polish Android TV navigation menu * Refine Android TV cards, chrome, and collection catalog lookup * Unify TV hero transitions and preload skyline artwork * Align Android TV detail hero copy * Show episode air date in TV detail facts * Improve TV detail starring legibility * Enlarge Android TV primary play icon * Emphasize TV detail selector values * Reveal the next TV detail section * Stabilize TV season and episode focus position * Keep TV season switching in place * Clarify TV episode card hierarchy * Show episode air date in TV details * Enlarge Android TV person names * Reduce Android TV person metadata pills * Constrain Android TV person biographies * Simplify Android TV filmography heading * Refine Android TV person filters * Make Android TV person headers scroll * Reduce Android TV calendar filter type * Refine Android TV calendar day cells * Scroll Android TV calendar controls with content * Compact Android TV calendar badges * Raise Android TV search controls * Refine Android TV search result status * Refine Android TV search filters * Show more Android TV search results * Restore Android TV search header position * Avoid profile switch preference flash * Match Android TV Dolby Vision detail metadata * Inline Android TV detail starring credits * Remove Android TV detail eyebrow pill * Match Android TV video library menu to tvOS * Improve Android TV cascade back focus * Fix TV person detail upward focus restoration * Redesign Android TV search experience * Fix cross-platform companion pairing * Bring SiloCast phone remote to Apple parity The working tree's v2 remote-playback handoff (offer/challenge/ready/ cancel, temporary TV identity overlay, TV standby screen) plus a full phone-side parity pass against silo-apple's SiloControl client: Controller lifecycle (mirrors SiloControlClient): - Phone-side heartbeat: ping every 3s, only pong resets liveness, 3 misses tear the transport down into the reconnect path. - Auto-reconnect with 1-4s backoff (5 attempts) and a "Reconnecting…" state that keeps target/playback for UI continuity; deliberate closes (ours or the TV's goodbye) never reconnect. - Persisted last target + silent foreground auto-resume, gated on the TV's Bonjour `playing` flag so idle TVs are never flipped into the standby takeover screen; unengaged auto-resumed sessions let go quietly. Wired via ProcessLifecycleOwner starter. - NSD browser now surfaces the server/serverName/playing TXT metadata. Phone remote UI (mirrors SiloControlRemoteView): - Blurred-artwork OLED backdrop, portrait poster (series poster for episodes - an episode's own poster is a landscape still), title block, "Playing on <TV>" pill, draggable scrubber with optimistic clock and elapsed/-remaining labels, 64dp play/pause with buffering spinner, +-10/30 skips, next episode, volume row, capability-gated Audio/Subtitles/Quality/Speed/Display menus. - Distinct connecting / reconnecting / launching / idle-connected / playing / error states; minimize chevron + overflow menu (Choose a Different TV / Stop Playback / Disconnect). - Target picker: searching -> 8s empty state -> rows with circled TV icon, "Playing now" / server-name / cross-server / update-required context, per-row connect spinner, stays open until connected. - Mini bar: poster thumb, reconnect spinner, "Playing on <TV>" line; rests above the bottom nav menu on tab screens (iOS accessory placement) and overlays only menu-less routes. - Home cast button: filled-disc active state with Remote Control / Choose TV / Turn Off Control Mode menu; "Play on device" from detail auto-presents the remote. Cross-device fixes found testing phone -> Shield: - Reused-identity launches (switching items mid-playback) deadlocked: the TV skips the challenge and answers handoff_ready directly, but the phone awaited only the challenge, timed out as a swallowed CancellationException, and the TV's ready-without-launch watchdog then ended the identity and closed the session mid-playback. The phone now races ready vs challenge, handoff timeouts surface as real errors, and the TV watchdog never tears down an identity a live player is using (handoff_cancel also disarms it). - Half-open connect no longer leaks the TLS socket when a reconnect attempt is cancelled mid-handshake. Co-Authored-By: Claude Fable 5 <[email protected]> * Make the bottom nav bar translucent glass like iOS Tab content now scrolls edge-to-edge beneath the bottom chrome instead of stopping above it: the main scaffold publishes the measured chrome height (nav bar + gesture inset + cast mini bar when visible) through LocalBottomChromeInset, and the five tab screens add it to their scroll end padding so the last items stay reachable. The bar's near-opaque fill becomes a translucent gradient scrim (72% -> 94% background) with the same hairline the top chrome uses, so content reads through it in motion — the dependency-free equivalent of iOS's glass tab bar (true backdrop blur would need API 31 + a blur pipeline like Haze). Co-Authored-By: Claude Fable 5 <[email protected]> * Match Android TV For You saved lists to tvOS * Polish Calendar focus and tvOS styling * Refine TV top navigation sizing * Increase TV media card typography * Adopt Inter typography for Android TV * Restore translucent TV card overlays * Smooth Android TV skyline first focus * Refine Android TV skyline transitions * Restore Home card focus after detail * Refine Android TV Home skyline layout * Reset Home to first card on menu re-select Selecting the Home tab from the bar now returns the skyline to its launch state: the row band animates back to the top at constant velocity and focus lands on row 0 / card 0. Direct focus requests from the bar were silently cancelled: a focusRestorer group cancels (and rolls back) any programmatic request that targets one of its descendants, while honoring a request on the group itself. Focus therefore walks down one scope per frame — content group, first-row group, then first card — with the row group hop exposed via a new rowContainerFocusRequester on TvMediaRow. * Gate feed focus token on RESUMED lifecycle The shell bumps contentFocusRequest for every menu selection, and during the route crossfade the exiting feed is still composed — so selecting Calendar made Home briefly flash focus on its first card before the Following filter handoff landed. The feed now waits for its own nav entry to reach RESUMED before applying the token; exiting entries never resume, so they park until disposal with the token already consumed. * Remove duplicate search query length constant TV_SEARCH_QUERY_MAX_LENGTH already lives in TvSearchInputRules.kt (internal, shared with TvRequestsScreen); the private duplicate in TvSearchScreen.kt collided with it and broke clean builds once stale compile caches were gone. * Align TV detail hero styling with tvOS Match the tvOS item detail visual language on the Android TV canvas (tvOS points ÷ 2): - Hero title set in bundled Inter Tight Black at 42sp (tvOS uses SF Pro Compressed .black at 92pt); Starring moves to a right-edge overlay like tvOS. - Editorial type rescaled per on-device review: episode title, season/episode line, synopsis, facts, source tokens, and section headers all bumped or trimmed to the tvOS proportions. - Buttons keep their original height while glyphs grow (fixed icon slot + requiredSize overflow); play glyph 30dp, Start Over 20dp. - Selector pills restyled (22x12 padding, larger label/value type); Version uses the tv glyph and Subtitles a chat bubble, matching tvOS captions.bubble instead of the narrower CC badge. - Source-parity test updated to pin the new tokens. * Match tvOS playback pill labels and date rendering - Audio/subtitle pill values follow Apple's formats: "Auto: English · EAC3 · 5.1", "English (Forced) · SRT", "Auto: Off"; track titles fall back language -> useful title -> "Track N", with SDH/Forced suffixes and codec tags appended like TVPlaybackSelectorRow.swift. - srt renders as SRT (was SubRip). - Dates parse as UTC instants (timestamps and bare dates alike) and render in the viewer's zone, replicating tvOS behavior; the episode rail delegates to the same formatter. Zone is injectable for tests. - Formatting/metadata tests updated to the new contracts, plus a viewer-zone regression test. * Pace TV detail anchor scrolls and fix focus traversal - Hero<->episodes anchor scrolls use a custom 260ms ease-in-out tween (animateScrollBy) instead of animateScrollToItem's fixed spec, and the bring-into-view spec moves to a 620ms ease-in-out, tracking tvOS TVDetailFocusScroll's easeInOut(0.45). - Focusing the episodes section (chips or cards) centers it in the viewport, matching tvOS's .center scroll anchor. - Entering the hero action cluster always lands on Play instead of the geometrically nearest toggle; Up from episodes stops at the Version/Audio/Subtitles selector row before reaching the actions. - Start Over uses the skip-to-start glyph and the next-up placeholder pill matches the real selector's styling. * Polish TV detail rhythm and restore cast focus on return - Derive every detail body section gap and the hero handoff from a single TvDetailSectionGap constant (28dp, matching the selectors -> Episodes gap) so the next section header peeks into view and the rhythm tunes in one place - Enlarge the hero "Starring" credit to 16sp with a wider max width - Remember which cast card pushed a person page and restore focus to it on return instead of snapping back to Play * Restore Home focus to the launch card after detail return The shell's content focusRestorer loses its saved child node when the outer item-detail route removes the shell, so returning from a detail page landed focus a row below the card the user left from. - Remember the launch (row, item) across the round trip and re-target it with an early recreation-time ladder (row group, then card, one restorer scope per frame), verified via the card's real focus callback - Point the content and row restorer enter fallbacks at the launch card while the return is pending so even default focus assignment resolves there - Skip the shell's ON_RESUME content claim when focus is already inside the content group - re-entering the group re-ran its focus search and yanked focus to the next row's first card for a frame * Restore focus to launching cast card on person-page return Route entries into the cast rail to the pending restore card instead of card 0 while a person-page return is in flight, and end the restore window on the card's real focus gain rather than a fixed frame count. * Align TV person page with tvOS and add scrollable bio modal Match tvOS PersonDetailView sizing/format (portrait, name, badges, filmography header with count label, filter chips, 6-column grid), strip the TMDB Wikipedia attribution paragraph from bios, and make the bio a focus stop reachable via Up from the filter chips — OK opens the full bio in a dimmed, D-pad-scrollable modal. * Hide person filmography chips for media types with no works Probe each media type's server-side total (limit=1, in parallel) when the person page loads and drop chips whose count is zero, intersected with the existing library gating. All always shows, failed probes keep their chip, and a vanished active filter falls back to All. * Match tvOS library Browse: sort/filter controls, facets, 6-column grid Port TVLibraryGridView's browse surface to Android TV: - Sort · Filter capsule control row above the grid, with direction hint and active-facet count badge (TVBrowseControlRow parity). - Sort overlay panel listing per-media-type sort keys; re-picking the active key flips direction (tvOS setSort semantics). - Two-level filter overlay panel (facet list -> values) with the full tvOS facet set, multi-select, per-facet clear, match all/any, and reset; selections lower to the same structured groups[...] catalog query iOS CatalogQueryBuilder emits. - Facet vocabulary loaded from /catalog/filters with include_technical. - Browse grid: 6 columns, always-on A-Z rail, taller tvOS content top inset (216pt -> 108dp), Title A-Z default sort. - Focusing the control row re-anchors the grid to offset 0 (looped while focused, since the focus bring-into-view scroll would cancel a one-shot scroll on the shared scrollable state). * Polish A-Z rail: dot peek, All pill, jump-to-All entry, Up hold, clear-filters pill - Collapsed rail renders a condensed dot cluster (every other entry, selected position brighter) instead of micro letters; entries stay single persistent focusable Surfaces so expansion cannot drop focus. - Expanded letters grow to 42dp/18sp chips; "All" renders as a standard app pill; margins sit outside the scroll viewport so scrolled letters clip instead of drawing over the nav bar. - Focus entering the rail always lands on "All"; the rail is hidden unless the browse sort is Title (A-Z). - D-pad Up inside the rail is routed through the shell's contentUpFallback hook (the shell consumes all Up keys in the preview phase, so rail-local key handlers never fire): letters step up, "All" holds instead of escaping to the top menu. - Active facet filters add a "Clear filters" pill next to Filter; focus hops to the Filter pill before the Clear pill leaves composition. * Restyle TV settings to tvOS parity: full-screen split rail, mono headers, focus-driven panes * Move search into tab cluster, restore feed focus after settings, avatar-return polish * Prefetch startup content during splash and snap first hero paint - Cap the startup splash at 4s (video end or cap, whichever first), matching StartupSplashView's maximumDisplayDuration on Apple; drop the TV-side 5.2s minimum floor - Compose the app underneath the splash overlay so Home fetches, paints, and settles entry focus while the animation plays; root-level key gate keeps input consumed until the reveal - Port StartupContentPrefetcher's artwork warmup: warm the first screen's posters, marquee backdrops/logo (TV, 28 URLs) or posters (phone, 12) plus the active profile avatar through Coil during the splash - Warm profile list + avatar art when a cold launch lands on profile selection (prefetchForInitialRoute(.needsProfile) parity) - Snap the FIRST marquee/backdrop/tint display instead of fading up from black; only content-to-content swaps crossfade (tvOS 07ed712/d313a3d) - Memoize sampled ambient accents per URL (HeroBackdropPalette.tintCache parity) so revisits paint the wash with the artwork * Update Android TV tests for UI polish * Finish updating Android TV UI tests * Wait for long press release before menu selection * Use dark styling for TV popup menus * Prevent duplicate TV playback launches * Clear cached resume when watched state changes * Fix TV card action menu focus * Restore Home first row from navigation * Avoid flashing intermediate Home focus * Animate Calendar re-selection to top * Polish TV search navigation and filtering * Respect audiobook visibility on people pages * Polish TV navigation menus * Polish Android TV settings * Refine Android TV settings and server management * Polish Android TV settings rail focus * Polish Android TV onboarding and PIN entry * Add episode long-press actions * fix: harden cast handoffs and watched state sync * fix: address follow-up PR review feedback --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: zZebrahz <[email protected]>
1 parent 6defbcf commit 04fb276

206 files changed

Lines changed: 12795 additions & 3149 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,4 @@ media-fixtures/*
5454

5555
# Local review notes (not for publishing)
5656
docs/reviews/
57+
ui-validation/
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package org.siloserver.silo.common.calendar
2+
3+
import org.siloserver.silo.model.calendar.CalendarItem
4+
import java.time.Instant
5+
import java.time.LocalTime
6+
import java.time.ZoneId
7+
import java.time.format.DateTimeFormatter
8+
import java.util.Locale
9+
10+
/**
11+
* Calendar air time in the viewer's local timezone, always using an AM/PM clock.
12+
* Absolute `air_at` values are authoritative; `air_time` is only a legacy
13+
* wall-clock fallback and cannot be timezone-converted safely.
14+
*/
15+
fun CalendarItem.localDisplayAirTime(
16+
zoneId: ZoneId = ZoneId.systemDefault(),
17+
locale: Locale = Locale.getDefault(),
18+
): String? {
19+
val formatter = DateTimeFormatter.ofPattern("h:mm a", locale)
20+
21+
airAt?.takeIf(String::isNotBlank)?.let { timestamp ->
22+
runCatching {
23+
Instant.parse(timestamp).atZone(zoneId).format(formatter)
24+
}.getOrNull()?.let { return it }
25+
}
26+
27+
val wallClock = airTime?.takeIf { it.isNotBlank() && it != "00:00" } ?: return null
28+
return runCatching {
29+
LocalTime.parse(wallClock).format(formatter)
30+
}.getOrElse { wallClock }
31+
}

‎android-shared/src/androidMain/kotlin/org/siloserver/silo/common/cast/SiloCastNsdBrowser.kt‎

Lines changed: 83 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.asStateFlow
1010
import kotlinx.coroutines.flow.update
1111
import org.siloserver.silo.cast.SiloCastProtocol
1212
import java.nio.charset.Charset
13+
import java.util.ArrayDeque
1314

1415
data class SiloCastTarget(
1516
val deviceId: String,
@@ -21,6 +22,14 @@ data class SiloCastTarget(
2122
* onServiceLost only reports this, so removal must match on it — the
2223
* display name comes from the TXT record and can collide/diverge. */
2324
val serviceName: String = name,
25+
/** The receiver's active server (TXT `server`) — same-server targets are
26+
* controllable without a handoff; others need the v2 profile handoff. */
27+
val serverId: String? = null,
28+
val serverName: String? = null,
29+
/** The receiver's advertised `playing` TXT flag. Drives the picker's
30+
* "Playing now" badge and gates silent auto-resume (idle TVs must never
31+
* be reattached — a bare connection flips them into standby takeover). */
32+
val isPlaying: Boolean = false,
2433
)
2534

2635
class SiloCastNsdBrowser(context: Context) {
@@ -31,6 +40,8 @@ class SiloCastNsdBrowser(context: Context) {
3140
val targets: StateFlow<List<SiloCastTarget>> = _targets.asStateFlow()
3241

3342
private var discoveryListener: NsdManager.DiscoveryListener? = null
43+
private val pendingResolutions = ArrayDeque<PendingResolution>()
44+
private var activeResolution: PendingResolution? = null
3445

3546
@Synchronized
3647
fun start() {
@@ -45,11 +56,17 @@ class SiloCastNsdBrowser(context: Context) {
4556
// trailing dot ("_silocast._tcp."); exact equality would
4657
// silently reject every receiver.
4758
if (serviceInfo.serviceType.trimEnd('.') != SiloCastProtocol.serviceType.trimEnd('.')) return
48-
resolve(serviceInfo)
59+
enqueueResolution(serviceInfo)
4960
}
5061

5162
override fun onServiceLost(serviceInfo: NsdServiceInfo) {
5263
val lostName = serviceInfo.serviceName
64+
synchronized(this@SiloCastNsdBrowser) {
65+
activeResolution
66+
?.takeIf { it.serviceInfo.serviceName == lostName }
67+
?.cancelled = true
68+
pendingResolutions.removeAll { it.serviceInfo.serviceName == lostName }
69+
}
5370
_targets.update { targets -> targets.filterNot { it.serviceName == lostName } }
5471
}
5572

@@ -76,26 +93,75 @@ class SiloCastNsdBrowser(context: Context) {
7693
runCatching { nsdManager.stopServiceDiscovery(listener) }
7794
}
7895
discoveryListener = null
96+
pendingResolutions.clear()
97+
activeResolution = null
7998
_targets.value = emptyList()
8099
}
81100

82-
private fun resolve(serviceInfo: NsdServiceInfo) {
83-
nsdManager.resolveService(
84-
serviceInfo,
101+
/**
102+
* Legacy NsdManager permits only one resolve at a time. Bonjour commonly
103+
* reports Apple TV and Android TV receivers together; resolving both in
104+
* parallel returns FAILURE_ALREADY_ACTIVE and silently drops one target.
105+
*/
106+
private fun enqueueResolution(serviceInfo: NsdServiceInfo) {
107+
val next = synchronized(this) {
108+
if (discoveryListener == null) return
109+
val serviceName = serviceInfo.serviceName
110+
if (activeResolution?.takeUnless { it.cancelled }?.serviceInfo?.serviceName == serviceName ||
111+
pendingResolutions.any { it.serviceInfo.serviceName == serviceName }
112+
) {
113+
return
114+
}
115+
pendingResolutions.addLast(PendingResolution(serviceInfo))
116+
takeNextResolutionLocked()
117+
}
118+
next?.let(::startResolution)
119+
}
120+
121+
private fun startResolution(pending: PendingResolution) {
122+
runCatching {
123+
nsdManager.resolveService(
124+
pending.serviceInfo,
85125
object : NsdManager.ResolveListener {
86126
override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {
87127
Log.w(TAG, "SiloCast resolve failed for ${info.serviceName}: $errorCode")
128+
finishResolution(pending)
88129
}
89130

90131
override fun onServiceResolved(info: NsdServiceInfo) {
91-
val target = info.toSiloCastTarget() ?: return
92-
_targets.update { current ->
93-
(current.filterNot { it.deviceId == target.deviceId } + target)
94-
.sortedBy { it.name.lowercase() }
132+
val mayPublish = synchronized(this@SiloCastNsdBrowser) {
133+
discoveryListener != null && activeResolution === pending && !pending.cancelled
134+
}
135+
if (mayPublish) {
136+
info.toSiloCastTarget()?.let { target ->
137+
_targets.update { current ->
138+
(current.filterNot { it.deviceId == target.deviceId } + target)
139+
.sortedBy { it.name.lowercase() }
140+
}
141+
}
95142
}
143+
finishResolution(pending)
96144
}
97145
},
98-
)
146+
)
147+
}.onFailure { error ->
148+
Log.w(TAG, "SiloCast resolve could not start for ${pending.serviceInfo.serviceName}", error)
149+
finishResolution(pending)
150+
}
151+
}
152+
153+
private fun finishResolution(completed: PendingResolution) {
154+
val next = synchronized(this) {
155+
if (activeResolution !== completed) return
156+
activeResolution = null
157+
takeNextResolutionLocked()
158+
}
159+
next?.let(::startResolution)
160+
}
161+
162+
private fun takeNextResolutionLocked(): PendingResolution? {
163+
if (activeResolution != null || pendingResolutions.isEmpty()) return null
164+
return pendingResolutions.removeFirst().also { activeResolution = it }
99165
}
100166

101167
private fun NsdServiceInfo.toSiloCastTarget(): SiloCastTarget? {
@@ -112,12 +178,20 @@ class SiloCastNsdBrowser(context: Context) {
112178
host = host,
113179
port = port,
114180
version = version,
181+
serverId = attributes.string("server"),
182+
serverName = attributes.string("serverName"),
183+
isPlaying = attributes.string("playing") == "1",
115184
)
116185
}
117186

118187
private fun Map<String, ByteArray>.string(key: String): String? =
119188
this[key]?.toString(Charset.forName("UTF-8"))?.takeIf { it.isNotBlank() }
120189

190+
private class PendingResolution(
191+
val serviceInfo: NsdServiceInfo,
192+
var cancelled: Boolean = false,
193+
)
194+
121195
private companion object {
122196
const val TAG = "SiloCastNsdBrowser"
123197
}

‎android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/DirtyOperationDao.kt‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,36 @@ interface DirtyOperationDao {
3939
)
4040
suspend fun deletePendingByCoalesceKey(coalesceKey: String)
4141

42+
@Query(
43+
"SELECT * FROM dirty_operations WHERE coalesceKey = :coalesceKey " +
44+
"ORDER BY id DESC LIMIT 1",
45+
)
46+
suspend fun getLatestByCoalesceKey(coalesceKey: String): DirtyOperationEntity?
47+
48+
@Query(
49+
"DELETE FROM dirty_operations WHERE serverId = :serverId AND profileId = :profileId " +
50+
"AND targetContentId = :contentId AND opKind = :opKind " +
51+
"AND state = '${DirtyOperationEntity.STATE_PENDING}'",
52+
)
53+
suspend fun deletePendingForTargetKind(
54+
serverId: String,
55+
profileId: String,
56+
contentId: String,
57+
opKind: String,
58+
)
59+
60+
@Query(
61+
"SELECT COUNT(*) FROM dirty_operations WHERE serverId = :serverId AND profileId = :profileId " +
62+
"AND targetContentId = :contentId AND opKind = :opKind " +
63+
"AND state = '${DirtyOperationEntity.STATE_IN_FLIGHT}'",
64+
)
65+
suspend fun countInFlightForTargetKind(
66+
serverId: String,
67+
profileId: String,
68+
contentId: String,
69+
opKind: String,
70+
): Int
71+
4272
/**
4373
* Oldest-due-first batch of sendable ops for one server/profile scope
4474
* (FIFO via the nextAttemptAtMs,id index). Scoped because the shared HTTP

‎android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/db/dao/UserItemStateDao.kt‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,35 @@ interface UserItemStateDao {
3030
)
3131
suspend fun getByContent(serverId: String, profileId: String, contentId: String): List<UserItemStateEntity>
3232

33+
/** Clears resume state without discarding per-file playback or reading preferences. */
34+
@Query(
35+
"UPDATE user_item_state SET positionSeconds = 0, clientUpdatedAtMs = :updatedAtMs " +
36+
"WHERE serverId = :serverId AND profileId = :profileId AND contentId = :contentId " +
37+
"AND positionSeconds <> 0",
38+
)
39+
suspend fun clearPlaybackProgress(
40+
serverId: String,
41+
profileId: String,
42+
contentId: String,
43+
updatedAtMs: Long,
44+
)
45+
46+
/** Restore a reset resume row only while it is still the untouched reset. */
47+
@Query(
48+
"UPDATE user_item_state SET positionSeconds = :positionSeconds, clientUpdatedAtMs = :previousUpdatedAtMs " +
49+
"WHERE serverId = :serverId AND profileId = :profileId AND contentId = :contentId " +
50+
"AND fileId = :fileId AND positionSeconds = 0 AND clientUpdatedAtMs = :clearedAtMs",
51+
)
52+
suspend fun restorePlaybackProgressIfUnchanged(
53+
serverId: String,
54+
profileId: String,
55+
contentId: String,
56+
fileId: Int,
57+
positionSeconds: Double,
58+
previousUpdatedAtMs: Long,
59+
clearedAtMs: Long,
60+
)
61+
3362
@Query(
3463
"SELECT * FROM user_item_state " +
3564
"WHERE serverId = :serverId AND profileId = :profileId " +

‎android-shared/src/androidMain/kotlin/org/siloserver/silo/common/data/repository/RoomUserItemStateRepository.kt‎

Lines changed: 70 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import org.siloserver.silo.common.data.db.entity.UserItemStateEntity
88
import org.siloserver.silo.common.data.sync.OutboxOperation
99
import org.siloserver.silo.common.data.sync.OutboxSyncScheduler
1010
import org.siloserver.silo.common.data.sync.revertForTerminalOp
11+
import org.siloserver.silo.common.data.sync.restorePlaybackProgressForTerminalOp
1112
import org.siloserver.silo.network.AuthScopeSnapshot
1213
import org.siloserver.silo.repository.port.EbookLocalProgress
1314
import org.siloserver.silo.repository.port.LocalContentState
@@ -52,7 +53,12 @@ class RoomUserItemStateRepository(
5253
private val outboxDao = db.dirtyOperationDao()
5354

5455
override suspend fun recordWatched(contentId: String, watched: Boolean): OutboxHandle =
55-
record(contentId, OutboxOperation.SET_WATCHED, JsonPrimitive(watched).toString()) {
56+
record(
57+
contentId,
58+
OutboxOperation.SET_WATCHED,
59+
JsonPrimitive(watched).toString(),
60+
clearPlaybackProgress = true,
61+
) {
5662
it.copy(watched = watched)
5763
}
5864

@@ -261,13 +267,28 @@ class RoomUserItemStateRepository(
261267
override suspend fun resolve(handle: OutboxHandle, outcome: WriteOutcome) {
262268
if (handle.opId < 0) return
263269
when (outcome) {
264-
// Acked: server matches our optimistic projection; just drop the op.
265-
WriteOutcome.SYNCED -> outboxDao.deleteById(handle.opId)
270+
// Acked: normally drop the op. A watched mutation recorded while an
271+
// older position was already in flight stays queued for one final,
272+
// idempotent replay so that position cannot land last and resurrect
273+
// Continue Watching.
274+
WriteOutcome.SYNCED -> {
275+
val op = outboxDao.getById(handle.opId)
276+
val requiresReplay = op?.takeIf { it.opKind == OutboxOperation.SET_WATCHED }
277+
?.let { runCatching { OutboxOperation.decodeWatchedPayload(it.payloadJson).requiresReplay }.getOrDefault(false) }
278+
?: false
279+
if (requiresReplay) syncScheduler.requestSync()
280+
else outboxDao.deleteById(handle.opId)
281+
}
266282
// Rejected for good: drop the op AND revert the optimistic projection
267283
// field so the card overlay defers to server state (no fake local state
268284
// across cold starts).
269285
WriteOutcome.TERMINAL -> db.withTransaction {
270-
outboxDao.getById(handle.opId)?.let { contentDao.revertForTerminalOp(it) }
286+
outboxDao.getById(handle.opId)?.let {
287+
if (outboxDao.countNewerPending(it.coalesceKey, it.id) == 0) {
288+
contentDao.revertForTerminalOp(it)
289+
userStateDao.restorePlaybackProgressForTerminalOp(it)
290+
}
291+
}
271292
outboxDao.deleteById(handle.opId)
272293
}
273294
// Transient: leave the pending op and ask the sync engine to drain it.
@@ -288,6 +309,7 @@ class RoomUserItemStateRepository(
288309
contentId: String,
289310
opKind: String,
290311
payloadJson: String,
312+
clearPlaybackProgress: Boolean = false,
291313
applyField: (ContentItemStateEntity) -> ContentItemStateEntity,
292314
): OutboxHandle {
293315
val snapshot = snapshotProvider() ?: return OutboxHandle.NONE
@@ -312,6 +334,49 @@ class RoomUserItemStateRepository(
312334
)
313335
contentDao.upsert(applyField(existing).copy(clientUpdatedAtMs = nowMs))
314336

337+
var operationPayload = payloadJson
338+
if (clearPlaybackProgress) {
339+
val watchedCoalesceKey = "$serverId|$profileId|$contentId|${OutboxOperation.SET_WATCHED}"
340+
// An older watched mutation may already be in flight. Preserve
341+
// its rollback data too: if it fails after this newer intent is
342+
// queued, the older op deliberately defers rollback to us.
343+
val inheritedPayload = outboxDao.getLatestByCoalesceKey(watchedCoalesceKey)
344+
?.let { runCatching { OutboxOperation.decodeWatchedPayload(it.payloadJson) }.getOrNull() }
345+
val clearedByFile = inheritedPayload?.clearedProgress
346+
.orEmpty()
347+
.associateByTo(linkedMapOf()) { it.fileId }
348+
userStateDao.getByContent(serverId, profileId, contentId)
349+
.filter { it.positionSeconds > 0.0 }
350+
.forEach { row ->
351+
clearedByFile[row.fileId] = OutboxOperation.ClearedPlaybackProgress(
352+
fileId = row.fileId,
353+
positionSeconds = row.positionSeconds,
354+
previousClientUpdatedAtMs = row.clientUpdatedAtMs,
355+
clearedAtMs = nowMs,
356+
)
357+
}
358+
val hasInFlightPosition = outboxDao.countInFlightForTargetKind(
359+
serverId = serverId,
360+
profileId = profileId,
361+
contentId = contentId,
362+
opKind = OutboxOperation.SET_POSITION,
363+
) > 0
364+
outboxDao.deletePendingForTargetKind(
365+
serverId = serverId,
366+
profileId = profileId,
367+
contentId = contentId,
368+
opKind = OutboxOperation.SET_POSITION,
369+
)
370+
userStateDao.clearPlaybackProgress(serverId, profileId, contentId, nowMs)
371+
operationPayload = OutboxOperation.encodeWatchedPayload(
372+
OutboxOperation.WatchedPayload(
373+
watched = OutboxOperation.decodeBooleanPayload(payloadJson),
374+
clearedProgress = clearedByFile.values.toList(),
375+
requiresReplay = inheritedPayload?.requiresReplay == true || hasInFlightPosition,
376+
),
377+
)
378+
}
379+
315380
opId = outboxDao.enqueueCoalescing(
316381
DirtyOperationEntity(
317382
opKind = opKind,
@@ -321,7 +386,7 @@ class RoomUserItemStateRepository(
321386
targetFileId = null,
322387
coalesceKey = "$serverId|$profileId|$contentId|$opKind",
323388
idempotencyKey = idGenerator(),
324-
payloadJson = payloadJson,
389+
payloadJson = operationPayload,
325390
createdAtMs = nowMs,
326391
nextAttemptAtMs = nowMs,
327392
),

0 commit comments

Comments
 (0)