ProfileTogetherSession.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSession.kt
1package eu.friedcutlet.yokan.services.together23import eu.friedcutlet.yokan.data.YokanRepository4import eu.friedcutlet.yokan.database.DbSettings5import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.database.YokanDatabase7import eu.friedcutlet.yokan.database.DbSyncPreference8import eu.friedcutlet.yokan.database.SyncServerProvider9import eu.friedcutlet.yokan.services.catchingNonCancellation10import eu.friedcutlet.yokan.services.runJoined11import eu.friedcutlet.yokan.services.logging.AppLogger12import eu.friedcutlet.yokan.services.library.sortedChapters13import eu.friedcutlet.yokan.services.http.HttpService14import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine15import eu.friedcutlet.yokan.services.http.normalizeHubServer16import io.ktor.client.engine.HttpClientEngine17import kotlinx.coroutines.CancellationException18import kotlinx.coroutines.CoroutineScope19import kotlinx.coroutines.ExperimentalCoroutinesApi20import kotlinx.coroutines.Job21import kotlinx.coroutines.NonCancellable22import kotlinx.coroutines.SupervisorJob23import kotlinx.coroutines.currentCoroutineContext24import kotlinx.coroutines.ensureActive25import kotlinx.coroutines.flow.MutableStateFlow26import kotlinx.coroutines.flow.asStateFlow27import kotlinx.coroutines.flow.flatMapLatest28import kotlinx.coroutines.flow.flowOf29import kotlinx.coroutines.flow.map30import kotlinx.coroutines.flow.distinctUntilChanged31import kotlinx.coroutines.flow.update32import kotlinx.coroutines.launch33import kotlinx.coroutines.sync.Mutex34import kotlinx.coroutines.sync.withLock35import kotlinx.coroutines.withContext3637/** Where following a room's media leads in this profile's library. */38internal sealed interface RoomMediaTarget {39 data class Open(val mangaId: Long, val chapterId: Long) : RoomMediaTarget40 data class NotInLibrary(val title: String, val sourceName: String?) : RoomMediaTarget41 data class NoChapters(val title: String) : RoomMediaTarget42}4344/** Mutable room state and transports belong to the captured profile, including external UI calls. */45@OptIn(ExperimentalCoroutinesApi::class)46internal class ProfileTogetherSession(47 val profileId: ProfileId,48 private val database: YokanDatabase,49 ownerScope: CoroutineScope,50 private val engineFactory: (ProfileId) -> HttpClientEngine = ::createPlatformHttpClientEngine,51) {52 private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Together requires an owner job" }53 private val job = SupervisorJob(ownerJob)54 private val scope = CoroutineScope(ownerScope.coroutineContext + job)55 private val operationLock = Mutex()56 // Retain clients until successful cleanup, including an interrupted room replacement.57 private val clients = mutableListOf<RoomClient>()58 private var activeAccount: RoomAccount? = null59 private val _client = MutableStateFlow<RoomClient?>(null)60 val client = _client.asStateFlow()61 val state = _client.flatMapLatest { it?.state ?: flowOf(null) }62 private val _following = MutableStateFlow(true)63 val following = _following.asStateFlow()64 private val _driving = MutableStateFlow(false)65 val driving = _driving.asStateFlow()6667 init {68 scope.launch {69 database.snapshots().map { account(it.syncPreferences.firstOrNull()) }.distinctUntilChanged().collect {70 catchingNonCancellation {71 operationLock.withLock {72 val current = _client.value73 if (current != null && (activeAccount != currentAccount() || !current.isAvailable)) {74 clearCurrent()75 closeClients()76 }77 }78 }.onFailure {79 // Keep failed cleanup targets for explicit leave/join or session retirement.80 AppLogger.warn("[together] account-change cleanup failed (${it::class.simpleName}); cleanup can be retried")81 }82 }83 }84 }8586 fun setFollowing(value: Boolean) { if (ownerJob.isActive && job.isActive && _client.value?.isAvailable != false) _following.update { value } }87 fun setDriving(value: Boolean) { if (ownerJob.isActive && job.isActive && _client.value?.isAvailable != false) _driving.update { value } }8889 private data class RoomAccount(val syncId: Long?, val session: HubSession)9091 private fun account(pref: DbSyncPreference?): RoomAccount? {92 pref ?: return null93 if (pref.serverProvider != SyncServerProvider.YokanHub) return null94 val server = normalizeHubServer(pref.server) ?: return null95 val token = pref.authToken?.takeIf { it.isNotBlank() } ?: return null96 return RoomAccount(pref.syncId, HubSession(server, token, pref.deviceId ?: "unknown"))97 }9899 private fun currentAccount(): RoomAccount? {100 if (!ownerJob.isActive || !job.isActive) return null101 return account(database.syncPreferences().firstOrNull())102 }103104 fun hubSession(): HubSession? = currentAccount()?.session105106 private fun clearCurrent() {107 _client.value?.revoke()108 _client.update { null }; activeAccount = null109 _following.update { true }; _driving.update { false }110 }111112 private suspend fun closeClients() {113 while (clients.isNotEmpty()) {114 clients.first().closeAndJoin()115 clients.removeAt(0)116 }117 }118119 private suspend fun <T> runOwned(action: suspend () -> T): T = scope.runJoined { action() }120121 /** A completed create operation retains its exact client for guarded UI delivery. */122 class JoinedRoom(val created: RoomApi.Created, val client: RoomClient)123124 fun owns(candidate: RoomClient): Boolean = ownerJob.isActive && job.isActive &&125 _client.value === candidate && candidate.isAvailable126127 /**128 * Resolves the room's [media] against this profile's library: the matching chapter (or the129 * first unread, or the first) of the local title. Null once the current room no longer shows130 * [media]. Repository reads are synchronous snapshot lookups.131 */132 fun resolveMedia(media: RoomMedia, repository: YokanRepository, settings: DbSettings): RoomMediaTarget? {133 if (_client.value?.state?.value?.media != media) return null134 val manga = repository.snapshots.value.mangas.firstOrNull {135 it.link == media.link &&136 (it.sourceId == media.sourceId || (media.sourceName != null && it.source.equals(media.sourceName, ignoreCase = true)))137 }?.id?.let(repository::manga)138 ?: return RoomMediaTarget.NotInLibrary(media.title ?: media.link, media.sourceName)139 val chapters = sortedChapters(manga, repository.chapters(manga.id), settings)140 val target = media.chapter?.url?.let { url -> chapters.firstOrNull { it.url == url } }141 ?: chapters.firstOrNull { !it.isRead } ?: chapters.firstOrNull()142 return target?.let { RoomMediaTarget.Open(manga.id, it.id) } ?: RoomMediaTarget.NoChapters(manga.name)143 }144145 /** Own REST creation and socket replacement as one joined profile/controller call. */146 suspend fun createAndJoin(http: HttpService, media: RoomMedia): Result<JoinedRoom>? = runOwned {147 val captured = currentAccount() ?: return@runOwned null148 val callJob = requireNotNull(currentCoroutineContext()[Job])149 val created = RoomApi(http) { callJob.isActive && currentAccount() == captured }150 .create(captured.session, media)151 val result = created.getOrElse { return@runOwned Result.failure(it) }152 currentCoroutineContext().ensureActive()153 val next = joinAccount(captured, result.code)154 ?: throw CancellationException("Together account changed before joining the created room.")155 Result.success(JoinedRoom(result, next))156 }157158 /** Reject an old account snapshot rather than connecting its token after settings changed. */159 suspend fun join(session: HubSession, code: String): RoomClient? = runOwned {160 val captured = currentAccount()?.takeIf { it.session == session } ?: return@runOwned null161 joinAccount(captured, code)162 }163164 private suspend fun joinAccount(captured: RoomAccount, code: String): RoomClient? = operationLock.withLock {165 currentCoroutineContext().ensureActive(); ownerJob.ensureActive()166 if (currentAccount() != captured) return@withLock null167 clearCurrent()168 closeClients()169 currentCoroutineContext().ensureActive(); ownerJob.ensureActive()170 if (currentAccount() != captured) return@withLock null171 val next = RoomClient(engineFactory(profileId), captured.session, code, scope) { currentAccount() == captured }172 clients += next173 activeAccount = captured174 _following.update { true }; _driving.update { false }175 _client.update { next }176 next.connect()177 next178 }179180 suspend fun leave(expectedClient: RoomClient? = null) = runOwned {181 operationLock.withLock {182 if (expectedClient != null && _client.value !== expectedClient) return@withLock183 clearCurrent()184 closeClients()185 }186 }187188 suspend fun closeAndJoin() {189 job.cancel()190 withContext(NonCancellable) {191 job.join()192 operationLock.withLock {193 clearCurrent()194 closeClients()195 }196 }197 }198}199