package eu.friedcutlet.yokan.services.together import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.SyncServerProvider import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.runJoined import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.library.sortedChapters import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine import eu.friedcutlet.yokan.services.http.normalizeHubServer import io.ktor.client.engine.HttpClientEngine import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /** Where following a room's media leads in this profile's library. */ internal sealed interface RoomMediaTarget { data class Open(val mangaId: Long, val chapterId: Long) : RoomMediaTarget data class NotInLibrary(val title: String, val sourceName: String?) : RoomMediaTarget data class NoChapters(val title: String) : RoomMediaTarget } /** Mutable room state and transports belong to the captured profile, including external UI calls. */ @OptIn(ExperimentalCoroutinesApi::class) internal class ProfileTogetherSession( val profileId: ProfileId, private val database: YokanDatabase, ownerScope: CoroutineScope, private val engineFactory: (ProfileId) -> HttpClientEngine = ::createPlatformHttpClientEngine, ) { private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Together requires an owner job" } private val job = SupervisorJob(ownerJob) private val scope = CoroutineScope(ownerScope.coroutineContext + job) private val operationLock = Mutex() // Retain clients until successful cleanup, including an interrupted room replacement. private val clients = mutableListOf() private var activeAccount: RoomAccount? = null private val _client = MutableStateFlow(null) val client = _client.asStateFlow() val state = _client.flatMapLatest { it?.state ?: flowOf(null) } private val _following = MutableStateFlow(true) val following = _following.asStateFlow() private val _driving = MutableStateFlow(false) val driving = _driving.asStateFlow() init { scope.launch { database.snapshots().map { account(it.syncPreferences.firstOrNull()) }.distinctUntilChanged().collect { catchingNonCancellation { operationLock.withLock { val current = _client.value if (current != null && (activeAccount != currentAccount() || !current.isAvailable)) { clearCurrent() closeClients() } } }.onFailure { // Keep failed cleanup targets for explicit leave/join or session retirement. AppLogger.warn("[together] account-change cleanup failed (${it::class.simpleName}); cleanup can be retried") } } } } fun setFollowing(value: Boolean) { if (ownerJob.isActive && job.isActive && _client.value?.isAvailable != false) _following.update { value } } fun setDriving(value: Boolean) { if (ownerJob.isActive && job.isActive && _client.value?.isAvailable != false) _driving.update { value } } private data class RoomAccount(val syncId: Long?, val session: HubSession) private fun account(pref: DbSyncPreference?): RoomAccount? { pref ?: return null if (pref.serverProvider != SyncServerProvider.YokanHub) return null val server = normalizeHubServer(pref.server) ?: return null val token = pref.authToken?.takeIf { it.isNotBlank() } ?: return null return RoomAccount(pref.syncId, HubSession(server, token, pref.deviceId ?: "unknown")) } private fun currentAccount(): RoomAccount? { if (!ownerJob.isActive || !job.isActive) return null return account(database.syncPreferences().firstOrNull()) } fun hubSession(): HubSession? = currentAccount()?.session private fun clearCurrent() { _client.value?.revoke() _client.update { null }; activeAccount = null _following.update { true }; _driving.update { false } } private suspend fun closeClients() { while (clients.isNotEmpty()) { clients.first().closeAndJoin() clients.removeAt(0) } } private suspend fun runOwned(action: suspend () -> T): T = scope.runJoined { action() } /** A completed create operation retains its exact client for guarded UI delivery. */ class JoinedRoom(val created: RoomApi.Created, val client: RoomClient) fun owns(candidate: RoomClient): Boolean = ownerJob.isActive && job.isActive && _client.value === candidate && candidate.isAvailable /** * Resolves the room's [media] against this profile's library: the matching chapter (or the * first unread, or the first) of the local title. Null once the current room no longer shows * [media]. Repository reads are synchronous snapshot lookups. */ fun resolveMedia(media: RoomMedia, repository: YokanRepository, settings: DbSettings): RoomMediaTarget? { if (_client.value?.state?.value?.media != media) return null val manga = repository.snapshots.value.mangas.firstOrNull { it.link == media.link && (it.sourceId == media.sourceId || (media.sourceName != null && it.source.equals(media.sourceName, ignoreCase = true))) }?.id?.let(repository::manga) ?: return RoomMediaTarget.NotInLibrary(media.title ?: media.link, media.sourceName) val chapters = sortedChapters(manga, repository.chapters(manga.id), settings) val target = media.chapter?.url?.let { url -> chapters.firstOrNull { it.url == url } } ?: chapters.firstOrNull { !it.isRead } ?: chapters.firstOrNull() return target?.let { RoomMediaTarget.Open(manga.id, it.id) } ?: RoomMediaTarget.NoChapters(manga.name) } /** Own REST creation and socket replacement as one joined profile/controller call. */ suspend fun createAndJoin(http: HttpService, media: RoomMedia): Result? = runOwned { val captured = currentAccount() ?: return@runOwned null val callJob = requireNotNull(currentCoroutineContext()[Job]) val created = RoomApi(http) { callJob.isActive && currentAccount() == captured } .create(captured.session, media) val result = created.getOrElse { return@runOwned Result.failure(it) } currentCoroutineContext().ensureActive() val next = joinAccount(captured, result.code) ?: throw CancellationException("Together account changed before joining the created room.") Result.success(JoinedRoom(result, next)) } /** Reject an old account snapshot rather than connecting its token after settings changed. */ suspend fun join(session: HubSession, code: String): RoomClient? = runOwned { val captured = currentAccount()?.takeIf { it.session == session } ?: return@runOwned null joinAccount(captured, code) } private suspend fun joinAccount(captured: RoomAccount, code: String): RoomClient? = operationLock.withLock { currentCoroutineContext().ensureActive(); ownerJob.ensureActive() if (currentAccount() != captured) return@withLock null clearCurrent() closeClients() currentCoroutineContext().ensureActive(); ownerJob.ensureActive() if (currentAccount() != captured) return@withLock null val next = RoomClient(engineFactory(profileId), captured.session, code, scope) { currentAccount() == captured } clients += next activeAccount = captured _following.update { true }; _driving.update { false } _client.update { next } next.connect() next } suspend fun leave(expectedClient: RoomClient? = null) = runOwned { operationLock.withLock { if (expectedClient != null && _client.value !== expectedClient) return@withLock clearCurrent() closeClients() } } suspend fun closeAndJoin() { job.cancel() withContext(NonCancellable) { job.join() operationLock.withLock { clearCurrent() closeClients() } } } }