package eu.friedcutlet.yokan.services.tracking import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbSource import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackPreference import eu.friedcutlet.yokan.database.DbTrackSearch import eu.friedcutlet.yokan.database.DbTrackStatus import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import io.ktor.http.Url import io.ktor.http.decodeURLQueryComponent import kotlinx.serialization.json.JsonElement import kotlin.io.encoding.Base64 /** * Shared shape of the self-hosted [EnhancedTracker]s (Komga, Kavita, Suwayomi, Jellyfin): the server and its * credentials come from the tracker's own login (Yokan cannot read extension preferences), an entry is * addressed by a server item key parsed from a source link, and the server's read state is the list entry. */ abstract class ServerTrackerService( final override val syncId: Int, protected val database: YokanDatabase, protected val http: HttpService, ) : TrackerService, EnhancedTracker { /** Lower-case source-name keywords [accept] matches. */ protected abstract val sourceKeywords: List protected abstract val forManga: Boolean /** Server item key from a source link, a tracking URL or a bare id; null when unrecognized. */ protected abstract fun itemKey(link: String): String? /** The remote state of [key], `trackingUrl` canonical on the configured server. */ protected abstract suspend fun fetch(key: String): DbTrackSearch /** Marks [key] read/watched up to [progress]. */ protected abstract suspend fun push(key: String, progress: Int) protected abstract fun authHeaders(preference: DbTrackPreference): Map /** A renewed preference after a 401, already persisted; null when the provider cannot renew. */ protected open suspend fun reauthenticate(preference: DbTrackPreference): DbTrackPreference? = null protected fun preference(): DbTrackPreference? = database.trackPreference(syncId)?.takeIf { !it.oauth.isNullOrBlank() } private fun loggedIn(): DbTrackPreference = preference() ?: throw IllegalStateException("Not logged in to $name") protected fun server(): String = loggedIn().credentials().serverUrl ?: throw IllegalStateException("Not logged in to $name") protected suspend fun send(url: String, method: String = "GET", body: String? = null, headers: Map = emptyMap()): HttpResponse { val current = loggedIn() val response = http.request(HttpRequest(url, method, authHeaders(current) + headers, body)) if (response.statusCode != 401) return response val renewed = reauthenticate(current) ?: return response return http.request(HttpRequest(url, method, authHeaders(renewed) + headers, body)) } protected suspend fun getJson(url: String): JsonElement = send(url).json(name) protected fun loginPreference(username: String?, oauth: String, credentials: TrackerCredentials, accountName: String? = null) = DbTrackPreference( syncId = syncId.toLong(), username = username, accountName = accountName, oauth = oauth, prefs = credentials.encode(), refreshing = false, ) protected fun remoteStatus(unread: Boolean, completed: Boolean): String = when { unread -> if (forManga) DbTrackStatus.PlanToRead else DbTrackStatus.PlanToWatch completed -> DbTrackStatus.Completed else -> if (forManga) DbTrackStatus.Reading else DbTrackStatus.Watching }.name override fun supports(isManga: Boolean): Boolean = isManga == forManga override suspend fun checkRefresh(): Boolean = preference() != null override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? = database.tracks(track.mangaId).firstOrNull { it.syncId == syncId } override fun statusList(isManga: Boolean): List = if (forManga) listOf(DbTrackStatus.PlanToRead, DbTrackStatus.Reading, DbTrackStatus.Completed) else listOf(DbTrackStatus.PlanToWatch, DbTrackStatus.Watching, DbTrackStatus.Completed) override fun scoreValue(): Pair = 0 to 0 override fun displayScore(score: Int): String = "" override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List = emptyList() override suspend fun fetchUserData(isManga: Boolean): List = emptyList() /** Enhanced trackers are not searched; `id:` resolves like [match]. */ override suspend fun search(query: String, isManga: Boolean): List = listOfNotNull(trackerSearchId(query)?.let { lookup(it) }) override fun accept(source: DbSource): Boolean { val sourceName = source.name.lowercase() if (sourceKeywords.any { it in sourceName }) return true val serverHost = preference()?.credentials()?.serverUrl?.let(::hostOf) ?: return false return listOf(source.baseUrl, source.apiUrl).any { hostOf(it) == serverHost } } override suspend fun match(manga: DbManga): DbTrackSearch? = manga.link?.let { lookup(it) } private suspend fun lookup(link: String): DbTrackSearch? { if (preference() == null) return null val key = itemKey(link) ?: return null return try { fetch(key) } catch (e: TrackerHttpException) { if (e.status == 404) null else throw e } } override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack { val key = track.trackingUrl?.let(::itemKey) ?: return track val remote = try { fetch(key) } catch (e: TrackerHttpException) { if (e.status == 404) return track else throw e } return track.copy( mediaId = remote.mediaId ?: track.mediaId, title = remote.title ?: track.title, lastChapterRead = remote.lastChapterRead, totalChapter = remote.totalChapter, status = DbTrackStatus.valueOf(remote.status), trackingUrl = remote.trackingUrl, ) } override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack = refresh(track, isManga) override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack { val key = track.trackingUrl?.let(::itemKey) ?: throw IllegalArgumentException("$name entry has no server URL") push(key, track.lastChapterRead ?: 0) return refresh(track, isManga) } } internal fun basicAuth(username: String, password: String): String = "Basic " + Base64.encode("$username:$password".encodeToByteArray()) private fun hostOf(raw: String): String? = raw.takeIf { it.isNotBlank() }?.let { runCatching { Url(normalizeServerUrl(it)).host.lowercase() }.getOrNull() } /** The path segment after `//` (case-insensitive), e.g. `series` in `…/api/v1/series/ABC/thumbnail` → `ABC`. */ internal fun segmentAfter(link: String, marker: String): String? { val start = link.indexOf("/$marker/", ignoreCase = true).takeIf { it >= 0 } ?: return null return link.substring(start + marker.length + 2).takeWhile { it != '/' && it != '?' && it != '#' && it != '&' } .takeIf { it.isNotEmpty() } } /** Value of the query/fragment parameter [name] (exact, case-insensitive name). */ internal fun linkParameter(link: String, name: String): String? = link.split('?', '&', '#', ';').firstOrNull { it.substringBefore('=').equals(name, ignoreCase = true) && '=' in it } ?.substringAfter('=')?.let { runCatching { it.decodeURLQueryComponent() }.getOrDefault(it) } ?.takeIf { it.isNotEmpty() }