RoomSync.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomSync.kt
1package eu.friedcutlet.yokan.services.together23import eu.friedcutlet.yokan.domain.Chapter4import eu.friedcutlet.yokan.domain.Manga5import eu.friedcutlet.yokan.services.media.player.MediaPlayerController6import eu.friedcutlet.yokan.util.nowMillis7import kotlin.math.abs8import kotlinx.coroutines.currentCoroutineContext9import kotlinx.coroutines.delay10import kotlinx.coroutines.ensureActive11import kotlinx.serialization.json.JsonObject12import kotlinx.serialization.json.booleanOrNull13import kotlinx.serialization.json.jsonPrimitive1415/*16 * Position sync between a room and the local reader/player. Host side reports, follower side17 * applies. `drives`/`follows` are the caller's admission checks; they are re-read before every18 * room message or player effect so a disposed screen or a replaced room stops immediately.19 */2021/** The room's identity for [manga] / [chapter]. */22internal fun roomMediaFor(manga: Manga, chapter: Chapter?): RoomMedia = RoomMedia(23 itemType = manga.itemType.name.lowercase(),24 sourceId = manga.sourceId ?: 0L,25 link = manga.link,26 sourceName = manga.source,27 lang = manga.lang,28 title = manga.name,29 cover = manga.imageUrl,30 chapter = chapter?.let { RoomChapter(url = it.url, name = it.name) },31)3233/** Same title and chapter as the room is showing? */34internal fun roomShows(media: RoomMedia?, manga: Manga, chapter: Chapter?): Boolean {35 media ?: return false36 val sameTitle = media.link == manga.link &&37 (media.sourceId == (manga.sourceId ?: 0L) || media.sourceName.equals(manga.source, ignoreCase = true))38 return sameTitle && media.chapter?.url == chapter?.url39}4041/** Host: announce what is open unless the room already shows it. */42internal fun announceMedia(client: RoomClient, room: RoomState?, manga: Manga, chapter: Chapter) {43 if (!roomShows(room?.media, manga, chapter)) client.setMedia(roomMediaFor(manga, chapter))44}4546/**47 * Anime host: reports play/pause/speed and position every 5 s while playing, at once on a jump48 * or a paused seek. Runs until [drives] turns false.49 */50internal suspend fun reportPlayback(51 client: RoomClient,52 controller: MediaPlayerController,53 isPlaying: Boolean,54 speed: Float,55 drives: () -> Boolean,56) {57 var lastSentAt = 0L58 var lastSentPos = -1L59 while (drives()) {60 currentCoroutineContext().ensureActive()61 val pos = controller.currentPositionMs()62 val now = nowMillis()63 val expected = if (lastSentPos < 0) pos else lastSentPos + ((now - lastSentAt) * speed).toLong()64 val jumped = isPlaying && abs(pos - expected) > 1_50065 if (lastSentPos < 0 || jumped || (isPlaying && now - lastSentAt >= 5_000) || (!isPlaying && lastSentPos != pos)) {66 if (!drives()) break67 client.sendPlayback(pos, isPlaying, speed.toDouble())68 lastSentAt = now69 lastSentPos = pos70 }71 delay(1_000)72 }73}7475/**76 * Anime follower: seeks when more than a second off the host's extrapolated position and mirrors77 * play/pause, reporting it through [onFollowPlaying]. Re-checks every 3 s while the host plays.78 * [position] is the snapshot the caller keyed on; [room] is the room as of now.79 */80internal suspend fun followPlayback(81 position: JsonObject?,82 room: RoomState?,83 manga: Manga,84 chapter: Chapter,85 controller: MediaPlayerController,86 follows: (RoomState?) -> Boolean,87 onFollowPlaying: (Boolean) -> Unit,88) {89 if (position == null || room == null || !follows(room) || !roomShows(room.media, manga, chapter)) return90 val hostPlaying = position["playing"]?.jsonPrimitive?.booleanOrNull ?: return91 while (follows(room)) {92 currentCoroutineContext().ensureActive()93 val expected = RoomReducer.expectedPositionMs(room, nowMillis()) ?: break94 if (abs(controller.currentPositionMs() - expected) > 1_000 && follows(room)) controller.seekTo(expected.coerceAtLeast(0))95 if (follows(room) && controller.isPlaying() != hostPlaying) {96 if (!follows(room)) break97 if (hostPlaying) controller.play() else controller.pause()98 if (follows(room)) onFollowPlaying(hostPlaying)99 }100 if (!hostPlaying) break101 delay(3_000)102 }103}104105/** Manga host: announce the chapter and report the current page. */106internal fun reportPage(107 client: RoomClient,108 room: RoomState?,109 manga: Manga,110 chapter: Chapter,111 pageIndex: Int,112 pageCount: Int,113 drives: () -> Boolean,114) {115 announceMedia(client, room, manga, chapter)116 if (pageCount > 0 && drives()) client.sendPage(pageIndex + 1, pageCount)117}118119/**120 * Manga follower: the room's [page] (the snapshot the caller keyed on) as a clamped index,121 * passed to [onJump] when it differs from [pageIndex].122 */123internal suspend fun followPage(124 page: Int?,125 room: RoomState?,126 manga: Manga,127 chapter: Chapter,128 pageIndex: Int,129 pageCount: Int,130 follows: (RoomState?) -> Boolean,131 onJump: (Int) -> Unit,132) {133 if (page == null || !follows(room) || pageCount == 0 || !roomShows(room?.media, manga, chapter)) return134 val index = (page - 1).coerceIn(0, pageCount - 1)135 currentCoroutineContext().ensureActive()136 if (index != pageIndex && follows(room)) onJump(index)137}138139/** Novel host: report the scroll percentage after a 500 ms debounce. */140internal suspend fun reportProgress(client: RoomClient, progressPercent: Int, drives: () -> Boolean) {141 delay(500)142 if (drives()) client.sendProgress(progressPercent / 100.0)143}144145/** Novel follower. Remembers the last applied ratio so jitter under 2 % is not re-applied. */146internal class ProgressFollower {147 private var lastApplied = -1.0148149 /** [progress] is the snapshot the caller keyed on; [room] is the room as of now. */150 suspend fun follow(151 progress: Double?,152 room: RoomState?,153 manga: Manga,154 chapter: Chapter,155 follows: (RoomState?) -> Boolean,156 onFollow: suspend (Double) -> Unit,157 ) {158 if (progress == null || !progress.isFinite() || !follows(room) || !roomShows(room?.media, manga, chapter)) return159 if (abs(progress - lastApplied) < 0.02) return160 currentCoroutineContext().ensureActive()161 if (!follows(room)) return162 onFollow(progress.coerceIn(0.0, 1.0))163 lastApplied = progress164 }165}166