package eu.friedcutlet.yokan.services.together import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.media.player.MediaPlayerController import eu.friedcutlet.yokan.util.nowMillis import kotlin.math.abs import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.ensureActive import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.jsonPrimitive /* * Position sync between a room and the local reader/player. Host side reports, follower side * applies. `drives`/`follows` are the caller's admission checks; they are re-read before every * room message or player effect so a disposed screen or a replaced room stops immediately. */ /** The room's identity for [manga] / [chapter]. */ internal fun roomMediaFor(manga: Manga, chapter: Chapter?): RoomMedia = RoomMedia( itemType = manga.itemType.name.lowercase(), sourceId = manga.sourceId ?: 0L, link = manga.link, sourceName = manga.source, lang = manga.lang, title = manga.name, cover = manga.imageUrl, chapter = chapter?.let { RoomChapter(url = it.url, name = it.name) }, ) /** Same title and chapter as the room is showing? */ internal fun roomShows(media: RoomMedia?, manga: Manga, chapter: Chapter?): Boolean { media ?: return false val sameTitle = media.link == manga.link && (media.sourceId == (manga.sourceId ?: 0L) || media.sourceName.equals(manga.source, ignoreCase = true)) return sameTitle && media.chapter?.url == chapter?.url } /** Host: announce what is open unless the room already shows it. */ internal fun announceMedia(client: RoomClient, room: RoomState?, manga: Manga, chapter: Chapter) { if (!roomShows(room?.media, manga, chapter)) client.setMedia(roomMediaFor(manga, chapter)) } /** * Anime host: reports play/pause/speed and position every 5 s while playing, at once on a jump * or a paused seek. Runs until [drives] turns false. */ internal suspend fun reportPlayback( client: RoomClient, controller: MediaPlayerController, isPlaying: Boolean, speed: Float, drives: () -> Boolean, ) { var lastSentAt = 0L var lastSentPos = -1L while (drives()) { currentCoroutineContext().ensureActive() val pos = controller.currentPositionMs() val now = nowMillis() val expected = if (lastSentPos < 0) pos else lastSentPos + ((now - lastSentAt) * speed).toLong() val jumped = isPlaying && abs(pos - expected) > 1_500 if (lastSentPos < 0 || jumped || (isPlaying && now - lastSentAt >= 5_000) || (!isPlaying && lastSentPos != pos)) { if (!drives()) break client.sendPlayback(pos, isPlaying, speed.toDouble()) lastSentAt = now lastSentPos = pos } delay(1_000) } } /** * Anime follower: seeks when more than a second off the host's extrapolated position and mirrors * play/pause, reporting it through [onFollowPlaying]. Re-checks every 3 s while the host plays. * [position] is the snapshot the caller keyed on; [room] is the room as of now. */ internal suspend fun followPlayback( position: JsonObject?, room: RoomState?, manga: Manga, chapter: Chapter, controller: MediaPlayerController, follows: (RoomState?) -> Boolean, onFollowPlaying: (Boolean) -> Unit, ) { if (position == null || room == null || !follows(room) || !roomShows(room.media, manga, chapter)) return val hostPlaying = position["playing"]?.jsonPrimitive?.booleanOrNull ?: return while (follows(room)) { currentCoroutineContext().ensureActive() val expected = RoomReducer.expectedPositionMs(room, nowMillis()) ?: break if (abs(controller.currentPositionMs() - expected) > 1_000 && follows(room)) controller.seekTo(expected.coerceAtLeast(0)) if (follows(room) && controller.isPlaying() != hostPlaying) { if (!follows(room)) break if (hostPlaying) controller.play() else controller.pause() if (follows(room)) onFollowPlaying(hostPlaying) } if (!hostPlaying) break delay(3_000) } } /** Manga host: announce the chapter and report the current page. */ internal fun reportPage( client: RoomClient, room: RoomState?, manga: Manga, chapter: Chapter, pageIndex: Int, pageCount: Int, drives: () -> Boolean, ) { announceMedia(client, room, manga, chapter) if (pageCount > 0 && drives()) client.sendPage(pageIndex + 1, pageCount) } /** * Manga follower: the room's [page] (the snapshot the caller keyed on) as a clamped index, * passed to [onJump] when it differs from [pageIndex]. */ internal suspend fun followPage( page: Int?, room: RoomState?, manga: Manga, chapter: Chapter, pageIndex: Int, pageCount: Int, follows: (RoomState?) -> Boolean, onJump: (Int) -> Unit, ) { if (page == null || !follows(room) || pageCount == 0 || !roomShows(room?.media, manga, chapter)) return val index = (page - 1).coerceIn(0, pageCount - 1) currentCoroutineContext().ensureActive() if (index != pageIndex && follows(room)) onJump(index) } /** Novel host: report the scroll percentage after a 500 ms debounce. */ internal suspend fun reportProgress(client: RoomClient, progressPercent: Int, drives: () -> Boolean) { delay(500) if (drives()) client.sendProgress(progressPercent / 100.0) } /** Novel follower. Remembers the last applied ratio so jitter under 2 % is not re-applied. */ internal class ProgressFollower { private var lastApplied = -1.0 /** [progress] is the snapshot the caller keyed on; [room] is the room as of now. */ suspend fun follow( progress: Double?, room: RoomState?, manga: Manga, chapter: Chapter, follows: (RoomState?) -> Boolean, onFollow: suspend (Double) -> Unit, ) { if (progress == null || !progress.isFinite() || !follows(room) || !roomShows(room?.media, manga, chapter)) return if (abs(progress - lastApplied) < 0.02) return currentCoroutineContext().ensureActive() if (!follows(room)) return onFollow(progress.coerceIn(0.0, 1.0)) lastApplied = progress } }