Yokan / rebuild
Course 1 8624561

ServerTrackerService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/ServerTrackerService.kt

implementation165 lines
1package eu.friedcutlet.yokan.services.tracking23import eu.friedcutlet.yokan.database.DbManga4import eu.friedcutlet.yokan.database.DbSource5import eu.friedcutlet.yokan.database.DbTrack6import eu.friedcutlet.yokan.database.DbTrackPreference7import eu.friedcutlet.yokan.database.DbTrackSearch8import eu.friedcutlet.yokan.database.DbTrackStatus9import eu.friedcutlet.yokan.database.YokanDatabase10import eu.friedcutlet.yokan.services.http.HttpRequest11import eu.friedcutlet.yokan.services.http.HttpResponse12import eu.friedcutlet.yokan.services.http.HttpService13import io.ktor.http.Url14import io.ktor.http.decodeURLQueryComponent15import kotlinx.serialization.json.JsonElement16import kotlin.io.encoding.Base641718/**19 * Shared shape of the self-hosted [EnhancedTracker]s (Komga, Kavita, Suwayomi, Jellyfin): the server and its20 * credentials come from the tracker's own login (Yokan cannot read extension preferences), an entry is21 * addressed by a server item key parsed from a source link, and the server's read state is the list entry.22 */23abstract class ServerTrackerService(24    final override val syncId: Int,25    protected val database: YokanDatabase,26    protected val http: HttpService,27) : TrackerService, EnhancedTracker {28    /** Lower-case source-name keywords [accept] matches. */29    protected abstract val sourceKeywords: List<String>30    protected abstract val forManga: Boolean3132    /** Server item key from a source link, a tracking URL or a bare id; null when unrecognized. */33    protected abstract fun itemKey(link: String): String?3435    /** The remote state of [key], `trackingUrl` canonical on the configured server. */36    protected abstract suspend fun fetch(key: String): DbTrackSearch3738    /** Marks [key] read/watched up to [progress]. */39    protected abstract suspend fun push(key: String, progress: Int)4041    protected abstract fun authHeaders(preference: DbTrackPreference): Map<String, String>4243    /** A renewed preference after a 401, already persisted; null when the provider cannot renew. */44    protected open suspend fun reauthenticate(preference: DbTrackPreference): DbTrackPreference? = null4546    protected fun preference(): DbTrackPreference? =47        database.trackPreference(syncId)?.takeIf { !it.oauth.isNullOrBlank() }4849    private fun loggedIn(): DbTrackPreference = preference() ?: throw IllegalStateException("Not logged in to $name")5051    protected fun server(): String =52        loggedIn().credentials().serverUrl ?: throw IllegalStateException("Not logged in to $name")5354    protected suspend fun send(url: String, method: String = "GET", body: String? = null, headers: Map<String, String> = emptyMap()): HttpResponse {55        val current = loggedIn()56        val response = http.request(HttpRequest(url, method, authHeaders(current) + headers, body))57        if (response.statusCode != 401) return response58        val renewed = reauthenticate(current) ?: return response59        return http.request(HttpRequest(url, method, authHeaders(renewed) + headers, body))60    }6162    protected suspend fun getJson(url: String): JsonElement = send(url).json(name)6364    protected fun loginPreference(username: String?, oauth: String, credentials: TrackerCredentials, accountName: String? = null) =65        DbTrackPreference(66            syncId = syncId.toLong(),67            username = username,68            accountName = accountName,69            oauth = oauth,70            prefs = credentials.encode(),71            refreshing = false,72        )7374    protected fun remoteStatus(unread: Boolean, completed: Boolean): String = when {75        unread -> if (forManga) DbTrackStatus.PlanToRead else DbTrackStatus.PlanToWatch76        completed -> DbTrackStatus.Completed77        else -> if (forManga) DbTrackStatus.Reading else DbTrackStatus.Watching78    }.name7980    override fun supports(isManga: Boolean): Boolean = isManga == forManga8182    override suspend fun checkRefresh(): Boolean = preference() != null8384    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =85        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }8687    override fun statusList(isManga: Boolean): List<DbTrackStatus> =88        if (forManga) listOf(DbTrackStatus.PlanToRead, DbTrackStatus.Reading, DbTrackStatus.Completed)89        else listOf(DbTrackStatus.PlanToWatch, DbTrackStatus.Watching, DbTrackStatus.Completed)9091    override fun scoreValue(): Pair<Int, Int> = 0 to 09293    override fun displayScore(score: Int): String = ""9495    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> = emptyList()9697    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()9899    /** Enhanced trackers are not searched; `id:<server item id>` resolves like [match]. */100    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> =101        listOfNotNull(trackerSearchId(query)?.let { lookup(it) })102103    override fun accept(source: DbSource): Boolean {104        val sourceName = source.name.lowercase()105        if (sourceKeywords.any { it in sourceName }) return true106        val serverHost = preference()?.credentials()?.serverUrl?.let(::hostOf) ?: return false107        return listOf(source.baseUrl, source.apiUrl).any { hostOf(it) == serverHost }108    }109110    override suspend fun match(manga: DbManga): DbTrackSearch? = manga.link?.let { lookup(it) }111112    private suspend fun lookup(link: String): DbTrackSearch? {113        if (preference() == null) return null114        val key = itemKey(link) ?: return null115        return try {116            fetch(key)117        } catch (e: TrackerHttpException) {118            if (e.status == 404) null else throw e119        }120    }121122    override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack {123        val key = track.trackingUrl?.let(::itemKey) ?: return track124        val remote = try {125            fetch(key)126        } catch (e: TrackerHttpException) {127            if (e.status == 404) return track else throw e128        }129        return track.copy(130            mediaId = remote.mediaId ?: track.mediaId,131            title = remote.title ?: track.title,132            lastChapterRead = remote.lastChapterRead,133            totalChapter = remote.totalChapter,134            status = DbTrackStatus.valueOf(remote.status),135            trackingUrl = remote.trackingUrl,136        )137    }138139    override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack = refresh(track, isManga)140141    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {142        val key = track.trackingUrl?.let(::itemKey) ?: throw IllegalArgumentException("$name entry has no server URL")143        push(key, track.lastChapterRead ?: 0)144        return refresh(track, isManga)145    }146}147148internal fun basicAuth(username: String, password: String): String =149    "Basic " + Base64.encode("$username:$password".encodeToByteArray())150151private fun hostOf(raw: String): String? =152    raw.takeIf { it.isNotBlank() }?.let { runCatching { Url(normalizeServerUrl(it)).host.lowercase() }.getOrNull() }153154/** The path segment after `/<marker>/` (case-insensitive), e.g. `series` in `…/api/v1/series/ABC/thumbnail` → `ABC`. */155internal fun segmentAfter(link: String, marker: String): String? {156    val start = link.indexOf("/$marker/", ignoreCase = true).takeIf { it >= 0 } ?: return null157    return link.substring(start + marker.length + 2).takeWhile { it != '/' && it != '?' && it != '#' && it != '&' }158        .takeIf { it.isNotEmpty() }159}160161/** Value of the query/fragment parameter [name] (exact, case-insensitive name). */162internal fun linkParameter(link: String, name: String): String? =163    link.split('?', '&', '#', ';').firstOrNull { it.substringBefore('=').equals(name, ignoreCase = true) && '=' in it }164        ?.substringAfter('=')?.let { runCatching { it.decodeURLQueryComponent() }.getOrDefault(it) }165        ?.takeIf { it.isNotEmpty() }166

Search chapters, reference and source filenames.