Yokan / rebuild
Course 1 8624561

Metadata, discovery, Home and trackers

243 min read + implementationSnapshot 8624561Markdown

Prerequisites: repository, HTTP, title identity and profile-bound credentials. File workbook.

How to write this chapter

Implement metadata enrichment, provider-owned tracker accounts and Home/discovery projections without confusing source identity, external provider identity or reading progress units.

The 71 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.

Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.

Implementation sequence:

  • Step 1: Define metadata/discovery/recommendation/watch-order contracts.
  • Step 2: Implement tracker APIs, login/account ownership and provider adapters.
  • Step 3: Connect tracker settings, bind/search and library views.
  • Step 4: Build Home models, asynchronous shelves and resume behavior.
  • Step 5: Render recommendations, source relations, sequels and watch order.
  • Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #

Step 1: build metadata contracts

Implement MetadataService, metadata-server configuration, title/credit mapping and local metadata selection policy. Keep source title identity distinct from external provider IDs. A metadata match enriches the title; it must not silently rebind its reading source. Handle ambiguous matches with selection/preview where the UI requires it.

Implement recommendation, watch-order and discovery services with their protocol fixtures. AniList supplies discovery/recommendations and parts of watch order; preserve the alternate watch-order service behavior and sequel relations in the source. Normalize status/format/genres/credits without inventing missing data. Cache within the documented ownership and freshness boundaries.

Follow the code

Metadata enriches an existing source title; it does not automatically choose a new reading source. Normalize provider IDs/status/credits in mapping code and retain unknown/ambiguous values for selection where required. Discovery/recommendation/watch-order services supply different views over provider data. Keep their HTTP/cache/error behavior independently testable, so one missing shelf or relation does not blank unrelated content.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/MetadataService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/MetadataServerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/TitleCastMetadata.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/discovery/DiscoveryService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/RecommendationService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/WatchOrderService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/discovery/HttpDiscoveryService.kt

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/MetadataService.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MetadataService, health, search, bestMatch, library, upsertLibraryEntry, MetadataMedia, MetadataApplyResult, LocalMetadataField, selectedLocalMetadataFields and 1 further declarations.

Cross-chapter imports used by this file: DbItemType, Status. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.metadata

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.domain.Status

interface MetadataService {
    suspend fun health(baseUrl: String): Boolean
    suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int = 10): List<MetadataMedia>
    suspend fun bestMatch(baseUrl: String, query: String, itemType: DbItemType): MetadataMedia? =
        search(baseUrl, query, itemType, limit = 8).firstOrNull()
    suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>>
    suspend fun upsertLibraryEntry(
        baseUrl: String,
        token: String,
        mediaId: String,
        status: String,
        progress: Int,
        score: Int?,
        isFavorite: Boolean,
    ): Boolean
}

data class MetadataMedia(
    val id: String,
    val source: String,
    val mediaType: DbItemType,
    val title: String,
    val titleEnglish: String? = null,
    val titleNative: String? = null,
    val description: String? = null,
    val status: String? = null,
    val score: Double? = null,
    val coverUrl: String? = null,
    val url: String? = null,
    val genres: List<String> = emptyList(),
    val year: Int? = null,
    val totalProgress: Int? = null,
) {
    val titles: List<String>
        get() = listOf(title, titleEnglish, titleNative)
            .mapNotNull { it?.trim()?.takeIf(String::isNotBlank) }
            .distinctBy { it.lowercase() }
}

data class MetadataApplyResult(
    val mangaId: Long,
    val matched: Boolean,
    val media: MetadataMedia? = null,
    val applied: Boolean = false,
    val message: String? = null,
)

enum class LocalMetadataField { Title, Cover, Description, Genres, Status, MetadataLink }

fun selectedLocalMetadataFields(current: Set<LocalMetadataField>, candidate: MetadataMedia): Set<LocalMetadataField> =
    current.intersect(LocalMetadataField.entries.toSet()).filterTo(mutableSetOf()) { field ->
        when (field) {
            LocalMetadataField.Title -> candidate.title.isNotBlank()
            LocalMetadataField.Cover -> !candidate.coverUrl.isNullOrBlank()
            LocalMetadataField.Description -> !candidate.description.isNullOrBlank()
            LocalMetadataField.Genres -> candidate.genres.isNotEmpty()
            LocalMetadataField.Status -> !candidate.status.isNullOrBlank()
            LocalMetadataField.MetadataLink -> candidate.id.isNotBlank() && candidate.source.isNotBlank()
        }
    }

data class MetadataLibraryEntry(
    val mediaId: String,
    val status: String,
    val progress: Int,
    val score: Int? = null,
    val isFavorite: Boolean = false,
)

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/MetadataServerService.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines HttpMetadataService, health, search, bestMatch, library, upsertLibraryEntry, JsonObject.toMetadataMedia, JsonObject.genres, jsonHeaders, authHeaders and 8 further declarations.

Cross-chapter imports used by this file: DbItemType, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.metadata

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put

class HttpMetadataService(
    private val http: HttpService,
) : MetadataService {
    private val json = Json { ignoreUnknownKeys = true; isLenient = true }

    override suspend fun health(baseUrl: String): Boolean {
        val base = normalizedBase(baseUrl) ?: return false
        val response = catchingNonCancellation {
            http.request(HttpRequest("$base/health", headers = jsonHeaders()))
        }.getOrNull() ?: return false
        return response.statusCode in 200..299
    }

    override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int): List<MetadataMedia> {
        val base = normalizedBase(baseUrl) ?: return emptyList()
        val url = buildString {
            append(base)
            append("/api/v1/media?type=")
            append(itemType.mediaTypeParam())
            append("&per_page=")
            append(limit.coerceIn(1, 100))
            if (query.isNotBlank()) {
                append("&q=")
                append(percentEncode(query.trim()))
            }
        }
        val response = catchingNonCancellation {
            http.request(HttpRequest(url, headers = jsonHeaders()))
        }.getOrNull() ?: return emptyList()
        if (response.statusCode !in 200..299) return emptyList()
        val payload = runCatching { json.parseToJsonElement(response.body) as? JsonObject }.getOrNull() ?: return emptyList()
        val data = payload["data"] as? JsonArray ?: return emptyList()
        return data.mapNotNull { (it as? JsonObject)?.toMetadataMedia() }
    }

    override suspend fun bestMatch(baseUrl: String, query: String, itemType: DbItemType): MetadataMedia? {
        val normalized = query.normalizedTitle()
        return search(baseUrl, query, itemType, limit = 8)
            .maxWithOrNull(
                compareBy<MetadataMedia> { media ->
                    when {
                        normalized.isBlank() -> 0
                        media.titles.any { it.normalizedTitle() == normalized } -> 3
                        media.titles.any { it.normalizedTitle().contains(normalized) } -> 2
                        normalized in media.title.normalizedTitle() -> 1
                        else -> 0
                    }
                }.thenByDescending { it.score ?: 0.0 },
            )
    }

    override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>> {
        val base = normalizedBase(baseUrl) ?: return emptyList()
        val cleanToken = token.trim().takeIf { it.isNotBlank() } ?: return emptyList()
        val response = catchingNonCancellation {
            http.request(
                HttpRequest(
                    "$base/api/v1/library?type=${itemType.mediaTypeParam()}&per_page=100",
                    headers = authHeaders(cleanToken),
                ),
            )
        }.getOrNull() ?: return emptyList()
        if (response.statusCode !in 200..299) return emptyList()
        val payload = runCatching { json.parseToJsonElement(response.body) as? JsonObject }.getOrNull() ?: return emptyList()
        val data = payload["data"] as? JsonArray ?: return emptyList()
        return data.mapNotNull { element ->
            val obj = element as? JsonObject ?: return@mapNotNull null
            val media = (obj["media"] as? JsonObject)?.toMetadataMedia() ?: return@mapNotNull null
            val entry = MetadataLibraryEntry(
                mediaId = obj.string("media_id") ?: media.id,
                status = obj.string("status").orEmpty(),
                progress = obj.int("progress") ?: 0,
                score = obj.int("score"),
                isFavorite = obj.boolean("is_favorite") ?: false,
            )
            entry to media
        }
    }

    override suspend fun upsertLibraryEntry(
        baseUrl: String,
        token: String,
        mediaId: String,
        status: String,
        progress: Int,
        score: Int?,
        isFavorite: Boolean,
    ): Boolean {
        val base = normalizedBase(baseUrl) ?: return false
        val cleanToken = token.trim().takeIf { it.isNotBlank() } ?: return false
        val body = buildJsonObject {
            put("media_id", mediaId)
            put("status", status)
            put("progress", progress.coerceAtLeast(0))
            score?.takeIf { it > 0 }?.let { put("score", it.coerceIn(1, 10)) }
            put("is_favorite", isFavorite)
        }.toString()
        val response = catchingNonCancellation {
            http.request(
                HttpRequest(
                    "$base/api/v1/library",
                    method = "POST",
                    headers = authHeaders(cleanToken),
                    body = body,
                ),
            )
        }.getOrNull() ?: return false
        return response.statusCode in 200..299
    }

    private fun JsonObject.toMetadataMedia(): MetadataMedia? {
        val id = string("id") ?: return null
        val title = string("title") ?: return null
        val type = when (string("media_type")?.lowercase()) {
            "anime" -> DbItemType.Anime
            "novel" -> DbItemType.Novel
            else -> DbItemType.Manga
        }
        val metadata = this["metadata"] as? JsonObject
        val totalProgress = when (type) {
            DbItemType.Anime -> metadata?.int("episodes")
            DbItemType.Manga,
            DbItemType.Novel -> metadata?.int("chapters") ?: metadata?.string("lastChapter")?.substringBefore('.')?.toIntOrNull()
        }
        return MetadataMedia(
            id = id,
            source = string("source").orEmpty(),
            mediaType = type,
            title = title,
            titleEnglish = string("title_english"),
            titleNative = string("title_native"),
            description = string("description"),
            status = string("status"),
            score = double("score"),
            coverUrl = string("cover_url"),
            url = string("url"),
            genres = genres(),
            year = int("year"),
            totalProgress = totalProgress,
        )
    }

    private fun JsonObject.genres(): List<String> =
        (this["genres"] as? JsonArray)
            ?.mapNotNull { element ->
                when (element) {
                    is JsonPrimitive -> element.contentOrNull
                    is JsonObject -> element.string("name") ?: element.string("title")
                    else -> null
                }?.trim()?.takeIf { it.isNotBlank() }
            }
            ?.distinctBy { it.lowercase() }
            .orEmpty()

    private fun jsonHeaders(): Map<String, String> = mapOf("Accept" to "application/json")

    private fun authHeaders(token: String): Map<String, String> =
        jsonHeaders() + mapOf("Authorization" to "Bearer $token")
}

private fun DbItemType.mediaTypeParam(): String = when (this) {
    DbItemType.Manga -> "manga"
    DbItemType.Anime -> "anime"
    DbItemType.Novel -> "novel"
}

private fun normalizedBase(baseUrl: String): String? =
    baseUrl.trim().trimEnd('/').takeIf { it.startsWith("http://") || it.startsWith("https://") }

private fun percentEncode(value: String): String {
    val allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"
    return buildString {
        value.encodeToByteArray().forEach { byte ->
            val int = byte.toInt() and 0xff
            val char = int.toChar()
            if (char in allowed) {
                append(char)
            } else {
                append('%')
                append(int.toString(16).uppercase().padStart(2, '0'))
            }
        }
    }
}

private fun String.normalizedTitle(): String =
    lowercase().filter { it.isLetterOrDigit() || it.isWhitespace() }.trim()

private fun JsonObject.string(key: String): String? =
    this[key]?.jsonPrimitive?.contentOrNull?.trim()?.takeIf { it.isNotBlank() }

private fun JsonObject.int(key: String): Int? =
    this[key]?.jsonPrimitive?.intOrNull

private fun JsonObject.double(key: String): Double? =
    this[key]?.jsonPrimitive?.doubleOrNull

private fun JsonObject.boolean(key: String): Boolean? =
    this[key]?.jsonPrimitive?.booleanOrNull

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/TitleCastMetadata.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines parseTitleCast, JsonObject.text.

The source describes its contract as:

Null is omitted/invalid metadata; an empty array explicitly clears previously saved cast.

Cross-chapter imports used by this file: TitleCredit. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.metadata

import eu.friedcutlet.yokan.domain.TitleCredit
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive

/** Null is omitted/invalid metadata; an empty array explicitly clears previously saved cast. */
internal fun parseTitleCast(element: JsonElement?): List<TitleCredit>? {
    val rows = element as? JsonArray ?: return null
    if (rows.size > 500) return null
    fun JsonObject.text(key: String) = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.content?.trim()?.takeIf(String::isNotEmpty)
    val credits = rows.mapNotNull { row ->
        val value = row as? JsonObject ?: return@mapNotNull null
        val name = value.text("name") ?: return@mapNotNull null
        TitleCredit(name, value.text("role"), value.text("character"), value.text("image_url"))
    }.distinctBy { Triple(it.name, it.role, it.character) }
    return credits.takeUnless { it.isEmpty() && rows.isNotEmpty() }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/discovery/DiscoveryService.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines DiscoveryMedia, DiscoveryIssue, DiscoveryException, TmdbSeed, DiscoveryService, popular, recommendations, sourceFeed, tmdbRecommendations.

The source describes its contract as:

Actual catalog score on a ten-point scale; recommendation votes are never used as ratings.

Cross-chapter imports used by this file: DbHomeSourceFeed, HomeMediaFilter, ItemType. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.discovery

import eu.friedcutlet.yokan.database.DbHomeSourceFeed
import eu.friedcutlet.yokan.database.HomeMediaFilter
import eu.friedcutlet.yokan.domain.ItemType

data class DiscoveryMedia(
    val key: String,
    val title: String,
    val kind: HomeMediaFilter,
    val coverUrl: String? = null,
    val backdropUrl: String? = null,
    val description: String = "",
    val genres: List<String> = emptyList(),
    /** Actual catalog score on a ten-point scale; recommendation votes are never used as ratings. */
    val rating: Double? = null,
    val aliases: List<String> = emptyList(),
    val sourceId: Long? = null,
    val sourceUrl: String? = null,
) {
    val itemType: ItemType get() = when (kind) {
        HomeMediaFilter.Manga -> ItemType.Manga
        HomeMediaFilter.Novel -> ItemType.Novel
        else -> ItemType.Anime
    }
}

enum class DiscoveryIssue { Network, RateLimited, Credentials, SourceUnavailable, PresetChanged }
class DiscoveryException(val issue: DiscoveryIssue) : Exception(issue.name)

/** A TMDB title the user tracks: [type] is `movie` or `tv`. */
data class TmdbSeed(val type: String, val id: Long) {
    val key: String get() = "tmdb:$type:$id"
}

interface DiscoveryService {
    suspend fun popular(kind: HomeMediaFilter, token: String, includeAdult: Boolean, refresh: Boolean = false): List<DiscoveryMedia>
    suspend fun recommendations(title: String, kind: HomeMediaFilter, includeAdult: Boolean, refresh: Boolean = false): List<DiscoveryMedia>
    suspend fun sourceFeed(feed: DbHomeSourceFeed, includeAdult: Boolean, refresh: Boolean = false): List<DiscoveryMedia>
    /**
     * TMDB recommendations for [seeds], ranked by how many seeds recommend each title; seeds themselves are excluded.
     * Uses the TMDB tracker's API key, else the Home read access [token]; returns empty without a credential or seeds.
     */
    suspend fun tmdbRecommendations(seeds: List<TmdbSeed>, token: String, includeAdult: Boolean, refresh: Boolean = false): List<DiscoveryMedia>
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/RecommendationService.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines RecommendationService, recommendations, simplifyTitle, fetch, String.stripAnilistHtml, JsonObject.obj, JsonObject.string, RecommendationResult.

The source describes its contract as:

Cross-catalog recommendations backed by AniList's Media.recommendations graph. Mangayomi sourced this screen from anibrain.ai, but that service shut down ("AniBrain - Farewell"), so the feature keeps its shape — discover titles beyond the local library, ranked by similarity — on AniList's data instead. Results are matched back against the local library so in-library entries stay clickable.

Cross-chapter imports used by this file: DbItemType, YokanDatabase, HttpRequest, decodeHtmlEntities. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.metadata

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.util.decodeHtmlEntities
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject

/**
 * Cross-catalog recommendations backed by AniList's `Media.recommendations`
 * graph. Mangayomi sourced this screen from anibrain.ai, but that service shut
 * down ("AniBrain - Farewell"), so the feature keeps its shape — discover
 * titles beyond the local library, ranked by similarity — on AniList's data
 * instead. Results are matched back against the local library so in-library
 * entries stay clickable.
 */
class RecommendationService(
    private val http: HttpService,
    private val database: YokanDatabase,
) {
    private val endpoint = "https://graphql.anilist.co"
    private val json = Json { ignoreUnknownKeys = true; isLenient = true }

    suspend fun recommendations(title: String, itemType: DbItemType): List<RecommendationResult> {
        if (title.isBlank()) return emptyList()
        val primary = fetch(title, itemType)
        if (primary != null && primary.isNotEmpty()) return primary
        // Decorated titles ("Main Title ~subtitle~ (TL)") often miss AniList's
        // fuzzy search; retry once with the decorations stripped.
        val simplified = simplifyTitle(title)
        if (simplified != title && simplified.isNotBlank()) {
            fetch(simplified, itemType)?.let { return it }
        }
        return primary ?: emptyList()
    }

    private fun simplifyTitle(title: String): String = title
        .substringBefore('~')
        .substringBefore('(')
        .substringBefore('[')
        .substringBefore(':')
        .trim()

    /** Returns null when AniList cannot resolve the title (data.Media == null / HTTP 404). */
    private suspend fun fetch(title: String, itemType: DbItemType): List<RecommendationResult>? {
        val body = buildJsonObject {
            put(
                "query",
                """
                query (${'$'}search: String, ${'$'}type: MediaType) {
                  Media(search: ${'$'}search, type: ${'$'}type) {
                    recommendations(sort: RATING_DESC, perPage: 25) {
                      nodes {
                        rating
                        mediaRecommendation {
                          title { romaji english native }
                          description
                          coverImage { large }
                          genres
                        }
                      }
                    }
                  }
                }
                """.trimIndent(),
            )
            putJsonObject("variables") {
                put("search", title)
                put("type", if (itemType == DbItemType.Anime) "ANIME" else "MANGA")
            }
        }.toString()
        val response = http.request(
            HttpRequest(
                url = endpoint,
                method = "POST",
                headers = mapOf("Content-Type" to "application/json", "Accept" to "application/json"),
                body = body,
            ),
        )
        val root = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()
            ?: if (response.statusCode in 200..299) {
                return emptyList()
            } else {
                error("AniList request failed with HTTP ${response.statusCode}")
            }
        val media = root.obj("data")?.obj("Media")
        if (media == null) {
            // "Not Found." responses carry data.Media == null alongside HTTP 404.
            if (root.containsKey("data") || response.statusCode == 404) return null
            error("AniList request failed with HTTP ${response.statusCode}")
        }
        val nodes = media.obj("recommendations")?.get("nodes") as? JsonArray ?: return emptyList()
        val libraryTitles = database.mangas(itemType)
        val maxRating = nodes.maxOfOrNull { node ->
            (node as? JsonObject)?.get("rating")?.let { (it as? JsonPrimitive)?.intOrNull } ?: 0
        }?.coerceAtLeast(1) ?: 1
        return nodes.mapNotNull { node ->
            val entry = node as? JsonObject ?: return@mapNotNull null
            val media = entry.obj("mediaRecommendation") ?: return@mapNotNull null
            val titles = media.obj("title")
            val english = titles?.string("english")
            val romaji = titles?.string("romaji")
            val native = titles?.string("native")
            val display = english ?: romaji ?: native ?: return@mapNotNull null
            val genres = (media["genres"] as? JsonArray)
                ?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
                .orEmpty()
            val rating = entry["rating"]?.let { (it as? JsonPrimitive)?.intOrNull } ?: 0
            val localMatch = libraryTitles.firstOrNull { candidate ->
                val name = candidate.name.orEmpty()
                name.equals(display, ignoreCase = true) ||
                    (romaji != null && name.equals(romaji, ignoreCase = true)) ||
                    (native != null && name.equals(native, ignoreCase = true))
            }
            RecommendationResult(
                title = display,
                score = ((rating * 100) / maxRating).coerceIn(0, 100),
                reason = genres.take(4).joinToString(", ").ifBlank { "AniList recommendation" },
                itemType = itemType,
                mangaId = localMatch?.id,
                coverUrl = media.obj("coverImage")?.string("large"),
                description = media.string("description")?.stripAnilistHtml(),
                genres = genres,
            )
        }
    }

    /** AniList descriptions embed light HTML (`<br>`, `<i>`, entities). */
    private fun String.stripAnilistHtml(): String = decodeHtmlEntities(
        replace(Regex("<br\\s*/?>", RegexOption.IGNORE_CASE), "\n").replace(Regex("<[^>]+>"), ""),
    )
        .replace(Regex("\n{3,}"), "\n\n")
        .trim()

    private fun JsonObject.obj(key: String): JsonObject? = get(key) as? JsonObject

    private fun JsonObject.string(key: String): String? =
        (get(key) as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }
}

data class RecommendationResult(
    val title: String,
    val score: Int,
    val reason: String,
    val itemType: DbItemType,
    val mangaId: Long? = null,
    val coverUrl: String? = null,
    val description: String? = null,
    val genres: List<String> = emptyList(),
)

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/metadata/WatchOrderService.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines WatchOrderService, search, watchOrderByName, searchAniList, searchChiaki, watchOrder, fetchMediaWithRelations, parseAniListMedia, sequels, JsonObject.primitive and 11 further declarations.

The source describes its contract as:

AniList franchise relations and watch-order service, mirroring Mangayomi's rebuilt lib/services/fetch_watch_order.dart (2b8a99f3, 912b5337). Traverses the AniList relation graph (prequel/sequel/parent chain + side stories, anime-only, up to 20 lookups), orders entries chronologically by air date, and labels them relative to the queried anchor (Previous, Currently watching, Up next). The tracker-based sequel locator flow (sequels) remains backed by chiaki.site.

Cross-chapter imports used by this file: HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.metadata

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import io.ktor.http.encodeURLParameter
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject

/**
 * AniList franchise relations and watch-order service, mirroring Mangayomi's
 * rebuilt `lib/services/fetch_watch_order.dart` (`2b8a99f3`, `912b5337`).
 *
 * Traverses the AniList relation graph (prequel/sequel/parent chain + side stories,
 * anime-only, up to 20 lookups), orders entries chronologically by air date, and
 * labels them relative to the queried anchor (Previous, Currently watching, Up next).
 * The tracker-based sequel locator flow (`sequels`) remains backed by chiaki.site.
 */
class WatchOrderService(
    private val http: HttpService,
) {
    private val json = Json { ignoreUnknownKeys = true; isLenient = true }

    /**
     * Searches AniList for anime to build a watch order from.
     */
    suspend fun search(name: String): List<WatchOrderSearchResult> = searchAniList(name)

    /**
     * Resolves an anime title to its AniList franchise and builds its chronological watch order
     * directly with no manual pick step. The resolved title becomes the "Current" anchor.
     */
    suspend fun watchOrderByName(name: String): List<WatchOrderEntry> {
        if (name.isBlank()) return emptyList()
        val hits = searchAniList(name)
        val rootId = hits.firstOrNull()?.id ?: return emptyList()
        return watchOrder(rootId)
    }

    /**
     * Searches AniList for anime using the lightweight search GraphQL selection.
     */
    suspend fun searchAniList(name: String): List<WatchOrderSearchResult> {
        if (name.isBlank()) return emptyList()
        val query = """
            query (${'$'}search: String) {
              Page(page: 1, perPage: 15) {
                media(type: ANIME, sort: [SEARCH_MATCH], search: ${'$'}search) {
                  id
                  idMal
                  title { romaji english native }
                  coverImage { large color }
                  format
                  episodes
                  seasonYear
                  startDate { year month }
                }
              }
            }
        """.trimIndent()
        val body = buildJsonObject {
            put("query", query)
            putJsonObject("variables") {
                put("search", name)
            }
        }.toString()
        val response = http.request(
            HttpRequest(
                url = ANILIST_ENDPOINT,
                method = "POST",
                headers = anilistHeaders,
                body = body,
            ),
        )
        if (response.statusCode !in 200..299) return emptyList()
        val root = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()
            ?: return emptyList()
        val mediaArray = root["data"]?.jsonObject?.get("Page")?.jsonObject?.get("media") as? JsonArray
            ?: return emptyList()
        return mediaArray.mapNotNull { element ->
            val media = element as? JsonObject ?: return@mapNotNull null
            val id = (media["id"] as? JsonPrimitive)?.intOrNull ?: return@mapNotNull null
            val titleObj = media["title"] as? JsonObject
            val title = titleObj?.primitive("english")
                ?: titleObj?.primitive("romaji")
                ?: titleObj?.primitive("native")
                ?: return@mapNotNull null
            val coverImage = (media["coverImage"] as? JsonObject)?.primitive("large").orEmpty()
            val format = media.primitive("format").orEmpty()
            val seasonYear = (media["seasonYear"] as? JsonPrimitive)?.intOrNull
                ?: ((media["startDate"] as? JsonObject)?.get("year") as? JsonPrimitive)?.intOrNull
            WatchOrderSearchResult(
                id = id.toString(),
                name = title,
                imageUrl = coverImage,
                type = format,
                year = seasonYear,
            )
        }
    }

    /**
     * Legacy chiaki.site autocomplete series search retained for backwards compatibility.
     */
    suspend fun searchChiaki(name: String): List<WatchOrderSearchResult> {
        if (name.isBlank()) return emptyList()
        val response = http.request(
            HttpRequest(
                url = "https://chiaki.site/?/tools/autocomplete_series&term=${name.encodeURLParameter()}",
                headers = chiakiHeaders,
            ),
        )
        if (response.statusCode !in 200..299) return emptyList()
        val entries = runCatching { json.parseToJsonElement(response.body) }.getOrNull() as? JsonArray
            ?: return emptyList()
        return entries.mapNotNull { element ->
            val entry = element as? JsonObject ?: return@mapNotNull null
            WatchOrderSearchResult(
                id = entry.primitive("id") ?: return@mapNotNull null,
                name = entry.primitive("value") ?: return@mapNotNull null,
                imageUrl = entry.primitive("image")?.let { "https://chiaki.site/$it" }.orEmpty(),
                type = entry.primitive("type").orEmpty(),
                year = (entry["year"] as? JsonPrimitive)?.intOrNull,
            )
        }
    }

    /**
     * Builds a watch order from an AniList media ID by walking its franchise relation graph.
     * Capped at 20 lookups; strictly anime-only; ordered chronologically by release date.
     */
    suspend fun watchOrder(seriesId: String): List<WatchOrderEntry> {
        if (seriesId.isBlank()) return emptyList()
        val rootId = seriesId.toIntOrNull()
        if (rootId == null) {
            val response = http.request(
                HttpRequest(
                    url = "https://chiaki.site/?/tools/watch_order/id/$seriesId",
                    headers = chiakiHeaders,
                ),
            )
            if (response.statusCode !in 200..299) return emptyList()
            return parseWatchOrderRows(response.body)
        }

        val chain = setOf("PREQUEL", "SEQUEL", "PARENT")
        val extra = setOf("SIDE_STORY", "SPIN_OFF", "ALTERNATIVE", "SUMMARY", "COMPILATION")
        val collected = mutableMapOf<Int, AniListMedia>()
        val queue = ArrayDeque<Int>()
        val visited = mutableSetOf<Int>()
        var queries = 0

        queue.add(rootId)
        while (queue.isNotEmpty() && queries < 20) {
            val current = queue.removeFirst()
            if (!visited.add(current)) continue
            queries++
            val (self, relations) = fetchMediaWithRelations(current)
            if (self != null && self.isAnime) {
                collected[self.id] = self
            }
            for (r in relations) {
                if (!r.media.isAnime) continue
                if (r.relationType in chain) {
                    collected[r.media.id] = r.media
                    if (r.media.id !in visited) queue.add(r.media.id)
                } else if (r.relationType in extra) {
                    collected[r.media.id] = r.media
                }
            }
        }

        if (collected.isEmpty()) {
            val response = catchingNonCancellation {
                http.request(
                    HttpRequest(
                        url = "https://chiaki.site/?/tools/watch_order/id/$seriesId",
                        headers = chiakiHeaders,
                    ),
                )
            }.getOrNull()
            if (response != null && response.statusCode in 200..299) {
                val legacyRows = parseWatchOrderRows(response.body)
                if (legacyRows.isNotEmpty()) return legacyRows
            }
            return emptyList()
        }

        val sorted = collected.values.sortedWith(
            compareBy<AniListMedia> { it.startSortKey }.thenBy { it.id },
        )
        val currentIndex = sorted.indexOfFirst { it.id == rootId }

        return sorted.mapIndexed { index, m ->
            val role = when {
                currentIndex < 0 -> WatchOrderRole.Next
                index < currentIndex -> WatchOrderRole.Previous
                index == currentIndex -> WatchOrderRole.Current
                else -> WatchOrderRole.Next
            }
            val meta = listOfNotNull(
                m.format,
                m.episodes?.let { "$it eps" },
                m.startYear?.toString(),
            ).joinToString(" | ")
            WatchOrderEntry(
                id = m.id.toString(),
                anilistId = m.id.toString(),
                title = m.romaji ?: m.title,
                titleEnglish = m.english,
                info = meta,
                imageUrl = m.coverImage.orEmpty(),
                role = role,
            )
        }
    }

    private suspend fun fetchMediaWithRelations(mediaId: Int): Pair<AniListMedia?, List<AniListRelation>> {
        val query = """
            query (${'$'}id: Int) {
              Media(id: ${'$'}id) {
                id
                idMal
                title { romaji english native }
                coverImage { large color }
                format
                status
                type
                episodes
                seasonYear
                startDate { year month }
                relations {
                  edges {
                    relationType
                    node {
                      id
                      idMal
                      title { romaji english native }
                      coverImage { large color }
                      format
                      status
                      type
                      episodes
                      seasonYear
                      startDate { year month }
                    }
                  }
                }
              }
            }
        """.trimIndent()
        val body = buildJsonObject {
            put("query", query)
            putJsonObject("variables") {
                put("id", mediaId)
            }
        }.toString()
        val response = http.request(
            HttpRequest(
                url = ANILIST_ENDPOINT,
                method = "POST",
                headers = anilistHeaders,
                body = body,
            ),
        )
        if (response.statusCode !in 200..299) return null to emptyList()
        val root = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()
            ?: return null to emptyList()
        val mediaObj = root["data"]?.jsonObject?.get("Media") as? JsonObject ?: return null to emptyList()
        val self = parseAniListMedia(mediaObj)
        val edges = (mediaObj["relations"] as? JsonObject)?.get("edges") as? JsonArray
        val relations = edges.orEmpty().mapNotNull { edgeElem ->
            val edge = edgeElem as? JsonObject ?: return@mapNotNull null
            val relType = edge.primitive("relationType") ?: return@mapNotNull null
            val nodeObj = edge["node"] as? JsonObject ?: return@mapNotNull null
            val nodeMedia = parseAniListMedia(nodeObj) ?: return@mapNotNull null
            AniListRelation(relationType = relType, media = nodeMedia)
        }
        return self to relations
    }

    private fun parseAniListMedia(obj: JsonObject): AniListMedia? {
        val id = (obj["id"] as? JsonPrimitive)?.intOrNull ?: return null
        val titleObj = obj["title"] as? JsonObject
        val coverObj = obj["coverImage"] as? JsonObject
        val dateObj = obj["startDate"] as? JsonObject
        return AniListMedia(
            id = id,
            idMal = (obj["idMal"] as? JsonPrimitive)?.intOrNull,
            romaji = titleObj?.primitive("romaji"),
            english = titleObj?.primitive("english"),
            native = titleObj?.primitive("native"),
            coverImage = coverObj?.primitive("large"),
            format = obj.primitive("format"),
            status = obj.primitive("status"),
            type = obj.primitive("type") ?: "ANIME",
            episodes = (obj["episodes"] as? JsonPrimitive)?.intOrNull,
            startYear = (dateObj?.get("year") as? JsonPrimitive)?.intOrNull
                ?: (obj["seasonYear"] as? JsonPrimitive)?.intOrNull,
            startMonth = (dateObj?.get("month") as? JsonPrimitive)?.intOrNull,
        )
    }

    suspend fun sequels(malUsername: String?, anilistUsername: String?): List<SequelEntry> {
        val user = malUsername?.takeIf(String::isNotBlank)
            ?: anilistUsername?.takeIf(String::isNotBlank)
            ?: return emptyList()
        val source = if (malUsername?.isNotBlank() == true) "mal" else "anilist"
        val response = http.request(
            HttpRequest(
                url = "https://chiaki.site/?/tools/sequel_locator_fetch",
                method = "POST",
                headers = chiakiHeaders + ("Content-Type" to "application/x-www-form-urlencoded"),
                body = "user=${user.encodeURLParameter()}&list_source=$source$SEQUEL_FILTERS",
            ),
        )
        if (response.statusCode !in 200..299) return emptyList()
        val root = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()
            ?: return emptyList()
        // Live chiaki wraps the list: {"data":{"result":[…],"entry_count":N}}.
        // Mangayomi's parser predates that and expected a bare array — accept both.
        val data = when (val payload = root["data"]) {
            is JsonArray -> payload
            is JsonObject -> payload["result"] as? JsonArray ?: return emptyList()
            else -> return emptyList()
        }
        return data.mapNotNull { element ->
            val entry = element as? JsonObject ?: return@mapNotNull null
            SequelEntry(
                id = entry.primitive("id") ?: return@mapNotNull null,
                anilistId = entry.primitive("anilist_id"),
                title = entry.primitive("title") ?: return@mapNotNull null,
                imageUrl = entry.primitive("image_url")?.let { "https://chiaki.site/$it" }.orEmpty(),
                episodes = entry.primitive("episodes").orEmpty(),
                period = entry.primitive("period").orEmpty(),
                score = entry.primitive("score")?.formatChiakiScore().orEmpty(),
                type = entry.primitive("type").orEmpty(),
                reasons = (entry["reason"] as? JsonArray).orEmpty().mapNotNull { reason ->
                    val obj = reason as? JsonObject ?: return@mapNotNull null
                    SequelReasonRef(
                        id = obj.primitive("id") ?: return@mapNotNull null,
                        title = obj.primitive("title").orEmpty(),
                        imageUrl = obj.primitive("image_url")?.let { "https://chiaki.site/$it" }.orEmpty(),
                    )
                },
            )
        }
    }

    private fun JsonObject.primitive(key: String): String? =
        (get(key) as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }

    /** chiaki scores arrive as hundredths ("811" == 8.11); older payloads were already formatted. */
    private fun String.formatChiakiScore(): String {
        val hundredths = toIntOrNull() ?: return this
        return "${hundredths / 100}.${(hundredths % 100).toString().padStart(2, '0')}"
    }

    private fun JsonArray?.orEmpty(): List<kotlinx.serialization.json.JsonElement> = this ?: emptyList()

    private companion object {
        const val ANILIST_ENDPOINT = "https://graphql.anilist.co"

        val anilistHeaders = mapOf(
            "Content-Type" to "application/json",
            "Accept" to "application/json",
            "User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
        )

        val chiakiHeaders = mapOf(
            "priority" to "u=1, i",
            "Referer" to "https://chiaki.site/?/tools/watch_order",
            "User-Agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
        )

        /** Fixed filter payload copied from Mangayomi's `_sequelData`. */
        const val SEQUEL_FILTERS =
            "&types%5B%5D=1&types%5B%5D=3&types%5B%5D=2&types%5B%5D=4&types%5B%5D=9&score=0&date_from=false&date_to=false" +
                "&include_ptw=1&exclude_h=1&exclude_planned=1&exclude_dropped=0&exclude_not_aired=0&exclude_short=1&exclude_short_value=3"
    }
}

data class AniListMedia(
    val id: Int,
    val idMal: Int? = null,
    val romaji: String? = null,
    val english: String? = null,
    val native: String? = null,
    val coverImage: String? = null,
    val format: String? = null,
    val status: String? = null,
    val type: String? = null,
    val episodes: Int? = null,
    val startYear: Int? = null,
    val startMonth: Int? = null,
) {
    val title: String get() = english ?: romaji ?: native ?: "Unknown"
    val isAnime: Boolean get() = type == null || type.equals("ANIME", ignoreCase = true)
    val startSortKey: Int get() = if (startYear == null) (1 shl 30) else (startYear * 12 + (startMonth ?: 0))
}

data class AniListRelation(
    val relationType: String,
    val media: AniListMedia,
)

/** Where an entry sits relative to the title opened by the user. */
enum class WatchOrderRole {
    Previous,
    Current,
    Next,
}

/**
 * Parses chiaki's rendered watch-order table without a DOM: one `<tr>` per
 * entry carrying `data-id`/`data-anilist-id`, a `wo_title` span, an optional
 * plain `uk-text-small` English title, a muted info span, and a CSS
 * `background-image:url('…')` avatar.
 */
internal fun parseWatchOrderRows(html: String): List<WatchOrderEntry> {
    val rowRegex = Regex(
        "(?s)<tr[^>]*data-id=\"(?<id>\\d+)\"[^>]*>(?<body>.*?)</tr>",
    )
    val anilistRegex = Regex("data-anilist-id=\"(?<v>\\d+)\"")
    val titleRegex = Regex("class=\"[^\"]*wo_title[^\"]*\"[^>]*>(?<v>[^<]+)<")
    val mutedRegex = Regex("class=\"[^\"]*uk-text-muted[^\"]*\"[^>]*>(?<v>[^<]+)<")
    val metaRegex = Regex(
        "(?s)class=\"[^\"]*wo_meta[^\"]*\"[^>]*>(?<v>.*?)(?:<div class=\"list_status|</td>)",
    )
    val englishRegex = Regex("class=\"uk-text-small\"[^>]*>(?<v>[^<]+)<")
    val imageRegex = Regex("url\\('(?<v>[^']+)'\\)")
    return rowRegex.findAll(html).mapNotNull { row ->
        val body = row.groups["body"]?.value ?: return@mapNotNull null
        val title = titleRegex.find(body)?.groups?.get("v")?.value?.trim()
            ?.takeIf(String::isNotBlank) ?: return@mapNotNull null
        WatchOrderEntry(
            id = row.groups["id"]?.value ?: return@mapNotNull null,
            anilistId = anilistRegex.find(row.value)?.groups?.get("v")?.value,
            title = title,
            titleEnglish = englishRegex.find(body)?.groups?.get("v")?.value?.trim()
                ?.takeIf(String::isNotBlank),
            info = metaRegex.find(body)?.groups?.get("v")?.value?.cleanWatchOrderMeta()
                ?: mutedRegex.find(body)?.groups?.get("v")?.value?.trim().orEmpty(),
            imageUrl = imageRegex.find(body)?.groups?.get("v")?.value
                ?.let { "https://chiaki.site/$it" }.orEmpty(),
        )
    }.toList()
}

/** Flattens chiaki's `wo_meta` markup into a single "date | type | eps | ★score" line. */
private fun String.cleanWatchOrderMeta(): String = this
    .replace(Regex("(?s)<a\\b.*?</a>"), "")
    .replace(Regex("<[^>]+>"), " ")
    .replace(Regex("\\s+"), " ")
    .trim()
    .trim('|')
    .trim()

/** chiaki.site `autocomplete_series` hit or AniList search hit. */
data class WatchOrderSearchResult(
    val id: String,
    val name: String,
    val imageUrl: String,
    val type: String,
    val year: Int?,
)

/** One row of a watch-order table. */
data class WatchOrderEntry(
    val id: String,
    val anilistId: String?,
    val title: String,
    val titleEnglish: String?,
    val info: String,
    val imageUrl: String,
    val role: WatchOrderRole = WatchOrderRole.Next,
)

/** Series that caused a sequel-locator hit. */
data class SequelReasonRef(
    val id: String,
    val title: String,
    val imageUrl: String,
)

/** chiaki.site `sequel_locator_fetch` result. */
data class SequelEntry(
    val id: String,
    val anilistId: String?,
    val title: String,
    val imageUrl: String,
    val episodes: String,
    val period: String,
    val score: String,
    val type: String,
    val reasons: List<SequelReasonRef>,
)

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/discovery/HttpDiscoveryService.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines HttpDiscoveryService, Cached, popular, recommendations, tmdbRecommendations, sourceFeed, cached, aniList, tmdbTrending, tmdbRecommendationsFor and 10 further declarations.

The source describes its contract as:

Profile-owned, bounded metadata cache. Failed requests never replace usable cached data.

Cross-chapter imports used by this file: HttpRequest, decodeHtmlEntities, nowMillis. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.discovery

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.extensions.*
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.credentials
import eu.friedcutlet.yokan.util.decodeHtmlEntities
import eu.friedcutlet.yokan.util.nowMillis
import io.ktor.http.encodeURLParameter
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withTimeout
import kotlinx.serialization.json.*

/** Profile-owned, bounded metadata cache. Failed requests never replace usable cached data. */
class HttpDiscoveryService(
    private val http: HttpService,
    private val database: YokanDatabase,
    private val runtimes: ExtensionRuntimeFactory,
    private val clock: () -> Long = ::nowMillis,
) : DiscoveryService {
    private data class Cached(val at: Long, val items: List<DiscoveryMedia>)
    private val cache = linkedMapOf<String, Cached>()
    private val cacheLock = Mutex()
    private val json = Json { ignoreUnknownKeys = true }

    override suspend fun popular(kind: HomeMediaFilter, token: String, includeAdult: Boolean, refresh: Boolean): List<DiscoveryMedia> {
        require(kind != HomeMediaFilter.All)
        val tmdb = kind == HomeMediaFilter.Movie || kind == HomeMediaFilter.Series
        if (tmdb && token.isBlank()) throw DiscoveryException(DiscoveryIssue.Credentials)
        // The cache only contains public metadata, but token changes still invalidate its namespace.
        return cached("popular:$kind:$includeAdult:${if (tmdb) token.hashCode() else 0}", refresh) {
            if (tmdb) tmdbTrending(kind, token, includeAdult) else aniList(kind, null, includeAdult)
        }
    }

    override suspend fun recommendations(title: String, kind: HomeMediaFilter, includeAdult: Boolean, refresh: Boolean): List<DiscoveryMedia> =
        cached("recommend:$kind:${title.trim()}:$includeAdult", refresh) { aniList(kind, title, includeAdult) }

    override suspend fun tmdbRecommendations(seeds: List<TmdbSeed>, token: String, includeAdult: Boolean, refresh: Boolean): List<DiscoveryMedia> {
        // Prefer the TMDB tracker's own v3 API key; the Home read access token is the fallback.
        val apiKey = database.trackPreferences().firstOrNull { it.syncId?.toInt() == TmdbTrackerSyncId }
            ?.credentials()?.apiKey?.trim()?.takeIf { it.isNotEmpty() }
        val unique = seeds.distinct()
        if (unique.isEmpty() || (apiKey == null && token.isBlank())) return emptyList()
        val key = "tmdb-recommend:${unique.map { it.key }.sorted()}:$includeAdult:${(apiKey ?: token).hashCode()}"
        return cached(key, refresh, ttl = 6 * 60 * 60_000L) {
            val gate = Semaphore(3)
            val results = coroutineScope {
                unique.map { seed -> async {
                    try { Result.success(gate.withPermit { tmdbRecommendationsFor(seed, apiKey, token, includeAdult) }) }
                    catch (cancel: CancellationException) { throw cancel }
                    catch (failure: Exception) { Result.failure<List<DiscoveryMedia>>(failure) }
                } }.awaitAll()
            }
            // One failing seed must not hide the shelf; only a total failure surfaces as an issue.
            if (results.none { it.isSuccess }) throw results.first().exceptionOrNull()!!
            mergeTmdbRecommendations(results.mapNotNull { it.getOrNull() }, unique.mapTo(mutableSetOf()) { it.key })
        }
    }

    override suspend fun sourceFeed(feed: DbHomeSourceFeed, includeAdult: Boolean, refresh: Boolean): List<DiscoveryMedia> {
        val source = database.source(feed.sourceId)?.takeIf { it.isActive && it.isAdded && (includeAdult || !it.isNsfw) }
            ?: throw DiscoveryException(DiscoveryIssue.SourceUnavailable)
        val preset = if (feed.mode == HomeFeedMode.SavedSearch) database.settings().savedSearches.orEmpty()
            .firstOrNull { it.id == feed.presetId && it.sourceId == source.id }
            ?: throw DiscoveryException(DiscoveryIssue.PresetChanged) else null
        val preferences = database.settings().sourcePreferences.orEmpty().filter { it.sourceId == source.id }
        return cached("source:${feed.key}:${source.version}:${source.updatedAt}:${preset.hashCode()}:${preferences.hashCode()}:$includeAdult", refresh) {
            runtimes.withSourceRuntime(database, source.id) { runtime ->
                val listing = when (feed.mode) {
                    HomeFeedMode.Popular -> runtime.popular(1)
                    HomeFeedMode.Latest -> {
                        if (!runtime.supportsLatest()) throw DiscoveryException(DiscoveryIssue.SourceUnavailable)
                        runtime.latest(1)
                    }
                    HomeFeedMode.SavedSearch -> {
                        val saved = requireNotNull(preset)
                        val filters = runtime.filterList()
                        val validated = validateSourcePreset(saved, source, filters)
                        if (validated.issues.isNotEmpty()) throw DiscoveryException(DiscoveryIssue.PresetChanged)
                        runtime.search(saved.query, 1, filters.map { it.copy(selection = validated.selections[it.id]) })
                    }
                }
                val kind = when (source.itemType) {
                    DbItemType.Manga -> HomeMediaFilter.Manga
                    DbItemType.Anime -> HomeMediaFilter.Anime
                    DbItemType.Novel -> HomeMediaFilter.Novel
                }
                listing.items.filter { it.title.isNotBlank() && it.url.isNotBlank() }.take(24).map {
                    DiscoveryMedia("source:${source.id}:${it.url}", it.title, kind, it.thumbnailUrl,
                        description = it.description.orEmpty(), sourceId = source.id, sourceUrl = it.url)
                }
            }
        }
    }

    private suspend fun cached(key: String, refresh: Boolean, ttl: Long = 300_000L, load: suspend () -> List<DiscoveryMedia>): List<DiscoveryMedia> {
        if (!refresh) cacheLock.withLock { cache[key]?.takeIf { clock() - it.at in 0..ttl } }?.let { return it.items }
        val items = withTimeout(15_000) { load() }.distinctBy { it.key }.take(24)
        cacheLock.withLock {
            cache.remove(key)
            cache[key] = Cached(clock(), items)
            while (cache.size > 32) cache.remove(cache.keys.first())
        }
        return items
    }

    private suspend fun aniList(kind: HomeMediaFilter, search: String?, includeAdult: Boolean): List<DiscoveryMedia> {
        val fields = "id format title { romaji english native } coverImage { large } bannerImage description genres meanScore isAdult"
        // AniList treats an explicit null format differently from an omitted argument.
        val formatArgument = if (kind == HomeMediaFilter.Novel) ", format: NOVEL" else ""
        val adultArgument = if (includeAdult) "" else ", isAdult: false"
        val request = buildJsonObject {
            put("query", if (search == null) """
                query(${ '$' }type: MediaType) {
                  Page(page: 1, perPage: 24) { media(type: ${ '$' }type$formatArgument$adultArgument, sort: POPULARITY_DESC) { $fields } }
                }
            """.trimIndent() else """
                query(${ '$' }search: String, ${ '$' }type: MediaType) {
                  Media(search: ${ '$' }search, type: ${ '$' }type$formatArgument) {
                    recommendations(sort: RATING_DESC, perPage: 24) { nodes { mediaRecommendation { $fields } } }
                  }
                }
            """.trimIndent())
            putJsonObject("variables") {
                put("type", if (kind == HomeMediaFilter.Anime) "ANIME" else "MANGA")
                if (search != null) put("search", search)
            }
        }
        val response = http.request(HttpRequest("https://graphql.anilist.co", "POST",
            headers = mapOf("Content-Type" to "application/json", "Accept" to "application/json"), body = request.toString()))
        if (response.statusCode == 404 && search != null) return emptyList()
        checkStatus(response.statusCode)
        val root = json.parseToJsonElement(response.body).jsonObject
        if (root["errors"] is JsonArray) throw DiscoveryException(DiscoveryIssue.Network)
        val data = root.obj("data") ?: throw DiscoveryException(DiscoveryIssue.Network)
        val rows = if (search == null) data.obj("Page")?.array("media").orEmpty() else
            data.obj("Media")?.obj("recommendations")?.array("nodes").orEmpty().mapNotNull { (it as? JsonObject)?.get("mediaRecommendation") }
        return rows.mapNotNull { element ->
            val media = element as? JsonObject ?: return@mapNotNull null
            if (!includeAdult && media.bool("isAdult")) return@mapNotNull null
            val format = media.string("format")
            if (kind == HomeMediaFilter.Manga && format == "NOVEL") return@mapNotNull null
            val titles = media.obj("title") ?: return@mapNotNull null
            val aliases = listOfNotNull(titles.string("english"), titles.string("romaji"), titles.string("native")).distinct()
            val title = aliases.firstOrNull() ?: return@mapNotNull null
            val id = media.string("id") ?: return@mapNotNull null
            val actualKind = if (format == "NOVEL") HomeMediaFilter.Novel else kind
            DiscoveryMedia("anilist:$id", title, actualKind, media.obj("coverImage")?.string("large"), media.string("bannerImage"),
                cleanDescription(media.string("description").orEmpty()), media.array("genres").mapNotNull { (it as? JsonPrimitive)?.contentOrNull },
                media.number("meanScore")?.takeIf { it > 0 }?.div(10.0), aliases)
        }
    }

    private suspend fun tmdbTrending(kind: HomeMediaFilter, token: String, includeAdult: Boolean): List<DiscoveryMedia> {
        val type = if (kind == HomeMediaFilter.Movie) "movie" else "tv"
        val response = http.request(HttpRequest("https://api.themoviedb.org/3/trending/$type/week?language=en-US",
            headers = mapOf("Authorization" to "Bearer ${token.trim()}", "Accept" to "application/json")))
        checkStatus(response.statusCode, credentials = true)
        return tmdbRows(response.body, type, includeAdult)
    }

    /** TMDB v3 accepts either the `api_key` query parameter or a Bearer read access token. */
    private suspend fun tmdbRecommendationsFor(seed: TmdbSeed, apiKey: String?, token: String, includeAdult: Boolean): List<DiscoveryMedia> {
        val auth = apiKey?.let { "&api_key=${it.encodeURLParameter()}" }.orEmpty()
        val headers = if (apiKey != null) mapOf("Accept" to "application/json")
            else mapOf("Authorization" to "Bearer ${token.trim()}", "Accept" to "application/json")
        val response = http.request(HttpRequest("https://api.themoviedb.org/3/${seed.type}/${seed.id}/recommendations?page=1&language=en-US$auth",
            headers = headers))
        checkStatus(response.statusCode, credentials = true)
        return tmdbRows(response.body, seed.type, includeAdult)
    }

    private fun tmdbRows(body: String, defaultType: String, includeAdult: Boolean): List<DiscoveryMedia> =
        json.parseToJsonElement(body).jsonObject.array("results").mapNotNull { row ->
            val media = row as? JsonObject ?: return@mapNotNull null
            if (!includeAdult && media.bool("adult")) return@mapNotNull null
            val type = media.string("media_type")?.takeIf { it == "movie" || it == "tv" } ?: defaultType
            val id = media.string("id") ?: return@mapNotNull null
            val title = media.string("title") ?: media.string("name") ?: return@mapNotNull null
            fun image(field: String, size: String): String? = media.string(field)?.takeIf { it.startsWith('/') }?.let { "https://image.tmdb.org/t/p/$size$it" }
            DiscoveryMedia("tmdb:$type:$id", title, if (type == "movie") HomeMediaFilter.Movie else HomeMediaFilter.Series,
                image("poster_path", "w500"), image("backdrop_path", "w780"),
                media.string("overview").orEmpty(), rating = media.number("vote_average")?.takeIf { it > 0 },
                aliases = listOfNotNull(media.string("original_title"), media.string("original_name")))
        }

    private fun checkStatus(code: Int, credentials: Boolean = false) {
        if (code in 200..299) return
        throw DiscoveryException(when (code) {
            401, 403 -> if (credentials) DiscoveryIssue.Credentials else DiscoveryIssue.Network
            429 -> DiscoveryIssue.RateLimited
            else -> DiscoveryIssue.Network
        })
    }
}

/** Ranks by how many seed lists contain a title, then by its best position; [exclude]d keys are dropped. */
internal fun mergeTmdbRecommendations(perSeed: List<List<DiscoveryMedia>>, exclude: Set<String>): List<DiscoveryMedia> {
    val first = linkedMapOf<String, DiscoveryMedia>()
    val count = mutableMapOf<String, Int>()
    val bestRank = mutableMapOf<String, Int>()
    perSeed.forEach { list ->
        list.distinctBy { it.key }.forEachIndexed { rank, media ->
            if (media.key in exclude) return@forEachIndexed
            first.getOrPut(media.key) { media }
            count[media.key] = (count[media.key] ?: 0) + 1
            bestRank[media.key] = minOf(bestRank[media.key] ?: rank, rank)
        }
    }
    return first.values.sortedWith(compareByDescending<DiscoveryMedia> { count.getValue(it.key) }.thenBy { bestRank.getValue(it.key) })
}

internal fun cleanDescription(text: String): String = decodeHtmlEntities(
    text.replace(Regex("<br\\s*/?>", RegexOption.IGNORE_CASE), "\n").replace(Regex("<[^>]+>"), ""),
).trim()
private fun JsonObject.obj(key: String) = get(key) as? JsonObject
private fun JsonObject.array(key: String) = (get(key) as? JsonArray).orEmpty()
private fun JsonObject.string(key: String) = (get(key) as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() }
private fun JsonObject.number(key: String) = (get(key) as? JsonPrimitive)?.doubleOrNull
private fun JsonObject.bool(key: String) = (get(key) as? JsonPrimitive)?.booleanOrNull == true

Check your understanding

Apply an external metadata match to a followed source title and verify that its sourceId/link and reading chapters are unchanged. [chapter-content-end]: #

Step 2: implement tracker contracts and account ownership

Write TrackerService, account/profile models, login/OAuth helpers, score normalization and TrackerAccounts controller. Define search, exact-ID lookup, bind/fetch/update, status/progress/score conversion, logout and supported media types. Credentials belong to the captured profile, and OAuth callbacks to the exact pending attempt. A response after logout/account replacement must not resurrect the old account.

Implement provider adapters separately: MyAnimeList, AniList, Kitsu, Simkl, Trakt, internal metadata tracker, MangaUpdates, Shikimori, Bangumi, Hikka, MangaBaka, TMDB, Komga, Kavita, Suwayomi and Jellyfin. Use the registered numeric sync IDs unchanged. Recreate provider-specific URL encoding, result parsing, status/rating scales, token refresh and error mapping from each adapter and its tests.

User-hosted Komga/Kavita/Suwayomi/Jellyfin requests use the appropriate raw transport, preserving LAN/server URL handling. Do not route them through public-source challenge/DNS assumptions. Not every tracker offers the same operations; expose capabilities.

Follow the code

Start with shared tracker/account/login models, then each provider's wire adapter. Provider IDs and score/status scales are persistent contracts. normalizedTrackerScore rejects missing/invalid/zero/out-of-range values rather than treating them as zero-star ratings. Capture profile/account/attempt identity across OAuth, refresh and updates so a late response cannot restore a logged-out account. Raw user-hosted APIs retain LAN/server behavior.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerAccount.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerLogin.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerOAuth.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerScores.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerAccounts.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/AnilistTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/BangumiTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/HikkaTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/JellyfinTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/KavitaTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/KitsuTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/KomgaTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/MalTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/MangaBakaTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/MangaUpdatesTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/MetadataTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/ServerTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/ShikimoriTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/SimklTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/SuwayomiTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/TmdbTrackerService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/tracking/TraktTrackerService.kt

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines TrackerService, checkRefresh, findLibraryItem, update, statusList, search, fetchGeneralData, fetchUserData, accountProfile, scoreValue and 14 further declarations.

The source describes its contract as:

The metadata-server tracker, configured with the metadata server instead of the tracker settings.

Cross-chapter imports used by this file: DbItemType, DbManga, DbSettings, DbSource, DbTrack, DbTrackPreference. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSettings
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

interface TrackerService {
    val syncId: Int
    val name: String

    /** The metadata-server tracker, configured with the metadata server instead of the tracker settings. */
    val isMetadataSource: Boolean get() = false

    suspend fun checkRefresh(): Boolean
    suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack?

    /**
     * Pushes [track]'s progress/status/score. Remote adapters return the provider's state for the caller
     * ([TrackerAccounts]) to store; the original local-only adapters store it themselves.
     */
    suspend fun update(track: DbTrack, isManga: Boolean): DbTrack
    fun statusList(isManga: Boolean): List<DbTrackStatus>

    /** Free-text search; remote adapters resolve `id:<provider id>` (see [trackerSearchId]) to that entry. */
    suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch>
    suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch>
    suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch>
    suspend fun accountProfile(): TrackerAccountProfile? = null
    fun scoreValue(): Pair<Int, Int>
    fun displayScore(score: Int): String

    /** Whether this tracker handles manga/novel ([isManga]) or anime entries. */
    fun supports(isManga: Boolean): Boolean = true

    /** Connect-dialog fields. Empty keeps the original paste-a-token/OAuth dialog and [TrackerAccounts.connect]. */
    val loginFields: List<TrackerLoginField> get() = emptyList()

    /** Browser sign-in page for the entered values (OAuth/approval), or null when the provider has none. */
    suspend fun authorizeUrl(values: Map<TrackerLoginField, String>): String? = null

    /** Whether the connect dialog offers [authorizeUrl] ("Open sign-in"). */
    val browserSignIn: Boolean get() = TrackerLoginField.AuthorizationCode in loginFields

    /**
     * Exchanges the entered credentials for the preference to store: the access token/session in
     * [DbTrackPreference.oauth], everything else in [TrackerCredentials] ([DbTrackPreference.prefs]).
     * Throws with a user-readable message on rejected credentials.
     */
    suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference =
        throw UnsupportedOperationException("$name uses token sign-in")

    /** Creates or fetches the remote list entry for a newly bound [track]; returns the state to store. */
    suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack = track

    /** Fetches the remote state of a bound [track]; returns the state to store. */
    suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack = track

    /** Removes the remote list entry of [track]; local removal is the caller's. */
    suspend fun unbind(track: DbTrack, isManga: Boolean) {}
}

/**
 * Animetail `EnhancedTracker`: a server-backed tracker that is never searched manually. It binds titles that
 * come from its own server's source ([accept]) by resolving the title's source URL ([match]), and its
 * progress is synchronized both ways with the local chapter/episode read state.
 */
interface EnhancedTracker {
    fun accept(source: DbSource): Boolean

    /** Zero or one entry for [manga] on the configured server. */
    suspend fun match(manga: DbManga): DbTrackSearch?
}

internal fun DbItemType.isMangaTracking(): Boolean = this != DbItemType.Anime

data class TrackerAccountProfile(
    val name: String? = null,
    val avatarUrl: String? = null,
)

// Sync ids the registry assigns; they key stored tracks and preferences, so they never change.
const val MalTrackerSyncId = 1
const val AnilistTrackerSyncId = 2
const val KitsuTrackerSyncId = 3
const val SimklTrackerSyncId = 4
const val TraktTrackerSyncId = 5
const val MetadataTrackerSyncId = 6
const val MangaUpdatesTrackerSyncId = 10
const val ShikimoriTrackerSyncId = 11
const val BangumiTrackerSyncId = 12
const val HikkaTrackerSyncId = 13
const val MangaBakaTrackerSyncId = 14
const val TmdbTrackerSyncId = 15
const val KomgaTrackerSyncId = 20
const val KavitaTrackerSyncId = 21
const val SuwayomiTrackerSyncId = 22
const val JellyfinTrackerSyncId = 23

/** [all] in the user's configured tracker order, followed by unordered trackers in their default order. */
fun orderedTrackers(all: List<TrackerService>, db: DbSettings): List<TrackerService> {
    val configured = db.trackerOrder.orEmpty().mapNotNull { id -> all.firstOrNull { it.syncId == id } }
    return (configured + all).distinctBy { it.syncId }
}

fun DbTrack.readableStatusList(isManga: Boolean): List<DbTrackStatus> =
    if (isManga) {
        listOf(
            DbTrackStatus.Reading,
            DbTrackStatus.Completed,
            DbTrackStatus.OnHold,
            DbTrackStatus.Dropped,
            DbTrackStatus.PlanToRead,
            DbTrackStatus.ReReading,
        )
    } else {
        listOf(
            DbTrackStatus.Watching,
            DbTrackStatus.Completed,
            DbTrackStatus.OnHold,
            DbTrackStatus.Dropped,
            DbTrackStatus.PlanToWatch,
            DbTrackStatus.ReWatching,
        )
    }

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines TrackerAccount, toProfile, anilistAccount, malAccount, simklAccount, kitsuAccount, traktAccount, cleanText.

The source describes its contract as:

Account identity returned by tracker services. Distinct [id] (used by API calls) and [name] (shown to the user). Direct port of Mangayomi's lib/services/trackers/tracker_account.dart (commit 3efb6199).

Cross-chapter imports used by this file: DbTrackPreference. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrackPreference
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull

/**
 * Account identity returned by tracker services.
 *
 * Distinct [id] (used by API calls) and [name] (shown to the user).
 * Direct port of Mangayomi's `lib/services/trackers/tracker_account.dart` (commit 3efb6199).
 */
data class TrackerAccount(
    val id: String,
    val name: String? = null,
    val avatarUrl: String? = null,
) {
    fun toProfile(): TrackerAccountProfile = TrackerAccountProfile(
        name = name ?: id,
        avatarUrl = avatarUrl,
    )
}

/**
 * Parses viewer from AniList's GraphQL Viewer query.
 */
fun anilistAccount(viewer: JsonObject): TrackerAccount {
    val id = (viewer["id"] as? JsonPrimitive)?.contentOrNull
        ?: (viewer["id"] as? JsonPrimitive)?.toString().orEmpty()
    val name = cleanText((viewer["name"] as? JsonPrimitive)?.contentOrNull)
    val avatarObj = viewer["avatar"] as? JsonObject
    val avatar = cleanText((avatarObj?.get("large") as? JsonPrimitive)?.contentOrNull)
        ?: cleanText((avatarObj?.get("medium") as? JsonPrimitive)?.contentOrNull)
    return TrackerAccount(
        id = id,
        name = name,
        avatarUrl = avatar,
    )
}

/**
 * Parses user from MyAnimeList's `/users/@me` endpoint.
 *
 * MAL uses the username as the account handle and identifier.
 */
fun malAccount(user: JsonObject): TrackerAccount {
    val name = cleanText((user["name"] as? JsonPrimitive)?.contentOrNull).orEmpty()
    val picture = cleanText((user["picture"] as? JsonPrimitive)?.contentOrNull)
    return TrackerAccount(
        id = name,
        name = name.ifBlank { null },
        avatarUrl = picture,
    )
}

/**
 * Parses settings from Simkl's `/users/settings` endpoint.
 *
 * Account ID is stored in `account.id`, while user profile is in `user`.
 */
fun simklAccount(settings: JsonObject): TrackerAccount {
    val accountObj = settings["account"] as? JsonObject
    val id = (accountObj?.get("id") as? JsonPrimitive)?.contentOrNull
        ?: (accountObj?.get("id") as? JsonPrimitive)?.toString().orEmpty()
    val userObj = settings["user"] as? JsonObject
    val name = cleanText((userObj?.get("name") as? JsonPrimitive)?.contentOrNull)
    val rawAvatar = cleanText((userObj?.get("avatar") as? JsonPrimitive)?.contentOrNull)
    val avatarUrl = rawAvatar?.let {
        if (it.startsWith("http://") || it.startsWith("https://")) it else "https://simkl.in/avatars/$it"
    }
    return TrackerAccount(
        id = id,
        name = name,
        avatarUrl = avatarUrl,
    )
}

/**
 * Parses user from Kitsu's `/users?filter[self]=true` endpoint.
 *
 * Kitsu name is optional while slug is always present, so slug falls back
 * when name is absent rather than showing numeric id.
 */
fun kitsuAccount(data: JsonObject): TrackerAccount {
    val id = (data["id"] as? JsonPrimitive)?.contentOrNull.orEmpty()
    val attributes = data["attributes"] as? JsonObject
    val name = cleanText((attributes?.get("name") as? JsonPrimitive)?.contentOrNull)
        ?: cleanText((attributes?.get("slug") as? JsonPrimitive)?.contentOrNull)
    val avatarObj = attributes?.get("avatar") as? JsonObject
    val avatarUrl = cleanText((avatarObj?.get("original") as? JsonPrimitive)?.contentOrNull)
        ?: cleanText((avatarObj?.get("medium") as? JsonPrimitive)?.contentOrNull)
    return TrackerAccount(
        id = id,
        name = name,
        avatarUrl = avatarUrl,
    )
}

/**
 * Parses user from Trakt's `/users/settings` endpoint.
 */
fun traktAccount(settings: JsonObject): TrackerAccount {
    val userObj = settings["user"] as? JsonObject
    val username = cleanText((userObj?.get("username") as? JsonPrimitive)?.contentOrNull).orEmpty()
    val name = cleanText((userObj?.get("name") as? JsonPrimitive)?.contentOrNull) ?: username.ifBlank { null }
    val images = userObj?.get("images") as? JsonObject
    val avatarObj = images?.get("avatar") as? JsonObject
    val avatarUrl = cleanText((avatarObj?.get("full") as? JsonPrimitive)?.contentOrNull)
    return TrackerAccount(
        id = username,
        name = name,
        avatarUrl = avatarUrl,
    )
}

/**
 * Returns clean non-empty string or null.
 */
private fun cleanText(value: String?): String? =
    value?.trim()?.takeIf { it.isNotEmpty() }

/**
 * Displayable account label for a tracker preference.
 */
val DbTrackPreference.accountLabel: String?
    get() = accountName?.takeIf { it.isNotBlank() }
        ?: username?.takeIf { it.isNotBlank() && it.toLongOrNull() == null }

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines TrackerLoginField, TrackerCredentials, DbTrackPreference.credentials, TrackerCredentials.encode, YokanDatabase.trackPreference, trackerSearchId, callbackParameter, Map, TrackerHttpException, HttpResponse.requireSuccess and 10 further declarations.

The source describes its contract as:

A credential the connect dialog asks for; adapters list theirs in [TrackerService.loginFields].

Cross-chapter imports used by this file: DbTrackPreference, YokanDatabase, HttpRequest, HttpResponse, nowMillis. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrackPreference
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 eu.friedcutlet.yokan.util.nowMillis
import io.ktor.http.decodeURLQueryComponent
import io.ktor.http.encodeURLParameter
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.longOrNull

/** A credential the connect dialog asks for; adapters list theirs in [TrackerService.loginFields]. */
enum class TrackerLoginField(val label: String, val secret: Boolean = false) {
    ServerUrl("Server URL"),
    Username("Username"),
    Password("Password", secret = true),
    ApiKey("API key / access token", secret = true),
    ClientId("OAuth client ID"),
    ClientSecret("OAuth client secret", secret = true),
    /** The code the provider shows, or the whole callback URL copied from the browser. */
    AuthorizationCode("Authorization code or callback URL", secret = true),
}

/**
 * User-owned tracker configuration stored as JSON in [DbTrackPreference.prefs]; the access token or
 * session itself lives in [DbTrackPreference.oauth]. Exported only with sensitive backups.
 */
@Serializable
data class TrackerCredentials(
    val serverUrl: String? = null,
    val clientId: String? = null,
    val clientSecret: String? = null,
    val refreshToken: String? = null,
    /** Epoch milliseconds; null when the provider gives no expiry. */
    val expiresAt: Long? = null,
    val userId: String? = null,
    val apiKey: String? = null,
)

internal val trackerJson = Json { ignoreUnknownKeys = true; isLenient = true; explicitNulls = false }

fun DbTrackPreference.credentials(): TrackerCredentials =
    prefs?.takeIf { it.isNotBlank() }?.let { runCatching { trackerJson.decodeFromString(TrackerCredentials.serializer(), it) }.getOrNull() }
        ?: TrackerCredentials()

fun TrackerCredentials.encode(): String = trackerJson.encodeToString(TrackerCredentials.serializer(), this)

/** The stored sign-in of tracker [syncId], or null when it was never connected. */
fun YokanDatabase.trackPreference(syncId: Int): DbTrackPreference? =
    trackPreferences().firstOrNull { it.syncId?.toInt() == syncId }

/** `id:12345` (case-insensitive prefix) → `12345`; null for a free-text query. */
fun trackerSearchId(query: String): String? =
    query.trim().takeIf { it.startsWith("id:", ignoreCase = true) }?.substring(3)?.trim()?.takeIf { it.isNotEmpty() }

/** [raw] is either a bare value or a pasted callback URL carrying `name=value`. */
fun callbackParameter(raw: String, name: String): String {
    val value = raw.trim()
    if (!value.contains("$name=")) return value
    return value.substringAfter('?', value).replace('#', '&').split('&')
        .firstOrNull { it.startsWith("$name=") }?.substringAfter('=')
        ?.let { runCatching { it.decodeURLQueryComponent(plusIsSpace = true) }.getOrDefault(it) } ?: value
}

/** Required non-blank login value, or a user-readable failure. */
fun Map<TrackerLoginField, String>.required(field: TrackerLoginField): String =
    this[field]?.trim()?.takeIf { it.isNotEmpty() } ?: throw IllegalArgumentException("${field.label} is required")

fun Map<TrackerLoginField, String>.optional(field: TrackerLoginField): String? =
    this[field]?.trim()?.takeIf { it.isNotEmpty() }

/** A non-2xx tracker response; [status] 401/403 means the stored credentials were rejected. */
class TrackerHttpException(val tracker: String, val status: Int, body: String) :
    Exception("$tracker returned HTTP $status${body.trim().take(200).takeIf { it.isNotEmpty() }?.let { ": $it" }.orEmpty()}") {
    val unauthorized: Boolean get() = status == 401 || status == 403
}

fun HttpResponse.requireSuccess(tracker: String): HttpResponse =
    if (statusCode in 200..299) this else throw TrackerHttpException(tracker, statusCode, body)

fun HttpResponse.json(tracker: String): JsonElement = trackerJson.parseToJsonElement(requireSuccess(tracker).body)

/** `application/x-www-form-urlencoded` body. */
fun formBody(vararg fields: Pair<String, String>): String =
    fields.joinToString("&") { (k, v) -> "${k.encodeURLParameter()}=${v.encodeURLParameter()}" }

/** OAuth token response expiry in epoch millis (one minute early), or null without `expires_in`. */
internal fun JsonObject.oauthExpiresAt(): Long? =
    (this["expires_in"] as? JsonPrimitive)?.longOrNull?.let { nowMillis() + (it - 60) * 1000 }

/**
 * Bearer-token calls for a tracker signed in with the user's own OAuth application, whose client id/secret and
 * refresh token live in [TrackerCredentials]. [refreshFields] are extra form fields the provider's refresh grant
 * needs (Bangumi's `redirect_uri`).
 */
internal class TrackerOAuthClient(
    private val tracker: String,
    private val syncId: Int,
    private val tokenUrl: String,
    private val database: YokanDatabase,
    private val http: HttpService,
    private val refreshFields: List<Pair<String, String>> = emptyList(),
) {
    /** Form POST to the token endpoint; returns the token response. */
    suspend fun tokenRequest(vararg fields: Pair<String, String>): JsonObject = http.request(
        HttpRequest(
            url = tokenUrl,
            method = "POST",
            headers = mapOf("User-Agent" to UserAgent, "Content-Type" to "application/x-www-form-urlencoded"),
            body = formBody(*fields),
        ),
    ).json(tracker) as JsonObject

    /** Authorized call; a login with a refresh token refreshes an expired token up front, or once after a 401. */
    suspend fun api(method: String, url: String, body: String? = null): HttpResponse {
        val pref = database.trackPreference(syncId)
        val token = pref?.oauth?.takeIf { it.isNotBlank() } ?: throw IllegalStateException("Not logged in to $tracker")
        val credentials = pref.credentials()
        val canRefresh = credentials.refreshToken != null
        val expiresAt = credentials.expiresAt
        if (canRefresh && expiresAt != null && nowMillis() >= expiresAt) return send(method, url, refresh(pref), body)
        val response = send(method, url, token, body)
        if (response.statusCode != 401 || !canRefresh) return response
        return send(method, url, refresh(pref), body)
    }

    suspend fun send(method: String, url: String, token: String, body: String? = null): HttpResponse =
        http.request(
            HttpRequest(
                url = url,
                method = method,
                headers = mapOf("User-Agent" to UserAgent, "Authorization" to "Bearer $token"),
                body = body,
            ),
        )

    /** Exchanges the stored refresh token, stores the new token and returns it. */
    private suspend fun refresh(pref: DbTrackPreference): String {
        val credentials = pref.credentials()
        val response = tokenRequest(
            "grant_type" to "refresh_token",
            "client_id" to credentials.clientId.orEmpty(),
            "client_secret" to credentials.clientSecret.orEmpty(),
            "refresh_token" to credentials.refreshToken.orEmpty(),
            *refreshFields.toTypedArray(),
        )
        val token = response.string("access_token") ?: throw TrackerHttpException(tracker, 401, "No access token")
        database.upsertTrackPreference(
            pref.copy(
                oauth = token,
                prefs = credentials.copy(
                    refreshToken = response.string("refresh_token") ?: credentials.refreshToken,
                    expiresAt = response.oauthExpiresAt(),
                ).encode(),
            ),
        )
        return token
    }

    private fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull

    private companion object {
        const val UserAgent = "Yokan"
    }
}

/** Trailing-slash-free server origin a user typed, with `https://` assumed when no scheme is given. */
fun normalizeServerUrl(raw: String): String {
    val trimmed = raw.trim().trimEnd('/')
    require(trimmed.isNotEmpty()) { "Server URL is required" }
    return if ("://" in trimmed) trimmed else "https://$trimmed"
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines TrackerOAuth, authorizeUrl, redirectUri, listenForCallback, parseCallback, slug, TrackerOAuthResult.

The source describes its contract as:

Builds tracker OAuth login URLs and listens for callback deep-links. Each tracker advertises a redirect URI under the yokan:// scheme that the Android manifest already routes back into the app via [AppDeepLinks.dispatch]. Real OAuth requires client IDs/secrets which the port doesn't ship; the URL builders use the documented endpoints so once a client is provisioned by the user they can paste credentials in the Connect dialog and the callback will deliver code/access_token/token into [onCallback].

Cross-chapter imports used by this file: AppLogger, AppDeepLinks. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.system.AppDeepLinks

/**
 * Builds tracker OAuth login URLs and listens for callback deep-links. Each tracker advertises a
 * redirect URI under the `yokan://` scheme that the Android manifest already routes back into
 * the app via [AppDeepLinks.dispatch].
 *
 * Real OAuth requires client IDs/secrets which the port doesn't ship; the URL builders use the
 * documented endpoints so once a client is provisioned by the user they can paste credentials in
 * the Connect dialog and the callback will deliver `code`/`access_token`/`token` into
 * [onCallback].
 */
object TrackerOAuth {
    private const val MalAuthorizeUrl = "https://myanimelist.net/v1/oauth2/authorize"
    private const val AnilistAuthorizeUrl = "https://anilist.co/api/v2/oauth/authorize"
    private const val KitsuAuthorizeUrl = "https://kitsu.io/users/sign_in"
    private const val SimklAuthorizeUrl = "https://simkl.com/oauth/authorize"
    private const val TraktAuthorizeUrl = "https://trakt.tv/oauth/authorize"

    private const val CallbackPrefix = "yokan://tracker"

    fun authorizeUrl(serviceSyncId: Int, clientId: String): String? {
        val redirect = redirectUri(serviceSyncId)
        return when (serviceSyncId) {
            MalTrackerSyncId -> "$MalAuthorizeUrl?response_type=code&client_id=$clientId&redirect_uri=$redirect&code_challenge=yokan&code_challenge_method=plain"
            AnilistTrackerSyncId -> "$AnilistAuthorizeUrl?client_id=$clientId&response_type=token&redirect_uri=$redirect"
            KitsuTrackerSyncId -> "$KitsuAuthorizeUrl?redirect_to=$redirect"
            SimklTrackerSyncId -> "$SimklAuthorizeUrl?response_type=code&client_id=$clientId&redirect_uri=$redirect"
            TraktTrackerSyncId -> "$TraktAuthorizeUrl?response_type=code&client_id=$clientId&redirect_uri=$redirect"
            else -> null
        }
    }

    fun redirectUri(serviceSyncId: Int): String = "$CallbackPrefix/${slug(serviceSyncId)}"

    fun listenForCallback(serviceSyncId: Int, onCallback: (TrackerOAuthResult) -> Unit): () -> Unit {
        val prefix = redirectUri(serviceSyncId)
        return AppDeepLinks.registerPrefix(prefix) { url ->
            val result = parseCallback(url)
            result.error?.let { AppLogger.warn("[tracking] ${slug(serviceSyncId)} OAuth callback returned error: $it") }
            onCallback(result)
        }
    }

    fun parseCallback(url: String): TrackerOAuthResult {
        val fragment = url.substringAfter('#', "")
        val query = url.substringAfter('?', "").substringBefore('#')
        val parts = (fragment + "&" + query).split('&').filter { it.contains('=') }
        val map = parts.associate { piece ->
            val key = piece.substringBefore('=').trim()
            val value = piece.substringAfter('=').trim()
            key to value
        }
        return TrackerOAuthResult(
            accessToken = map["access_token"] ?: map["token"],
            authorizationCode = map["code"],
            state = map["state"],
            error = map["error"],
            raw = url,
        )
    }

    private fun slug(serviceSyncId: Int): String = when (serviceSyncId) {
        MalTrackerSyncId -> "myanimelist"
        AnilistTrackerSyncId -> "anilist"
        KitsuTrackerSyncId -> "kitsu"
        SimklTrackerSyncId -> "simkl"
        TraktTrackerSyncId -> "trakt"
        MangaUpdatesTrackerSyncId -> "mangaupdates"
        ShikimoriTrackerSyncId -> "shikimori"
        BangumiTrackerSyncId -> "bangumi"
        HikkaTrackerSyncId -> "hikka"
        MangaBakaTrackerSyncId -> "mangabaka"
        TmdbTrackerSyncId -> "tmdb"
        else -> "unknown"
    }
}

data class TrackerOAuthResult(
    val accessToken: String?,
    val authorizationCode: String?,
    val state: String?,
    val error: String?,
    val raw: String,
)

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The shared scale helper returns null for unknown providers, invalid maxima, missing/zero scores or scores above the maximum. Valid values normalize to a ten-point scale for library/Home calculations.

The implementation below defines trackerScoreMaximum, normalizedTrackerScore.

The source describes its contract as:

Defaults for existing saved rows; production callers may provide the service's advertised scale.

package eu.friedcutlet.yokan.services.tracking

/** Defaults for existing saved rows; production callers may provide the service's advertised scale. */
fun trackerScoreMaximum(providerId: Int?): Int? = when (providerId) {
    1, 4, 5, 6, in 10..15 -> 10
    2, 3 -> 100
    else -> null
}

fun normalizedTrackerScore(providerId: Int?, score: Int?, maximum: Int? = trackerScoreMaximum(providerId)): Double? {
    if (score == null || maximum == null || maximum <= 0 || score <= 0 || score > maximum) return null
    return score.toDouble() * 10.0 / maximum
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

Account writes must remain tied to the captured profile/provider attempt. Keep logout, refresh and late-response guards as part of the authentication contract.

The implementation below defines TrackerAccounts, connect, login, disconnect, bound, updated, progressed, removed, refresh, addedToLibrary and 20 further declarations.

The source describes its contract as:

Tracker accounts and the remote side of tracking. The repository stores every local track change first and then calls the hooks here ([bound], [updated], [progressed], [removed], [addedToLibrary]); remote calls run in [scope] (the profile's service scope), so they finish even when the screen that started them is gone, and failures are logged without touching the local state. Remote results are merged with "smart sync": progress never goes backwards, local progress ahead of the provider is pushed, and [EnhancedTracker] progress (a chapter/episode number) also marks local chapters read.

Cross-chapter imports used by this file: DbChapter, DbItemType, DbManga, DbTrack, DbTrackPreference, DbTrackSearch. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
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.domain.ChapterRecognition
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/**
 * Tracker accounts and the remote side of tracking. The repository stores every local track change first and
 * then calls the hooks here ([bound], [updated], [progressed], [removed], [addedToLibrary]); remote calls run in
 * [scope] (the profile's service scope), so they finish even when the screen that started them is gone, and
 * failures are logged without touching the local state.
 *
 * Remote results are merged with "smart sync": progress never goes backwards, local progress ahead of the
 * provider is pushed, and [EnhancedTracker] progress (a chapter/episode number) also marks local chapters read.
 */
class TrackerAccounts(
    private val database: YokanDatabase,
    private val trackers: List<TrackerService>,
    private val scope: CoroutineScope,
) {
    // ponytail: one lock serializes every remote tracker call; per-track locks if many trackers ever contend.
    private val remote = Mutex()

    /** Original token dialog: stores the credentials, then fetches the account profile in the background. */
    fun connect(syncId: Long, username: String, oauthToken: String) {
        database.upsertTrackPreference(
            DbTrackPreference(
                syncId = syncId,
                username = username.ifBlank { null },
                oauth = oauthToken.ifBlank { null },
                refreshing = false,
            ),
        )
        fetchProfile(syncId)
    }

    /** Credential dialog of trackers with [TrackerService.loginFields]; throws the provider's rejection. */
    suspend fun login(syncId: Long, values: Map<TrackerLoginField, String>) {
        val tracker = checkNotNull(tracker(syncId.toInt())) { "Unknown tracker" }
        val preference = tracker.login(values).copy(syncId = syncId)
        database.upsertTrackPreference(preference)
        AppLogger.info("[tracking] ${tracker.name} signed in")
        if (preference.accountName == null) fetchProfile(syncId)
    }

    fun disconnect(syncId: Long) {
        database.upsertTrackPreference(DbTrackPreference(syncId = syncId, username = null, oauth = null, refreshing = false))
    }

    /** A track was just bound locally (manual search result or `id:` lookup). */
    fun bound(trackId: Long): Job = scope.launch { run(trackId, "bind", remoteOnly = true) { tracker, track -> bindRemote(tracker, track) } }

    /** The user edited progress/status/score locally. */
    fun updated(trackId: Long): Job = scope.launch {
        run(trackId, "update") { tracker, track -> store(tracker.update(track, track.isManga())) }
    }

    /** Chapters/episodes of [mangaId] were marked read; honours "Update progress after reading". */
    fun progressed(mangaId: Long): Job? {
        if (!database.settings().updateProgressAfterReading) return null
        val ids = database.tracks(mangaId).map { it.id }
        if (ids.isEmpty()) return null
        return scope.launch {
            ids.forEach { id ->
                run(id, "progress", remoteOnly = true) { tracker, track ->
                    val pushed = if (tracker is EnhancedTracker) track.copy(lastChapterRead = continuousReadNumber(track)) else track
                    store(tracker.update(pushed, track.isManga()))
                }
            }
        }
    }

    /** The local track is already gone; this removes the provider's list entry. */
    fun removed(track: DbTrack): Job = scope.launch {
        val tracker = tracker(track.syncId)?.takeIf { it.isRemote() && hasToken(it) } ?: return@launch
        remote.withLock {
            catchingNonCancellation { tracker.unbind(track, track.isManga()) }
                .onFailure { warn(tracker, "unbind of track ${track.id}", it) }
        }
    }

    /** Pulls every bound tracker of [mangaId] (detail screen open), merging and syncing as in [bindRemote]. */
    fun refresh(mangaId: Long): Job = scope.launch {
        database.tracks(mangaId).forEach { track ->
            run(track.id, "refresh", remoteOnly = true) { tracker, current -> reconcile(tracker, current, tracker.refresh(current, current.isManga())) }
        }
    }

    /**
     * [mangaId] was added to the library: logged-in [EnhancedTracker]s that accept its source always bind it
     * (Animetail semantics); with the opt-in preference, other logged-in trackers bind their single result
     * whose title equals the title's name.
     */
    fun addedToLibrary(mangaId: Long): Job = scope.launch {
        val manga = database.manga(mangaId) ?: return@launch
        val source = manga.sourceId?.let(database::source)
        val isManga = manga.itemType.isMangaTracking()
        val autoBind = database.settings().features.tracking.autoBindOnAdd
        trackers.forEach { tracker ->
            if (!tracker.supports(isManga) || !hasToken(tracker)) return@forEach
            if (database.tracks(mangaId).any { it.syncId == tracker.syncId }) return@forEach
            val match = catchingNonCancellation {
                when {
                    tracker is EnhancedTracker -> if (source != null && tracker.accept(source)) remote.withLock { tracker.match(manga) } else null
                    autoBind -> remote.withLock { tracker.search(manga.name.orEmpty(), isManga) }.singleTitleMatch(manga)
                    else -> null
                }
            }.onFailure { warn(tracker, "automatic bind of title $mangaId", it) }.getOrNull() ?: return@forEach
            // The title may have left the library or been bound meanwhile.
            if (database.manga(mangaId)?.favorite != true || database.tracks(mangaId).any { it.syncId == tracker.syncId }) return@forEach
            val track = database.upsertTrack(match.copy(syncId = tracker.syncId).toDbTrack(mangaId, manga.itemType))
            AppLogger.info("[tracking] ${tracker.name} automatically bound title $mangaId")
            run(track.id, "bind", remoteOnly = true) { t, current -> bindRemote(t, current) }
        }
    }

    private suspend fun bindRemote(tracker: TrackerService, track: DbTrack) {
        val read = readCount(track)
        val prepared = track.copy(
            lastChapterRead = maxOf(track.lastChapterRead ?: 0, localProgress(tracker, track)),
            status = if (read == 0 && track.status == track.inProgressStatus()) track.plannedStatus() else track.status,
        )
        reconcile(tracker, prepared, tracker.bind(prepared, track.isManga()))
    }

    /** Stores [remote], first pushing local progress the provider is behind on; enhanced trackers mark chapters read. */
    private suspend fun reconcile(tracker: TrackerService, local: DbTrack, remote: DbTrack) {
        val localProgress = maxOf(local.lastChapterRead ?: 0, localProgress(tracker, local))
        val merged = if (localProgress > (remote.lastChapterRead ?: 0)) {
            tracker.update(remote.copy(lastChapterRead = localProgress), local.isManga())
        } else remote
        store(merged)
        if (tracker is EnhancedTracker) markReadUpTo(local, merged.lastChapterRead ?: 0)
    }

    private fun store(result: DbTrack) {
        val current = database.tracks(result.mangaId).firstOrNull { it.id == result.id } ?: return
        val merged = current.copy(
            mediaId = result.mediaId ?: current.mediaId,
            libraryId = result.libraryId ?: current.libraryId,
            title = result.title ?: current.title,
            lastChapterRead = result.lastChapterRead ?: current.lastChapterRead,
            totalChapter = result.totalChapter ?: current.totalChapter,
            score = result.score ?: current.score,
            status = result.status,
            startedReadingDate = result.startedReadingDate ?: current.startedReadingDate,
            finishedReadingDate = result.finishedReadingDate ?: current.finishedReadingDate,
            trackingUrl = result.trackingUrl ?: current.trackingUrl,
        )
        if (merged != current) database.upsertTrack(merged.copy(updatedAt = nowMillis()))
    }

    private fun localProgress(tracker: TrackerService, track: DbTrack): Int =
        if (tracker is EnhancedTracker) continuousReadNumber(track) else readCount(track)

    private fun readCount(track: DbTrack): Int = track.mangaId?.let { id -> database.chapters(id).count { it.isRead } } ?: 0

    /** Animetail's enhanced progress: the number of the last chapter of the continuous read run. */
    private fun continuousReadNumber(track: DbTrack): Int {
        val manga = track.mangaId?.let(database::manga) ?: return 0
        return numbered(manga).takeWhile { (chapter, _) -> chapter.isRead }.lastOrNull()?.second?.toInt() ?: 0
    }

    private fun markReadUpTo(track: DbTrack, number: Int) {
        val manga = track.mangaId?.let(database::manga) ?: return
        val unread = numbered(manga).filter { (chapter, n) -> !chapter.isRead && n <= number }
        if (unread.isEmpty()) return
        database.batch { unread.forEach { (chapter, _) -> database.upsertChapter(chapter.copy(isRead = true, updatedAt = nowMillis())) } }
    }

    private fun numbered(manga: DbManga): List<Pair<DbChapter, Double>> = database.chapters(manga.id).mapNotNull { chapter ->
        val number = chapter.number?.takeIf { it.isFinite() && it >= 0 }
            ?: ChapterRecognition.rawSeasonAndNumber(manga.name.orEmpty(), chapter.numberingName?.takeIf(String::isNotBlank) ?: chapter.name.orEmpty()).second
        number?.let { chapter to it }
    }.sortedBy { it.second }

    /**
     * Runs [block] for the current state of [trackId]; failures are logged. Remote adapters need a stored
     * token; the original local-only adapters keep receiving [TrackerService.update] as before ([remoteOnly] skips them).
     */
    private suspend fun run(trackId: Long, action: String, remoteOnly: Boolean = false, block: suspend (TrackerService, DbTrack) -> Unit) {
        remote.withLock {
            val track = database.tracks().firstOrNull { it.id == trackId } ?: return
            val tracker = tracker(track.syncId)?.takeIf { if (it.isRemote()) hasToken(it) else !remoteOnly } ?: return
            catchingNonCancellation { block(tracker, track) }
                .onSuccess { AppLogger.info("[tracking] ${tracker.name} $action of track $trackId done") }
                .onFailure { warn(tracker, "$action of track $trackId", it) }
        }
    }

    private fun tracker(syncId: Int?): TrackerService? = trackers.firstOrNull { it.syncId == syncId }

    private fun hasToken(tracker: TrackerService): Boolean =
        database.trackPreferences().any { it.syncId == tracker.syncId.toLong() && !it.oauth.isNullOrBlank() }

    /** Adapters that talk to the provider in bind/refresh/update; the original ones only store locally. */
    private fun TrackerService.isRemote(): Boolean = loginFields.isNotEmpty() || this is EnhancedTracker

    private fun fetchProfile(syncId: Long) {
        val tracker = tracker(syncId.toInt()) ?: return
        scope.launch {
            val profile = catchingNonCancellation { tracker.accountProfile() }
                .onFailure { warn(tracker, "profile fetch", it) }
                .getOrNull()
                ?: return@launch
            AppLogger.info("[tracking] ${tracker.name} connected")
            val current = database.trackPreferences().firstOrNull { it.syncId == syncId } ?: return@launch
            database.upsertTrackPreference(current.copy(accountName = profile.name, accountAvatarUrl = profile.avatarUrl))
        }
    }

    private fun warn(tracker: TrackerService, what: String, error: Throwable) =
        AppLogger.warn("[tracking] ${tracker.name} $what failed: ${error.message?.lineSequence()?.firstOrNull() ?: error::class.simpleName}")
}

/** The repository's mapping of a search result to a new local binding. */
fun DbTrackSearch.toDbTrack(mangaId: Long, itemType: DbItemType): DbTrack = DbTrack(
    libraryId = libraryId ?: mangaId,
    mediaId = mediaId,
    mangaId = mangaId,
    syncId = syncId,
    title = title,
    lastChapterRead = lastChapterRead,
    totalChapter = totalChapter,
    score = score?.toInt(),
    status = DbTrackStatus.entries.firstOrNull { it.name.equals(status, ignoreCase = true) }
        ?: if (itemType == DbItemType.Anime) DbTrackStatus.Watching else DbTrackStatus.Reading,
    startedReadingDate = startedReadingDate,
    finishedReadingDate = finishedReadingDate,
    trackingUrl = trackingUrl,
    itemType = itemType,
    updatedAt = nowMillis(),
)

private fun List<DbTrackSearch>.singleTitleMatch(manga: DbManga): DbTrackSearch? {
    val name = manga.name?.normalizedTitle()?.takeIf { it.isNotEmpty() } ?: return null
    return filter { it.title?.normalizedTitle() == name }.singleOrNull()
}

private fun String.normalizedTitle(): String = lowercase().filter { it.isLetterOrDigit() }

private fun DbTrack.isManga(): Boolean = itemType.isMangaTracking()

private fun DbTrack.inProgressStatus(): DbTrackStatus = if (itemType == DbItemType.Anime) DbTrackStatus.Watching else DbTrackStatus.Reading

private fun DbTrack.plannedStatus(): DbTrackStatus = if (itemType == DbItemType.Anime) DbTrackStatus.PlanToWatch else DbTrackStatus.PlanToRead

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines AnilistTrackerService, checkRefresh, findLibraryItem, update, statusList, search, fetchGeneralData, fetchUserData, accountProfile, scoreValue and 4 further declarations.

Cross-chapter imports used by this file: DbTrack, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.database.DbTrack
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.HttpService
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class AnilistTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "AniList"

    private val endpoint = "https://graphql.anilist.co"

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack =
        database.upsertTrack(track.copy(syncId = syncId))

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        if (query.isBlank()) return emptyList()
        val type = if (isManga) "MANGA" else "ANIME"
        trackerSearchId(query)?.let { id ->
            val numeric = id.toIntOrNull() ?: return emptyList()
            val byId = buildGraphqlBody(
                """
                query (${'$'}id: Int, ${'$'}type: MediaType) {
                  Media(id: ${'$'}id, type: ${'$'}type) {
                    id
                    title { romaji english native }
                    coverImage { large }
                    description
                    status
                    format
                    chapters
                    episodes
                    startDate { year month day }
                    averageScore
                    siteUrl
                  }
                }
                """.trimIndent(),
                "id" to JsonPrimitive(numeric),
                "type" to JsonPrimitive(type),
            )
            val item = postGraphql(byId)?.jsonObject?.get("data")?.jsonObject?.get("Media") as? JsonObject
            return listOfNotNull(item?.toTrackSearch(isManga))
        }
        val body = buildGraphqlBody(
            """
            query (${'$'}search: String, ${'$'}type: MediaType) {
              Page(perPage: 20) {
                media(search: ${'$'}search, type: ${'$'}type) {
                  id
                  title { romaji english native }
                  coverImage { large }
                  description
                  status
                  format
                  chapters
                  episodes
                  startDate { year month day }
                  averageScore
                  siteUrl
                }
              }
            }
            """.trimIndent(),
            "search" to JsonPrimitive(query),
            "type" to JsonPrimitive(type),
        )
        val media = postGraphql(body)
            ?.jsonObject?.get("data")
            ?.jsonObject?.get("Page")
            ?.jsonObject?.get("media") as? JsonArray
            ?: return emptyList()
        return media.mapNotNull { (it as? JsonObject)?.toTrackSearch(isManga) }
    }

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> {
        val type = if (isManga) "MANGA" else "ANIME"
        val (sort, status) = when (rankingType.lowercase()) {
            "trending" -> "TRENDING_DESC" to null
            "popular" -> "POPULARITY_DESC" to null
            "top" -> "SCORE_DESC" to null
            "upcoming" -> "TRENDING_DESC" to "NOT_YET_RELEASED"
            "latest" -> "UPDATED_AT_DESC" to "RELEASING"
            else -> "TRENDING_DESC" to null
        }
        val body = buildGraphqlBody(
            """
            query (${'$'}type: MediaType, ${'$'}sort: [MediaSort], ${'$'}status: MediaStatus) {
              Page(perPage: 25) {
                media(type: ${'$'}type, sort: ${'$'}sort, status: ${'$'}status) {
                  id
                  title { romaji english native }
                  coverImage { large }
                  description
                  status
                  format
                  chapters
                  episodes
                  startDate { year month day }
                  averageScore
                  siteUrl
                }
              }
            }
            """.trimIndent(),
            "type" to JsonPrimitive(type),
            "sort" to JsonPrimitive(sort),
            "status" to JsonPrimitive(status),
        )
        val media = postGraphql(body)
            ?.jsonObject?.get("data")
            ?.jsonObject?.get("Page")
            ?.jsonObject?.get("media") as? JsonArray
            ?: return emptyList()
        return media.mapNotNull { (it as? JsonObject)?.toTrackSearch(isManga) }
    }

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> {
        val token = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() } ?: return emptyList()
        val type = if (isManga) "MANGA" else "ANIME"
        val viewerBody = buildGraphqlBody(
            """
            query {
              Viewer { id name }
            }
            """.trimIndent(),
        )
        val viewerId = postGraphql(viewerBody, token)
            ?.jsonObject?.get("data")
            ?.jsonObject?.get("Viewer")
            ?.jsonObject?.get("id")
            ?.jsonPrimitive?.intOrNull
            ?: return emptyList()
        val listBody = buildGraphqlBody(
            """
            query (${'$'}userId: Int, ${'$'}type: MediaType) {
              MediaListCollection(userId: ${'$'}userId, type: ${'$'}type) {
                lists {
                  entries {
                    progress
                    score
                    status
                    media {
                      id
                      title { romaji english native }
                      coverImage { large }
                      description
                      status
                      format
                      chapters
                      episodes
                      startDate { year month day }
                      averageScore
                      siteUrl
                    }
                  }
                }
              }
            }
            """.trimIndent(),
            "userId" to JsonPrimitive(viewerId),
            "type" to JsonPrimitive(type),
        )
        val lists = postGraphql(listBody, token)
            ?.jsonObject?.get("data")
            ?.jsonObject?.get("MediaListCollection")
            ?.jsonObject?.get("lists") as? JsonArray
            ?: return emptyList()
        val results = mutableListOf<DbTrackSearch>()
        lists.forEach { listEntry ->
            ((listEntry as? JsonObject)?.get("entries") as? JsonArray)?.forEach { entry ->
                val obj = entry as? JsonObject ?: return@forEach
                val media = obj["media"] as? JsonObject ?: return@forEach
                val base = media.toTrackSearch(isManga) ?: return@forEach
                results += base.copy(
                    lastChapterRead = (obj["progress"] as? JsonPrimitive)?.intOrNull ?: base.lastChapterRead,
                    score = (obj["score"] as? JsonPrimitive)?.doubleOrNull ?: base.score,
                    status = (obj["status"] as? JsonPrimitive)?.contentOrNull?.lowercase() ?: base.status,
                )
            }
        }
        return results
    }

    override suspend fun accountProfile(): TrackerAccountProfile? {
        val token = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() } ?: return null
        val viewer = postGraphql(
            buildGraphqlBody("""
                query { Viewer { id name avatar { large medium } } }
            """.trimIndent()),
            token,
        )?.jsonObject?.get("data")?.jsonObject?.get("Viewer")?.jsonObject ?: return null
        return anilistAccount(viewer).toProfile()
    }

    override fun scoreValue(): Pair<Int, Int> = 0 to 100

    override fun displayScore(score: Int): String = "$score/100"

    private suspend fun postGraphql(body: String, token: String? = null): JsonElement? {
        val headers = mutableMapOf("Content-Type" to "application/json", "Accept" to "application/json")
        if (!token.isNullOrBlank()) headers["Authorization"] = "Bearer $token"
        return catchingNonCancellation {
            http.request(HttpRequest(url = endpoint, method = "POST", headers = headers, body = body)).json(name)
        }.getOrNull()
    }

    private fun buildGraphqlBody(query: String, vararg variables: Pair<String, JsonPrimitive>): String =
        buildJsonObject {
            put("query", JsonPrimitive(query))
            if (variables.isNotEmpty()) {
                put("variables", buildJsonObject {
                    variables.forEach { (key, value) -> put(key, value) }
                })
            }
        }.toString()

    private fun JsonObject.toTrackSearch(isManga: Boolean): DbTrackSearch? {
        val mediaId = (this["id"] as? JsonPrimitive)?.intOrNull ?: return null
        val titles = (this["title"] as? JsonObject) ?: JsonObject(emptyMap())
        val romaji = (titles["romaji"] as? JsonPrimitive)?.contentOrNull
        val english = (titles["english"] as? JsonPrimitive)?.contentOrNull
        val title = (english ?: romaji ?: (titles["native"] as? JsonPrimitive)?.contentOrNull).orEmpty()
        val cover = ((this["coverImage"] as? JsonObject)?.get("large") as? JsonPrimitive)?.contentOrNull.orEmpty()
        val description = (this["description"] as? JsonPrimitive)?.contentOrNull
            ?.replace(Regex("<[^>]+>"), "")
            ?.replace("&nbsp;", " ")
            .orEmpty()
        val chapterCount = (this["chapters"] as? JsonPrimitive)?.intOrNull
        val episodeCount = (this["episodes"] as? JsonPrimitive)?.intOrNull
        val publishing = (this["status"] as? JsonPrimitive)?.contentOrNull?.lowercase().orEmpty()
        val format = (this["format"] as? JsonPrimitive)?.contentOrNull.orEmpty()
        val score = (this["averageScore"] as? JsonPrimitive)?.doubleOrNull
        val siteUrl = (this["siteUrl"] as? JsonPrimitive)?.contentOrNull.orEmpty()
        return DbTrackSearch(
            mediaId = mediaId.toLong(),
            syncId = syncId,
            title = title,
            totalChapter = if (isManga) chapterCount else episodeCount,
            score = score,
            status = publishing,
            trackingUrl = siteUrl,
            coverUrl = cover,
            summary = description,
            publishingStatus = publishing,
            publishingType = format,
            startDate = (this["startDate"] as? JsonObject)?.let { sd ->
                val y = (sd["year"] as? JsonPrimitive)?.intOrNull
                val m = (sd["month"] as? JsonPrimitive)?.intOrNull
                val d = (sd["day"] as? JsonPrimitive)?.intOrNull
                if (y != null && m != null && d != null) "$y-${m.toString().padStart(2, '0')}-${d.toString().padStart(2, '0')}" else ""
            }.orEmpty(),
        )
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines BangumiTrackerService, checkRefresh, findLibraryItem, statusList, scoreValue, displayScore, fetchGeneralData, fetchUserData, authorizeUrl, login and 15 further declarations.

The source describes its contract as:

Bangumi v0 API (https://bangumi.github.io/api/). Signs in with a personal access token, or with the user's own OAuth application (bgm.tv's token endpoint sends no CORS headers, so the web build needs the token).

Cross-chapter imports used by this file: DbTrack, DbTrackPreference, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpResponse. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

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.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import io.ktor.http.encodeURLParameter
import io.ktor.http.encodeURLPathPart
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject

/**
 * Bangumi v0 API (https://bangumi.github.io/api/). Signs in with a personal access token, or with the
 * user's own OAuth application (bgm.tv's token endpoint sends no CORS headers, so the web build needs the token).
 */
class BangumiTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "Bangumi"

    private val oauth = TrackerOAuthClient(
        tracker = name,
        syncId = syncId,
        tokenUrl = "https://bgm.tv/oauth/access_token",
        database = database,
        http = http,
        refreshFields = listOf("redirect_uri" to TrackerOAuth.redirectUri(syncId)),
    )

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    // Bangumi has no re-reading collection type.
    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)
            .filter { it != DbTrackStatus.ReReading && it != DbTrackStatus.ReWatching }

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = if (score == 0) "-" else "$score/10"

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> = emptyList()

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()

    override val loginFields: List<TrackerLoginField> = listOf(
        TrackerLoginField.ApiKey,
        TrackerLoginField.ClientId,
        TrackerLoginField.ClientSecret,
        TrackerLoginField.AuthorizationCode,
    )

    /** OAuth page for an entered client id; otherwise the personal access token page. */
    override suspend fun authorizeUrl(values: Map<TrackerLoginField, String>): String {
        val clientId = values.optional(TrackerLoginField.ClientId) ?: return TokenPage
        return "https://bgm.tv/oauth/authorize?client_id=${clientId.encodeURLParameter()}&response_type=code" +
            "&redirect_uri=${TrackerOAuth.redirectUri(syncId).encodeURLParameter()}"
    }

    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        val apiKey = values.optional(TrackerLoginField.ApiKey)
        val token: String
        val credentials: TrackerCredentials
        if (apiKey != null) {
            token = apiKey
            credentials = TrackerCredentials()
        } else {
            val clientId = values.required(TrackerLoginField.ClientId)
            val clientSecret = values.required(TrackerLoginField.ClientSecret)
            val response = oauth.tokenRequest(
                "grant_type" to "authorization_code",
                "client_id" to clientId,
                "client_secret" to clientSecret,
                "code" to callbackParameter(values.required(TrackerLoginField.AuthorizationCode), "code"),
                "redirect_uri" to TrackerOAuth.redirectUri(syncId),
            )
            token = response.str("access_token") ?: throw TrackerHttpException(name, 401, "No access token")
            credentials = TrackerCredentials(
                clientId = clientId,
                clientSecret = clientSecret,
                refreshToken = response.str("refresh_token"),
                expiresAt = response.oauthExpiresAt(),
                userId = response.str("user_id"),
            )
        }
        val me = oauth.send("GET", "$ApiUrl/v0/me", token).json(name) as JsonObject
        // `username` is the stringified user id until the user sets one; collection URLs accept both.
        val username = me.str("username") ?: me.str("id")
        return DbTrackPreference(
            syncId = syncId.toLong(),
            username = username,
            accountName = me.str("nickname")?.takeIf { it.isNotBlank() } ?: username,
            accountAvatarUrl = (me["avatar"] as? JsonObject)?.str("large"),
            oauth = token,
            prefs = credentials.copy(userId = me.str("id") ?: credentials.userId).encode(),
            refreshing = false,
        )
    }

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        trackerSearchId(query)?.let { id ->
            val response = oauth.api("GET", "$ApiUrl/v0/subjects/${id.encodeURLPathPart()}")
            if (response.statusCode == 404) return emptyList()
            return listOfNotNull((response.json(name) as? JsonObject)?.toSearch(isManga))
        }
        if (query.isBlank()) return emptyList()
        val body = buildJsonObject {
            put("keyword", query.trim())
            put("sort", "match")
            putJsonObject("filter") { putJsonArray("type") { add(if (isManga) 1 else 2) } }
        }.toString()
        val result = oauth.api("POST", "$ApiUrl/v0/search/subjects?limit=20", body).json(name) as? JsonObject
        return (result?.get("data") as? JsonArray).orEmpty().mapNotNull { (it as? JsonObject)?.toSearch(isManga) }
    }

    override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack {
        collection(track)?.let { return track.withCollection(it, isManga) }
        write("POST", track)
        return track
    }

    override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack =
        collection(track)?.let { track.withCollection(it, isManga) } ?: track

    /** PATCH needs an existing collection (404 otherwise), so a missing one is created with POST. */
    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {
        val adjusted = track.autoStatus(isManga)
        val response = write("PATCH", adjusted, requireSuccess = false)
        if (response.statusCode == 404) write("POST", adjusted) else response.requireSuccess(name)
        return adjusted
    }

    // ponytail: the v0 API has no collection delete endpoint; unbinding only removes the local track.
    override suspend fun unbind(track: DbTrack, isManga: Boolean) {}

    private suspend fun collection(track: DbTrack): JsonObject? {
        val username = database.trackPreference(syncId)?.username?.takeIf { it.isNotBlank() }
            ?: throw IllegalStateException("Not logged in to $name")
        val response = oauth.api("GET", "$ApiUrl/v0/users/${username.encodeURLPathPart()}/collections/${mediaId(track)}")
        if (response.statusCode == 404) return null
        return response.json(name) as? JsonObject
    }

    // Upstream sends chapter progress as `ep_status` for books too.
    private suspend fun write(method: String, track: DbTrack, requireSuccess: Boolean = true): HttpResponse {
        val body = buildJsonObject {
            put("type", track.status.toBangumi())
            put("rate", (track.score ?: 0).coerceIn(0, 10))
            put("ep_status", track.lastChapterRead ?: 0)
        }.toString()
        val response = oauth.api(method, "$ApiUrl/v0/users/-/collections/${mediaId(track)}", body)
        return if (requireSuccess) response.requireSuccess(name) else response
    }

    private fun mediaId(track: DbTrack): Long = track.mediaId ?: error("Bangumi track has no media id")

    private fun DbTrack.withCollection(collection: JsonObject, isManga: Boolean): DbTrack = copy(
        status = collection.int("type")?.let { fromBangumi(it, isManga) } ?: status,
        score = collection.int("rate") ?: score,
        lastChapterRead = collection.int("ep_status") ?: lastChapterRead,
        totalChapter = (collection["subject"] as? JsonObject)?.int("eps")?.takeIf { it > 0 } ?: totalChapter,
        trackingUrl = trackingUrl ?: mediaId?.let { "$WebUrl/subject/$it" },
    )

    private fun JsonObject.toSearch(isManga: Boolean): DbTrackSearch? {
        val id = (this["id"] as? JsonPrimitive)?.longOrNull ?: return null
        val name = str("name").orEmpty()
        val nameCn = str("name_cn").orEmpty()
        val summary = str("summary")?.trim().orEmpty()
        return DbTrackSearch(
            syncId = syncId,
            mediaId = id,
            title = nameCn.ifBlank { name },
            trackingUrl = "$WebUrl/subject/$id",
            totalChapter = int("eps")?.takeIf { it > 0 },
            coverUrl = (this["images"] as? JsonObject)?.str("common").orEmpty(),
            summary = if (nameCn.isNotBlank() && name.isNotBlank()) "$name\n$summary".trim() else summary,
            publishingStatus = "",
            publishingType = str("platform").orEmpty(),
            startDate = str("date").orEmpty(),
            score = ((this["rating"] as? JsonObject)?.get("score") as? JsonPrimitive)?.doubleOrNull,
            status = "",
        )
    }

    private companion object {
        const val ApiUrl = "https://api.bgm.tv"
        const val WebUrl = "https://bgm.tv"
        const val TokenPage = "https://next.bgm.tv/demo/access-token"

        fun DbTrackStatus.toBangumi(): Int = when (this) {
            DbTrackStatus.PlanToRead, DbTrackStatus.PlanToWatch -> 1
            DbTrackStatus.Completed -> 2
            DbTrackStatus.Reading, DbTrackStatus.Watching, DbTrackStatus.ReReading, DbTrackStatus.ReWatching -> 3
            DbTrackStatus.OnHold -> 4
            DbTrackStatus.Dropped -> 5
        }

        fun fromBangumi(type: Int, isManga: Boolean): DbTrackStatus? = when (type) {
            1 -> if (isManga) DbTrackStatus.PlanToRead else DbTrackStatus.PlanToWatch
            2 -> DbTrackStatus.Completed
            3 -> if (isManga) DbTrackStatus.Reading else DbTrackStatus.Watching
            4 -> DbTrackStatus.OnHold
            5 -> DbTrackStatus.Dropped
            else -> null
        }
    }
}

private fun DbTrack.autoStatus(isManga: Boolean): DbTrack {
    val progress = lastChapterRead ?: 0
    val total = totalChapter ?: 0
    return when {
        status == DbTrackStatus.Completed -> this
        total > 0 && progress >= total -> copy(status = DbTrackStatus.Completed)
        progress > 0 && (status == DbTrackStatus.PlanToRead || status == DbTrackStatus.PlanToWatch) ->
            copy(status = if (isManga) DbTrackStatus.Reading else DbTrackStatus.Watching)
        else -> this
    }
}

private fun JsonObject.str(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull

private fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines HikkaTrackerService, checkRefresh, findLibraryItem, statusList, scoreValue, displayScore, fetchGeneralData, fetchUserData, authorizeUrl, login and 20 further declarations.

The source describes its contract as:

Hikka (api.hikka.io): third-party client flow with a user-registered client. The browser approves hikka.io/oauth?reference=\<client\>, the callback carries the request reference, and POST /auth/token exchanges it for a secret sent as the auth header. No refresh tokens.

Cross-chapter imports used by this file: DbTrack, DbTrackPreference, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

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 eu.friedcutlet.yokan.util.nowMillis
import io.ktor.http.encodeURLParameter
import io.ktor.http.encodeURLPathPart
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put

/**
 * Hikka (api.hikka.io): third-party client flow with a user-registered client. The browser approves
 * `hikka.io/oauth?reference=<client>`, the callback carries the request `reference`, and
 * `POST /auth/token` exchanges it for a `secret` sent as the `auth` header. No refresh tokens.
 */
class HikkaTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "Hikka"

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = if (score == 0) "-" else "$score/10"

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> = emptyList()

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()

    override val loginFields: List<TrackerLoginField> =
        listOf(TrackerLoginField.ClientId, TrackerLoginField.ClientSecret, TrackerLoginField.AuthorizationCode)

    override suspend fun authorizeUrl(values: Map<TrackerLoginField, String>): String =
        "$Site/oauth?reference=${values.required(TrackerLoginField.ClientId).encodeURLParameter()}" +
            "&scope=${Scope.encodeURLParameter()}"

    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        val clientId = values.required(TrackerLoginField.ClientId)
        val secret = values.required(TrackerLoginField.ClientSecret)
        val reference = callbackParameter(values.required(TrackerLoginField.AuthorizationCode), "reference")
        val body = buildJsonObject {
            put("request_reference", reference)
            put("client_secret", secret)
        }.toString()
        val token = http.request(HttpRequest("$Api/auth/token", "POST", body = body)).json(name).jsonObject
        val session = token.string("secret") ?: throw IllegalStateException("Hikka returned no session secret")
        val user = http.request(HttpRequest("$Api/user/me", headers = mapOf("auth" to session))).json(name).jsonObject
        return DbTrackPreference(
            syncId = syncId.toLong(),
            username = user.string("username"),
            accountName = user.string("username"),
            oauth = session,
            prefs = TrackerCredentials(
                clientId = clientId,
                clientSecret = secret,
                expiresAt = token.long("expiration")?.let { it * 1000 },
                userId = user.string("reference"),
            ).encode(),
            refreshing = false,
        )
    }

    override suspend fun accountProfile(): TrackerAccountProfile? {
        val user = request("$Api/user/me").json(name).jsonObject
        return TrackerAccountProfile(name = user.string("username"), avatarUrl = user.string("avatar"))
    }

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        val kind = kind(isManga)
        trackerSearchId(query)?.let { slug ->
            val response = request("$Api/$kind/${slug.encodeURLPathPart()}")
            if (response.statusCode == 404) return emptyList()
            return listOf(response.json(name).jsonObject.toSearch(kind))
        }
        if (query.isBlank()) return emptyList()
        val body = buildJsonObject {
            put("query", query.trim())
            put("sort", buildJsonArray { add(JsonPrimitive("score:desc")); add(JsonPrimitive("scored_by:desc")) })
        }.toString()
        val list = request("$Api/$kind?page=1&size=50", "POST", body).json(name).jsonObject["list"] as? JsonArray
        return list.orEmpty().mapNotNull { (it as? JsonObject)?.toSearch(kind) }
    }

    override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack {
        val remote = getEntry(track, isManga) ?: return update(track, isManga)
        return track.withRemote(remote, isManga)
    }

    override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack =
        getEntry(track, isManga)?.let { track.withRemote(it, isManga) } ?: track

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {
        val progress = track.lastChapterRead ?: 0
        val total = track.totalChapter ?: 0
        val status = when {
            track.status == DbTrackStatus.Completed -> track.status
            total > 0 && progress >= total -> DbTrackStatus.Completed
            progress > 0 && track.status == DbTrackStatus.PlanToRead -> DbTrackStatus.Reading
            progress > 0 && track.status == DbTrackStatus.PlanToWatch -> DbTrackStatus.Watching
            else -> track.status
        }
        val repeating = status == DbTrackStatus.ReReading || status == DbTrackStatus.ReWatching
        // Hikka has no "repeating" status: keep the remote repeat counter and mark at least one repeat.
        val repeats = (getEntry(track, isManga)?.int(repeatsKey(isManga)) ?: 0).let { if (repeating && it == 0) 1 else it }
        val body = buildJsonObject {
            put("note", "")
            put(progressKey(isManga), progress)
            if (isManga) put("volumes", 0)
            put(repeatsKey(isManga), repeats)
            put("score", (track.score ?: 0).coerceIn(0, 10))
            put("status", status.toHikka(isManga))
            put("start_date", track.startedReadingDate?.takeIf { it > 0 }?.let { JsonPrimitive(it / 1000) } ?: JsonNull)
            put("end_date", track.finishedReadingDate?.takeIf { it > 0 }?.let { JsonPrimitive(it / 1000) } ?: JsonNull)
        }.toString()
        val remote = request(entryUrl(track, isManga), "PUT", body).json(name).jsonObject
        return track.withRemote(remote, isManga)
    }

    override suspend fun unbind(track: DbTrack, isManga: Boolean) {
        val response = request(entryUrl(track, isManga), "DELETE")
        if (response.statusCode != 404) response.requireSuccess(name)
    }

    private suspend fun getEntry(track: DbTrack, isManga: Boolean): JsonObject? {
        val response = request(entryUrl(track, isManga))
        if (response.statusCode == 404) return null
        return response.json(name).jsonObject
    }

    private fun entryUrl(track: DbTrack, isManga: Boolean): String {
        val slug = track.trackingUrl?.trimEnd('/')?.substringAfterLast('/')?.takeIf { it.isNotBlank() }
            ?: throw IllegalStateException("Hikka entry has no tracking URL")
        return if (isManga) "$Api/read/manga/${slug.encodeURLPathPart()}" else "$Api/watch/${slug.encodeURLPathPart()}"
    }

    private fun DbTrack.withRemote(remote: JsonObject, isManga: Boolean): DbTrack {
        val content = (remote["manga"] ?: remote["anime"] ?: remote["content"]) as? JsonObject
        return copy(
            status = remote.string("status")?.let { fromHikka(it, isManga) } ?: status,
            lastChapterRead = remote.int(progressKey(isManga)) ?: lastChapterRead,
            score = remote.int("score") ?: score,
            startedReadingDate = remote.long("start_date")?.let { it * 1000 },
            finishedReadingDate = remote.long("end_date")?.let { it * 1000 },
            totalChapter = content?.let { total(it) } ?: totalChapter,
        )
    }

    private fun JsonObject.toSearch(kind: String): DbTrackSearch {
        val slug = string("slug").orEmpty()
        return DbTrackSearch(
            syncId = syncId,
            mediaId = slug.toLongOrNull(),
            title = string("title_ua") ?: string("title_en") ?: string("title_ja") ?: string("title_original"),
            trackingUrl = "$Site/$kind/$slug",
            totalChapter = total(this),
            coverUrl = string("image").orEmpty(),
            summary = string("synopsis_ua") ?: string("synopsis_en") ?: "",
            publishingStatus = string("status").orEmpty(),
            publishingType = string("media_type").orEmpty(),
            startDate = int("year")?.toString().orEmpty(),
            score = (this["score"] as? JsonPrimitive)?.doubleOrNull,
            status = "",
        )
    }

    private fun total(obj: JsonObject): Int? = obj.int("chapters") ?: obj.int("episodes_total")

    /** Authenticated request; a passed session expiry fails like a rejected session (re-login needed). */
    private suspend fun request(url: String, method: String = "GET", body: String? = null): HttpResponse {
        val preference = database.trackPreference(syncId)
        val session = preference?.oauth?.takeIf { it.isNotBlank() } ?: throw IllegalStateException("Not logged in to $name")
        val expiresAt = preference.credentials().expiresAt
        if (expiresAt != null && expiresAt <= nowMillis()) throw TrackerHttpException(name, 401, "Session expired; sign in again")
        val response = http.request(HttpRequest(url, method, mapOf("auth" to session), body))
        if (response.statusCode == 401 || response.statusCode == 403) throw TrackerHttpException(name, response.statusCode, response.body)
        return response
    }

    private companion object {
        const val Api = "https://api.hikka.io"
        const val Site = "https://hikka.io"
        const val Scope = "readlist,watchlist,read:user-details"

        fun kind(isManga: Boolean) = if (isManga) "manga" else "anime"
        fun progressKey(isManga: Boolean) = if (isManga) "chapters" else "episodes"
        fun repeatsKey(isManga: Boolean) = if (isManga) "rereads" else "rewatches"

        fun DbTrackStatus.toHikka(isManga: Boolean): String = when (this) {
            DbTrackStatus.Completed -> "completed"
            DbTrackStatus.OnHold -> "on_hold"
            DbTrackStatus.Dropped -> "dropped"
            DbTrackStatus.PlanToRead, DbTrackStatus.PlanToWatch -> "planned"
            else -> if (isManga) "reading" else "watching"
        }

        fun fromHikka(status: String, isManga: Boolean): DbTrackStatus = when (status) {
            "completed" -> DbTrackStatus.Completed
            "on_hold" -> DbTrackStatus.OnHold
            "dropped" -> DbTrackStatus.Dropped
            "planned" -> if (isManga) DbTrackStatus.PlanToRead else DbTrackStatus.PlanToWatch
            else -> if (isManga) DbTrackStatus.Reading else DbTrackStatus.Watching
        }

        fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull
        fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull
        fun JsonObject.long(key: String): Long? = (this[key] as? JsonPrimitive)?.longOrNull
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines JellyfinTrackerService, login, authHeaders, itemKey, userId, itemUrl, fetch, push, episodes, JsonObject.played and 1 further declarations.

The source describes its contract as:

Jellyfin (Animetail JellyfinApi). Signs in with username/password for an access token (X-Emby-Token). Item keys are item ids; a series or season counts its leading run of played episodes (season: episode IndexNumber, whole series: position), anything else (movie) is 1 when played.

Cross-chapter imports used by this file: DbTrackPreference, DbTrackSearch, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put

/**
 * Jellyfin (Animetail `JellyfinApi`). Signs in with username/password for an access token (`X-Emby-Token`).
 * Item keys are item ids; a series or season counts its leading run of played episodes (season: episode
 * `IndexNumber`, whole series: position), anything else (movie) is 1 when played.
 */
class JellyfinTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) :
    ServerTrackerService(syncId, database, http) {
    override val name: String = "Jellyfin"
    override val sourceKeywords = listOf("jellyfin")
    override val forManga = false

    override val loginFields = listOf(TrackerLoginField.ServerUrl, TrackerLoginField.Username, TrackerLoginField.Password)

    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        val server = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl))
        val body = buildJsonObject {
            put("Username", values.required(TrackerLoginField.Username))
            put("Pw", values[TrackerLoginField.Password].orEmpty())
        }
        val auth = http.request(
            HttpRequest(
                "$server/Users/AuthenticateByName",
                method = "POST",
                headers = mapOf("X-Emby-Authorization" to CLIENT_AUTHORIZATION),
                body = body.toString(),
            ),
        ).json(name).jsonObject
        val user = auth["User"]?.jsonObject
        val token = auth["AccessToken"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }
        val userId = user?.get("Id")?.jsonPrimitive?.contentOrNull
        if (token == null || userId == null) throw IllegalStateException("Jellyfin did not return a session")
        return loginPreference(
            username = user["Name"]?.jsonPrimitive?.contentOrNull,
            oauth = token,
            credentials = TrackerCredentials(serverUrl = server, userId = userId),
        )
    }

    override fun authHeaders(preference: DbTrackPreference): Map<String, String> =
        mapOf("X-Emby-Token" to preference.oauth.orEmpty())

    override fun itemKey(link: String): String? =
        (segmentAfter(link, "Items") ?: linkParameter(link, "Id") ?: linkParameter(link, "seriesId") ?: link.trim())
            .takeIf { id -> id.isNotEmpty() && id.all { it.isLetterOrDigit() || it == '-' } }

    private fun userId(): String = preference()?.credentials()?.userId.orEmpty()

    // Current (10.9+) routes; the `/Users/{userId}/Items|PlayedItems` forms are deprecated upstream.
    private fun itemUrl(key: String): String = "${server()}/Items/$key?userId=${userId()}"

    override suspend fun fetch(key: String): DbTrackSearch {
        val url = "${server()}/Items/$key"
        val item = getJson(itemUrl(key)).jsonObject
        val episodes = episodes(item, key)
        val total: Int
        val progress: Int
        if (episodes == null) {
            total = 1
            progress = if (item.played()) 1 else 0
        } else {
            total = episodes.lastOrNull()?.first ?: 0
            val firstUnplayed = episodes.indexOfFirst { !it.second.played() }
            progress = when (firstUnplayed) {
                -1 -> total
                0 -> 0
                else -> episodes[firstUnplayed - 1].first
            }
        }
        return DbTrackSearch(
            syncId = syncId,
            title = item["Name"]?.jsonPrimitive?.contentOrNull,
            trackingUrl = url,
            coverUrl = "${server()}/Items/$key/Images/Primary",
            summary = item["Overview"]?.jsonPrimitive?.contentOrNull.orEmpty(),
            totalChapter = total,
            lastChapterRead = progress,
            status = remoteStatus(unread = progress == 0, completed = total > 0 && progress >= total),
        )
    }

    /** Marks every unplayed episode numbered up to [progress] (or the movie) played. */
    override suspend fun push(key: String, progress: Int) {
        val item = getJson(itemUrl(key)).jsonObject
        val ids = episodes(item, key)?.filter { (number, episode) -> number <= progress && !episode.played() }?.map { it.second.id() }
            ?: listOf(key).takeIf { progress > 0 && !item.played() }.orEmpty()
        for (id in ids) send("${server()}/UserPlayedItems/$id?userId=${userId()}", method = "POST").requireSuccess(name)
    }

    /** `(episode number, episode)` in order for a series or season; null for a single playable item. */
    private suspend fun episodes(item: JsonObject, key: String): List<Pair<Int, JsonObject>>? {
        val userId = userId()
        val url = when (item["Type"]?.jsonPrimitive?.contentOrNull) {
            "Series" -> "${server()}/Shows/$key/Episodes?userId=$userId"
            "Season" -> "${server()}/Shows/${item["SeriesId"]?.jsonPrimitive?.contentOrNull}/Episodes?userId=$userId&seasonId=$key"
            else -> return null
        }
        val season = item["Type"]?.jsonPrimitive?.contentOrNull == "Season"
        val list = (getJson(url).jsonObject["Items"] as? JsonArray).orEmpty().map { it.jsonObject }
        return list.mapIndexed { i, episode ->
            ((if (season) episode["IndexNumber"]?.jsonPrimitive?.intOrNull else null) ?: (i + 1)) to episode
        }
    }

    private fun JsonObject.played(): Boolean =
        (this["UserData"] as? JsonObject)?.get("Played")?.jsonPrimitive?.booleanOrNull == true

    private fun JsonObject.id(): String = this["Id"]?.jsonPrimitive?.contentOrNull.orEmpty()

    private companion object {
        const val CLIENT_AUTHORIZATION = "MediaBrowser Client=\"Yokan\", Device=\"Yokan\", DeviceId=\"yokan\", Version=\"1\""
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines KavitaTrackerService, login, authenticate, reauthenticate, JsonObject.token, authHeaders, itemKey, fetch, totalChapters, JsonObject.chapterNumber and 1 further declarations.

The source describes its contract as:

Kavita (Animetail KavitaApi). The API key is exchanged for a JWT via the plugin endpoint and renewed the same way on a 401. Item keys are numeric series ids; progress is the latest read chapter number.

Cross-chapter imports used by this file: DbTrackPreference, DbTrackSearch, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import io.ktor.http.encodeURLParameter
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

/**
 * Kavita (Animetail `KavitaApi`). The API key is exchanged for a JWT via the plugin endpoint and renewed the
 * same way on a 401. Item keys are numeric series ids; progress is the latest read chapter number.
 */
class KavitaTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) :
    ServerTrackerService(syncId, database, http) {
    override val name: String = "Kavita"
    override val sourceKeywords = listOf("kavita")
    override val forManga = true

    override val loginFields = listOf(TrackerLoginField.ServerUrl, TrackerLoginField.ApiKey)

    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        // A pasted `…/api` or OPDS URL still names the server.
        val typed = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl))
        val server = typed.substringBefore("://") + "://" + "${typed.substringAfter("://")}/".substringBefore("/api/").trimEnd('/')
        val apiKey = values.required(TrackerLoginField.ApiKey)
        val user = authenticate(server, apiKey)
        return loginPreference(
            username = user["username"]?.jsonPrimitive?.contentOrNull,
            oauth = user.token(),
            credentials = TrackerCredentials(serverUrl = server, apiKey = apiKey),
        )
    }

    private suspend fun authenticate(server: String, apiKey: String): JsonObject =
        http.request(
            HttpRequest(
                "$server/api/Plugin/authenticate?apiKey=${apiKey.encodeURLParameter()}&pluginName=Yokan",
                method = "POST",
                body = "{}",
            ),
        ).json(name).jsonObject

    override suspend fun reauthenticate(preference: DbTrackPreference): DbTrackPreference {
        val credentials = preference.credentials()
        val token = authenticate(credentials.serverUrl.orEmpty(), credentials.apiKey.orEmpty()).token()
        return database.upsertTrackPreference(preference.copy(oauth = token))
    }

    private fun JsonObject.token(): String =
        this["token"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }
            ?: throw IllegalStateException("Kavita did not return a session token")

    override fun authHeaders(preference: DbTrackPreference): Map<String, String> =
        mapOf("Authorization" to "Bearer ${preference.oauth}")

    override fun itemKey(link: String): String? =
        (segmentAfter(link, "series") ?: linkParameter(link, "seriesId") ?: link.trim())
            .takeIf { id -> id.isNotEmpty() && id.all { it.isDigit() } }

    override suspend fun fetch(key: String): DbTrackSearch {
        val api = "${server()}/api"
        val url = "$api/Series/$key"
        val series = getJson(url).jsonObject
        val pages = series["pages"]?.jsonPrimitive?.intOrNull ?: 0
        val pagesRead = series["pagesRead"]?.jsonPrimitive?.intOrNull ?: 0
        val volumes = getJson("$api/Series/volumes?seriesId=$key") as? JsonArray ?: JsonArray(emptyList())
        val latest = send("$api/Tachiyomi/latest-chapter?seriesId=$key").requireSuccess(name)
        val lastRead = if (latest.statusCode == 204 || latest.body.isBlank()) 0.0
        else trackerJson.parseToJsonElement(latest.body).jsonObject.chapterNumber()
        return DbTrackSearch(
            syncId = syncId,
            mediaId = key.toLong(),
            title = series["name"]?.jsonPrimitive?.contentOrNull,
            trackingUrl = url,
            totalChapter = totalChapters(volumes),
            lastChapterRead = lastRead.toInt(),
            status = remoteStatus(unread = pagesRead == 0, completed = pagesRead == pages),
        )
    }

    /** Upstream rule: the highest chapter number, or the count of chapterless (single-file) volumes if larger. */
    private fun totalChapters(volumes: JsonArray): Int {
        var volumeCount = 0
        var maxChapter = 0
        for (volume in volumes) {
            val chapters = (volume.jsonObject["chapters"] as? JsonArray).orEmpty()
            if (chapters.isEmpty()) continue
            val highest = chapters.maxOf { it.jsonObject.chapterNumber() }
            if (highest == 0.0) volumeCount++ else if (highest > maxChapter) maxChapter = highest.toInt()
        }
        return maxOf(maxChapter, volumeCount)
    }

    /** Kavita chapter `number` is a string (`"12"`, `"12,5"`); negatives mark specials/loose volumes. */
    private fun JsonObject.chapterNumber(): Double =
        (this["number"]?.jsonPrimitive?.contentOrNull?.replace(',', '.')?.toDoubleOrNull() ?: 0.0).coerceAtLeast(0.0)

    override suspend fun push(key: String, progress: Int) {
        send(
            "${server()}/api/Tachiyomi/mark-chapter-until-as-read?seriesId=$key&chapterNumber=$progress",
            method = "POST",
            body = "{}",
        ).requireSuccess(name)
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines KitsuTrackerService, checkRefresh, findLibraryItem, update, statusList, search, fetchGeneralData, fetchUserData, scoreValue, displayScore and 3 further declarations.

Cross-chapter imports used by this file: DbTrack, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.database.DbTrack
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.HttpService
import io.ktor.http.encodeURLParameter
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull

class KitsuTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "Kitsu"

    private val baseUrl = "https://kitsu.io/api/edge"

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack =
        database.upsertTrack(track.copy(syncId = syncId))

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        if (query.isBlank()) return emptyList()
        val kind = if (isManga) "manga" else "anime"
        trackerSearchId(query)?.let { id ->
            if (id.toLongOrNull() == null) return emptyList()
            val payload = catchingNonCancellation {
                http.request(HttpRequest("$baseUrl/$kind/$id", headers = mapOf("Accept" to "application/vnd.api+json"))).json(name) as? JsonObject
            }.getOrNull()
            return listOfNotNull((payload?.get("data") as? JsonObject)?.toTrackSearch(isManga))
        }
        val url = "$baseUrl/$kind?filter[text]=${query.encodeURLParameter()}&page[limit]=20"
        return fetchKitsu(url, isManga)
    }

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> {
        val kind = if (isManga) "manga" else "anime"
        // Kitsu's JSON:API sorts by camelCase attribute names.
        val sortParam = when (rankingType.lowercase()) {
            "trending" -> "-userCount"
            "popular" -> "-favoritesCount"
            "top", "best" -> "-averageRating"
            "latest" -> "-updatedAt"
            else -> "-userCount"
        }
        val url = "$baseUrl/$kind?sort=$sortParam&page[limit]=25"
        return fetchKitsu(url, isManga)
    }

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> {
        // Kitsu's authenticated library entries require a userId discovery + include=... call.
        // Without the OAuth client this returns empty for now.
        return emptyList()
    }

    override fun scoreValue(): Pair<Int, Int> = 0 to 100

    override fun displayScore(score: Int): String = "$score/100"

    private suspend fun fetchKitsu(url: String, isManga: Boolean): List<DbTrackSearch> {
        val payload = catchingNonCancellation {
            http.request(HttpRequest(url, headers = mapOf("Accept" to "application/vnd.api+json"))).json(name) as? JsonObject
        }.getOrNull() ?: return emptyList()
        val data = payload["data"] as? JsonArray ?: return emptyList()
        return data.mapNotNull { (it as? JsonObject)?.toTrackSearch(isManga) }
    }

    private fun JsonObject.toTrackSearch(isManga: Boolean): DbTrackSearch? {
        val mediaId = (this["id"] as? JsonPrimitive)?.contentOrNull?.toLongOrNull() ?: return null
        val attributes = this["attributes"] as? JsonObject ?: return null
        val title = (attributes["canonicalTitle"] as? JsonPrimitive)?.contentOrNull
            ?: ((attributes["titles"] as? JsonObject)?.values?.firstOrNull() as? JsonPrimitive)?.contentOrNull
            ?: return null
        val synopsis = (attributes["synopsis"] as? JsonPrimitive)?.contentOrNull.orEmpty()
        val poster = ((attributes["posterImage"] as? JsonObject)
            ?.let { (it["medium"] ?: it["small"] ?: it["original"]) as? JsonPrimitive }
            ?.contentOrNull)
            .orEmpty()
        val total = ((if (isManga) attributes["chapterCount"] else attributes["episodeCount"]) as? JsonPrimitive)?.intOrNull
        val rating = (attributes["averageRating"] as? JsonPrimitive)?.contentOrNull?.toDoubleOrNull()
            ?: (attributes["averageRating"] as? JsonPrimitive)?.doubleOrNull
        val status = (attributes["status"] as? JsonPrimitive)?.contentOrNull?.lowercase().orEmpty()
        val subtype = (attributes["subtype"] as? JsonPrimitive)?.contentOrNull.orEmpty()
        val slug = (attributes["slug"] as? JsonPrimitive)?.contentOrNull.orEmpty()
        return DbTrackSearch(
            mediaId = mediaId,
            syncId = syncId,
            title = title,
            totalChapter = total,
            score = rating,
            status = status,
            trackingUrl = if (slug.isNotBlank()) "https://kitsu.io/${if (isManga) "manga" else "anime"}/$slug" else "",
            coverUrl = poster,
            summary = synopsis,
            publishingStatus = status,
            publishingType = subtype,
            startDate = (attributes["startDate"] as? JsonPrimitive)?.contentOrNull.orEmpty(),
        )
    }

    override suspend fun accountProfile(): TrackerAccountProfile? {
        val token = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() } ?: return null
        val obj = catchingNonCancellation {
            http.request(
                HttpRequest(
                    url = "https://kitsu.io/api/edge/users?filter[self]=true",
                    headers = mapOf(
                        "Authorization" to "Bearer $token",
                        "Accept" to "application/vnd.api+json",
                    ),
                ),
            ).json(name) as? JsonObject
        }.getOrNull() ?: return null
        val dataArray = obj["data"] as? JsonArray ?: return null
        val first = dataArray.firstOrNull() as? JsonObject ?: return null
        return kitsuAccount(first).toProfile()
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines KomgaTrackerService, login, authHeaders, itemKey, fetch, push, progressUrl, JsonObject.int, JsonObject.double.

The source describes its contract as:

Komga (Animetail KomgaApi). Item keys are series/\<id\> or readlists/\<id\>; progress is the series' last continuously read book numberSort (read lists: book index), via the read-progress/tachiyomi API.

Cross-chapter imports used by this file: DbTrackPreference, DbTrackSearch, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.put

/**
 * Komga (Animetail `KomgaApi`). Item keys are `series/<id>` or `readlists/<id>`; progress is the series'
 * last continuously read book `numberSort` (read lists: book index), via the `read-progress/tachiyomi` API.
 */
class KomgaTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) :
    ServerTrackerService(syncId, database, http) {
    override val name: String = "Komga"
    override val sourceKeywords = listOf("komga")
    override val forManga = true

    override val loginFields = listOf(
        TrackerLoginField.ServerUrl,
        TrackerLoginField.Username,
        TrackerLoginField.Password,
        TrackerLoginField.ApiKey,
    )

    /** An API key (`X-API-Key`) when entered, else HTTP Basic with username and password. */
    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        val server = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl))
        val apiKey = values.optional(TrackerLoginField.ApiKey)
        val credentials = if (apiKey != null) {
            TrackerCredentials(serverUrl = server, apiKey = apiKey)
        } else {
            TrackerCredentials(
                serverUrl = server,
                apiKey = basicAuth(values.required(TrackerLoginField.Username), values.required(TrackerLoginField.Password)),
            )
        }
        val oauth = apiKey ?: BASIC
        val probe = loginPreference(null, oauth, credentials)
        val me = http.request(HttpRequest("$server/api/v2/users/me", headers = authHeaders(probe))).json(name).jsonObject
        return probe.copy(username = me["email"]?.jsonPrimitive?.contentOrNull)
    }

    override fun authHeaders(preference: DbTrackPreference): Map<String, String> {
        val secret = preference.credentials().apiKey.orEmpty()
        return if (preference.oauth == BASIC) mapOf("Authorization" to secret) else mapOf("X-API-Key" to secret)
    }

    override fun itemKey(link: String): String? =
        segmentAfter(link, "readlists")?.let { "readlists/$it" }
            ?: segmentAfter(link, "series")?.let { "series/$it" }
            ?: link.trim().takeIf { id -> id.isNotEmpty() && id.all { it.isLetterOrDigit() } }?.let { "series/$it" }

    override suspend fun fetch(key: String): DbTrackSearch {
        val url = "${server()}/api/v1/$key"
        val item = getJson(url).jsonObject
        val readList = key.startsWith("readlists/")
        val progress = getJson(progressUrl(key)).jsonObject
        val booksCount = progress.int("booksCount")
        val metadata = item["metadata"] as? JsonObject
        return DbTrackSearch(
            syncId = syncId,
            title = (if (readList) item["name"] else metadata?.get("title"))?.jsonPrimitive?.contentOrNull,
            trackingUrl = url,
            coverUrl = "$url/thumbnail",
            summary = metadata?.get("summary")?.jsonPrimitive?.contentOrNull.orEmpty(),
            publishingStatus = metadata?.get("status")?.jsonPrimitive?.contentOrNull.orEmpty(),
            totalChapter = if (readList) booksCount else progress.double("maxNumberSort").toInt(),
            lastChapterRead = (if (readList) progress.double("lastReadContinuousIndex") else progress.double("lastReadContinuousNumberSort")).toInt(),
            status = remoteStatus(
                unread = booksCount == progress.int("booksUnreadCount"),
                completed = booksCount == progress.int("booksReadCount"),
            ),
        )
    }

    override suspend fun push(key: String, progress: Int) {
        val body = buildJsonObject {
            if (key.startsWith("readlists/")) put("lastBookRead", progress) else put("lastBookNumberSortRead", progress.toDouble())
        }
        send(progressUrl(key), "PUT", body.toString()).requireSuccess(name)
    }

    /** Series read progress lives on the v2 API, read lists stay on v1. */
    private fun progressUrl(key: String): String =
        "${server()}/api/${if (key.startsWith("series/")) "v2" else "v1"}/$key/read-progress/tachiyomi"

    private fun JsonObject.int(field: String): Int = this[field]?.jsonPrimitive?.intOrNull ?: 0
    private fun JsonObject.double(field: String): Double = this[field]?.jsonPrimitive?.doubleOrNull ?: 0.0

    private companion object {
        const val BASIC = "basic"
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MalTrackerService, checkRefresh, findLibraryItem, update, statusList, search, fetchGeneralData, fetchUserData, scoreValue, displayScore and 4 further declarations.

The source describes its contract as:

MyAnimeList tracker backed by the public Jikan REST mirror so search/popular/trending work without needing OAuth credentials. Authenticated user-list calls go through MAL's official API when an OAuth token is configured.

Cross-chapter imports used by this file: DbTrack, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.database.DbTrack
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.HttpService
import io.ktor.http.encodeURLParameter
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull

/**
 * MyAnimeList tracker backed by the public Jikan REST mirror so search/popular/trending work
 * without needing OAuth credentials. Authenticated user-list calls go through MAL's official API
 * when an OAuth token is configured.
 */
class MalTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "MyAnimeList"

    private val jikanBase = "https://api.jikan.moe/v4"
    private val malBase = "https://api.myanimelist.net/v2"

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack =
        database.upsertTrack(track.copy(syncId = syncId))

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        if (query.isBlank()) return emptyList()
        val kind = if (isManga) "manga" else "anime"
        trackerSearchId(query)?.let { id ->
            if (id.toIntOrNull() == null) return emptyList()
            val pref = database.trackPreference(syncId)
            val token = pref?.oauth?.takeIf { it.isNotBlank() }
            val clientId = pref?.credentials()?.clientId?.takeIf { it.isNotBlank() }
            val authHeader = when {
                token != null -> "Authorization" to "Bearer $token"
                clientId != null -> "X-MAL-CLIENT-ID" to clientId
                else -> null
            }
            if (authHeader == null) {
                // No MAL credentials: Jikan mirrors GET /{kind}/{id} as { "data": {...} }.
                val payload = catchingNonCancellation {
                    http.request(HttpRequest("$jikanBase/$kind/$id", headers = mapOf("Accept" to "application/json"))).json(name) as? JsonObject
                }.getOrNull()
                return listOfNotNull((payload?.get("data") as? JsonObject)?.toJikanTrackSearch(isManga))
            }
            val total = if (isManga) "num_chapters" else "num_episodes"
            val item = catchingNonCancellation {
                http.request(
                    HttpRequest(
                        "$malBase/$kind/$id?fields=id,title,main_picture,synopsis,$total,status,mean,media_type,start_date",
                        headers = mapOf(authHeader, "Accept" to "application/json"),
                    ),
                ).json(name) as? JsonObject
            }.getOrNull()
            return listOfNotNull(item?.toTrackSearch(isManga))
        }
        val response = catchingNonCancellation {
            http.request(HttpRequest("$jikanBase/$kind?q=${query.encodeURLParameter()}&limit=20", headers = mapOf("Accept" to "application/json")))
        }.getOrNull() ?: return emptyList()
        return parseJikan(response.body, isManga)
    }

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> {
        val kind = if (isManga) "manga" else "anime"
        // Jikan /v4/{anime,manga} search params: status= gates airing/upcoming
        // (anime) and publishing (manga); type= narrows manga to manhwa/manhua.
        val sortParam = when (rankingType.lowercase()) {
            "trending", "airing" ->
                if (isManga) "?status=publishing&order_by=popularity&sort=asc&limit=25"
                else "?status=airing&order_by=popularity&sort=asc&limit=25"
            "popular", "bypopularity" -> "?order_by=members&sort=desc&limit=25"
            "top", "manga" -> "?order_by=score&sort=desc&limit=25"
            "upcoming" -> "?status=upcoming&order_by=popularity&sort=asc&limit=25"
            "manhwa" -> "?type=manhwa&order_by=score&sort=desc&limit=25"
            "manhua" -> "?type=manhua&order_by=score&sort=desc&limit=25"
            else -> "?order_by=popularity&sort=asc&limit=25"
        }
        val response = catchingNonCancellation {
            http.request(HttpRequest("$jikanBase/$kind$sortParam", headers = mapOf("Accept" to "application/json")))
        }.getOrNull() ?: return emptyList()
        return parseJikan(response.body, isManga)
    }

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> {
        val token = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() } ?: return emptyList()
        val kind = if (isManga) "mangalist" else "animelist"
        val fields = if (isManga) {
            "node{id,title,main_picture,num_chapters,status,start_date,synopsis,mean},list_status{score,num_chapters_read,status}"
        } else {
            "node{id,title,main_picture,num_episodes,status,start_date,synopsis,mean},list_status{score,num_episodes_watched,status}"
        }
        val payload = catchingNonCancellation {
            http.request(
                HttpRequest(
                    "$malBase/users/@me/$kind?fields=$fields&limit=100",
                    headers = mapOf("Authorization" to "Bearer $token", "Accept" to "application/json"),
                ),
            ).json(name) as? JsonObject
        }.getOrNull() ?: return emptyList()
        val data = payload["data"] as? JsonArray ?: return emptyList()
        return data.mapNotNull { entry ->
            val obj = entry as? JsonObject ?: return@mapNotNull null
            val node = obj["node"] as? JsonObject ?: return@mapNotNull null
            val list = obj["list_status"] as? JsonObject
            val base = node.toTrackSearch(isManga) ?: return@mapNotNull null
            base.copy(
                score = (list?.get("score") as? kotlinx.serialization.json.JsonPrimitive)?.doubleOrNull ?: base.score,
                lastChapterRead = (list?.get(if (isManga) "num_chapters_read" else "num_episodes_watched") as? kotlinx.serialization.json.JsonPrimitive)?.intOrNull,
                status = (list?.get("status") as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty(),
            )
        }
    }

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = "$score/10"

    private fun parseJikan(body: String, isManga: Boolean): List<DbTrackSearch> {
        val payload = runCatching { trackerJson.parseToJsonElement(body) as? JsonObject }.getOrNull() ?: return emptyList()
        val items = payload["data"] as? JsonArray ?: return emptyList()
        return items.mapNotNull { (it as? JsonObject)?.toJikanTrackSearch(isManga) }
    }

    private fun JsonObject.toJikanTrackSearch(isManga: Boolean): DbTrackSearch? {
        val mediaId = (this["mal_id"] as? kotlinx.serialization.json.JsonPrimitive)?.intOrNull ?: return null
        val title = (this["title"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty()
        val cover = ((this["images"] as? JsonObject)?.get("jpg") as? JsonObject)
            ?.let { (it["image_url"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull }
            .orEmpty()
        val synopsis = (this["synopsis"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty()
        val statusValue = (this["status"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull?.lowercase().orEmpty()
        val format = (this["type"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty()
        val total = ((if (isManga) this["chapters"] else this["episodes"]) as? kotlinx.serialization.json.JsonPrimitive)?.intOrNull
        val score = (this["score"] as? kotlinx.serialization.json.JsonPrimitive)?.doubleOrNull
        val url = (this["url"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty()
        return DbTrackSearch(
            mediaId = mediaId.toLong(),
            syncId = syncId,
            title = title,
            totalChapter = total,
            score = score,
            status = statusValue,
            trackingUrl = url,
            coverUrl = cover,
            summary = synopsis,
            publishingStatus = statusValue,
            publishingType = format,
        )
    }

    private fun JsonObject.toTrackSearch(isManga: Boolean): DbTrackSearch? {
        val mediaId = (this["id"] as? kotlinx.serialization.json.JsonPrimitive)?.intOrNull ?: return null
        val title = (this["title"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty()
        val cover = ((this["main_picture"] as? JsonObject)
            ?.let { (it["large"] ?: it["medium"]) as? kotlinx.serialization.json.JsonPrimitive }
            ?.contentOrNull)
            .orEmpty()
        val synopsis = (this["synopsis"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty()
        val total = ((if (isManga) this["num_chapters"] else this["num_episodes"]) as? kotlinx.serialization.json.JsonPrimitive)?.intOrNull
        val score = (this["mean"] as? kotlinx.serialization.json.JsonPrimitive)?.doubleOrNull
        val publishing = (this["status"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull?.lowercase().orEmpty()
        return DbTrackSearch(
            mediaId = mediaId.toLong(),
            syncId = syncId,
            title = title,
            totalChapter = total,
            score = score,
            status = publishing,
            trackingUrl = "https://myanimelist.net/${if (isManga) "manga" else "anime"}/$mediaId",
            coverUrl = cover,
            summary = synopsis,
            publishingStatus = publishing,
            publishingType = "",
            startDate = (this["start_date"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty(),
        )
    }

    override suspend fun accountProfile(): TrackerAccountProfile? {
        val token = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() } ?: return null
        val obj = catchingNonCancellation {
            http.request(
                HttpRequest(
                    url = "$malBase/users/@me",
                    headers = mapOf(
                        "Authorization" to "Bearer $token",
                        "Accept" to "application/json",
                    ),
                ),
            ).json(name) as? JsonObject
        }.getOrNull() ?: return null
        return malAccount(obj).toProfile()
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MangaBakaTrackerService, checkRefresh, findLibraryItem, supports, statusList, scoreValue, displayScore, fetchGeneralData, fetchUserData, login and 24 further declarations.

The source describes its contract as:

MangaBaka (manga only) with a user Personal Access Token (mb-…) sent as x-api-key (https://mangabaka.org/api.json, security scheme x-api-key), so no OAuth client is needed.

Cross-chapter imports used by this file: DbTrack, DbTrackPreference, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

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.encodeURLParameter
import kotlin.math.roundToInt
import kotlin.time.Instant
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.atStartOfDayIn
import kotlinx.datetime.toLocalDateTime
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put

/**
 * MangaBaka (manga only) with a user Personal Access Token (`mb-…`) sent as `x-api-key`
 * (https://mangabaka.org/api.json, security scheme `x-api-key`), so no OAuth client is needed.
 */
class MangaBakaTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "MangaBaka"

    private val baseUrl = "https://api.mangabaka.org/v1"

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override fun supports(isManga: Boolean): Boolean = isManga

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(true)

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = if (score == 0) "-" else "$score/10"

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> = emptyList()

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()

    override val loginFields: List<TrackerLoginField> = listOf(TrackerLoginField.ApiKey)

    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        val key = values.required(TrackerLoginField.ApiKey)
        val profile = profile(key)
        return DbTrackPreference(
            syncId = syncId.toLong(),
            username = profile?.str("preferred_username") ?: profile?.str("nickname"),
            accountName = profile?.str("nickname") ?: profile?.str("preferred_username"),
            accountAvatarUrl = profile?.str("picture"),
            oauth = key,
            prefs = TrackerCredentials(userId = profile?.str("id"), apiKey = key).encode(),
            refreshing = false,
        )
    }

    override suspend fun accountProfile(): TrackerAccountProfile? {
        val key = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() } ?: return null
        val profile = profile(key) ?: return null
        return TrackerAccountProfile(profile.str("nickname") ?: profile.str("preferred_username"), profile.str("picture"))
    }

    private suspend fun profile(key: String): JsonObject? =
        http.request(HttpRequest("$baseUrl/my/profile", headers = auth(key))).json(name).obj()?.get("data").obj()

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        trackerSearchId(query)?.let { id ->
            val response = http.request(HttpRequest("$baseUrl/series/${id.toLongOrNull() ?: return emptyList()}"))
            if (response.statusCode == 404) return emptyList()
            return listOfNotNull(response.json(name).obj()?.get("data").obj()?.toSearch())
        }
        if (query.isBlank()) return emptyList()
        val data = http.request(HttpRequest("$baseUrl/series/search?q=${query.trim().encodeURLParameter()}"))
            .json(name).obj()?.get("data") as? JsonArray ?: return emptyList()
        return data.mapNotNull { it.obj()?.toSearch() }
    }

    override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack {
        remote(track)?.let { return it }
        send("POST", track, body(track))
        return track
    }

    override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack = remote(track) ?: track

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {
        val progress = track.lastChapterRead ?: 0
        val total = track.totalChapter ?: 0
        val updated = when {
            total > 0 && progress >= total && track.status != DbTrackStatus.Completed ->
                track.copy(status = DbTrackStatus.Completed, finishedReadingDate = track.finishedReadingDate ?: eu.friedcutlet.yokan.util.nowMillis())
            track.status == DbTrackStatus.PlanToRead && progress > 0 ->
                track.copy(status = DbTrackStatus.Reading, startedReadingDate = track.startedReadingDate ?: eu.friedcutlet.yokan.util.nowMillis())
            else -> track
        }
        send("PATCH", updated, body(updated))
        return updated
    }

    override suspend fun unbind(track: DbTrack, isManga: Boolean) {
        val response = http.request(HttpRequest(libraryUrl(track), "DELETE", auth(token())))
        if (response.statusCode != 404) response.requireSuccess(name)
    }

    /** The library entry, or null when the series is not in the user's library (404). */
    private suspend fun remote(track: DbTrack): DbTrack? {
        val response = http.request(HttpRequest(libraryUrl(track), headers = auth(token())))
        if (response.statusCode == 404) return null
        val entry = response.json(name).obj()?.get("data").obj() ?: return null
        return track.copy(
            status = status(entry.str("state")),
            lastChapterRead = entry.double("progress_chapter")?.toInt() ?: 0,
            score = entry.double("rating")?.let { (it / 10).roundToInt().coerceIn(0, 10) } ?: 0,
            startedReadingDate = entry.str("start_date")?.let(::parseDate),
            finishedReadingDate = entry.str("finish_date")?.let(::parseDate),
        )
    }

    // A 0 rating/progress is stored as null by the API; dates are bare `YYYY-MM-DD`.
    private fun body(track: DbTrack): JsonObject = buildJsonObject {
        put("state", state(track.status))
        put("progress_chapter", track.lastChapterRead?.takeIf { it > 0 })
        put("rating", track.score?.takeIf { it > 0 }?.let { it.coerceAtMost(10) * 10 })
        put("start_date", track.startedReadingDate?.takeIf { it > 0 }?.let(::formatDate))
        put("finish_date", track.finishedReadingDate?.takeIf { it > 0 }?.let(::formatDate))
    }

    private suspend fun send(method: String, track: DbTrack, body: JsonElement): HttpResponse =
        http.request(HttpRequest(libraryUrl(track), method, auth(token()), body.toString())).requireSuccess(name)

    private fun libraryUrl(track: DbTrack): String =
        "$baseUrl/my/library/${track.mediaId ?: throw IllegalStateException("$name track has no series id")}"

    private fun state(status: DbTrackStatus): String = when (status) {
        DbTrackStatus.Completed -> "completed"
        DbTrackStatus.OnHold -> "paused"
        DbTrackStatus.Dropped -> "dropped"
        DbTrackStatus.PlanToRead, DbTrackStatus.PlanToWatch -> "plan_to_read"
        DbTrackStatus.ReReading, DbTrackStatus.ReWatching -> "rereading"
        else -> "reading"
    }

    private fun status(state: String?): DbTrackStatus = when (state) {
        "completed" -> DbTrackStatus.Completed
        "paused" -> DbTrackStatus.OnHold
        "dropped" -> DbTrackStatus.Dropped
        "plan_to_read", "considering" -> DbTrackStatus.PlanToRead
        "rereading" -> DbTrackStatus.ReReading
        else -> DbTrackStatus.Reading
    }

    private fun parseDate(raw: String): Long? = runCatching {
        LocalDate.parse(raw.substringBefore('T')).atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds()
    }.getOrNull()

    private fun formatDate(millis: Long): String =
        Instant.fromEpochMilliseconds(millis).toLocalDateTime(TimeZone.UTC).date.toString()

    private fun JsonObject.toSearch(): DbTrackSearch? {
        val id = long("id") ?: return null
        return DbTrackSearch(
            syncId = syncId,
            mediaId = id,
            title = bestTitle() ?: str("title").orEmpty(),
            trackingUrl = "https://mangabaka.org/$id",
            totalChapter = str("total_chapters")?.toDoubleOrNull()?.toInt(),
            coverUrl = this["cover"].obj()?.get("x250").obj()?.str("x1").orEmpty(),
            summary = str("description")?.trim().orEmpty(),
            publishingStatus = str("status").orEmpty(),
            publishingType = str("type").orEmpty().replaceFirstChar { it.uppercaseChar() },
            startDate = this["published"].obj()?.str("start_date").orEmpty(),
            score = double("rating"),
            status = "",
        )
    }

    /** https://mangabaka.org/pages/announcements/15-titles-v2: primary, then official, then native per language. */
    private fun JsonObject.bestTitle(): String? {
        val titles = (this["titles"] as? JsonArray)?.mapNotNull { it.obj() } ?: return null
        fun rank(t: JsonObject): Int {
            val traits = (t["traits"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }.orEmpty()
            return when {
                (t["is_primary"] as? JsonPrimitive)?.booleanOrNull == true -> 0
                "official" in traits -> 1
                "native" in traits -> 2
                else -> 3
            }
        }
        return listOf("en", "ja-Latn", "ja", "ko-Latn", "ko", "zh-Latn", "zh")
            .firstNotNullOfOrNull { lang -> titles.filter { it.str("language") == lang }.minByOrNull(::rank)?.str("title") }
            ?: titles.firstOrNull()?.str("title")
    }

    private fun auth(key: String) = mapOf("x-api-key" to key)

    private fun token(): String = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() }
        ?: throw IllegalStateException("Not logged in to $name")

    private fun JsonElement?.obj(): JsonObject? = this as? JsonObject
    private fun JsonObject.str(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it !is JsonNull }?.contentOrNull
    private fun JsonObject.long(key: String): Long? = (this[key] as? JsonPrimitive)?.longOrNull
    private fun JsonObject.double(key: String): Double? = (this[key] as? JsonPrimitive)?.doubleOrNull
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MangaUpdatesTrackerService, checkRefresh, findLibraryItem, supports, statusList, scoreValue, displayScore, fetchGeneralData, fetchUserData, login and 21 further declarations.

The source describes its contract as:

MangaUpdates (manga only): username/password session, https://api.mangaupdates.com/ (v1).

Cross-chapter imports used by this file: DbTrack, DbTrackPreference, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

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 kotlin.math.roundToInt
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.add
import kotlinx.serialization.json.addJsonObject
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject

/** MangaUpdates (manga only): username/password session, https://api.mangaupdates.com/ (v1). */
class MangaUpdatesTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "MangaUpdates"

    private val baseUrl = "https://api.mangaupdates.com/v1"

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override fun supports(isManga: Boolean): Boolean = isManga

    override fun statusList(isManga: Boolean): List<DbTrackStatus> = listOf(
        DbTrackStatus.Reading,
        DbTrackStatus.Completed,
        DbTrackStatus.OnHold,
        DbTrackStatus.Dropped,
        DbTrackStatus.PlanToRead,
    )

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = if (score == 0) "-" else "$score/10"

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> = emptyList()

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()

    override val loginFields: List<TrackerLoginField> = listOf(TrackerLoginField.Username, TrackerLoginField.Password)

    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        val body = buildJsonObject {
            put("username", values.required(TrackerLoginField.Username))
            put("password", values.required(TrackerLoginField.Password))
        }
        val context = http.request(HttpRequest("$baseUrl/account/login", "PUT", body = body.toString()))
            .json(name).obj()?.get("context").obj()
        val token = context?.str("session_token") ?: throw IllegalStateException("$name did not return a session")
        val username = profileName(token)
        return DbTrackPreference(
            syncId = syncId.toLong(),
            username = username,
            accountName = username,
            oauth = token,
            prefs = TrackerCredentials(userId = context.long("uid")?.toString()).encode(),
            refreshing = false,
        )
    }

    override suspend fun accountProfile(): TrackerAccountProfile? =
        database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() }?.let { TrackerAccountProfile(name = profileName(it)) }

    private suspend fun profileName(token: String): String? =
        http.request(HttpRequest("$baseUrl/account/profile", headers = auth(token))).json(name).obj()?.str("username")

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        trackerSearchId(query)?.let { id ->
            val response = http.request(HttpRequest("$baseUrl/series/${id.toLongOrNull() ?: return emptyList()}"))
            if (response.statusCode == 404) return emptyList()
            return listOfNotNull(response.json(name).obj()?.toSearch())
        }
        if (query.isBlank()) return emptyList()
        val body = buildJsonObject {
            put("search", query.trim())
            putJsonArray("filter_types") { add("drama cd") }
        }
        val results = http.request(HttpRequest("$baseUrl/series/search", "POST", body = body.toString()))
            .json(name).obj()?.get("results") as? JsonArray ?: return emptyList()
        return results.mapNotNull { it.obj()?.get("record").obj()?.toSearch() }
    }

    override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack {
        remote(track)?.let { return it }
        val status = listId(track.status)
        val progress = track.lastChapterRead ?: 0
        val body = buildJsonArray {
            addJsonObject {
                putJsonObject("series") { put("id", seriesId(track)) }
                put("list_id", status)
                putJsonObject("status") { put("chapter", progress) }
            }
        }
        send("POST", "$baseUrl/lists/series", body)
        putRating(track)
        return track.copy(status = status(status), lastChapterRead = progress)
    }

    override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack = remote(track) ?: track

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {
        val progress = track.lastChapterRead ?: 0
        val total = track.totalChapter ?: 0
        val status = when {
            total > 0 && progress >= total -> DbTrackStatus.Completed
            track.status == DbTrackStatus.PlanToRead && progress > 0 -> DbTrackStatus.Reading
            else -> track.status
        }
        val body = buildJsonArray {
            addJsonObject {
                putJsonObject("series") { put("id", seriesId(track)) }
                put("list_id", listId(status))
                putJsonObject("status") { put("chapter", progress) }
            }
        }
        send("POST", "$baseUrl/lists/series/update", body)
        putRating(track)
        return track.copy(status = status, lastChapterRead = progress)
    }

    override suspend fun unbind(track: DbTrack, isManga: Boolean) {
        val response = http.request(
            HttpRequest("$baseUrl/lists/series/delete", "POST", auth(token()), buildJsonArray { add(seriesId(track)) }.toString()),
        )
        if (response.statusCode != 404) response.requireSuccess(name)
    }

    /** The list entry and rating, or null when the series is not on any of the user's lists. */
    private suspend fun remote(track: DbTrack): DbTrack? {
        val id = seriesId(track)
        val response = http.request(HttpRequest("$baseUrl/lists/series/$id", headers = auth(token())))
        if (response.statusCode == 404) return null
        val item = response.json(name).obj() ?: return null
        val rating = http.request(HttpRequest("$baseUrl/series/$id/rating", headers = auth(token())))
            .takeIf { it.statusCode in 200..299 }
            ?.let { runCatching { trackerJson.parseToJsonElement(it.body).obj()?.double("rating") }.getOrNull() }
        return track.copy(
            status = status(item.long("list_id")?.toInt() ?: 0),
            lastChapterRead = item["status"].obj()?.int("chapter") ?: 0,
            score = rating?.roundToInt()?.coerceIn(0, 10) ?: 0,
        )
    }

    private suspend fun putRating(track: DbTrack) {
        val score = track.score ?: 0
        val url = "$baseUrl/series/${seriesId(track)}/rating"
        if (score > 0) {
            send("PUT", url, buildJsonObject { put("rating", score.coerceAtMost(10)) })
        } else {
            val response = http.request(HttpRequest(url, "DELETE", auth(token())))
            if (response.statusCode != 404) response.requireSuccess(name)
        }
    }

    private suspend fun send(method: String, url: String, body: JsonElement): HttpResponse =
        http.request(HttpRequest(url, method, auth(token()), body.toString())).requireSuccess(name)

    private fun seriesId(track: DbTrack): Long = track.mediaId ?: throw IllegalStateException("$name track has no series id")

    private fun listId(status: DbTrackStatus): Int = when (status) {
        DbTrackStatus.PlanToRead, DbTrackStatus.PlanToWatch -> 1
        DbTrackStatus.Completed -> 2
        DbTrackStatus.Dropped -> 3
        DbTrackStatus.OnHold -> 4
        else -> 0
    }

    // Custom user lists (id >= 5) count as reading.
    private fun status(listId: Int): DbTrackStatus = when (listId) {
        1 -> DbTrackStatus.PlanToRead
        2 -> DbTrackStatus.Completed
        3 -> DbTrackStatus.Dropped
        4 -> DbTrackStatus.OnHold
        else -> DbTrackStatus.Reading
    }

    private fun JsonObject.toSearch(): DbTrackSearch? {
        val id = long("series_id") ?: return null
        return DbTrackSearch(
            syncId = syncId,
            mediaId = id,
            title = str("title").orEmpty(),
            trackingUrl = str("url"),
            totalChapter = null,
            coverUrl = this["image"].obj()?.get("url").obj()?.str("original").orEmpty(),
            summary = str("description").orEmpty(),
            publishingStatus = "",
            publishingType = str("type").orEmpty(),
            startDate = str("year").orEmpty(),
            score = double("bayesian_rating")?.takeIf { it > 0 },
            status = "",
        )
    }

    private fun auth(token: String) = mapOf("Authorization" to "Bearer $token")

    private fun token(): String = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() }
        ?: throw IllegalStateException("Not logged in to $name")

    private fun JsonElement?.obj(): JsonObject? = this as? JsonObject
    private fun JsonObject.str(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull
    private fun JsonObject.long(key: String): Long? = (this[key] as? JsonPrimitive)?.longOrNull
    private fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull
    private fun JsonObject.double(key: String): Double? = (this[key] as? JsonPrimitive)?.doubleOrNull
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines MetadataTrackerService, checkRefresh, findLibraryItem, update, statusList, search, fetchGeneralData, fetchUserData, scoreValue, displayScore and 4 further declarations.

Cross-chapter imports used by this file: DbItemType, DbTrack, DbTrackSearch, DbTrackStatus, YokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.services.metadata.MetadataService

class MetadataTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val metadata: MetadataService,
) : TrackerService {
    override val name: String = "Metadata Server"

    override val isMetadataSource: Boolean = true

    override suspend fun checkRefresh(): Boolean = token().isNotBlank()

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {
        val mediaId = track.trackingUrl?.takeIf { it.isNotBlank() } ?: track.mediaId?.toString().orEmpty()
        if (mediaId.isNotBlank()) {
            metadata.upsertLibraryEntry(
                baseUrl = database.settings().metadataServerUrl,
                token = token(),
                mediaId = mediaId,
                status = track.status.metadataStatus(isManga),
                progress = track.lastChapterRead ?: 0,
                score = track.score,
                isFavorite = false,
            )
        }
        return database.upsertTrack(track.copy(syncId = syncId))
    }

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        if (query.isBlank()) return emptyList()
        return metadata.search(database.settings().metadataServerUrl, query, if (isManga) DbItemType.Manga else DbItemType.Anime)
            .map { it.toTrackSearch(syncId) }
    }

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> =
        metadata.search(database.settings().metadataServerUrl, "", if (isManga) DbItemType.Manga else DbItemType.Anime, limit = 25)
            .map { it.toTrackSearch(syncId) }

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> =
        metadata.library(database.settings().metadataServerUrl, token(), if (isManga) DbItemType.Manga else DbItemType.Anime)
            .map { (entry, media) ->
                media.toTrackSearch(syncId).copy(
                    lastChapterRead = entry.progress,
                    score = entry.score?.toDouble(),
                    status = entry.status,
                )
            }

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = "$score/10"

    private fun token(): String =
        database.settings().metadataServerToken.trim().ifBlank {
            database.trackPreferences().firstOrNull { it.syncId == syncId.toLong() }?.oauth.orEmpty()
        }
}

private fun MetadataMedia.toTrackSearch(syncId: Int): DbTrackSearch =
    DbTrackSearch(
        mediaId = id.toLongOrNull() ?: stablePositiveId(id),
        syncId = syncId,
        title = title,
        totalChapter = totalProgress,
        score = score,
        status = status.orEmpty(),
        trackingUrl = id,
        coverUrl = coverUrl.orEmpty(),
        summary = description.orEmpty(),
        publishingStatus = status.orEmpty(),
        publishingType = source,
        startDate = year?.toString().orEmpty(),
    )

private fun DbTrackStatus.metadataStatus(isManga: Boolean): String = when (this) {
    DbTrackStatus.Completed -> "completed"
    DbTrackStatus.OnHold -> "on_hold"
    DbTrackStatus.Dropped -> "dropped"
    DbTrackStatus.PlanToRead,
    DbTrackStatus.PlanToWatch -> "planned"
    DbTrackStatus.ReReading -> "rereading"
    DbTrackStatus.ReWatching -> "rewatching"
    DbTrackStatus.Watching -> "watching"
    DbTrackStatus.Reading -> if (isManga) "reading" else "watching"
}

private fun stablePositiveId(value: String): Long {
    var hash = 1125899906842597L
    value.forEach { char -> hash = 31L * hash + char.code }
    return hash and Long.MAX_VALUE
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines ServerTrackerService, itemKey, fetch, push, authHeaders, reauthenticate, preference, loggedIn, server, send and 22 further declarations.

The source describes its contract as:

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.

Cross-chapter imports used by this file: DbManga, DbSource, DbTrack, DbTrackPreference, DbTrackSearch, DbTrackStatus. Keep those contracts available as you connect this step.

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<String>
    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<String, String>

    /** 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<String, String> = 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<DbTrackStatus> =
        if (forManga) listOf(DbTrackStatus.PlanToRead, DbTrackStatus.Reading, DbTrackStatus.Completed)
        else listOf(DbTrackStatus.PlanToWatch, DbTrackStatus.Watching, DbTrackStatus.Completed)

    override fun scoreValue(): Pair<Int, Int> = 0 to 0

    override fun displayScore(score: Int): String = ""

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> = emptyList()

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()

    /** Enhanced trackers are not searched; `id:<server item id>` resolves like [match]. */
    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> =
        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 `/<marker>/` (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() }

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines ShikimoriTrackerService, checkRefresh, findLibraryItem, statusList, scoreValue, displayScore, fetchGeneralData, fetchUserData, authorizeUrl, login and 18 further declarations.

The source describes its contract as:

Shikimori REST API (https://shikimori.io/api/doc) with the user's own OAuth application.

Cross-chapter imports used by this file: DbTrack, DbTrackPreference, DbTrackSearch, DbTrackStatus, YokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

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.HttpService
import io.ktor.http.encodeURLParameter
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject

/** Shikimori REST API (https://shikimori.io/api/doc) with the user's own OAuth application. */
class ShikimoriTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "Shikimori"

    private val oauth = TrackerOAuthClient(
        tracker = name,
        syncId = syncId,
        tokenUrl = "$BaseUrl/oauth/token",
        database = database,
        http = http,
    )

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = if (score == 0) "-" else "$score/10"

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> = emptyList()

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()

    override val loginFields: List<TrackerLoginField> =
        listOf(TrackerLoginField.ClientId, TrackerLoginField.ClientSecret, TrackerLoginField.AuthorizationCode)

    override suspend fun authorizeUrl(values: Map<TrackerLoginField, String>): String =
        "$BaseUrl/oauth/authorize?client_id=${values.required(TrackerLoginField.ClientId).encodeURLParameter()}" +
            "&redirect_uri=${TrackerOAuth.redirectUri(syncId).encodeURLParameter()}&response_type=code&scope=user_rates"

    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        val clientId = values.required(TrackerLoginField.ClientId)
        val clientSecret = values.required(TrackerLoginField.ClientSecret)
        val code = callbackParameter(values.required(TrackerLoginField.AuthorizationCode), "code")
        val token = oauth.tokenRequest(
            "grant_type" to "authorization_code",
            "client_id" to clientId,
            "client_secret" to clientSecret,
            "code" to code,
            "redirect_uri" to TrackerOAuth.redirectUri(syncId),
        )
        val accessToken = token.str("access_token") ?: throw TrackerHttpException(name, 401, "No access token")
        val user = oauth.send("GET", "$BaseUrl/api/users/whoami", accessToken).json(name) as JsonObject
        val nickname = user.str("nickname")
        return DbTrackPreference(
            syncId = syncId.toLong(),
            username = nickname,
            accountName = nickname,
            oauth = accessToken,
            prefs = TrackerCredentials(
                clientId = clientId,
                clientSecret = clientSecret,
                refreshToken = token.str("refresh_token"),
                expiresAt = token.oauthExpiresAt(),
                userId = user.str("id"),
            ).encode(),
            refreshing = false,
        )
    }

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        val kind = kind(isManga)
        trackerSearchId(query)?.let { id ->
            val response = oauth.api("GET", "$BaseUrl/api/$kind/${id.encodeURLParameter()}")
            if (response.statusCode == 404) return emptyList()
            return listOfNotNull((response.json(name) as? JsonObject)?.toSearch(isManga))
        }
        if (query.isBlank()) return emptyList()
        val results = oauth.api("GET", "$BaseUrl/api/$kind?search=${query.trim().encodeURLParameter()}&limit=20").json(name)
        return (results as? JsonArray).orEmpty().mapNotNull { (it as? JsonObject)?.toSearch(isManga) }
    }

    override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack {
        findRate(track, isManga)?.let { return track.withRate(it, isManga) }
        return track.withRate(createRate(track, isManga), isManga)
    }

    override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack =
        findRate(track, isManga)?.let { track.withRate(it, isManga) } ?: track

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {
        val adjusted = track.autoStatus(isManga)
        val rate = findRate(adjusted, isManga) ?: return adjusted.withRate(createRate(adjusted, isManga), isManga)
        val body = buildJsonObject { putJsonObject("user_rate") { putPersonal(adjusted, isManga) } }.toString()
        val updated = oauth.api("PATCH", "$BaseUrl/api/v2/user_rates/${rate.str("id")}", body).json(name) as JsonObject
        return adjusted.withRate(updated, isManga)
    }

    override suspend fun unbind(track: DbTrack, isManga: Boolean) {
        val rate = findRate(track, isManga) ?: return
        oauth.api("DELETE", "$BaseUrl/api/v2/user_rates/${rate.str("id")}").requireSuccess(name)
    }

    private suspend fun findRate(track: DbTrack, isManga: Boolean): JsonObject? {
        val mediaId = track.mediaId ?: error("Shikimori track has no media id")
        val userId = userId()
        val url = "$BaseUrl/api/v2/user_rates?user_id=$userId&target_id=$mediaId&target_type=${targetType(isManga)}"
        return (oauth.api("GET", url).json(name) as? JsonArray)?.firstOrNull() as? JsonObject
    }

    private suspend fun createRate(track: DbTrack, isManga: Boolean): JsonObject {
        val userId = userId()
        val body = buildJsonObject {
            putJsonObject("user_rate") {
                put("user_id", userId)
                put("target_id", track.mediaId ?: error("Shikimori track has no media id"))
                put("target_type", targetType(isManga))
                putPersonal(track, isManga)
            }
        }.toString()
        return oauth.api("POST", "$BaseUrl/api/v2/user_rates", body).json(name) as JsonObject
    }

    private fun kotlinx.serialization.json.JsonObjectBuilder.putPersonal(track: DbTrack, isManga: Boolean) {
        put("status", track.status.toShikimori())
        put("score", (track.score ?: 0).coerceIn(0, 10))
        put(if (isManga) "chapters" else "episodes", track.lastChapterRead ?: 0)
    }

    private fun DbTrack.withRate(rate: JsonObject, isManga: Boolean): DbTrack = copy(
        status = rate.str("status")?.let { fromShikimori(it, isManga) } ?: status,
        score = rate.int("score") ?: score,
        lastChapterRead = rate.int(if (isManga) "chapters" else "episodes") ?: lastChapterRead,
        trackingUrl = trackingUrl ?: mediaId?.let { "$BaseUrl/${kind(isManga)}/$it" },
    )

    private fun JsonObject.toSearch(isManga: Boolean): DbTrackSearch? {
        val id = (this["id"] as? JsonPrimitive)?.longOrNull ?: return null
        val image = (this["image"] as? JsonObject)?.str("original")
        return DbTrackSearch(
            syncId = syncId,
            mediaId = id,
            title = str("name") ?: str("russian"),
            trackingUrl = "$BaseUrl/${kind(isManga)}/$id",
            totalChapter = int(if (isManga) "chapters" else "episodes")?.takeIf { it > 0 },
            coverUrl = image?.let { if (it.startsWith("/")) "$BaseUrl$it" else it }.orEmpty(),
            summary = str("description").orEmpty(),
            publishingStatus = str("status").orEmpty(),
            publishingType = str("kind").orEmpty(),
            startDate = str("aired_on").orEmpty(),
            score = str("score")?.toDoubleOrNull(),
            status = "",
        )
    }

    private fun userId(): String =
        database.trackPreference(syncId)?.credentials()?.userId ?: error("Not logged in to $name")

    private companion object {
        const val BaseUrl = "https://shikimori.io"

        fun kind(isManga: Boolean) = if (isManga) "mangas" else "animes"
        fun targetType(isManga: Boolean) = if (isManga) "Manga" else "Anime"

        fun DbTrackStatus.toShikimori(): String = when (this) {
            DbTrackStatus.Reading, DbTrackStatus.Watching -> "watching"
            DbTrackStatus.Completed -> "completed"
            DbTrackStatus.OnHold -> "on_hold"
            DbTrackStatus.Dropped -> "dropped"
            DbTrackStatus.PlanToRead, DbTrackStatus.PlanToWatch -> "planned"
            DbTrackStatus.ReReading, DbTrackStatus.ReWatching -> "rewatching"
        }

        fun fromShikimori(status: String, isManga: Boolean): DbTrackStatus? = when (status) {
            "watching" -> if (isManga) DbTrackStatus.Reading else DbTrackStatus.Watching
            "completed" -> DbTrackStatus.Completed
            "on_hold" -> DbTrackStatus.OnHold
            "dropped" -> DbTrackStatus.Dropped
            "planned" -> if (isManga) DbTrackStatus.PlanToRead else DbTrackStatus.PlanToWatch
            "rewatching" -> if (isManga) DbTrackStatus.ReReading else DbTrackStatus.ReWatching
            else -> null
        }
    }
}

/** Upstream update rule: progress on a planned entry starts it; reaching the total completes it. */
private fun DbTrack.autoStatus(isManga: Boolean): DbTrack {
    val progress = lastChapterRead ?: 0
    val total = totalChapter ?: 0
    return when {
        status == DbTrackStatus.Completed -> this
        total > 0 && progress >= total -> copy(status = DbTrackStatus.Completed)
        progress > 0 && (status == DbTrackStatus.PlanToRead || status == DbTrackStatus.PlanToWatch) ->
            copy(status = if (isManga) DbTrackStatus.Reading else DbTrackStatus.Watching)
        else -> this
    }
}

private fun JsonObject.str(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull

private fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines SimklTrackerService, checkRefresh, findLibraryItem, update, statusList, search, fetchGeneralData, fetchUserData, scoreValue, displayScore and 4 further declarations.

The source describes its contract as:

SIMKL tracker covers anime (default) and movies; we surface anime entries only because the library currently models manga/anime/novel item types. Search/trending/popular hit the public unauthenticated endpoints; authenticated user-list calls remain pending until an API key is provisioned.

Cross-chapter imports used by this file: DbTrack, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.database.DbTrack
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.HttpService
import io.ktor.http.encodeURLParameter
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull

/**
 * SIMKL tracker covers anime (default) and movies; we surface anime entries only because the
 * library currently models manga/anime/novel item types. Search/trending/popular hit the public
 * unauthenticated endpoints; authenticated user-list calls remain pending until an API key is
 * provisioned.
 */
class SimklTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "SIMKL"

    private val base = "https://api.simkl.com"

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack =
        database.upsertTrack(track.copy(syncId = syncId))

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        if (query.isBlank()) return emptyList()
        if (isManga) return emptyList()
        trackerSearchId(query)?.let { id ->
            if (id.toIntOrNull() == null) return emptyList()
            val clientId = database.trackPreference(syncId)?.username ?: "anonymous"
            val item = catchingNonCancellation {
                http.request(HttpRequest("$base/anime/$id?extended=full&client_id=$clientId", headers = headersForRead())).json(name) as? JsonObject
            }.getOrNull()
            return listOfNotNull(item?.toTrackSearch())
        }
        val response = catchingNonCancellation {
            http.request(HttpRequest("$base/search/anime?q=${query.encodeURLParameter()}&extended=full", headers = headersForRead()))
        }.getOrNull() ?: return emptyList()
        return parseList(response.body)
    }

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> {
        // Mangayomi repurposes isManga as "movies" for Simkl; false = tv series.
        val type = if (isManga) "movies" else "tv"
        val key = rankingType.lowercase()
        val path = when (key) {
            "airing" -> "airing"
            "best", "top" -> "best"
            else -> "trending"
        }
        val query = buildString {
            append("?extended=overview&limit=15")
            if (path == "airing") append("&date=today&sort=rank")
            if (path == "best") append("&filter=all&type=series")
        }
        val response = catchingNonCancellation {
            http.request(HttpRequest("$base/$type/$path$query", headers = headersForRead()))
        }.getOrNull() ?: return emptyList()
        return parseList(response.body)
    }

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = "$score/10"

    private fun headersForRead(): Map<String, String> {
        val pref = database.trackPreference(syncId)
        val token = pref?.oauth?.takeIf { it.isNotBlank() }
        return buildMap {
            put("Accept", "application/json")
            put("simkl-api-key", pref?.username ?: "anonymous")
            if (token != null) put("Authorization", "Bearer $token")
        }
    }

    private fun parseList(body: String): List<DbTrackSearch> {
        val parsed = runCatching { trackerJson.parseToJsonElement(body) }.getOrNull() ?: return emptyList()
        val items = when (parsed) {
            is JsonArray -> parsed
            is JsonObject -> parsed["items"] as? JsonArray ?: parsed["result"] as? JsonArray ?: return emptyList()
            else -> return emptyList()
        }
        return items.mapNotNull { (it as? JsonObject)?.toTrackSearch() }
    }

    private fun JsonObject.toTrackSearch(): DbTrackSearch? {
        val media = (this["show"] as? JsonObject) ?: (this["movie"] as? JsonObject) ?: this
        val ids = media["ids"] as? JsonObject
        val mediaId = (ids?.get("simkl_id") ?: ids?.get("simkl") ?: media["id"])?.let {
            (it as? JsonPrimitive)?.intOrNull
        } ?: return null
        val title = (media["title"] as? JsonPrimitive)?.contentOrNull
            ?: ((media["title_en"] as? JsonPrimitive)?.contentOrNull)
            ?: return null
        val poster = (media["poster"] as? JsonPrimitive)?.contentOrNull?.let { "https://simkl.in/posters/$it.jpg" }
            .orEmpty()
        val description = (media["overview"] as? JsonPrimitive)?.contentOrNull.orEmpty()
        val rating = (media["rating"] as? JsonPrimitive)?.doubleOrNull
            ?: (media["ratings"] as? JsonObject)?.let { (it["simkl"] as? JsonObject)?.get("rating") as? JsonPrimitive }
                ?.doubleOrNull
        val total = (media["total_episodes"] as? JsonPrimitive)?.intOrNull
            ?: (media["episodes"] as? JsonPrimitive)?.intOrNull
        val status = (media["status"] as? JsonPrimitive)?.contentOrNull?.lowercase().orEmpty()
        val type = (media["type"] as? JsonPrimitive)?.contentOrNull.orEmpty()
        val year = (media["year"] as? JsonPrimitive)?.intOrNull?.toString().orEmpty()
        return DbTrackSearch(
            mediaId = mediaId.toLong(),
            syncId = syncId,
            title = title,
            totalChapter = total,
            score = rating,
            status = status,
            trackingUrl = "https://simkl.com/anime/$mediaId",
            coverUrl = poster,
            summary = description,
            publishingStatus = status,
            publishingType = type,
            startDate = year,
        )
    }

    override suspend fun accountProfile(): TrackerAccountProfile? {
        val token = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() } ?: return null
        val obj = catchingNonCancellation {
            http.request(
                HttpRequest(
                    url = "$base/users/settings",
                    headers = mapOf(
                        "Authorization" to "Bearer $token",
                        "Accept" to "application/json",
                        "simkl-api-client" to "yokan",
                    ),
                ),
            ).json(name) as? JsonObject
        }.getOrNull() ?: return null
        return simklAccount(obj).toProfile()
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines SuwayomiTrackerService, login, authHeaders, itemKey, fetch, push, JsonObject.chapterNumber, JsonObject.long.

The source describes its contract as:

Suwayomi-Server (Animetail SuwayomiApi, REST /api/v1; deprecated upstream in favour of GraphQL but still served). Optional HTTP Basic auth. Item keys are numeric manga ids; progress is the last read chapter number.

Cross-chapter imports used by this file: DbTrackPreference, DbTrackSearch, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackSearch
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
import kotlin.math.abs

/**
 * Suwayomi-Server (Animetail `SuwayomiApi`, REST `/api/v1`; deprecated upstream in favour of GraphQL but still
 * served). Optional HTTP Basic auth. Item keys are numeric manga ids; progress is the last read chapter number.
 */
class SuwayomiTrackerService(syncId: Int, database: YokanDatabase, http: HttpService) :
    ServerTrackerService(syncId, database, http) {
    override val name: String = "Suwayomi"
    override val sourceKeywords = listOf("suwayomi", "tachidesk")
    override val forManga = true

    override val loginFields = listOf(TrackerLoginField.ServerUrl, TrackerLoginField.Username, TrackerLoginField.Password)

    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        val server = normalizeServerUrl(values.required(TrackerLoginField.ServerUrl))
        val username = values.optional(TrackerLoginField.Username)
        val basic = username?.let { basicAuth(it, values.required(TrackerLoginField.Password)) }
        val preference = loginPreference(username, basic?.let { BASIC } ?: ANONYMOUS, TrackerCredentials(serverUrl = server, apiKey = basic))
        val about = http.request(HttpRequest("$server/api/v1/settings/about", headers = authHeaders(preference))).json(name).jsonObject
        return preference.copy(accountName = about["name"]?.jsonPrimitive?.contentOrNull)
    }

    override fun authHeaders(preference: DbTrackPreference): Map<String, String> =
        preference.credentials().apiKey?.takeIf { preference.oauth == BASIC }?.let { mapOf("Authorization" to it) }.orEmpty()

    override fun itemKey(link: String): String? =
        (segmentAfter(link, "manga") ?: link.trim()).takeIf { id -> id.isNotEmpty() && id.all { it.isDigit() } }

    override suspend fun fetch(key: String): DbTrackSearch {
        val url = "${server()}/api/v1/manga/$key"
        val manga = getJson("$url/full").jsonObject
        val chapterCount = manga.long("chapterCount")
        val unread = manga.long("unreadCount")
        return DbTrackSearch(
            syncId = syncId,
            mediaId = key.toLong(),
            title = manga["title"]?.jsonPrimitive?.contentOrNull,
            trackingUrl = url,
            coverUrl = "$url/thumbnail",
            summary = manga["description"]?.jsonPrimitive?.contentOrNull.orEmpty(),
            publishingStatus = manga["status"]?.jsonPrimitive?.contentOrNull.orEmpty(),
            totalChapter = chapterCount.toInt(),
            lastChapterRead = ((manga["lastChapterRead"] as? JsonObject)?.chapterNumber() ?: 0.0).toInt(),
            status = remoteStatus(unread = unread == chapterCount, completed = unread == 0L),
        )
    }

    /** Marks the chapter numbered [progress] and every earlier one read (`markPrevRead`). */
    override suspend fun push(key: String, progress: Int) {
        if (progress <= 0) return
        val url = "${server()}/api/v1/manga/$key"
        val chapter = getJson("$url/chapters").jsonArray
            .map { it.jsonObject }
            .firstOrNull { abs(it.chapterNumber() - progress) <= 0.001 }
            ?: throw IllegalArgumentException("Suwayomi has no chapter $progress")
        val index = chapter["index"]?.jsonPrimitive?.intOrNull ?: throw IllegalStateException("Suwayomi chapter has no index")
        send(
            "$url/chapter/$index",
            method = "PUT",
            body = formBody("markPrevRead" to "true", "read" to "true"),
            headers = mapOf("Content-Type" to "application/x-www-form-urlencoded"),
        ).requireSuccess(name)
    }

    private fun JsonObject.chapterNumber(): Double = this["chapterNumber"]?.jsonPrimitive?.doubleOrNull ?: 0.0
    private fun JsonObject.long(field: String): Long = this[field]?.jsonPrimitive?.longOrNull ?: 0L

    private companion object {
        const val BASIC = "basic"
        const val ANONYMOUS = "anonymous"
    }
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines TmdbTrackerService, checkRefresh, findLibraryItem, supports, statusList, scoreValue, displayScore, fetchGeneralData, fetchUserData, authorizeUrl and 20 further declarations.

The source describes its contract as:

TMDB v3 (movies + TV) with the user's own API key and a session from the request-token approval flow. TMDB has no episode progress: progress stays local; the watchlist mirrors PlanToWatch and ratings the score.

Cross-chapter imports used by this file: DbTrack, DbTrackPreference, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

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.encodeURLParameter
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put
import kotlin.math.roundToInt

/**
 * TMDB v3 (movies + TV) with the user's own API key and a session from the request-token approval flow.
 * TMDB has no episode progress: progress stays local; the watchlist mirrors PlanToWatch and ratings the score.
 */
class TmdbTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "TMDB"

    /** Request token from [authorizeUrl], keyed by the API key that created it. */
    private var pendingToken: Pair<String, String>? = null

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override fun supports(isManga: Boolean): Boolean = !isManga

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Watching).readableStatusList(false)

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = if (score == 0) "-" else "$score/10"

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> = emptyList()

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> = emptyList()

    override val loginFields: List<TrackerLoginField> = listOf(TrackerLoginField.ApiKey)

    override val browserSignIn: Boolean = true

    override suspend fun authorizeUrl(values: Map<TrackerLoginField, String>): String {
        val apiKey = values.required(TrackerLoginField.ApiKey)
        val token = http.request(HttpRequest("$Api/authentication/token/new?api_key=${apiKey.encodeURLParameter()}"))
            .json(name).jsonObject.string("request_token") ?: throw IllegalStateException("TMDB returned no request token")
        pendingToken = apiKey to token
        return "https://www.themoviedb.org/authenticate/$token?redirect_to=${TrackerOAuth.redirectUri(syncId).encodeURLParameter()}"
    }

    override suspend fun login(values: Map<TrackerLoginField, String>): DbTrackPreference {
        val apiKey = values.required(TrackerLoginField.ApiKey)
        val token = pendingToken?.takeIf { it.first == apiKey }?.second
            ?: throw IllegalStateException("Sign in first: open the TMDB approval page, approve, then connect")
        val key = apiKey.encodeURLParameter()
        val sessionBody = buildJsonObject { put("request_token", token) }.toString()
        val session = http.request(HttpRequest("$Api/authentication/session/new?api_key=$key", "POST", body = sessionBody))
            .json(name).jsonObject.string("session_id") ?: throw IllegalStateException("TMDB returned no session")
        pendingToken = null
        val account = http.request(HttpRequest("$Api/account?api_key=$key&session_id=${session.encodeURLParameter()}"))
            .json(name).jsonObject
        return DbTrackPreference(
            syncId = syncId.toLong(),
            username = account.string("username"),
            accountName = account.string("name")?.takeIf { it.isNotBlank() } ?: account.string("username"),
            oauth = session,
            prefs = TrackerCredentials(apiKey = apiKey, userId = account.long("id")?.toString()).encode(),
            refreshing = false,
        )
    }

    override suspend fun accountProfile(): TrackerAccountProfile? {
        val account = request("/account").json(name).jsonObject
        return TrackerAccountProfile(name = account.string("username"))
    }

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        trackerSearchId(query)?.let { raw ->
            val type = raw.substringBefore('/', "").lowercase().takeIf { it == "movie" || it == "tv" }
            val id = raw.substringAfter('/').toLongOrNull() ?: return emptyList()
            for (kind in type?.let { listOf(it) } ?: listOf("tv", "movie")) {
                val response = request("/$kind/$id")
                if (response.statusCode == 404) continue
                return listOf(response.json(name).jsonObject.toSearch(kind))
            }
            return emptyList()
        }
        if (query.isBlank()) return emptyList()
        val results = request("/search/multi", "query=${query.trim().encodeURLParameter()}").json(name).jsonObject["results"] as? JsonArray
        return results.orEmpty().mapNotNull { item ->
            val obj = item as? JsonObject ?: return@mapNotNull null
            obj.string("media_type")?.takeIf { it == "movie" || it == "tv" }?.let { obj.toSearch(it) }
        }
    }

    override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack {
        val states = accountStates(track)
        return if (states.watchlist() || states.rating() != null) track.withStates(states) else update(track, isManga)
    }

    override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack = track.withStates(accountStates(track))

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {
        val (kind, id) = media(track)
        setWatchlist(kind, id, track.status == DbTrackStatus.PlanToWatch)
        val score = (track.score ?: 0).coerceIn(0, 10)
        if (score > 0) {
            request("/$kind/$id/rating", method = "POST", body = buildJsonObject { put("value", score.toDouble()) }.toString())
                .requireSuccess(name)
        } else {
            deleteRating(kind, id)
        }
        return track.copy(score = score)
    }

    override suspend fun unbind(track: DbTrack, isManga: Boolean) {
        val (kind, id) = media(track)
        setWatchlist(kind, id, false)
        deleteRating(kind, id)
    }

    private suspend fun accountStates(track: DbTrack): JsonObject {
        val (kind, id) = media(track)
        return request("/$kind/$id/account_states").json(name).jsonObject
    }

    private fun DbTrack.withStates(states: JsonObject): DbTrack {
        val rating = states.rating()
        return copy(
            status = if (states.watchlist()) DbTrackStatus.PlanToWatch
            else if (status == DbTrackStatus.PlanToWatch) DbTrackStatus.Watching else status,
            score = rating?.let { it.roundToInt().coerceIn(1, 10) } ?: 0,
        )
    }

    private suspend fun setWatchlist(kind: String, id: Long, watchlist: Boolean) {
        val accountId = database.trackPreference(syncId)?.credentials()?.userId ?: throw IllegalStateException("Not logged in to $name")
        val body = buildJsonObject {
            put("media_type", kind)
            put("media_id", id)
            put("watchlist", watchlist)
        }.toString()
        request("/account/$accountId/watchlist", method = "POST", body = body).requireSuccess(name)
    }

    /** Deleting a rating that was never set answers 404; nothing to remove then. */
    private suspend fun deleteRating(kind: String, id: Long) {
        val response = request("/$kind/$id/rating", method = "DELETE")
        if (response.statusCode != 404) response.requireSuccess(name)
    }

    private fun media(track: DbTrack): Pair<String, Long> =
        tmdbMediaOf(track) ?: throw IllegalStateException("TMDB entry has no id")

    private fun JsonObject.toSearch(kind: String): DbTrackSearch {
        val id = long("id") ?: 0L
        return DbTrackSearch(
            syncId = syncId,
            mediaId = id,
            title = string(if (kind == "movie") "title" else "name") ?: string("original_title") ?: string("original_name"),
            trackingUrl = "https://www.themoviedb.org/$kind/$id",
            totalChapter = if (kind == "movie") 1 else int("number_of_episodes"),
            coverUrl = string("poster_path")?.let { "https://image.tmdb.org/t/p/w500$it" }.orEmpty(),
            summary = string("overview").orEmpty(),
            publishingStatus = string("status").orEmpty(),
            publishingType = kind,
            startDate = (string("release_date") ?: string("first_air_date")).orEmpty(),
            score = (this["vote_average"] as? JsonPrimitive)?.doubleOrNull,
            status = "",
        )
    }

    /** `api_key` + `session_id` query auth; 401 means the key or session was revoked (sign in again). */
    private suspend fun request(path: String, query: String? = null, method: String = "GET", body: String? = null): HttpResponse {
        val preference = database.trackPreference(syncId)
        val session = preference?.oauth?.takeIf { it.isNotBlank() } ?: throw IllegalStateException("Not logged in to $name")
        val apiKey = preference.credentials().apiKey ?: throw IllegalStateException("Not logged in to $name")
        val url = "$Api$path?api_key=${apiKey.encodeURLParameter()}&session_id=${session.encodeURLParameter()}" +
            query?.let { "&$it" }.orEmpty()
        val response = http.request(HttpRequest(url, method, body = body))
        if (response.statusCode == 401) throw TrackerHttpException(name, 401, response.body)
        return response
    }

    private companion object {
        const val Api = "https://api.themoviedb.org/3"

        fun JsonObject.watchlist(): Boolean = (this["watchlist"] as? JsonPrimitive)?.booleanOrNull == true

        /** `rated` is `false` or `{"value": 8.5}`. */
        fun JsonObject.rating(): Double? = ((this["rated"] as? JsonObject)?.get("value") as? JsonPrimitive)?.doubleOrNull

        fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull
        fun JsonObject.int(key: String): Int? = (this[key] as? JsonPrimitive)?.intOrNull
        fun JsonObject.long(key: String): Long? = (this[key] as? JsonPrimitive)?.longOrNull
    }
}

/** `movie`/`tv` and the TMDB id from the stored tracking URL (falls back to tv + [DbTrack.mediaId]). */
fun tmdbMediaOf(track: DbTrack): Pair<String, Long>? {
    val path = track.trackingUrl.orEmpty().substringAfter("themoviedb.org/", "").split('/')
    val kind = path.getOrNull(0)?.takeIf { it == "movie" || it == "tv" } ?: "tv"
    val id = path.getOrNull(1)?.substringBefore('-')?.toLongOrNull() ?: track.mediaId ?: return null
    return kind to id
}

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

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines TraktTrackerService, checkRefresh, findLibraryItem, update, statusList, search, fetchGeneralData, fetchUserData, scoreValue, displayScore and 5 further declarations.

Cross-chapter imports used by this file: DbTrack, DbTrackSearch, DbTrackStatus, YokanDatabase, HttpRequest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.database.DbTrack
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.HttpService
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
import io.ktor.http.encodeURLPathPart
import io.ktor.http.encodeURLParameter

class TraktTrackerService(
    override val syncId: Int,
    private val database: YokanDatabase,
    private val http: HttpService,
) : TrackerService {
    override val name: String = "trakt"

    private val base = "https://api.trakt.tv"

    override suspend fun checkRefresh(): Boolean = database.trackPreference(syncId)?.oauth?.isNotBlank() == true

    override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? =
        database.tracks(track.mangaId).firstOrNull { it.syncId == syncId }

    override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack =
        database.upsertTrack(track.copy(syncId = syncId))

    override fun statusList(isManga: Boolean): List<DbTrackStatus> =
        DbTrack(status = DbTrackStatus.Reading).readableStatusList(isManga)

    override suspend fun search(query: String, isManga: Boolean): List<DbTrackSearch> {
        if (query.isBlank() || isManga) return emptyList()
        trackerSearchId(query)?.let { id ->
            // Trakt accepts a numeric trakt id or a slug.
            val item = catchingNonCancellation {
                http.request(HttpRequest("$base/shows/${id.encodeURLPathPart()}?extended=full", headers = headersForRead())).json(name) as? JsonObject
            }.getOrNull()
            return listOfNotNull(item?.toTrackSearch())
        }
        val response = catchingNonCancellation {
            http.request(HttpRequest("$base/search/show?query=${query.encodeURLParameter()}&extended=full", headers = headersForRead()))
        }.getOrNull() ?: return emptyList()
        return parseSearchList(response.body)
    }

    override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String): List<DbTrackSearch> {
        // Mangayomi repurposes isManga as "movies" for Trakt; false = shows.
        val type = if (isManga) "movies" else "shows"
        val path = when (rankingType.lowercase()) {
            "popular" -> "popular"
            "top" -> "watched/weekly"
            "favorited", "favorited/all" -> "favorited/all"
            else -> "trending"
        }
        val response = catchingNonCancellation {
            http.request(HttpRequest("$base/$type/$path?extended=full&limit=25", headers = headersForRead()))
        }.getOrNull() ?: return emptyList()
        return parseRankList(response.body)
    }

    override suspend fun fetchUserData(isManga: Boolean): List<DbTrackSearch> {
        val token = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() } ?: return emptyList()
        val list = catchingNonCancellation {
            http.request(
                HttpRequest(
                    "$base/sync/watched/shows?extended=full",
                    headers = headersForRead() + ("Authorization" to "Bearer $token"),
                ),
            ).json(name) as? JsonArray
        }.getOrNull() ?: return emptyList()
        return list.mapNotNull { entry ->
            val obj = entry as? JsonObject ?: return@mapNotNull null
            val show = obj["show"] as? JsonObject ?: return@mapNotNull null
            val base = show.toTrackSearch() ?: return@mapNotNull null
            val watched = (obj["plays"] as? JsonPrimitive)?.intOrNull
            base.copy(lastChapterRead = watched ?: base.lastChapterRead)
        }
    }

    override fun scoreValue(): Pair<Int, Int> = 0 to 10

    override fun displayScore(score: Int): String = "$score/10"

    private fun headersForRead(): Map<String, String> {
        val pref = database.trackPreference(syncId)
        return mapOf(
            "Accept" to "application/json",
            "trakt-api-version" to "2",
            "trakt-api-key" to (pref?.username ?: "anonymous"),
        )
    }

    private fun parseSearchList(body: String): List<DbTrackSearch> {
        val list = runCatching { trackerJson.parseToJsonElement(body) as? JsonArray }.getOrNull() ?: return emptyList()
        return list.mapNotNull { entry ->
            val obj = entry as? JsonObject ?: return@mapNotNull null
            val show = obj["show"] as? JsonObject ?: return@mapNotNull null
            show.toTrackSearch()
        }
    }

    private fun parseRankList(body: String): List<DbTrackSearch> {
        val list = runCatching { trackerJson.parseToJsonElement(body) as? JsonArray }.getOrNull() ?: return emptyList()
        return list.mapNotNull { entry ->
            val obj = entry as? JsonObject ?: return@mapNotNull null
            val show = (obj["show"] as? JsonObject) ?: (obj["movie"] as? JsonObject) ?: obj
            show.toTrackSearch()
        }
    }

    private fun JsonObject.toTrackSearch(): DbTrackSearch? {
        val ids = this["ids"] as? JsonObject
        val mediaId = (ids?.get("trakt") as? JsonPrimitive)?.intOrNull
            ?: (ids?.get("imdb") as? JsonPrimitive)?.contentOrNull?.removePrefix("tt")?.toIntOrNull()
            ?: return null
        val title = (this["title"] as? JsonPrimitive)?.contentOrNull ?: return null
        val overview = (this["overview"] as? JsonPrimitive)?.contentOrNull.orEmpty()
        val year = (this["year"] as? JsonPrimitive)?.intOrNull?.toString().orEmpty()
        val rating = (this["rating"] as? JsonPrimitive)?.doubleOrNull
        val aired = (this["aired_episodes"] as? JsonPrimitive)?.intOrNull
        val status = (this["status"] as? JsonPrimitive)?.contentOrNull?.lowercase().orEmpty()
        val slug = (ids?.get("slug") as? JsonPrimitive)?.contentOrNull.orEmpty()
        return DbTrackSearch(
            mediaId = mediaId.toLong(),
            syncId = syncId,
            title = title,
            totalChapter = aired,
            score = rating,
            status = status,
            trackingUrl = if (slug.isNotBlank()) "https://trakt.tv/shows/$slug" else "",
            summary = overview,
            publishingStatus = status,
            publishingType = "show",
            startDate = year,
        )
    }

    override suspend fun accountProfile(): TrackerAccountProfile? {
        val token = database.trackPreference(syncId)?.oauth?.takeIf { it.isNotBlank() } ?: return null
        val obj = catchingNonCancellation {
            http.request(
                HttpRequest(
                    url = "$base/users/settings",
                    headers = mapOf(
                        "Authorization" to "Bearer $token",
                        "trakt-api-version" to "2",
                        "Accept" to "application/json",
                    ),
                ),
            ).json(name) as? JsonObject
        }.getOrNull() ?: return null
        return traktAccount(obj).toProfile()
    }
}

Check your understanding

Log out while token refresh is suspended, then finish it. Verify neither credentials nor account status are resurrected. Compare a valid 100-point score with a valid 10-point score after normalization. [chapter-content-end]: #

Step 3: connect tracking UI

Build tracker settings/account management, login dialogs, tracker detail/search, bind/unbind and library/status screens. Normalize scores through TrackerScores so UI averages and home recommendations agree. Use actual supported media types and provider scales. Distinguish search results from a user's tracked library.

The inspected branch does not have a general automatic tracker-progress write on every reader event. Reproduce the existing explicit/repository call paths; do not claim read completion automatically updates every external tracker. If adding that later, apply per-source incognito and ownership rules first.

Follow the code

The settings/account/detail UI is listed in chapter 24 and detail binding is in chapter 11. Connect those consumers to this chapter's real supported operations rather than treating all providers as identical. Search results and a user's tracked library are separate resources. The baseline does not universally write tracker progress on every reader event; follow the explicit repository/service call paths before claiming automatic synchronization.

This step connects or verifies implementations already listed in this chapter or its prerequisites. Follow the named call paths above while reading the complete tests at the end.

Check your understanding

For one provider, trace Login → Search → Bind → Refresh/Update → Logout. Identify the stored account/track records and every unsupported operation. [chapter-content-end]: #

Step 4: implement Home as a projection

Define HomeModels and HomeViewModel before HomeScreen/route/customization. Build featured shelves, continue reading/watching, recent/recommended content, optional TMDB movie/series shelves and source/library hiding. New installs start at Home; preserve explicit existing navigation order and append missing Home according to navigation migration policy.

Resume combines all media while preserving page/percentage/video units. Ignore deleted history references; a finished chapter can advance to the next unread release in reader order. Recommendation scoring uses shared normalized tracker scores and recent activity/genres. The user supplies a TMDB token; do not embed an account credential.

Featured automatic advance is optional, defaults off, and pauses during scrolling, e-ink and zero motion scale. Persist shelf visibility/order/customization without confusing a loading failure with a disabled shelf. Async shelves should fail independently.

Follow the code

Home is a projection of history, library, tracker scores and independent remote shelves. Preserve resume units for pages, percentages and video time, and use shared reading order when advancing a completed chapter. A deleted history reference contributes nothing. Shelf errors remain local to that shelf; user visibility and loading failure are different states. Featured auto-advance follows motion/e-ink/scroll preferences.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeModels.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeViewModel.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeRoute.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeScreen.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeCustomizeSheet.kt

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeModels.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines HomeCard, HomeLocalData, HomeRemoteShelf, HomeShelf, HomeState, ItemType.homeKind, projectHomeLocal, card, normalizedHomeTitle, buildHomeState and 5 further declarations.

The source describes its contract as:

Most recently updated/watched TMDB-tracked titles feeding [HomeSection.TmdbRecommended].

Cross-chapter imports used by this file: toDomainChapter, ItemType, Manga, hiddenNavigationSections, readingChapterSequence. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.home

import androidx.compose.runtime.Immutable
import eu.friedcutlet.yokan.data.toDomainChapter
import eu.friedcutlet.yokan.data.toDomainMangas
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.discovery.DiscoveryIssue
import eu.friedcutlet.yokan.services.discovery.DiscoveryMedia
import eu.friedcutlet.yokan.services.discovery.TmdbSeed
import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.tmdbMediaOf
import eu.friedcutlet.yokan.ui.navigation.hiddenNavigationSections
import eu.friedcutlet.yokan.ui.navigation.librarySection
import eu.friedcutlet.yokan.services.library.readingChapterSequence

@Immutable
internal data class HomeCard(
    val media: DiscoveryMedia,
    val mangaId: Long? = null,
    val chapterId: Long? = null,
    val coverBytes: ByteArray? = null,
    val completed: Boolean = false,
    val chapterName: String? = null,
    val position: Long = 0,
    val progress: Float? = null,
    val novelProgress: Float? = null,
)

internal data class HomeLocalData(
    val library: List<HomeCard> = emptyList(),
    val resume: List<HomeCard> = emptyList(),
    val seed: HomeCard? = null,
    val titlesByTypeAndName: Map<Pair<ItemType, String>, Manga> = emptyMap(),
    val titlesBySourceUrl: Map<Pair<Long?, String>, Manga> = emptyMap(),
    val sources: List<DbSource> = emptyList(),
    val presets: List<DbSavedSearch> = emptyList(),
    val hiddenTypes: Set<ItemType> = emptySet(),
    /** Most recently updated/watched TMDB-tracked titles feeding [HomeSection.TmdbRecommended]. */
    val tmdbSeeds: List<TmdbSeed> = emptyList(),
    /** Every TMDB-tracked [TmdbSeed.key]; never recommended back. */
    val tmdbTracked: Set<String> = emptySet(),
)

internal data class HomeRemoteShelf(
    val id: String,
    val section: HomeSection,
    val items: List<DiscoveryMedia> = emptyList(),
    val loading: Boolean = false,
    val issue: DiscoveryIssue? = null,
    val sourceName: String? = null,
)

internal data class HomeShelf(
    val id: String,
    val section: HomeSection,
    val cards: List<HomeCard>,
    val loading: Boolean = false,
    val issue: DiscoveryIssue? = null,
    val sourceName: String? = null,
)

internal data class HomeState(
    val preferences: DbHomePreferences = DbHomePreferences(),
    val shelves: List<HomeShelf> = emptyList(),
    val featured: List<HomeCard> = emptyList(),
    val seedTitle: String? = null,
    val sources: List<DbSource> = emptyList(),
    val presets: List<DbSavedSearch> = emptyList(),
    val feeds: List<DbHomeSourceFeed> = emptyList(),
    val tmdbConfigured: Boolean = false,
    val refreshing: Boolean = false,
    val customizeOpen: Boolean = false,
    val searchOpen: Boolean = false,
    val searchQuery: String = "",
    val openIssue: DiscoveryIssue? = null,
)

internal fun ItemType.homeKind(): HomeMediaFilter = when (this) {
    ItemType.Manga -> HomeMediaFilter.Manga
    ItemType.Anime -> HomeMediaFilter.Anime
    ItemType.Novel -> HomeMediaFilter.Novel
}

internal fun projectHomeLocal(snapshot: YokanDatabaseSnapshot, trackerScoreRanges: Map<Int, IntRange> = emptyMap()): HomeLocalData {
    val settings = snapshot.settings
    val hidden = hiddenNavigationSections(settings)
    val hiddenTypes = ItemType.entries.filterTo(mutableSetOf()) { it.librarySection() in hidden }
    val blockedSources = snapshot.sources.filter { !settings.showNsfw && it.isNsfw }.mapTo(mutableSetOf()) { it.id }
    val mangas = snapshot.mangas.toDomainMangas(settings).filter { it.itemType !in hiddenTypes && it.sourceId !in blockedSources }
    val byId = mangas.associateBy { it.id }
    val chapters = snapshot.chapters.groupBy { it.mangaId }
    val pageCounts = snapshot.pageCache.associate { it.chapterId to it.urls.orEmpty().size }
    val downloads = snapshot.downloads.filter { it.isDownload == true }.mapNotNullTo(mutableSetOf()) { it.chapterId }
    val scores = snapshot.tracks.groupBy { it.mangaId }.mapValues { (_, rows) -> rows.mapNotNull { track ->
        eu.friedcutlet.yokan.services.tracking.normalizedTrackerScore(track.syncId, track.score,
            trackerScoreRanges[track.syncId]?.last ?: eu.friedcutlet.yokan.services.tracking.trackerScoreMaximum(track.syncId))
    }.average().takeIf { !it.isNaN() } }
    fun card(manga: Manga): HomeCard = HomeCard(
        media = DiscoveryMedia("library:${manga.id}", manga.name, manga.itemType.homeKind(), manga.imageUrl,
            description = manga.description, genres = manga.genres, rating = scores[manga.id], aliases = manga.alternativeTitles),
        mangaId = manga.id, coverBytes = manga.customCoverImage,
        completed = chapters[manga.id].orEmpty().let { it.isNotEmpty() && it.all { chapter -> chapter.isRead } },
    )
    val recent = snapshot.histories.sortedByDescending { it.updatedAt }.distinctBy { it.mangaId }
    val resume = recent.mapNotNull { history ->
        val manga = byId[history.mangaId] ?: return@mapNotNull null
        val all = chapters[manga.id].orEmpty().map(::toDomainChapter)
        val current = all.firstOrNull { it.id == history.chapterId } ?: return@mapNotNull null
        val sequence = readingChapterSequence(manga, current.id, all, settings, downloads)
        val chapter = if (!current.isRead) sequence.firstOrNull { it.id == current.id } else {
            val index = sequence.indexOfFirst { it.id == current.id }
            sequence.drop(index + 1).firstOrNull { !it.isRead }
        } ?: return@mapNotNull null
        val position = chapter.lastPageRead.toLongOrNull()?.coerceAtLeast(0) ?: 0L
        val totalPages = pageCounts[chapter.id] ?: 0
        card(manga).copy(chapterId = chapter.id, chapterName = chapter.name, position = position,
            novelProgress = if (manga.itemType == ItemType.Novel) chapter.lastPageRead.toFloatOrNull()?.coerceIn(0f, 1f) ?: 0f else null,
            progress = when {
                manga.itemType == ItemType.Novel -> chapter.lastPageRead.toFloatOrNull()?.coerceIn(0f, 1f)
                manga.itemType == ItemType.Manga && totalPages > 0 -> ((position + 1f) / totalPages).coerceIn(0f, 1f)
                else -> null
            })
    }.take(24)
    val index = buildMap {
        mangas.sortedByDescending { it.favorite }.forEach { manga ->
            (listOf(manga.name) + manga.alternativeTitles).forEach { name ->
                val key = manga.itemType to normalizedHomeTitle(name)
                if (key !in this) put(key, manga)
            }
        }
    }
    val tmdbTracks = snapshot.tracks.mapNotNull { track ->
        if (track.syncId != TmdbTrackerSyncId) null else tmdbMediaOf(track)?.let { (type, id) -> track to TmdbSeed(type, id) }
    }
    val lastWatched = recent.associate { it.mangaId to it.updatedAt }
    return HomeLocalData(
        library = mangas.filter { it.favorite && it.parentId == null }.sortedByDescending { it.lastReadMillis }.map(::card),
        resume = resume,
        seed = recent.firstNotNullOfOrNull { byId[it.mangaId]?.let(::card) },
        titlesByTypeAndName = index,
        titlesBySourceUrl = mangas.associateBy { it.sourceId to it.link },
        sources = snapshot.sources.filter { it.isAdded && it.isActive && (settings.showNsfw || !it.isNsfw) },
        presets = settings.savedSearches.orEmpty(), hiddenTypes = hiddenTypes,
        tmdbSeeds = tmdbTracks.filter { (track, _) -> track.mangaId in byId }
            .sortedByDescending { (track, _) -> maxOf(track.updatedAt, lastWatched[track.mangaId] ?: 0L) }
            .map { it.second }.distinct().take(TmdbSeedLimit),
        tmdbTracked = tmdbTracks.mapTo(mutableSetOf()) { it.second.key },
    )
}

private const val TmdbSeedLimit = 8

internal fun normalizedHomeTitle(title: String): String = title.trim().lowercase().replace(Regex("\\s+"), " ")

internal fun buildHomeState(local: HomeLocalData, remote: List<HomeRemoteShelf>, settings: DbSettings): HomeState {
    val prefs = settings.home
    val limit = prefs.itemsPerShelf.coerceIn(6, 24)
    val libraryById = local.library.associateBy { it.mangaId }
    fun match(media: DiscoveryMedia): HomeCard {
        val manga = if (media.sourceId != null) local.titlesBySourceUrl[media.sourceId to media.sourceUrl.orEmpty()] else
            (listOf(media.title) + media.aliases).firstNotNullOfOrNull {
            local.titlesByTypeAndName[media.itemType to normalizedHomeTitle(it)]
        }
        return HomeCard(media, manga?.id, coverBytes = manga?.customCoverImage, completed = libraryById[manga?.id]?.completed == true)
    }
    fun visible(card: HomeCard) = card.media.itemType !in local.hiddenTypes &&
        (prefs.filter == HomeMediaFilter.All || prefs.filter == card.media.kind) && (!prefs.hideCompleted || !card.completed)
    fun sectionKind(section: HomeSection): HomeMediaFilter? = when (section) {
        HomeSection.PopularAnime -> HomeMediaFilter.Anime
        HomeSection.PopularManga -> HomeMediaFilter.Manga
        HomeSection.PopularNovels -> HomeMediaFilter.Novel
        HomeSection.PopularMovies -> HomeMediaFilter.Movie
        HomeSection.PopularSeries -> HomeMediaFilter.Series
        HomeSection.BecauseYouRead -> local.seed?.media?.kind
        else -> null
    }
    val remoteShelves = remote.filter { it.section !in prefs.hiddenSections &&
        (prefs.filter == HomeMediaFilter.All || sectionKind(it.section) == null || sectionKind(it.section) == prefs.filter) &&
        sectionKind(it.section)?.let { kind -> DiscoveryMedia("", "", kind).itemType !in local.hiddenTypes } != false &&
        (it.section != HomeSection.TmdbRecommended || (prefs.filter in TmdbFilters && ItemType.Anime !in local.hiddenTypes))
    }.map { shelf ->
        // Source feeds honour Browse's per-type "hide entries already in library" (re-applied on every settings/library change).
        fun hiddenInLibrary(card: HomeCard) = shelf.section == HomeSection.Sources && card.mangaId in libraryById &&
            settings.features.browse.hidesLibrary(card.media.itemType)
        // TMDB recommendations never suggest what the user already tracks or keeps in the library.
        fun known(card: HomeCard) = shelf.section == HomeSection.TmdbRecommended &&
            (card.media.key in local.tmdbTracked || card.mangaId in libraryById)
        HomeShelf(shelf.id, shelf.section, shelf.items.map(::match).filter { visible(it) && !hiddenInLibrary(it) && !known(it) }
            .distinctBy { it.mangaId?.let { id -> "library:$id" } ?: it.media.key }.take(limit),
            shelf.loading, shelf.issue, shelf.sourceName)
    }
    val seedGenres = local.seed?.media?.genres.orEmpty().mapTo(mutableSetOf()) { it.lowercase() }
    val recommendationCandidates = remote.flatMap { it.items }.map(::match) + local.library
    val recommended = recommendationCandidates.filter(::visible).filter { it.mangaId == null || it.mangaId != local.seed?.mangaId }
        .distinctBy { it.mangaId?.let { id -> "library:$id" } ?: it.media.key }
        .sortedByDescending { card -> card.media.genres.count { it.lowercase() in seedGenres } }.take(limit)
    val shelves = buildList {
        if (HomeSection.Continue !in prefs.hiddenSections) add(HomeShelf("continue", HomeSection.Continue, local.resume.filter(::visible).take(limit)))
        if (HomeSection.Recommended !in prefs.hiddenSections) add(HomeShelf("recommended", HomeSection.Recommended, recommended,
            loading = remote.any { it.loading } && recommended.isEmpty()))
        addAll(remoteShelves)
    }
    val featuredPool = if (prefs.featuredLibraryOnly) local.library else local.resume + recommended + remoteShelves.flatMap { it.cards }
    val featured = if (prefs.showFeatured) featuredPool.filter(::visible).distinctBy { it.mangaId?.let { id -> "library:$id" } ?: it.media.key }.take(7) else emptyList()
    return HomeState(prefs.forPresentation(), shelves, featured, local.seed?.media?.title, local.sources, local.presets,
        prefs.sourceFeeds, prefs.tmdbReadAccessToken.isNotBlank(), remote.any { it.loading })
}

private val TmdbFilters = setOf(HomeMediaFilter.All, HomeMediaFilter.Movie, HomeMediaFilter.Series)

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeViewModel.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

This is a derived multi-source screen. Keep independent shelf failures, deleted-history filtering and media-specific resume units separate from persisted visibility/customization.

The implementation below defines HomeViewModel, RequestKey, setActive, customize, search, query, openIssue, updatePreferences, setTmdbToken, addFeed and 6 further declarations.

Cross-chapter imports used by this file: SettingsStore, YokanRepository, AwaitedViewModelCleanup. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.home

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.discovery.*
import eu.friedcutlet.yokan.ui.navigation.AwaitedViewModelCleanup
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit

@OptIn(ExperimentalCoroutinesApi::class)
internal class HomeViewModel(
    private val repository: YokanRepository,
    private val settings: SettingsStore,
    private val discovery: DiscoveryService,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
    private val trackerScoreRanges: Map<Int, IntRange> = emptyMap(),
) : ViewModel(), AwaitedViewModelCleanup {
    private val _state = MutableStateFlow(HomeState(preferences = settings.db.value.home.forPresentation()))
    val state = _state.asStateFlow()
    private val active = MutableStateFlow(false)
    private val local = MutableStateFlow(HomeLocalData())
    private val remote = MutableStateFlow<List<HomeRemoteShelf>>(emptyList())
    private var requestKey: RequestKey? = null
    private var loadJob: Job? = null
    private val jobs = mutableListOf<Job>()
    private var generation = 0L

    private data class RequestKey(
        val aniList: Boolean, val tmdb: Boolean, val token: String, val adult: Boolean,
        val hidden: Set<HomeSection>, val featured: Boolean, val libraryOnly: Boolean,
        val seedTitle: String?, val seedKind: HomeMediaFilter?, val feeds: List<DbHomeSourceFeed>,
        val sourceRevisions: List<Pair<Long, Long>>, val presets: List<DbSavedSearch>,
        val sourcePreferences: List<DbSourcePreference>, val hiddenTypes: Set<eu.friedcutlet.yokan.domain.ItemType>,
        val tmdbSeeds: List<TmdbSeed>,
    )

    init {
        jobs += viewModelScope.launch {
            combine(active, repository.snapshots.distinctUntilChanged { old, new ->
                old.mangas === new.mangas && old.chapters === new.chapters && old.histories === new.histories &&
                    old.tracks === new.tracks && old.sources === new.sources && old.downloads === new.downloads &&
                    old.pageCache === new.pageCache && old.settings === new.settings
            }) { visible, snapshot -> visible to snapshot }.collectLatest { (visible, snapshot) ->
                if (visible) local.value = withContext(workDispatcher) { projectHomeLocal(snapshot, trackerScoreRanges) }
            }
        }
        jobs += viewModelScope.launch {
            combine(local, remote, settings.db) { data, shelves, db -> Triple(data, shelves, db) }
                .mapLatest { (data, shelves, db) -> withContext(workDispatcher) { buildHomeState(data, shelves, db) } }
                .collect { content -> _state.update { content.copy(customizeOpen = it.customizeOpen, searchOpen = it.searchOpen, searchQuery = it.searchQuery, openIssue = it.openIssue) } }
        }
        jobs += viewModelScope.launch {
            combine(active, local, settings.db) { visible, data, db -> Triple(visible, data, db) }
                .collect { (visible, data, db) ->
                    if (!visible) {
                        generation++
                        loadJob?.cancel()
                        requestKey = null
                    } else {
                        val prefs = db.home
                        val key = RequestKey(prefs.enableAniList, prefs.enableTmdb, prefs.tmdbReadAccessToken, db.showNsfw,
                            prefs.hiddenSections, prefs.showFeatured, prefs.featuredLibraryOnly, data.seed?.media?.title, data.seed?.media?.kind,
                            prefs.sourceFeeds.distinctBy { it.key }.take(8), data.sources.map { it.id to it.updatedAt }, data.presets,
                            db.sourcePreferences.orEmpty(), data.hiddenTypes,
                            // Sorted: re-watching only reorders seeds and must not reload every shelf.
                            data.tmdbSeeds.sortedBy { it.key })
                        if (key != requestKey) load(key, refresh = false)
                    }
                }
        }
    }

    fun setActive(value: Boolean) { active.value = value }
    fun customize(value: Boolean) { _state.update { it.copy(customizeOpen = value) } }
    fun search(value: Boolean) { _state.update { it.copy(searchOpen = value) } }
    fun query(value: String) { _state.update { it.copy(searchQuery = value) } }
    fun openIssue(value: DiscoveryIssue?) { _state.update { it.copy(openIssue = value) } }
    fun updatePreferences(transform: (DbHomePreferences) -> DbHomePreferences) = settings.updateDb { it.copy(features = it.features.copy(home = transform(it.home))) }
    fun setTmdbToken(value: String) = updatePreferences { it.copy(tmdbReadAccessToken = value.trim().removePrefix("Bearer ")) }
    fun addFeed(feed: DbHomeSourceFeed) = updatePreferences {
        it.copy(sourceFeeds = (it.sourceFeeds + feed).distinctBy(DbHomeSourceFeed::key).take(8))
    }
    fun removeFeed(key: String) = updatePreferences { it.copy(sourceFeeds = it.sourceFeeds.filterNot { feed -> feed.key == key }) }
    fun moveFeed(key: String, delta: Int) = updatePreferences { prefs ->
        val feeds = prefs.sourceFeeds.toMutableList()
        val from = feeds.indexOfFirst { it.key == key }
        if (from >= 0) feeds.add((from + delta).coerceIn(0, feeds.lastIndex), feeds.removeAt(from))
        prefs.copy(sourceFeeds = feeds)
    }
    fun refresh() { requestKey?.let { load(it, refresh = true) } }

    private fun load(key: RequestKey, refresh: Boolean) {
        val oldKey = requestKey
        requestKey = key
        generation++
        val revision = generation
        loadJob?.cancel()
        val requests = buildList<Pair<HomeRemoteShelf, suspend () -> List<DiscoveryMedia>>> {
            fun popularity(kind: HomeMediaFilter, section: HomeSection) {
                if (DiscoveryMedia("", "", kind).itemType in key.hiddenTypes) return
                if (section !in key.hidden || (key.featured && !key.libraryOnly) || HomeSection.Recommended !in key.hidden) {
                    add(HomeRemoteShelf(section.name, section) to { discovery.popular(kind, key.token, key.adult, refresh) })
                }
            }
            if (key.aniList) {
                popularity(HomeMediaFilter.Anime, HomeSection.PopularAnime)
                popularity(HomeMediaFilter.Manga, HomeSection.PopularManga)
                popularity(HomeMediaFilter.Novel, HomeSection.PopularNovels)
                if (key.seedTitle != null && key.seedKind != null && HomeSection.BecauseYouRead !in key.hidden) {
                    add(HomeRemoteShelf("because", HomeSection.BecauseYouRead) to {
                        discovery.recommendations(key.seedTitle, key.seedKind, key.adult, refresh)
                    })
                }
            }
            if (key.tmdb) {
                if (key.tmdbSeeds.isNotEmpty() && HomeSection.TmdbRecommended !in key.hidden &&
                    eu.friedcutlet.yokan.domain.ItemType.Anime !in key.hiddenTypes) {
                    add(HomeRemoteShelf("tmdb-recommended", HomeSection.TmdbRecommended) to {
                        discovery.tmdbRecommendations(key.tmdbSeeds, key.token, key.adult, refresh)
                    })
                }
                popularity(HomeMediaFilter.Movie, HomeSection.PopularMovies)
                popularity(HomeMediaFilter.Series, HomeSection.PopularSeries)
            }
            if (HomeSection.Sources !in key.hidden) key.feeds.forEach { feed ->
                val source = local.value.sources.firstOrNull { it.id == feed.sourceId }
                val name = source?.name.orEmpty() + key.presets.firstOrNull { it.id == feed.presetId }?.name?.let { " · $it" }.orEmpty()
                add(HomeRemoteShelf("feed:${feed.key}", HomeSection.Sources, sourceName = name) to { discovery.sourceFeed(feed, key.adult, refresh) })
            }
        }
        val keep = oldKey != null && oldKey.adult == key.adult && oldKey.token == key.token
        val previous = remote.value.associateBy { it.id }
        remote.value = requests.map { (shelf, _) -> shelf.copy(
            items = if (keep && (shelf.id != "because" || oldKey.seedTitle == key.seedTitle)) previous[shelf.id]?.items.orEmpty() else emptyList(), loading = true) }
        loadJob = viewModelScope.launch {
            val gate = Semaphore(3)
            supervisorScope {
                requests.map { (shelf, request) -> launch {
                    val result = try {
                        Result.success(gate.withPermit { request() })
                    } catch (timeout: TimeoutCancellationException) { Result.failure(timeout) }
                    catch (cancel: CancellationException) { throw cancel }
                    catch (failure: Throwable) { Result.failure(failure) }
                    ensureActive()
                    if (revision != generation) return@launch
                    remote.update { rows -> rows.map { row -> if (row.id != shelf.id) row else result.fold(
                        { row.copy(items = it, loading = false, issue = null) },
                        { row.copy(loading = false, issue = (it as? DiscoveryException)?.issue ?: DiscoveryIssue.Network) },
                    ) } }
                } }.joinAll()
            }
        }
    }

    override suspend fun awaitCleanup() {
        generation++
        // Stop producers first, then join every request generation, including cancelled loads
        // still releasing a source-runtime lease in a non-cancellable finalizer.
        jobs.forEach { it.cancel() }
        jobs.joinAll()
        val owned = viewModelScope.coroutineContext[Job]?.children?.toList().orEmpty()
        owned.forEach { it.cancel() }
        owned.joinAll()
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeRoute.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines HomeRoute.

Cross-chapter imports used by this file: YokanRuntime, HomeMediaFilter, ItemType, RemoteManga, Navigator, Route. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.home

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.HomeMediaFilter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
import eu.friedcutlet.yokan.services.discovery.DiscoveryIssue

@Composable
internal fun HomeRoute(nav: Navigator) {
    val repository = YokanRuntime.repository
    val services = YokanRuntime.services
    val vm = viewModel { HomeViewModel(repository, YokanRuntime.settings, services.discovery,
        trackerScoreRanges = services.trackers.associate { tracker -> tracker.scoreValue().let { tracker.syncId to (it.first..it.second) } }) }
    val state by vm.state.collectAsStateWithLifecycle()
    val backStack by nav.backStack.collectAsStateWithLifecycle()
    val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateFlow.collectAsStateWithLifecycle(minActiveState = Lifecycle.State.CREATED)
    val visible = backStack.isEmpty() && lifecycleState.isAtLeast(Lifecycle.State.RESUMED)
    val scope = rememberCoroutineScope()
    DisposableEffect(vm, visible) {
        vm.setActive(visible)
        onDispose { vm.setActive(false) }
    }
    HomeScreen(
        state = if (visible) state else state.copy(preferences = state.preferences.copy(autoAdvanceFeatured = false)),
        onRefresh = vm::refresh,
        onCustomize = vm::customize,
        onSearch = vm::search,
        onQuery = vm::query,
        onSearchSubmit = {
            val type = when (state.preferences.filter) {
                HomeMediaFilter.Manga -> ItemType.Manga
                HomeMediaFilter.Novel -> ItemType.Novel
                HomeMediaFilter.Anime, HomeMediaFilter.Movie, HomeMediaFilter.Series -> ItemType.Anime
                HomeMediaFilter.All -> nav.itemType.value
            }
            vm.search(false)
            nav.navigate(Route.GlobalSearch(type, state.searchQuery.trim()))
        },
        onPreferences = vm::updatePreferences,
        onToken = vm::setTmdbToken,
        onAddFeed = vm::addFeed,
        onRemoveFeed = vm::removeFeed,
        onMoveFeed = vm::moveFeed,
        onBrowse = { nav.select(eu.friedcutlet.yokan.ui.navigation.NavSection.Browse) },
        onDismissIssue = { vm.openIssue(null) },
        onOpen = { card ->
            when {
                card.mangaId != null -> nav.navigate(if (card.chapterId != null) Route.Reader(card.mangaId, card.chapterId) else Route.Detail(card.mangaId))
                card.media.sourceId != null && card.media.sourceUrl != null -> scope.launch {
                    try {
                        val source = repository.source(card.media.sourceId)
                        if (source == null || !source.isActive || !source.isAdded) {
                            vm.openIssue(DiscoveryIssue.SourceUnavailable)
                            return@launch
                        }
                        val manga = withContext(Dispatchers.Default) {
                            repository.upsertRemoteTitle(source, RemoteManga(card.media.title, card.media.sourceUrl, card.media.coverUrl))
                        }
                        nav.navigate(Route.Detail(manga.id))
                    } catch (cancel: CancellationException) { throw cancel }
                    catch (_: Exception) {
                        vm.openIssue(DiscoveryIssue.SourceUnavailable)
                    }
                }
                else -> nav.navigate(Route.GlobalSearch(card.media.itemType, card.media.title))
            }
        },
    )
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeScreen.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines HomeScreen, HomeShelfContent, HomePoster, HomeFeatured, formatHomeRating, homeActionLabel, homeProgressLabel, homeFilterLabel, homeSectionLabel, homeIssueLabel.

Cross-chapter imports used by this file: CoverImage, EmptyState, YokanScaffold. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.home

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Explore
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.MotionDurationScale
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.discovery.DiscoveryIssue
import eu.friedcutlet.yokan.ui.components.CoverImage
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.theme.LocalEinkMode
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold

@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun HomeScreen(
    state: HomeState,
    onOpen: (HomeCard) -> Unit,
    onRefresh: () -> Unit,
    onCustomize: (Boolean) -> Unit,
    onSearch: (Boolean) -> Unit,
    onQuery: (String) -> Unit,
    onSearchSubmit: () -> Unit,
    onPreferences: ((DbHomePreferences) -> DbHomePreferences) -> Unit,
    onToken: (String) -> Unit,
    onAddFeed: (DbHomeSourceFeed) -> Unit,
    onRemoveFeed: (String) -> Unit,
    onMoveFeed: (String, Int) -> Unit,
    onBrowse: () -> Unit,
    onDismissIssue: () -> Unit = {},
) {
    state.openIssue?.let { issue -> AlertDialog(onDismissRequest = onDismissIssue,
        text = { Text(homeIssueLabel(issue)) },
        confirmButton = { TextButton(onClick = onDismissIssue) { Text(stringResource(Res.string.action_cancel)) } }) }
    if (state.customizeOpen) HomeCustomizeSheet(state, onPreferences, onToken, onAddFeed, onRemoveFeed, onMoveFeed) { onCustomize(false) }
    if (state.searchOpen) AlertDialog(
        onDismissRequest = { onSearch(false) },
        title = { Text(stringResource(Res.string.home_search)) },
        text = { OutlinedTextField(value = state.searchQuery, onValueChange = onQuery, singleLine = true,
            label = { Text(stringResource(Res.string.home_search_query)) }, modifier = Modifier.fillMaxWidth()) },
        confirmButton = { TextButton(onClick = onSearchSubmit, enabled = state.searchQuery.isNotBlank()) { Text(stringResource(Res.string.home_find_sources)) } },
        dismissButton = { TextButton(onClick = { onSearch(false) }) { Text(stringResource(Res.string.action_cancel)) } },
    )
    Scaffold(topBar = {
        TopAppBar(title = { Text(stringResource(Res.string.nav_home)) }, actions = {
            IconButton(onClick = { onSearch(true) }) { Icon(Icons.Filled.Search, stringResource(Res.string.home_search)) }
            IconButton(onClick = onRefresh, enabled = !state.refreshing) { Icon(Icons.Filled.Refresh, stringResource(Res.string.home_refresh)) }
            IconButton(onClick = { onCustomize(true) }) { Icon(Icons.Filled.Tune, stringResource(Res.string.home_customize)) }
        })
    }) { padding ->
        BoxWithConstraints(Modifier.fillMaxSize().padding(padding)) {
            val wide = maxWidth >= 840.dp
            val cardWidth = if (wide) 172.dp else 136.dp
            LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(24.dp)) {
                item(key = "filters", contentType = "filters") {
                    LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        items(HomeMediaFilter.entries, key = { it.name }) { filter ->
                            FilterChip(selected = state.preferences.filter == filter,
                                onClick = { onPreferences { it.copy(filter = filter) } }, label = { Text(homeFilterLabel(filter)) })
                        }
                    }
                }
                if (state.featured.isNotEmpty()) item(key = "featured", contentType = "featured") {
                    HomeFeatured(state.featured, state.preferences.autoAdvanceFeatured, wide, onOpen)
                }
                items(state.shelves, key = { it.id }, contentType = { "shelf" }) { shelf ->
                    if (shelf.cards.isNotEmpty() || shelf.loading || shelf.issue != null || shelf.section == HomeSection.Continue) {
                        HomeShelfContent(shelf, state.seedTitle, cardWidth, onOpen, onRefresh) { onCustomize(true) }
                    }
                }
                if (state.feeds.isEmpty() && HomeSection.Sources !in state.preferences.hiddenSections) item(key = "sources-empty", contentType = "empty") {
                    Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        Text(stringResource(Res.string.home_source_feeds), style = MaterialTheme.typography.titleLarge)
                        Text(stringResource(Res.string.home_sources_hint), color = MaterialTheme.colorScheme.onSurfaceVariant)
                        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                            OutlinedButton(onClick = { onCustomize(true) }) { Text(stringResource(Res.string.home_add_feed)) }
                            TextButton(onClick = onBrowse) { Text(stringResource(Res.string.home_browse)) }
                        }
                    }
                }
                if (state.shelves.none { it.loading || it.cards.isNotEmpty() || it.issue != null } && state.featured.isEmpty()) item(key = "empty", contentType = "empty") {
                    EmptyState(icon = Icons.Filled.Explore, title = stringResource(Res.string.home_empty), subtitle = stringResource(Res.string.home_empty_hint),
                        modifier = Modifier.fillMaxWidth().padding(24.dp))
                }
                if (state.preferences.enableTmdb) item(key = "tmdb-credit", contentType = "credit") {
                    Text(stringResource(Res.string.home_tmdb_credit), style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 20.dp))
                }
            }
        }
    }
}

@Composable
private fun HomeShelfContent(shelf: HomeShelf, seed: String?, cardWidth: androidx.compose.ui.unit.Dp,
    onOpen: (HomeCard) -> Unit, onRefresh: () -> Unit, onCustomize: () -> Unit) {
    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
        Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(if (shelf.section == HomeSection.BecauseYouRead && seed != null) stringResource(Res.string.home_because_title, seed)
                else shelf.sourceName?.takeIf { it.isNotBlank() } ?: homeSectionLabel(shelf.section),
                style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
            if (shelf.loading) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp)
        }
        if (shelf.issue != null) Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(homeIssueLabel(shelf.issue), style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f))
            TextButton(onClick = if (shelf.issue == DiscoveryIssue.Credentials || shelf.issue == DiscoveryIssue.PresetChanged) onCustomize else onRefresh) {
                Text(stringResource(if (shelf.issue == DiscoveryIssue.Credentials || shelf.issue == DiscoveryIssue.PresetChanged) Res.string.home_customize else Res.string.home_retry))
            }
        }
        if (shelf.cards.isNotEmpty()) LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
            items(shelf.cards, key = { it.media.key }, contentType = { "media" }) { card -> HomePoster(card, cardWidth) { onOpen(card) } }
        } else if (shelf.section == HomeSection.Continue) Text(stringResource(Res.string.home_continue_empty),
            modifier = Modifier.padding(horizontal = 20.dp), color = MaterialTheme.colorScheme.onSurfaceVariant)
        else if (shelf.loading) LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) {
            items(4, key = { "placeholder:$it" }) {
                Box(Modifier.width(cardWidth).aspectRatio(0.68f).clip(MaterialTheme.shapes.medium).background(MaterialTheme.colorScheme.surfaceContainerHighest))
            }
        }
    }
}

@Composable
private fun HomePoster(card: HomeCard, width: androidx.compose.ui.unit.Dp, onOpen: () -> Unit) {
    Surface(onClick = onOpen, color = Color.Transparent, shape = MaterialTheme.shapes.medium, modifier = Modifier.width(width)) {
        Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
            Box {
                CoverImage(card.coverBytes ?: card.media.coverUrl, card.media.title,
                    Modifier.fillMaxWidth().aspectRatio(0.68f), fallbackInitials = card.media.title.take(2))
                card.media.rating?.let { rating ->
                    Surface(color = MaterialTheme.colorScheme.inverseSurface, shape = RoundedCornerShape(6.dp),
                        modifier = Modifier.align(Alignment.BottomEnd).padding(6.dp)) {
                        Row(Modifier.padding(horizontal = 6.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) {
                            Icon(Icons.Filled.Star, null, Modifier.size(14.dp))
                            Text(formatHomeRating(rating), style = MaterialTheme.typography.labelMedium)
                        }
                    }
                }
            }
            Text(card.media.title, style = MaterialTheme.typography.titleSmall, maxLines = 2, overflow = TextOverflow.Ellipsis)
            Text(homeFilterLabel(card.media.kind), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
            if (card.chapterId != null) {
                Text(card.chapterName.orEmpty(), style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis)
                Text(homeProgressLabel(card), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                card.progress?.let { LinearProgressIndicator(progress = { it }, modifier = Modifier.fillMaxWidth()) }
            }
        }
    }
}

@Composable
private fun HomeFeatured(cards: List<HomeCard>, autoAdvance: Boolean, wide: Boolean, onOpen: (HomeCard) -> Unit) {
    val pager = rememberPagerState(pageCount = { cards.size })
    val scope = rememberCoroutineScope()
    val eink = LocalEinkMode.current
    LaunchedEffect(cards.map { it.media.key }, autoAdvance, eink) {
        if (autoAdvance && !eink && cards.size > 1) while (true) {
            delay(7_000)
            if (!pager.isScrollInProgress && (coroutineContext[MotionDurationScale]?.scaleFactor ?: 1f) > 0f)
                pager.animateScrollToPage((pager.currentPage + 1) % cards.size)
        }
    }
    Column(Modifier.padding(horizontal = 20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
        HorizontalPager(state = pager, key = { cards[it].media.key }) { page ->
            val card = cards[page]
            Box(Modifier.fillMaxWidth().height(if (wide) 340.dp else 320.dp).clip(MaterialTheme.shapes.large)
                .background(MaterialTheme.colorScheme.surfaceContainerHighest)) {
                CoverImage(card.media.backdropUrl ?: card.coverBytes ?: card.media.coverUrl, null,
                    Modifier.matchParentSize(), fallbackInitials = card.media.title.take(2))
                Box(Modifier.matchParentSize().background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.12f), Color.Black.copy(alpha = 0.94f)))))
                Column(Modifier.align(Alignment.BottomStart).padding(24.dp).widthIn(max = 680.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(card.media.title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.SemiBold,
                        color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis)
                    Text(homeFilterLabel(card.media.kind), style = MaterialTheme.typography.labelLarge, color = Color.White)
                    if (card.media.description.isNotBlank()) Text(card.media.description, style = MaterialTheme.typography.bodyMedium,
                        color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis)
                    Button(onClick = { onOpen(card) }) { Text(homeActionLabel(card)) }
                }
            }
        }
        if (cards.size > 1) Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center) {
            IconButton(onClick = { scope.launch { pager.animateScrollToPage((pager.currentPage - 1 + cards.size) % cards.size) } }) {
                Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(Res.string.home_previous))
            }
            Text(stringResource(Res.string.home_featured_page, pager.currentPage + 1, cards.size), style = MaterialTheme.typography.labelLarge)
            IconButton(onClick = { scope.launch { pager.animateScrollToPage((pager.currentPage + 1) % cards.size) } }) {
                Icon(Icons.AutoMirrored.Filled.ArrowForward, stringResource(Res.string.home_next))
            }
        }
    }
}

internal fun formatHomeRating(rating: Double): String {
    val tenths = (rating.coerceIn(0.0, 10.0) * 10).roundToInt()
    return "${tenths / 10}.${tenths % 10}"
}

@Composable
private fun homeActionLabel(card: HomeCard): String = stringResource(when {
    card.chapterId != null -> Res.string.home_resume
    card.mangaId != null || card.media.sourceId != null -> Res.string.home_open_title
    else -> Res.string.home_find_sources
})

@Composable
private fun homeProgressLabel(card: HomeCard): String = if (card.media.kind == HomeMediaFilter.Anime) {
    val seconds = card.position / 1_000
    stringResource(Res.string.home_video_position, "${seconds / 60}:${(seconds % 60).toString().padStart(2, '0')}")
} else if (card.media.kind == HomeMediaFilter.Novel) stringResource(Res.string.home_novel_position, "${((card.novelProgress ?: 0f) * 100).toInt()}%")
else stringResource(Res.string.home_page_position, card.position + 1)

@Composable
internal fun homeFilterLabel(filter: HomeMediaFilter): String = stringResource(when (filter) {
    HomeMediaFilter.All -> Res.string.home_all
    HomeMediaFilter.Anime -> Res.string.home_anime
    HomeMediaFilter.Manga -> Res.string.home_manga
    HomeMediaFilter.Novel -> Res.string.home_novels
    HomeMediaFilter.Movie -> Res.string.home_movies
    HomeMediaFilter.Series -> Res.string.home_series
})

@Composable
internal fun homeSectionLabel(section: HomeSection): String = stringResource(when (section) {
    HomeSection.Continue -> Res.string.home_continue
    HomeSection.Recommended -> Res.string.home_recommended
    HomeSection.BecauseYouRead -> Res.string.home_because
    HomeSection.PopularAnime -> Res.string.home_popular_anime
    HomeSection.PopularManga -> Res.string.home_popular_manga
    HomeSection.PopularNovels -> Res.string.home_popular_novels
    HomeSection.PopularMovies -> Res.string.home_popular_movies
    HomeSection.PopularSeries -> Res.string.home_popular_series
    HomeSection.Sources -> Res.string.home_source_feeds
    HomeSection.TmdbRecommended -> Res.string.home_tmdb_recommended
})

@Composable
private fun homeIssueLabel(issue: DiscoveryIssue): String = stringResource(when (issue) {
    DiscoveryIssue.Credentials -> Res.string.home_credentials_error
    DiscoveryIssue.RateLimited -> Res.string.home_rate_error
    DiscoveryIssue.PresetChanged -> Res.string.home_preset_error
    DiscoveryIssue.SourceUnavailable -> Res.string.home_source_error
    DiscoveryIssue.Network -> Res.string.home_network_error
})

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeCustomizeSheet.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines HomeCustomizeSheet, feedLabel.

Cross-chapter imports used by this file: SwitchTile. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.home

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDownward
import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import eu.friedcutlet.yokan.ui.screens.settings.SwitchTile
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun HomeCustomizeSheet(
    state: HomeState,
    onPreferences: ((DbHomePreferences) -> DbHomePreferences) -> Unit,
    onToken: (String) -> Unit,
    onAddFeed: (DbHomeSourceFeed) -> Unit,
    onRemoveFeed: (String) -> Unit,
    onMoveFeed: (String, Int) -> Unit,
    onDismiss: () -> Unit,
) {
    var tokenDraft by remember { mutableStateOf("") }
    var sourceMenuOpen by remember { mutableStateOf(false) }
    var selectedSourceId by remember { mutableStateOf(state.sources.firstOrNull()?.id) }
    var selectedFeed by remember(selectedSourceId) { mutableStateOf(selectedSourceId?.let { DbHomeSourceFeed(it) }) }
    val source = state.sources.firstOrNull { it.id == selectedSourceId }
    ModalBottomSheet(onDismissRequest = onDismiss, modifier = Modifier.compactSheetWidth()) {
        LazyColumn(Modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 32.dp)) {
            item(key = "title") {
                Text(stringResource(Res.string.home_customize), style = MaterialTheme.typography.headlineSmall,
                    modifier = Modifier.padding(horizontal = 24.dp, vertical = 12.dp))
            }
            item(key = "featured") { SwitchTile(stringResource(Res.string.home_show_featured), null, state.preferences.showFeatured,
                { value -> onPreferences { it.copy(showFeatured = value) } }) }
            item(key = "motion") { SwitchTile(stringResource(Res.string.home_auto_advance), stringResource(Res.string.home_auto_advance_hint), state.preferences.autoAdvanceFeatured,
                { value -> onPreferences { it.copy(autoAdvanceFeatured = value) } }, enabled = state.preferences.showFeatured) }
            item(key = "library-hero") { SwitchTile(stringResource(Res.string.home_library_featured), null, state.preferences.featuredLibraryOnly,
                { value -> onPreferences { it.copy(featuredLibraryOnly = value) } }, enabled = state.preferences.showFeatured) }
            item(key = "completed") { SwitchTile(stringResource(Res.string.home_hide_completed), null, state.preferences.hideCompleted,
                { value -> onPreferences { it.copy(hideCompleted = value) } }) }
            item(key = "count") {
                Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) {
                    Text(stringResource(Res.string.home_shelf_size), style = MaterialTheme.typography.titleMedium)
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        listOf(6, 12, 24).forEach { count -> FilterChip(selected = state.preferences.itemsPerShelf == count,
                            onClick = { onPreferences { it.copy(itemsPerShelf = count) } }, label = { Text(count.toString()) }) }
                    }
                }
            }
            item(key = "anilist") { SwitchTile(stringResource(Res.string.home_enable_anilist), null, state.preferences.enableAniList,
                { value -> onPreferences { it.copy(enableAniList = value) } }) }
            item(key = "tmdb") { SwitchTile(stringResource(Res.string.home_enable_tmdb), null, state.preferences.enableTmdb,
                { value -> onPreferences { it.copy(enableTmdb = value) } }) }
            if (state.preferences.enableTmdb) item(key = "token") {
                Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(stringResource(Res.string.home_tmdb_token_hint), style = MaterialTheme.typography.bodyMedium)
                    OutlinedTextField(value = tokenDraft, onValueChange = { tokenDraft = it }, singleLine = true,
                        label = { Text(stringResource(Res.string.home_tmdb_token)) }, visualTransformation = PasswordVisualTransformation(),
                        modifier = Modifier.fillMaxWidth())
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        Button(enabled = tokenDraft.isNotBlank(), onClick = { onToken(tokenDraft); tokenDraft = "" }) { Text(stringResource(Res.string.home_save_token)) }
                        if (state.tmdbConfigured) TextButton(onClick = { onToken(""); tokenDraft = "" }) { Text(stringResource(Res.string.home_remove_token)) }
                    }
                    if (state.tmdbConfigured) Text(stringResource(Res.string.home_token_saved), style = MaterialTheme.typography.labelLarge)
                }
            }
            item(key = "sections-heading") { Text(stringResource(Res.string.home_visible_sections), style = MaterialTheme.typography.titleLarge,
                modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp)) }
            items(HomeSection.entries, key = { "section:${it.name}" }, contentType = { "switch" }) { section ->
                SwitchTile(homeSectionLabel(section), null, section !in state.preferences.hiddenSections, { visible ->
                    onPreferences { prefs -> prefs.copy(hiddenSections = if (visible) prefs.hiddenSections - section else prefs.hiddenSections + section) }
                })
            }
            item(key = "feeds-heading") { Text(stringResource(Res.string.home_source_feeds), style = MaterialTheme.typography.titleLarge,
                modifier = Modifier.padding(horizontal = 24.dp, vertical = 16.dp)) }
            items(state.feeds, key = { "feed:${it.key}" }, contentType = { "feed" }) { feed ->
                val name = state.sources.firstOrNull { it.id == feed.sourceId }?.name ?: stringResource(Res.string.home_unavailable_source)
                Column(Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) {
                    Text(name, style = MaterialTheme.typography.titleMedium)
                    Text(feedLabel(feed, state.presets), color = MaterialTheme.colorScheme.onSurfaceVariant)
                    Row {
                        IconButton(onClick = { onMoveFeed(feed.key, -1) }, enabled = state.feeds.firstOrNull()?.key != feed.key) {
                            Icon(Icons.Filled.ArrowUpward, stringResource(Res.string.home_move_up))
                        }
                        IconButton(onClick = { onMoveFeed(feed.key, 1) }, enabled = state.feeds.lastOrNull()?.key != feed.key) {
                            Icon(Icons.Filled.ArrowDownward, stringResource(Res.string.home_move_down))
                        }
                        IconButton(onClick = { onRemoveFeed(feed.key) }) { Icon(Icons.Filled.Delete, stringResource(Res.string.home_remove_feed)) }
                    }
                }
            }
            item(key = "add-feed") {
                Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Text(stringResource(Res.string.home_add_feed), style = MaterialTheme.typography.titleMedium)
                    if (state.sources.isEmpty()) Text(stringResource(Res.string.home_install_sources)) else {
                        Box {
                            OutlinedButton(onClick = { sourceMenuOpen = true }) { Text(source?.name ?: stringResource(Res.string.home_select_source)) }
                            DropdownMenu(expanded = sourceMenuOpen, onDismissRequest = { sourceMenuOpen = false }, modifier = Modifier.heightIn(max = 320.dp)) {
                                state.sources.forEach { candidate -> DropdownMenuItem(text = { Text(candidate.name, maxLines = 1, overflow = TextOverflow.Ellipsis) },
                                    onClick = { selectedSourceId = candidate.id; sourceMenuOpen = false }) }
                            }
                        }
                        source?.let { selected ->
                            val options = listOf(DbHomeSourceFeed(selected.id)) +
                                (if (selected.supportLatest == true) listOf(DbHomeSourceFeed(selected.id, HomeFeedMode.Latest)) else emptyList()) +
                                state.presets.filter { it.sourceId == selected.id }.map { DbHomeSourceFeed(selected.id, HomeFeedMode.SavedSearch, it.id) }
                            options.forEach { option ->
                                Row(Modifier.fillMaxWidth().padding(vertical = 4.dp).clickable { selectedFeed = option }, verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
                                    RadioButton(selected = selectedFeed == option, onClick = { selectedFeed = option })
                                    Text(feedLabel(option, state.presets), modifier = Modifier.weight(1f))
                                }
                            }
                            Button(enabled = state.feeds.size < 8 && selectedFeed != null && state.feeds.none { it == selectedFeed },
                                onClick = { selectedFeed?.let(onAddFeed) }) { Text(stringResource(Res.string.home_add_feed)) }
                        }
                        Text(stringResource(Res.string.home_feed_limit), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                }
            }
            item(key = "done") { TextButton(onClick = onDismiss, modifier = Modifier.padding(horizontal = 16.dp)) { Text(stringResource(Res.string.home_done)) } }
        }
    }
}

@Composable
private fun feedLabel(feed: DbHomeSourceFeed, presets: List<DbSavedSearch>): String = when (feed.mode) {
    HomeFeedMode.Popular -> stringResource(Res.string.home_feed_popular)
    HomeFeedMode.Latest -> stringResource(Res.string.home_feed_latest)
    HomeFeedMode.SavedSearch -> presets.firstOrNull { it.id == feed.presetId }?.name ?: stringResource(Res.string.home_feed_saved)
}

Check your understanding

Give Home one failed remote shelf and healthy local continue entries. Verify the latter stay visible and opening one resumes the correct media/position. [chapter-content-end]: #

Step 5: finish discovery screens

Implement recommendations, source-related titles, sequels and watch order with independent load/error/retry states. Open/ingest selected results through repository identity rules. Avoid duplicating a title every time a recommendation card is opened.

Follow the code

These screens consume distinct service/source relations and maintain independent request/error state. Selecting a card must resolve or ingest the target through repository identity rules instead of inserting another row on each open. SourceRelatedViewModel uses the source relation contract, while metadata-provider recommendations use their provider IDs. A label alone is not a new title identity.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/SourceRelatedViewModel.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/SourceRelatedScreen.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/RecommendationsScreen.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/SequelsScreen.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/WatchOrderScreen.kt

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/SourceRelatedViewModel.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines SourceRelatedState, SourceRelatedViewModel, refresh, open, opened.

Cross-chapter imports used by this file: YokanRepository, YokanDatabase, ExtensionRuntimeFactory, RemoteManga, SourceRelatedGroup. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.discovery

import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceRelatedGroup
import eu.friedcutlet.yokan.services.extensions.withSourceRuntime
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@Immutable
internal data class SourceRelatedState(
    val title: String = "",
    val loading: Boolean = false,
    val supported: Boolean? = null,
    val groups: List<SourceRelatedGroup> = emptyList(),
    val error: String? = null,
    val sourceId: Long? = null,
    val parentUrl: String? = null,
    val openedTitleId: Long? = null,
    val opening: Boolean = false,
)

internal class SourceRelatedViewModel(
    private val mangaId: Long,
    private val repository: YokanRepository,
    private val database: YokanDatabase,
    private val runtimes: ExtensionRuntimeFactory,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    private val _state = MutableStateFlow(SourceRelatedState(loading = true))
    val state = _state.asStateFlow()
    private var loadJob: Job? = null

    init { refresh() }

    fun refresh() {
        if (loadJob?.isActive == true) return
        loadJob = viewModelScope.launch {
            _state.update { it.copy(loading = true, error = null) }
            catchingNonCancellation {
                val manga = withContext(workDispatcher) { repository.manga(mangaId) }
                val source = manga?.sourceId?.let { withContext(workDispatcher) { repository.source(it) } }
                if (manga == null || source == null || manga.isLocalArchive || manga.link.isBlank()) {
                    _state.update { it.copy(title = manga?.name.orEmpty(), supported = false, sourceId = null, groups = emptyList()) }
                } else {
                    val result = runtimes.withSourceRuntime(database, source.id) { it.related(manga.link) }
                    // The source/title may have been removed or rebound during the request.
                    val current = withContext(workDispatcher) { repository.manga(mangaId) }
                    check(current != null && current.sourceId == source.id && current.link == manga.link && repository.source(source.id) != null) {
                        "The source or title changed. Open related entries again."
                    }
                    _state.update { it.copy(title = current.name, supported = result.supported, groups = result.groups, sourceId = source.id, parentUrl = manga.link) }
                }
            }.onFailure { error -> _state.update { it.copy(error = error.message ?: "Unable to load related entries") } }
            _state.update { it.copy(loading = false) }
        }
    }

    fun open(item: RemoteManga) {
        val current = _state.value
        if (current.opening || current.openedTitleId != null || current.groups.none { item in it.items }) return
        val sourceId = current.sourceId ?: return
        _state.update { it.copy(opening = true) }
        // One transaction validates ownership and resolves an existing entry without changing favourites.
        viewModelScope.launch {
            catchingNonCancellation { withContext(workDispatcher) { database.batch {
                    val source = repository.source(sourceId) ?: error("The source was removed. Reload related entries.")
                    val parent = repository.manga(mangaId)
                    check(parent != null && parent.sourceId == sourceId && parent.link == current.parentUrl) { "The title changed. Reload related entries." }
                    repository.upsertRemoteTitle(source, item).id
                } }
            }.onSuccess { id -> _state.update { it.copy(openedTitleId = id) } }
                .onFailure { error -> _state.update { it.copy(error = error.message ?: "Unable to open related entry") } }
            _state.update { it.copy(opening = false) }
        }
    }

    fun opened() { _state.update { it.copy(openedTitleId = null) } }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/SourceRelatedScreen.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines SourceRelatedRoute, SourceRelatedScreen.

Cross-chapter imports used by this file: YokanRuntime, RemoteManga, CoverImage, EmptyState, RouteScaffold, Navigator. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.discovery

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.ui.components.CoverImage
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*

@Composable
internal fun SourceRelatedRoute(route: Route.SourceRelated, nav: Navigator) {
    val vm = viewModel { SourceRelatedViewModel(route.mangaId, YokanRuntime.repository,
        YokanRuntime.database, YokanRuntime.services.extensionRuntimeFactory) }
    val state by vm.state.collectAsStateWithLifecycle()
    LaunchedEffect(state.openedTitleId) {
        state.openedTitleId?.let { id -> vm.opened(); nav.navigate(Route.Detail(id)) }
    }
    SourceRelatedScreen(state, onOpen = vm::open, onRefresh = vm::refresh, onBack = nav::back)
}

@Composable
internal fun SourceRelatedScreen(
    state: SourceRelatedState,
    onOpen: (RemoteManga) -> Unit,
    onRefresh: () -> Unit,
    onBack: () -> Unit,
) {
    RouteScaffold(stringResource(Res.string.source_related_entries), onBack, actions = {
        IconButton(onClick = onRefresh, enabled = !state.loading && !state.opening) {
            Icon(Icons.Filled.Refresh, stringResource(Res.string.source_related_reload))
        }
    }) {
        if (state.title.isNotBlank()) item(key = "title", contentType = "title") {
            Text(state.title, style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
        }
        if (state.loading) item(key = "loading", contentType = "loading") {
            Box(Modifier.fillMaxWidth().padding(vertical = 24.dp), contentAlignment = Alignment.Center) {
                CircularProgressIndicator()
            }
        }
        if (state.error != null) item(key = "error", contentType = "error") {
            Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                Text(stringResource(Res.string.source_related_failed), style = MaterialTheme.typography.titleMedium)
                Text(state.error, color = MaterialTheme.colorScheme.error)
                TextButton(onClick = onRefresh, enabled = !state.loading) { Text(stringResource(Res.string.source_related_retry)) }
            }
        }
        if (!state.loading && state.error == null && state.groups.isEmpty()) item(key = "empty", contentType = "empty") {
            EmptyState(
                icon = Icons.Filled.AccountTree,
                title = stringResource(if (state.supported == false) Res.string.source_related_unavailable else Res.string.source_related_empty),
                subtitle = if (state.supported == false) stringResource(Res.string.source_related_unavailable_hint) else null,
                modifier = Modifier.fillMaxWidth().padding(vertical = 40.dp),
            )
        }
        state.groups.forEachIndexed { groupIndex, group ->
            item(key = "group:${group.name}", contentType = "heading") {
                Text(group.name, style = MaterialTheme.typography.titleMedium,
                    modifier = Modifier.padding(top = 16.dp).semantics { heading() })
            }
            items(group.items, key = { "entry:$groupIndex:${it.url}" }, contentType = { "entry" }) { item ->
                Row(
                    modifier = Modifier.fillMaxWidth().clip(MaterialTheme.shapes.medium)
                        .hoverHighlight(onClick = { if (!state.opening) onOpen(item) })
                        .padding(8.dp).heightIn(min = 96.dp),
                    horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically,
                ) {
                    CoverImage(model = item.thumbnailUrl, contentDescription = null, fallbackInitials = item.title.take(2).uppercase(),
                        modifier = Modifier.size(56.dp, 80.dp).clip(MaterialTheme.shapes.small))
                    Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                        Text(item.title, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium,
                            maxLines = 3, overflow = TextOverflow.Ellipsis)
                        item.description?.takeIf(String::isNotBlank)?.let {
                            Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant,
                                maxLines = 2, overflow = TextOverflow.Ellipsis)
                        }
                    }
                }
            }
        }
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/RecommendationsScreen.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines RecommendationsState, RecommendationsViewModel, RecommendationsRoute, RecommendationsScreen, openRecommendationResult.

The source describes its contract as:

Opens the library title a recommendation matched, else searches every source for it.

Cross-chapter imports used by this file: YokanRuntime, YokanRepository, Manga, EmptyState, RouteScaffold, Navigator. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.discovery

import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Recommend
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.metadata.RecommendationResult
import eu.friedcutlet.yokan.services.metadata.RecommendationService
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

internal data class RecommendationsState(
    /** Null when the title does not exist. */
    val manga: Manga? = null,
    val loading: Boolean = false,
    val results: List<RecommendationResult> = emptyList(),
    val error: String? = null,
)

internal class RecommendationsViewModel(
    mangaId: Long,
    repository: YokanRepository,
    recommendation: RecommendationService,
) : ViewModel() {
    private val _state = MutableStateFlow(repository.manga(mangaId).let { RecommendationsState(manga = it, loading = it != null) })
    val state: StateFlow<RecommendationsState> = _state.asStateFlow()

    init {
        _state.value.manga?.let { manga ->
            viewModelScope.launch {
                val result = catchingNonCancellation { recommendation.recommendations(manga.name, manga.itemType.toDb()) }
                _state.update {
                    it.copy(
                        loading = false,
                        results = result.getOrDefault(emptyList()),
                        error = result.exceptionOrNull()?.let { error -> error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() } },
                    )
                }
            }
        }
    }
}

@Composable
internal fun RecommendationsRoute(route: Route.Recommendations, nav: Navigator) {
    val viewModel = viewModel {
        RecommendationsViewModel(route.mangaId, YokanRuntime.repository, YokanRuntime.services.recommendation)
    }
    val state by viewModel.state.collectAsStateWithLifecycle()
    RecommendationsScreen(
        state = state,
        title = "Recommendations",
        onOpen = { result -> openRecommendationResult(YokanRuntime.repository, nav::navigate, result) },
        onBack = nav::back,
    )
}

@Composable
internal fun RecommendationsScreen(
    state: RecommendationsState,
    title: String,
    onOpen: (RecommendationResult) -> Unit,
    onBack: () -> Unit,
) {
    val manga = state.manga
    val results = state.results
    val loading = state.loading
    val error = state.error
    RouteScaffold(title, onBack = onBack) {
        if (manga == null) {
            item {
                EmptyState(
                    icon = Icons.Filled.Recommend,
                    title = "No title selected",
                    modifier = Modifier.fillMaxWidth().padding(vertical = 48.dp),
                    subtitle = "Open recommendations from a detail page.",
                )
            }
        } else {
            item {
                Text(
                    "Based on ${manga.name}",
                    style = MaterialTheme.typography.titleSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
            when {
                loading -> item {
                    Box(Modifier.fillMaxWidth().padding(vertical = 48.dp), contentAlignment = Alignment.Center) {
                        androidx.compose.material3.CircularProgressIndicator()
                    }
                }
                error != null -> item {
                    Box(Modifier.fillMaxWidth().padding(vertical = 48.dp), contentAlignment = Alignment.Center) {
                        Text(error.orEmpty(), color = MaterialTheme.colorScheme.error)
                    }
                }
                results.isEmpty() -> item {
                    Box(Modifier.fillMaxWidth().padding(vertical = 48.dp), contentAlignment = Alignment.Center) {
                        Text("No result", color = MaterialTheme.colorScheme.onSurfaceVariant)
                    }
                }
            }
            items(results, key = { it.mangaId ?: "${it.itemType}:${it.title}" }) { result ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 8.dp, vertical = 2.dp)
                        .clip(MaterialTheme.shapes.large)
                        // Every card searches all sources for the title, like Mangayomi's
                        // ListTile onTap -> /globalSearch.
                        .hoverHighlight(onClick = { onOpen(result) })
                        .padding(horizontal = 8.dp, vertical = 8.dp),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    if (result.coverUrl != null) {
                        eu.friedcutlet.yokan.ui.components.CoverImage(
                            model = result.coverUrl,
                            contentDescription = result.title,
                            modifier = Modifier.size(width = 70.dp, height = 100.dp),
                            fallbackInitials = result.title.take(2),
                        )
                    } else {
                        Box(
                            modifier = Modifier
                                .size(width = 70.dp, height = 100.dp)
                                .clip(MaterialTheme.shapes.medium)
                                .background(MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.4f)),
                            contentAlignment = Alignment.Center,
                        ) {
                            Icon(
                                Icons.Filled.Recommend,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.onPrimaryContainer,
                            )
                        }
                    }
                    Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
                        Text(result.title, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis)
                        Text(
                            result.description?.takeIf(String::isNotBlank) ?: result.reason,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            maxLines = 3,
                            overflow = TextOverflow.Ellipsis,
                        )
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(6.dp),
                        ) {
                            if (result.genres.isNotEmpty()) {
                                Row(
                                    modifier = Modifier
                                        .weight(1f)
                                        .horizontalScroll(rememberScrollState()),
                                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                                ) {
                                    result.genres.forEach { genre ->
                                        Surface(
                                            shape = MaterialTheme.shapes.small,
                                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.08f),
                                        ) {
                                            Text(
                                                genre,
                                                modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                                                style = MaterialTheme.typography.labelSmall,
                                            )
                                        }
                                    }
                                }
                            } else {
                                Spacer(Modifier.weight(1f))
                            }
                            Text(
                                "${result.score}% similar",
                                style = MaterialTheme.typography.labelLarge,
                                fontWeight = FontWeight.SemiBold,
                                color = MaterialTheme.colorScheme.primary,
                            )
                        }
                    }
                }
            }
        }
    }
}

/** Opens the library title a recommendation matched, else searches every source for it. */
internal fun openRecommendationResult(repository: YokanRepository, navigate: (Route) -> Unit, result: RecommendationResult) {
    val localId = result.mangaId?.takeIf { repository.manga(it) != null }
    navigate(localId?.let { Route.Detail(it) } ?: Route.GlobalSearch(result.itemType.toDomain(), result.title))
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/SequelsScreen.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines SequelsState, SequelsViewModel, SequelsRoute, SequelsScreen.

The source describes its contract as:

The title has a tracker entry with a media id to look sequels up by.

Cross-chapter imports used by this file: YokanRuntime, YokanRepository, YokanDatabase, Manga, EmptyState, RouteScaffold. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.discovery

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.PlaylistAddCheck
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.metadata.SequelEntry
import eu.friedcutlet.yokan.services.metadata.WatchOrderService
import eu.friedcutlet.yokan.services.tracking.AnilistTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.MalTrackerSyncId
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

internal data class SequelsState(
    /** Null when the title does not exist. */
    val manga: Manga? = null,
    /** The title has a tracker entry with a media id to look sequels up by. */
    val tracked: Boolean = false,
    val loading: Boolean = false,
    val sequels: List<SequelEntry> = emptyList(),
    val error: String? = null,
)

internal class SequelsViewModel(
    mangaId: Long,
    repository: YokanRepository,
    database: YokanDatabase,
    watchOrder: WatchOrderService,
) : ViewModel() {
    private val manga = repository.manga(mangaId)
    private val mediaId = manga?.let { database.tracks(it.id).firstOrNull { track -> track.mediaId != null }?.mediaId }
    private val _state = MutableStateFlow(SequelsState(manga = manga, tracked = mediaId != null, loading = mediaId != null))
    val state: StateFlow<SequelsState> = _state.asStateFlow()

    init {
        mediaId?.let { id ->
            viewModelScope.launch {
                val preferences = database.trackPreferences()
                val mal = preferences.firstOrNull { it.syncId == MalTrackerSyncId.toLong() && !it.username.isNullOrBlank() }?.username
                val anilist = preferences.firstOrNull { it.syncId == AnilistTrackerSyncId.toLong() && !it.username.isNullOrBlank() }?.username
                val result = catchingNonCancellation {
                    watchOrder.sequels(mal, anilist).filter { entry -> entry.reasons.any { it.id == id.toString() } }
                }
                _state.update { it.copy(loading = false, sequels = result.getOrDefault(emptyList()), error = result.exceptionOrNull()?.message) }
            }
        }
    }
}

@Composable
internal fun SequelsRoute(route: Route.Sequels, nav: Navigator) {
    val viewModel = viewModel {
        SequelsViewModel(route.mangaId, YokanRuntime.repository, YokanRuntime.database, YokanRuntime.services.watchOrder)
    }
    val state by viewModel.state.collectAsStateWithLifecycle()
    SequelsScreen(state, "Sequels", onNavigate = nav::navigate, onBack = nav::back)
}

@Composable
internal fun SequelsScreen(state: SequelsState, title: String, onNavigate: (Route) -> Unit, onBack: () -> Unit) {
    val manga = state.manga
    val sequels = state.sequels
    val error = state.error
    RouteScaffold(title, onBack = onBack) {
        when {
            manga == null -> item {
                EmptyState(
                    icon = Icons.AutoMirrored.Filled.PlaylistAddCheck,
                    title = "No title selected",
                    modifier = Modifier.fillMaxWidth().padding(vertical = 48.dp),
                    subtitle = "Open sequels from a tracked detail page.",
                )
            }
            !state.tracked -> item {
                EmptyState(
                    icon = Icons.AutoMirrored.Filled.PlaylistAddCheck,
                    title = "Not tracked",
                    modifier = Modifier.fillMaxWidth().padding(vertical = 48.dp),
                    subtitle = "Track this title with MyAnimeList or AniList to locate sequels from your list.",
                )
            }
            state.loading -> item {
                Box(Modifier.fillMaxWidth().padding(vertical = 48.dp), contentAlignment = Alignment.Center) {
                    androidx.compose.material3.CircularProgressIndicator()
                }
            }
            error != null -> item {
                Box(Modifier.fillMaxWidth().padding(vertical = 48.dp), contentAlignment = Alignment.Center) {
                    Text(error.orEmpty(), color = MaterialTheme.colorScheme.error)
                }
            }
            sequels.isEmpty() -> item {
                Box(Modifier.fillMaxWidth().padding(vertical = 48.dp), contentAlignment = Alignment.Center) {
                    Text("No result", color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
            }
            else -> items(sequels, key = { it.id }) { sequel ->
                WatchOrderRow(
                    imageUrl = sequel.imageUrl,
                    title = sequel.title,
                    subtitle = listOf(sequel.type, sequel.episodes, sequel.period)
                        .filter(String::isNotBlank)
                        .joinToString(" · "),
                    info = sequel.score.takeIf(String::isNotBlank)?.let { "Score $it" },
                    onClick = { onNavigate(Route.GlobalSearch(manga.itemType, sequel.title)) },
                )
            }
        }
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/WatchOrderScreen.kt

Create this path in your reconstruction project. Source set: commonMain. Exact file download.

The implementation below defines WatchOrderState, WatchOrderViewModel, selectSeries, clearSeries, WatchOrderRoute, WatchOrderScreen, WatchOrderRoleBadge, WatchOrderRow.

The source describes its contract as:

Candidate series, offered when the title's own name does not resolve to a watch order.

Cross-chapter imports used by this file: YokanRuntime, YokanRepository, Manga, EmptyState, RouteScaffold, Navigator. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.discovery

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.PlaylistAddCheck
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.metadata.WatchOrderEntry
import eu.friedcutlet.yokan.services.metadata.WatchOrderSearchResult
import eu.friedcutlet.yokan.services.metadata.WatchOrderService
import eu.friedcutlet.yokan.ui.components.EmptyState
import eu.friedcutlet.yokan.ui.components.RouteScaffold
import eu.friedcutlet.yokan.ui.components.hoverHighlight
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

internal data class WatchOrderState(
    /** Null when the title does not exist. */
    val manga: Manga? = null,
    val loading: Boolean = false,
    val error: String? = null,
    /** Candidate series, offered when the title's own name does not resolve to a watch order. */
    val searchResults: List<WatchOrderSearchResult> = emptyList(),
    val selectedSeries: WatchOrderSearchResult? = null,
    val order: List<WatchOrderEntry> = emptyList(),
)

internal class WatchOrderViewModel(
    mangaId: Long,
    repository: YokanRepository,
    private val watchOrder: WatchOrderService,
) : ViewModel() {
    private val _state = MutableStateFlow(repository.manga(mangaId).let { WatchOrderState(manga = it, loading = it != null) })
    val state: StateFlow<WatchOrderState> = _state.asStateFlow()
    private var seriesJob: Job? = null

    init {
        _state.value.manga?.let { manga ->
            viewModelScope.launch {
                val built = catchingNonCancellation { watchOrder.watchOrderByName(manga.name) }
                val order = built.getOrDefault(emptyList())
                val search = if (order.isEmpty()) catchingNonCancellation { watchOrder.search(manga.name) } else null
                _state.update {
                    it.copy(
                        loading = false,
                        order = order,
                        searchResults = search?.getOrNull().orEmpty(),
                        error = built.exceptionOrNull()?.message ?: search?.exceptionOrNull()?.message,
                    )
                }
            }
        }
    }

    fun selectSeries(series: WatchOrderSearchResult) {
        seriesJob?.cancel()
        _state.update { it.copy(selectedSeries = series, loading = true, error = null) }
        seriesJob = viewModelScope.launch {
            val result = catchingNonCancellation { watchOrder.watchOrder(series.id) }
            _state.update { it.copy(loading = false, order = result.getOrDefault(emptyList()), error = result.exceptionOrNull()?.message) }
        }
    }

    fun clearSeries() {
        seriesJob?.cancel()
        _state.update { it.copy(selectedSeries = null, order = emptyList(), loading = false) }
    }
}

@Composable
internal fun WatchOrderRoute(route: Route.WatchOrder, nav: Navigator) {
    val viewModel = viewModel { WatchOrderViewModel(route.mangaId, YokanRuntime.repository, YokanRuntime.services.watchOrder) }
    val state by viewModel.state.collectAsStateWithLifecycle()
    WatchOrderScreen(
        state = state,
        title = "Watch Order",
        onSelectSeries = viewModel::selectSeries,
        onClearSeries = viewModel::clearSeries,
        onNavigate = nav::navigate,
        onBack = nav::back,
    )
}

@Composable
internal fun WatchOrderScreen(
    state: WatchOrderState,
    title: String,
    onSelectSeries: (WatchOrderSearchResult) -> Unit,
    onClearSeries: () -> Unit,
    onNavigate: (Route) -> Unit,
    onBack: () -> Unit,
) {
    val manga = state.manga
    val selectedSeries = state.selectedSeries
    val order = state.order
    val searchResults = state.searchResults
    val loading = state.loading
    val error = state.error
    RouteScaffold(title, onBack = onBack) {
        if (manga == null) {
            item {
                EmptyState(
                    icon = Icons.AutoMirrored.Filled.PlaylistAddCheck,
                    title = "No anime selected",
                    modifier = Modifier.fillMaxWidth().padding(vertical = 48.dp),
                    subtitle = "Open watch order from an anime detail page.",
                )
            }
            return@RouteScaffold
        }
        selectedSeries?.let { series ->
            item {
                TextButton(onClick = onClearSeries) {
                    Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null)
                    Spacer(Modifier.width(6.dp))
                    Text(series.name, maxLines = 1, overflow = TextOverflow.Ellipsis)
                }
            }
        }
        when {
            loading -> item {
                Box(Modifier.fillMaxWidth().padding(vertical = 48.dp), contentAlignment = Alignment.Center) {
                    androidx.compose.material3.CircularProgressIndicator()
                }
            }
            error != null -> item {
                Box(Modifier.fillMaxWidth().padding(vertical = 48.dp), contentAlignment = Alignment.Center) {
                    Text(error.orEmpty(), color = MaterialTheme.colorScheme.error)
                }
            }
            selectedSeries == null && searchResults.isEmpty() && order.isEmpty() -> item {
                Box(Modifier.fillMaxWidth().padding(vertical = 48.dp), contentAlignment = Alignment.Center) {
                    Text("No result", color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
            }
        }
        if (order.isNotEmpty()) {
            itemsIndexed(order, key = { index, it -> "${it.id}|${it.title}|$index" }) { index, entry ->
                WatchOrderRow(
                    index = index + 1,
                    role = entry.role,
                    imageUrl = entry.imageUrl,
                    title = entry.title,
                    subtitle = entry.titleEnglish.orEmpty(),
                    info = entry.info,
                    onClick = { onNavigate(Route.GlobalSearch(manga.itemType, entry.titleEnglish ?: entry.title)) },
                )
            }
        } else if (selectedSeries == null) {
            items(searchResults, key = { it.id }) { hit ->
                WatchOrderRow(
                    imageUrl = hit.imageUrl,
                    title = hit.name,
                    subtitle = listOfNotNull(hit.type.takeIf(String::isNotBlank), hit.year?.toString())
                        .joinToString(" · "),
                    info = null,
                    onClick = { onSelectSeries(hit) },
                )
            }
        }
    }
}

@Composable
private fun WatchOrderRoleBadge(role: eu.friedcutlet.yokan.services.metadata.WatchOrderRole) {
    val (label, color) = when (role) {
        eu.friedcutlet.yokan.services.metadata.WatchOrderRole.Current ->
            "Currently watching" to MaterialTheme.colorScheme.primary
        eu.friedcutlet.yokan.services.metadata.WatchOrderRole.Previous ->
            "Previous" to MaterialTheme.colorScheme.outline
        eu.friedcutlet.yokan.services.metadata.WatchOrderRole.Next ->
            "Up next" to MaterialTheme.colorScheme.tertiary
    }
    Surface(
        shape = RoundedCornerShape(6.dp),
        color = color.copy(alpha = 0.18f),
    ) {
        Text(
            text = label,
            color = color,
            style = MaterialTheme.typography.labelSmall.copy(
                fontWeight = FontWeight.SemiBold,
                fontSize = 11.sp,
            ),
            modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
        )
    }
}

@Composable
internal fun WatchOrderRow(
    index: Int? = null,
    role: eu.friedcutlet.yokan.services.metadata.WatchOrderRole? = null,
    imageUrl: String,
    title: String,
    subtitle: String,
    info: String?,
    onClick: () -> Unit,
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(MaterialTheme.shapes.large)
            .hoverHighlight(onClick = onClick)
            .padding(8.dp),
        horizontalArrangement = Arrangement.spacedBy(12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        if (index != null) {
            Text(
                text = "$index",
                style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
                modifier = Modifier.width(28.dp),
                textAlign = TextAlign.Center,
            )
        }
        eu.friedcutlet.yokan.ui.components.CoverImage(
            model = imageUrl.takeIf(String::isNotBlank),
            contentDescription = title,
            modifier = Modifier.size(width = 56.dp, height = 80.dp),
            fallbackInitials = title.take(2),
        )
        Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
            Text(title, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis)
            if (subtitle.isNotBlank() && subtitle != title) {
                Text(
                    subtitle,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            }
            if (!info.isNullOrBlank()) {
                Text(
                    info,
                    style = MaterialTheme.typography.labelSmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                )
            }
        }
        if (role != null) {
            WatchOrderRoleBadge(role)
        }
    }
}

Check your understanding

Open the same recommended/related result twice, then refresh its metadata. Confirm one library identity and the intended reading source. [chapter-content-end]: #

Recreate the tests and verify the chapter

Recreate metadata/discovery, each tracker adapter/account/OAuth, score normalization and Home/resume fixtures. Run deterministic HTTP fixtures on desktop, then real provider login/refresh/search checks with user-supplied credentials. Record unsupported provider operations and distinguish fake HTTP success from live protocol compatibility.

These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/discovery/HttpDiscoveryServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines HttpDiscoveryServiceTest, create, Http, request, service, page, dispose, supportsLatest, filterList, search and 1 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • aniListParsesActualScoreAliasesAndFiltersAdultAndNovels
  • novelsUseAnExplicitFormatAndAdultOptInOmitsRestriction
  • recommendationVotesAreNotUsedAsRatings
  • tmdbUsesUserTokenInHeaderAndSeparatesMoviesFromSeries
  • cacheExpiresAndFailedRefreshDoesNotDiscardUsableMetadata
  • graphQlErrorsDoNotBecomeAnEmptySuccessfulShelf
  • publicAniListFailureDoesNotAskForTmdbCredentials
  • cancellationPropagatesWithoutPublishingAnEmptyCache
  • unavailableSourceAndMissingSavedPresetAreActionable
  • sourceFeedsRunSavedQueryAndReleaseRuntimeOnSuccessFailureAndCancellation
package eu.friedcutlet.yokan.services.discovery

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.extensions.*
import eu.friedcutlet.yokan.services.http.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

class HttpDiscoveryServiceTest {
    private val noRuntime = object : ExtensionRuntimeFactory {
        override fun create(source: DbSource): ExtensionRuntimeService = error("No source runtime expected")
    }
    private class Http(var body: String, var status: Int = 200) : HttpService {
        val requests = mutableListOf<HttpRequest>()
        override suspend fun request(request: HttpRequest): HttpResponse {
            requests += request
            return HttpResponse(status, body)
        }
    }
    private fun service(http: HttpService, clock: () -> Long = { 0 }) =
        HttpDiscoveryService(http, InMemoryYokanDatabase(emptySnapshot()), noRuntime, clock)

    private val media = """{"id":1,"format":"MANGA","title":{"english":"Title","romaji":"Alias"},"meanScore":87,"isAdult":false,"description":"<b>Story</b><br>Two","genres":["Fantasy"]}"""
    private fun page(vararg rows: String) = """{"data":{"Page":{"media":[${rows.joinToString()}]}}}"""

    @Test fun aniListParsesActualScoreAliasesAndFiltersAdultAndNovels() = runTest {
        val http = Http(page(media, media.replace("\"id\":1", "\"id\":2").replace("\"isAdult\":false", "\"isAdult\":true"),
            media.replace("\"format\":\"MANGA\"", "\"format\":\"NOVEL\"")))
        val item = service(http).popular(HomeMediaFilter.Manga, "", false).single()
        assertEquals(8.7, item.rating)
        assertEquals(listOf("Title", "Alias"), item.aliases)
        assertEquals("Story\nTwo", item.description)
        assertContains(http.requests.single().body.orEmpty(), "POPULARITY_DESC")
        assertFalse(http.requests.single().body.orEmpty().contains("format:"), "Non-novel format must be omitted, not passed as null")
    }

    @Test fun novelsUseAnExplicitFormatAndAdultOptInOmitsRestriction() = runTest {
        val http = Http(page(media.replace("\"format\":\"MANGA\"", "\"format\":\"NOVEL\"")))
        assertEquals(HomeMediaFilter.Novel, service(http).popular(HomeMediaFilter.Novel, "", true).single().kind)
        assertContains(http.requests.single().body.orEmpty(), "format: NOVEL")
        assertFalse(http.requests.single().body.orEmpty().contains("isAdult: false"))
    }

    @Test fun recommendationVotesAreNotUsedAsRatings() = runTest {
        val http = Http("""{"data":{"Media":{"recommendations":{"nodes":[{"rating":500,"mediaRecommendation":$media}]}}}}""")
        assertEquals(8.7, service(http).recommendations("Seed", HomeMediaFilter.Manga, false).single().rating)
    }

    @Test fun tmdbUsesUserTokenInHeaderAndSeparatesMoviesFromSeries() = runTest {
        val http = Http("""{"results":[{"id":9,"title":"Film","vote_average":7.3,"poster_path":"/cover.jpg"}]}""")
        val service = service(http)
        val film = service.popular(HomeMediaFilter.Movie, "local-token", false).single()
        assertEquals("tmdb:movie:9", film.key)
        assertEquals(7.3, film.rating)
        assertEquals("Bearer local-token", http.requests.single().headers["Authorization"])
        assertFalse(http.requests.single().url.contains("local-token"))
        service.popular(HomeMediaFilter.Series, "local-token", false)
        assertContains(http.requests.last().url, "/trending/tv/week")
        assertFailsWith<DiscoveryException> { service.popular(HomeMediaFilter.Movie, "", false) }.also {
            assertEquals(DiscoveryIssue.Credentials, it.issue)
        }
    }

    @Test fun cacheExpiresAndFailedRefreshDoesNotDiscardUsableMetadata() = runTest {
        var now = 0L
        val http = Http(page(media))
        val service = service(http) { now }
        service.popular(HomeMediaFilter.Manga, "", false)
        service.popular(HomeMediaFilter.Manga, "", false)
        assertEquals(1, http.requests.size)
        http.status = 429
        assertFailsWith<DiscoveryException> { service.popular(HomeMediaFilter.Manga, "", false, refresh = true) }
            .also { assertEquals(DiscoveryIssue.RateLimited, it.issue) }
        assertEquals(1, service.popular(HomeMediaFilter.Manga, "", false).size)
        now = 300_001
        assertFailsWith<DiscoveryException> { service.popular(HomeMediaFilter.Manga, "", false) }
        assertEquals(3, http.requests.size)
    }

    @Test fun graphQlErrorsDoNotBecomeAnEmptySuccessfulShelf() = runTest {
        assertFailsWith<DiscoveryException> { service(Http("""{"errors":[{"message":"Unavailable"}]}"""))
            .popular(HomeMediaFilter.Anime, "", false) }
    }

    @Test fun publicAniListFailureDoesNotAskForTmdbCredentials() = runTest {
        val http = Http("{}", status = 403)
        val service = service(http)
        assertEquals(DiscoveryIssue.Network,
            assertFailsWith<DiscoveryException> { service.popular(HomeMediaFilter.Anime, "", false) }.issue)
        assertEquals(DiscoveryIssue.Credentials,
            assertFailsWith<DiscoveryException> { service.popular(HomeMediaFilter.Movie, "invalid", false) }.issue)
    }

    @Test fun cancellationPropagatesWithoutPublishingAnEmptyCache() = runTest {
        val waiting = CompletableDeferred<Unit>()
        val http = HttpService { waiting.complete(Unit); awaitCancellation() }
        val job = launch { service(http).popular(HomeMediaFilter.Anime, "", false) }
        waiting.await()
        job.cancelAndJoin()
        assertTrue(job.isCancelled)
    }

    @Test fun unavailableSourceAndMissingSavedPresetAreActionable() = runTest {
        val db = InMemoryYokanDatabase(emptySnapshot().copy(sources = listOf(DbSource(id = 10, name = "Source", isAdded = true))))
        val service = HttpDiscoveryService(Http(page(media)), db, noRuntime)
        assertEquals(DiscoveryIssue.SourceUnavailable,
            assertFailsWith<DiscoveryException> { service.sourceFeed(DbHomeSourceFeed(99), false) }.issue)
        assertEquals(DiscoveryIssue.PresetChanged,
            assertFailsWith<DiscoveryException> { service.sourceFeed(DbHomeSourceFeed(10, HomeFeedMode.SavedSearch, "gone"), false) }.issue)
    }

    @Test fun sourceFeedsRunSavedQueryAndReleaseRuntimeOnSuccessFailureAndCancellation() = runTest {
        val source = DbSource(id = 10, name = "Source", isAdded = true)
        val preset = DbSavedSearch(10, "Saved", "query")
        val db = InMemoryYokanDatabase(emptySnapshot(DbSettings(savedSearches = listOf(preset))).copy(sources = listOf(source)))
        var disposed = 0
        var searched: String? = null
        val started = CompletableDeferred<Unit>()
        val factory = object : ExtensionRuntimeFactory {
            override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, db) {
                override fun dispose() { disposed++ }
                override suspend fun supportsLatest() = false
                override suspend fun filterList() = emptyList<SourceFilter>()
                override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing {
                    searched = query
                    return SourceListing(listOf(RemoteManga("Result", "/result")), false)
                }
                override suspend fun popular(page: Int): SourceListing { started.complete(Unit); awaitCancellation() }
            }
        }
        val service = HttpDiscoveryService(Http(page(media)), db, factory)
        val result = service.sourceFeed(DbHomeSourceFeed(10, HomeFeedMode.SavedSearch, preset.id), false).single()
        assertEquals("query", searched)
        assertEquals(10L, result.sourceId)
        assertEquals("/result", result.sourceUrl)
        assertEquals(1, disposed)
        assertFailsWith<DiscoveryException> { service.sourceFeed(DbHomeSourceFeed(10, HomeFeedMode.Latest), false) }
        assertEquals(2, disposed)
        val job = launch { service.sourceFeed(DbHomeSourceFeed(10), false) }
        started.await()
        job.cancelAndJoin()
        assertEquals(3, disposed)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/discovery/TmdbRecommendationsTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines TmdbRecommendationsTest, create, Http, request, service.

The source describes its contract as:

Answers by /3/{type}/{id}/recommendations path; unknown paths are a 500.

Read the setup, action and assertions in these cases before implementing their production paths:

  • requestsSeedRecommendationsWithTrackerKeyAndRanksByFrequency
  • homeReadAccessTokenIsTheFallbackCredential
  • noCredentialOrNoSeedsMakesNoRequests
  • oneFailingSeedStillYieldsTheOthersButTotalFailureIsAnIssue
  • seedSetIsCachedForSixHours
  • seedRequestsAreBoundedToThreeAtOnce
  • cancellationPropagatesWithoutCachingAnEmptyShelf
package eu.friedcutlet.yokan.services.discovery

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.extensions.*
import eu.friedcutlet.yokan.services.http.*
import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId
import eu.friedcutlet.yokan.services.tracking.TrackerCredentials
import eu.friedcutlet.yokan.services.tracking.encode
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class TmdbRecommendationsTest {
    private val noRuntime = object : ExtensionRuntimeFactory {
        override fun create(source: DbSource): ExtensionRuntimeService = error("No source runtime expected")
    }

    /** Answers by `/3/{type}/{id}/recommendations` path; unknown paths are a 500. */
    private class Http(val routes: Map<String, Pair<Int, String>>) : HttpService {
        val requests = mutableListOf<HttpRequest>()
        override suspend fun request(request: HttpRequest): HttpResponse {
            requests += request
            val path = request.url.substringAfter("api.themoviedb.org").substringBefore('?')
            val (status, body) = routes[path] ?: (500 to "")
            return HttpResponse(status, body)
        }
    }

    private val trackerKey = DbTrackPreference(syncId = TmdbTrackerSyncId.toLong(), oauth = "session",
        prefs = TrackerCredentials(apiKey = "user key").encode())

    private fun service(http: HttpService, linked: Boolean = true, clock: () -> Long = { 0 }) = HttpDiscoveryService(http,
        InMemoryYokanDatabase(emptySnapshot().copy(trackPreferences = if (linked) listOf(trackerKey) else emptyList())), noRuntime, clock)

    private val movieSeed = TmdbSeed("movie", 1)
    private val tvSeed = TmdbSeed("tv", 2)
    private val routes = mapOf(
        "/3/movie/1/recommendations" to (200 to """{"results":[{"id":10,"title":"Ten"},{"id":11,"title":"Eleven"},{"id":2,"name":"Seed","media_type":"tv"}]}"""),
        "/3/tv/2/recommendations" to (200 to """{"results":[{"id":11,"title":"Eleven","media_type":"movie"},{"id":20,"name":"Twenty","media_type":"tv"},{"id":21,"name":"Adult","adult":true}]}"""),
    )

    @Test fun requestsSeedRecommendationsWithTrackerKeyAndRanksByFrequency() = runTest {
        val http = Http(routes)
        val items = service(http).tmdbRecommendations(listOf(movieSeed, tvSeed), "home-token", false)
        assertEquals(listOf("tmdb:movie:11", "tmdb:movie:10", "tmdb:tv:20"), items.map { it.key })
        assertEquals(HomeMediaFilter.Series, items.last().kind)
        assertEquals(setOf("/3/movie/1/recommendations", "/3/tv/2/recommendations"),
            http.requests.mapTo(mutableSetOf()) { it.url.substringAfter("api.themoviedb.org").substringBefore('?') })
        http.requests.forEach {
            assertContains(it.url, "page=1")
            assertContains(it.url, "api_key=user%20key")
            assertNull(it.headers["Authorization"])
        }
    }

    @Test fun homeReadAccessTokenIsTheFallbackCredential() = runTest {
        val http = Http(routes)
        assertEquals(3, service(http, linked = false).tmdbRecommendations(listOf(movieSeed, tvSeed), "home-token", false).size)
        http.requests.forEach {
            assertEquals("Bearer home-token", it.headers["Authorization"])
            assertFalse(it.url.contains("api_key"))
        }
    }

    @Test fun noCredentialOrNoSeedsMakesNoRequests() = runTest {
        val http = Http(routes)
        assertTrue(service(http, linked = false).tmdbRecommendations(listOf(movieSeed), "", false).isEmpty())
        assertTrue(service(http).tmdbRecommendations(emptyList(), "home-token", false).isEmpty())
        assertTrue(http.requests.isEmpty())
    }

    @Test fun oneFailingSeedStillYieldsTheOthersButTotalFailureIsAnIssue() = runTest {
        val http = Http(routes - "/3/movie/1/recommendations")
        assertEquals(listOf("tmdb:movie:11", "tmdb:tv:20"),
            service(http).tmdbRecommendations(listOf(movieSeed, tvSeed), "", false).map { it.key })
        val revoked = Http(mapOf("/3/movie/1/recommendations" to (401 to "")))
        assertEquals(DiscoveryIssue.Credentials, assertFailsWith<DiscoveryException> {
            service(revoked).tmdbRecommendations(listOf(movieSeed), "", false)
        }.issue)
    }

    @Test fun seedSetIsCachedForSixHours() = runTest {
        val http = Http(routes)
        var now = 0L
        val service = service(http) { now }
        service.tmdbRecommendations(listOf(movieSeed, tvSeed), "", false)
        now = 6 * 60 * 60_000L
        service.tmdbRecommendations(listOf(tvSeed, movieSeed), "", false)
        assertEquals(2, http.requests.size)
        service.tmdbRecommendations(listOf(movieSeed), "", false)
        assertEquals(3, http.requests.size, "a different seed set is a different cache entry")
        now += 1
        service.tmdbRecommendations(listOf(movieSeed, tvSeed), "", false)
        assertEquals(5, http.requests.size)
        service.tmdbRecommendations(listOf(movieSeed, tvSeed), "", false, refresh = true)
        assertEquals(7, http.requests.size)
    }

    @Test fun seedRequestsAreBoundedToThreeAtOnce() = runTest {
        var inFlight = 0
        var peak = 0
        val http = HttpService {
            peak = maxOf(peak, ++inFlight)
            delay(10)
            inFlight--
            HttpResponse(200, """{"results":[]}""")
        }
        service(http).tmdbRecommendations((1L..7L).map { TmdbSeed("movie", it) }, "", false)
        assertEquals(3, peak)
    }

    @Test fun cancellationPropagatesWithoutCachingAnEmptyShelf() = runTest {
        val waiting = CompletableDeferred<Unit>()
        var calls = 0
        val http = HttpService {
            calls++
            waiting.complete(Unit)
            awaitCancellation()
        }
        val service = service(http)
        val job = launch { service.tmdbRecommendations(listOf(movieSeed, tvSeed), "", false) }
        waiting.await()
        job.cancelAndJoin()
        assertTrue(job.isCancelled)
        val again = launch { service.tmdbRecommendations(listOf(movieSeed, tvSeed), "", false) }
        runCurrent()
        assertEquals(4, calls, "the cancelled load published nothing to the cache")
        again.cancelAndJoin()
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/metadata/AnilistRecommendationServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines AnilistRecommendationServiceTest, normalizesRatingsAndMatchesLibraryTitles, novelRecommendationsQueryMangaMediaType, unresolvedTitlesRetrySimplifiedAndDegradeToEmpty, serverErrorsPropagateToCaller.

Read the setup, action and assertions in these cases before implementing their production paths:

  • normalizesRatingsAndMatchesLibraryTitles
  • novelRecommendationsQueryMangaMediaType
  • unresolvedTitlesRetrySimplifiedAndDegradeToEmpty
  • serverErrorsPropagateToCaller

Cross-chapter imports used by this file: DbItemType, DbManga, InMemoryYokanDatabase, seedDatabaseSnapshot, HttpResponse, RecordingHttpService. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.metadata

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class AnilistRecommendationServiceTest {
    private val recommendationsBody = """
        {"data":{"Media":{"recommendations":{"nodes":[
          {"rating":200,"mediaRecommendation":{"title":{"english":"In Library","romaji":"Toshokan","native":null},
           "description":"desc","coverImage":{"large":"https://img/a.jpg"},"genres":["Action","Fantasy"]}},
          {"rating":50,"mediaRecommendation":{"title":{"english":null,"romaji":"Remote Only","native":null},
           "description":null,"coverImage":null,"genres":[]}}
        ]}}}}
    """.trimIndent()

    @Test
    fun normalizesRatingsAndMatchesLibraryTitles() = runTest {
        val library = DbManga(id = 7, name = "In Library", itemType = DbItemType.Manga)
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(library)))
        val http = RecordingHttpService { HttpResponse(statusCode = 200, body = recommendationsBody) }

        val results = RecommendationService(http, database)
            .recommendations("Seed Title", DbItemType.Manga)

        assertEquals(1, http.requests.size)
        assertEquals("POST", http.requests[0].method)
        assertTrue("\"type\":\"MANGA\"" in http.requests[0].body.orEmpty())
        assertTrue("\"search\":\"Seed Title\"" in http.requests[0].body.orEmpty())

        assertEquals(listOf("In Library", "Remote Only"), results.map(RecommendationResult::title))
        // Top rating maps to 100%, others scale off it.
        assertEquals(listOf(100, 25), results.map(RecommendationResult::score))
        assertEquals(7L, results[0].mangaId)
        assertNull(results[1].mangaId)
        assertEquals("https://img/a.jpg", results[0].coverUrl)
        assertEquals(listOf("Action", "Fantasy"), results[0].genres)
        assertEquals("desc", results[0].description)
    }

    @Test
    fun novelRecommendationsQueryMangaMediaType() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = emptyList()))
        val http = RecordingHttpService { HttpResponse(statusCode = 200, body = recommendationsBody) }

        RecommendationService(http, database).recommendations("Novel Seed", DbItemType.Novel)

        assertTrue("\"type\":\"MANGA\"" in http.requests[0].body.orEmpty())
    }

    @Test
    fun unresolvedTitlesRetrySimplifiedAndDegradeToEmpty() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = emptyList()))
        val http = RecordingHttpService { HttpResponse(statusCode = 200, body = """{"errors":[{"message":"Not Found."}],"data":{"Media":null}}""") }

        val results = RecommendationService(http, database)
            .recommendations("Main Title ~subtitle here~", DbItemType.Manga)

        // Full title misses, then a simplified "Main Title" retry also misses.
        assertEquals(2, http.requests.size)
        assertTrue("\"search\":\"Main Title\"" in http.requests[1].body.orEmpty())
        assertEquals(emptyList(), results)
    }

    @Test
    fun serverErrorsPropagateToCaller() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = emptyList()))
        val http = HttpService { HttpResponse(statusCode = 500, body = "boom") }

        val thrown = runCatching {
            RecommendationService(http, database).recommendations("Seed", DbItemType.Manga)
        }.exceptionOrNull()

        assertTrue(thrown is IllegalStateException)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/metadata/AnilistWatchOrderServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines AnilistWatchOrderServiceTest, searchQueriesAniListGraphQLAndParsesResults, watchOrderWalksRelationGraphFiltersNonAnimeOrdersChronologicallyAndMarksRoles, watchOrderByNameAutoBuildsWatchOrderDirectly, watchOrderAvoidsInfiniteLoopsOnCyclicRelationsAndRespectsQueryCap.

Read the setup, action and assertions in these cases before implementing their production paths:

  • searchQueriesAniListGraphQLAndParsesResults
  • watchOrderWalksRelationGraphFiltersNonAnimeOrdersChronologicallyAndMarksRoles
  • watchOrderByNameAutoBuildsWatchOrderDirectly
  • watchOrderAvoidsInfiniteLoopsOnCyclicRelationsAndRespectsQueryCap

Cross-chapter imports used by this file: HttpResponse, RecordingHttpService. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.metadata

import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class AnilistWatchOrderServiceTest {
    @Test
    fun searchQueriesAniListGraphQLAndParsesResults() = runTest {
        val http = RecordingHttpService { req ->
            assertTrue("graphql.anilist.co" in req.url)
            assertTrue("POST" == req.method)
            assertTrue("Mushoku Tensei" in req.body.orEmpty())
            HttpResponse(
                statusCode = 200,
                body = """
                    {
                      "data": {
                        "Page": {
                          "media": [
                            {
                              "id": 108465,
                              "idMal": 39535,
                              "title": {
                                "romaji": "Mushoku Tensei: Isekai Ittara Honki Dasu",
                                "english": "Mushoku Tensei: Jobless Reincarnation",
                                "native": "無職転生"
                              },
                              "coverImage": { "large": "https://s4.anilist.co/cover1.jpg", "color": "#f1a852" },
                              "format": "TV",
                              "episodes": 11,
                              "seasonYear": 2021,
                              "startDate": { "year": 2021, "month": 1 }
                            }
                          ]
                        }
                      }
                    }
                """.trimIndent(),
            )
        }

        val service = WatchOrderService(http)
        val hits = service.search("Mushoku Tensei")

        assertEquals(1, hits.size)
        assertEquals("108465", hits[0].id)
        assertEquals("Mushoku Tensei: Jobless Reincarnation", hits[0].name)
        assertEquals("https://s4.anilist.co/cover1.jpg", hits[0].imageUrl)
        assertEquals("TV", hits[0].type)
        assertEquals(2021, hits[0].year)
    }

    @Test
    fun watchOrderWalksRelationGraphFiltersNonAnimeOrdersChronologicallyAndMarksRoles() = runTest {
        // Media nodes:
        // S1: 108465 (2021/01) -> SEQUEL: 127720, SIDE_STORY: 146065, ADAPTATION (manga): 85470
        // S1 Part 2: 127720 (2021/10) -> SEQUEL: 146066
        // OVA: 146065 (2022/03) -> no further chain
        // S2: 146066 (2023/07) -> SEQUEL: 166873
        // S2 Part 2: 166873 (2024/04) -> SEQUEL: 180630
        // S3: 180630 (2026/04) -> no further chain

        val http = RecordingHttpService { req ->
            val body = req.body.orEmpty()
            val id = Regex("\"id\":\\s*(\\d+)").find(body)?.groupValues?.get(1)?.toIntOrNull()
            when (id) {
                108465 -> HttpResponse(
                    200,
                    """
                    {
                      "data": {
                        "Media": {
                          "id": 108465,
                          "title": { "romaji": "Mushoku Tensei S1", "english": "Jobless Reincarnation S1" },
                          "coverImage": { "large": "https://s4.anilist.co/s1.jpg" },
                          "format": "TV", "type": "ANIME", "episodes": 11,
                          "startDate": { "year": 2021, "month": 1 },
                          "relations": {
                            "edges": [
                              { "relationType": "SEQUEL", "node": { "id": 127720, "type": "ANIME", "startDate": { "year": 2021, "month": 10 } } },
                              { "relationType": "SIDE_STORY", "node": { "id": 146065, "type": "ANIME", "title": { "romaji": "Eris OVA" }, "coverImage": { "large": "https://s4.anilist.co/ova.jpg" }, "startDate": { "year": 2022, "month": 3 } } },
                              { "relationType": "ADAPTATION", "node": { "id": 85470, "type": "MANGA", "startDate": { "year": 2014, "month": 5 } } }
                            ]
                          }
                        }
                      }
                    }
                    """.trimIndent(),
                )
                127720 -> HttpResponse(
                    200,
                    """
                    {
                      "data": {
                        "Media": {
                          "id": 127720,
                          "title": { "romaji": "Mushoku Tensei S1 Part 2", "english": "Jobless Reincarnation S1 Part 2" },
                          "coverImage": { "large": "https://s4.anilist.co/s1p2.jpg" },
                          "format": "TV", "type": "ANIME", "episodes": 12,
                          "startDate": { "year": 2021, "month": 10 },
                          "relations": {
                            "edges": [
                              { "relationType": "PREQUEL", "node": { "id": 108465, "type": "ANIME", "startDate": { "year": 2021, "month": 1 } } },
                              { "relationType": "SEQUEL", "node": { "id": 146066, "type": "ANIME", "startDate": { "year": 2023, "month": 7 } } }
                            ]
                          }
                        }
                      }
                    }
                    """.trimIndent(),
                )
                146065 -> HttpResponse(
                    200,
                    """
                    {
                      "data": {
                        "Media": {
                          "id": 146065,
                          "title": { "romaji": "Eris the Goblin Slayer OVA" },
                          "coverImage": { "large": "https://s4.anilist.co/ova.jpg" },
                          "format": "OVA", "type": "ANIME", "episodes": 1,
                          "startDate": { "year": 2022, "month": 3 },
                          "relations": { "edges": [] }
                        }
                      }
                    }
                    """.trimIndent(),
                )
                146066 -> HttpResponse(
                    200,
                    """
                    {
                      "data": {
                        "Media": {
                          "id": 146066,
                          "title": { "romaji": "Mushoku Tensei S2", "english": "Jobless Reincarnation S2" },
                          "coverImage": { "large": "https://s4.anilist.co/s2.jpg" },
                          "format": "TV", "type": "ANIME", "episodes": 12,
                          "startDate": { "year": 2023, "month": 7 },
                          "relations": {
                            "edges": [
                              { "relationType": "PREQUEL", "node": { "id": 127720, "type": "ANIME", "startDate": { "year": 2021, "month": 10 } } },
                              { "relationType": "SEQUEL", "node": { "id": 166873, "type": "ANIME", "startDate": { "year": 2024, "month": 4 } } }
                            ]
                          }
                        }
                      }
                    }
                    """.trimIndent(),
                )
                166873 -> HttpResponse(
                    200,
                    """
                    {
                      "data": {
                        "Media": {
                          "id": 166873,
                          "title": { "romaji": "Mushoku Tensei S2 Part 2", "english": "Jobless Reincarnation S2 Part 2" },
                          "coverImage": { "large": "https://s4.anilist.co/s2p2.jpg" },
                          "format": "TV", "type": "ANIME", "episodes": 12,
                          "startDate": { "year": 2024, "month": 4 },
                          "relations": {
                            "edges": [
                              { "relationType": "PREQUEL", "node": { "id": 146066, "type": "ANIME", "startDate": { "year": 2023, "month": 7 } } },
                              { "relationType": "SEQUEL", "node": { "id": 180630, "type": "ANIME", "startDate": { "year": 2026, "month": 4 } } }
                            ]
                          }
                        }
                      }
                    }
                    """.trimIndent(),
                )
                180630 -> HttpResponse(
                    200,
                    """
                    {
                      "data": {
                        "Media": {
                          "id": 180630,
                          "title": { "romaji": "Mushoku Tensei S3", "english": "Jobless Reincarnation S3" },
                          "coverImage": { "large": "https://s4.anilist.co/s3.jpg" },
                          "format": "TV", "type": "ANIME", "episodes": 12,
                          "startDate": { "year": 2026, "month": 4 },
                          "relations": { "edges": [] }
                        }
                      }
                    }
                    """.trimIndent(),
                )
                else -> HttpResponse(404, "{}")
            }
        }

        val service = WatchOrderService(http)

        // Query anchored at S2 (146066)
        val entries = service.watchOrder("146066")

        // S1 (2021/01), S1 Part 2 (2021/10), OVA (2022/03), S2 (2023/07), S2 Part 2 (2024/04), S3 (2026/04)
        assertEquals(6, entries.size)

        // Verify chronological ordering
        assertEquals("108465", entries[0].id)
        assertEquals("127720", entries[1].id)
        assertEquals("146065", entries[2].id)
        assertEquals("146066", entries[3].id)
        assertEquals("166873", entries[4].id)
        assertEquals("180630", entries[5].id)

        // Verify roles relative to anchor (146066 / S2)
        assertEquals(WatchOrderRole.Previous, entries[0].role)
        assertEquals(WatchOrderRole.Previous, entries[1].role)
        assertEquals(WatchOrderRole.Previous, entries[2].role)
        assertEquals(WatchOrderRole.Current, entries[3].role) // anchor
        assertEquals(WatchOrderRole.Next, entries[4].role)
        assertEquals(WatchOrderRole.Next, entries[5].role)

        // Verify non-anime (Manga 85470) was excluded
        assertTrue(entries.none { it.id == "85470" })
    }

    @Test
    fun watchOrderByNameAutoBuildsWatchOrderDirectly() = runTest {
        val http = RecordingHttpService { req ->
            val body = req.body.orEmpty()
            if ("search" in body) {
                HttpResponse(
                    200,
                    """
                    {
                      "data": {
                        "Page": {
                          "media": [
                            {
                              "id": 108465,
                              "title": { "romaji": "Mushoku Tensei" },
                              "startDate": { "year": 2021, "month": 1 }
                            }
                          ]
                        }
                      }
                    }
                    """.trimIndent(),
                )
            } else {
                HttpResponse(
                    200,
                    """
                    {
                      "data": {
                        "Media": {
                          "id": 108465,
                          "title": { "romaji": "Mushoku Tensei S1" },
                          "format": "TV", "type": "ANIME", "episodes": 11,
                          "startDate": { "year": 2021, "month": 1 },
                          "relations": { "edges": [] }
                        }
                      }
                    }
                    """.trimIndent(),
                )
            }
        }

        val service = WatchOrderService(http)
        val entries = service.watchOrderByName("Mushoku Tensei")

        assertEquals(1, entries.size)
        assertEquals("108465", entries[0].id)
        assertEquals(WatchOrderRole.Current, entries[0].role)
    }

    @Test
    fun watchOrderAvoidsInfiniteLoopsOnCyclicRelationsAndRespectsQueryCap() = runTest {
        // Cyclic: A -> B -> A
        var callCount = 0
        val http = RecordingHttpService { req ->
            callCount++
            val id = Regex("\"id\":\\s*(\\d+)").find(req.body.orEmpty())?.groupValues?.get(1)?.toIntOrNull() ?: 1
            val nextId = if (id == 1) 2 else 1
            HttpResponse(
                200,
                """
                {
                  "data": {
                    "Media": {
                      "id": $id,
                      "title": { "romaji": "Anime $id" },
                      "format": "TV", "type": "ANIME",
                      "startDate": { "year": ${2020 + id}, "month": 1 },
                      "relations": {
                        "edges": [
                          { "relationType": "SEQUEL", "node": { "id": $nextId, "type": "ANIME" } }
                        ]
                      }
                    }
                  }
                }
                """.trimIndent(),
            )
        }

        val service = WatchOrderService(http)
        val entries = service.watchOrder("1")

        assertEquals(2, entries.size)
        assertEquals(2, callCount) // visited set stops the loop after node 1 and 2
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/metadata/ChiakiWatchOrderServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines ChiakiWatchOrderServiceTest, searchParsesAutocompleteHits, watchOrderParsesRenderedRows, watchOrderFlattensLiveMetaMarkup, sequelsPostListSourceAndParseWrappedResult, sequelsWithoutUsernamesShortCircuit.

Read the setup, action and assertions in these cases before implementing their production paths:

  • searchParsesAutocompleteHits
  • watchOrderParsesRenderedRows
  • watchOrderFlattensLiveMetaMarkup
  • sequelsPostListSourceAndParseWrappedResult
  • sequelsWithoutUsernamesShortCircuit

Cross-chapter imports used by this file: HttpResponse, RecordingHttpService. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.metadata

import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class ChiakiWatchOrderServiceTest {
    @Test
    fun searchParsesAutocompleteHits() = runTest {
        val http = RecordingHttpService {
            HttpResponse(
                statusCode = 200,
                body = """[{"id":52701,"value":"Dungeon Meshi","image":"media/a/be/t/52701.jpg","type":"TV","year":2024}]""",
            )
        }

        val hits = WatchOrderService(http).searchChiaki("Dungeon Meshi")

        assertTrue("autocomplete_series&term=Dungeon%20Meshi" in http.requests[0].url)
        assertEquals(
            listOf(
                WatchOrderSearchResult(
                    id = "52701",
                    name = "Dungeon Meshi",
                    imageUrl = "https://chiaki.site/media/a/be/t/52701.jpg",
                    type = "TV",
                    year = 2024,
                ),
            ),
            hits,
        )
    }

    @Test
    fun watchOrderParsesRenderedRows() {
        val html = """
            <table><tbody>
            <tr class="row" data-id="36577" data-anilist-id="">
              <td><div class="wo_avatar_big" style="background-image:url('media/a/b1/36577.jpg')"></div></td>
              <td><span class="wo_title uk-text-bold">Dungeon Meshi PVs</span>
                  <span class="uk-text-small">Delicious in Dungeon PVs</span>
                  <span class="uk-text-muted uk-text-small">PV · 3 eps · 2017</span></td>
            </tr>
            <tr class="row" data-id="52701" data-anilist-id="153518">
              <td><div class="wo_avatar_big" style="background-image:url('media/a/be/52701.jpg')"></div></td>
              <td><span class="wo_title">Dungeon Meshi</span>
                  <span class="uk-text-muted uk-text-small">TV · 24 eps · 2024</span></td>
            </tr>
            </tbody></table>
        """.trimIndent()

        val rows = parseWatchOrderRows(html)

        assertEquals(2, rows.size)
        assertEquals("36577", rows[0].id)
        assertEquals(null, rows[0].anilistId)
        assertEquals("Dungeon Meshi PVs", rows[0].title)
        assertEquals("Delicious in Dungeon PVs", rows[0].titleEnglish)
        assertEquals("PV · 3 eps · 2017", rows[0].info)
        assertEquals("https://chiaki.site/media/a/b1/36577.jpg", rows[0].imageUrl)
        assertEquals("153518", rows[1].anilistId)
        assertEquals(null, rows[1].titleEnglish)
    }

    @Test
    fun watchOrderFlattensLiveMetaMarkup() {
        val html = """
            <tr data-id="52701" data-anilist-id="153518" data-type="1" data-eps="24">
              <td><div class="wo_avatar_big" style="background-image:url('media/a/be/52701.jpg')"></div></td>
              <td class="uk-text-middle">
                <span class="wo_title">Dungeon Meshi</span><br>
                <span class="uk-text-small">Delicious in Dungeon</span><br>
                <span class="wo_meta">
                  Jan 4 – Jun 13, 2024 | TV | 24ep × 25min. | <span class="wo_rating">★8.59 (304,209)</span>
                  | <a href="https://myanimelist.net/anime/52701"><span class="uk-icon" style="background-image:url('media/mal.png')"></span></a>
                </span>
                <div class="list_status"></div>
              </td>
            </tr>
        """.trimIndent()

        val rows = parseWatchOrderRows(html)

        assertEquals(1, rows.size)
        assertEquals("Jan 4 – Jun 13, 2024 | TV | 24ep × 25min. | ★8.59 (304,209)", rows[0].info)
        assertEquals("https://chiaki.site/media/a/be/52701.jpg", rows[0].imageUrl)
    }

    @Test
    fun sequelsPostListSourceAndParseWrappedResult() = runTest {
        val http = RecordingHttpService {
            HttpResponse(
                statusCode = 200,
                body = """
                    {"data":{"result":[{"id":28171,"anilist_id":20923,"image_url":"media/s.jpg","episodes":24,"title":"Sequel S2",
                      "group":"g","group_id":1,"period":"2025","score":811,"score_users":1000,"type":"TV",
                      "reason":[{"id":52701,"image_url":"media/r.jpg","title":"Season 1"}]}],"entry_count":1}}
                """.trimIndent(),
            )
        }

        val sequels = WatchOrderService(http).sequels("maluser", null)

        assertEquals("POST", http.requests[0].method)
        assertTrue("user=maluser&list_source=mal" in http.requests[0].body.orEmpty())
        assertEquals(1, sequels.size)
        assertEquals("Sequel S2", sequels[0].title)
        assertEquals("8.11", sequels[0].score)
        assertEquals(listOf("52701"), sequels[0].reasons.map(SequelReasonRef::id))
    }

    @Test
    fun sequelsWithoutUsernamesShortCircuit() = runTest {
        val http = RecordingHttpService { HttpResponse(200, "{}") }

        assertEquals(emptyList(), WatchOrderService(http).sequels(null, null))
        assertEquals(0, http.requests.size)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/metadata/LocalMetadataSelectionPolicyTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines LocalMetadataSelectionPolicyTest, selectionOnlyAllowsExplicitlyChosenAvailableFields, emptySelectionCannotWriteAnything.

Read the setup, action and assertions in these cases before implementing their production paths:

  • selectionOnlyAllowsExplicitlyChosenAvailableFields
  • emptySelectionCannotWriteAnything

Cross-chapter imports used by this file: DbItemType. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.metadata

import eu.friedcutlet.yokan.database.DbItemType
import kotlin.test.Test
import kotlin.test.assertEquals

class LocalMetadataSelectionPolicyTest {
    @Test
    fun selectionOnlyAllowsExplicitlyChosenAvailableFields() {
        val candidate = MetadataMedia(
            id = "1",
            source = "metadata",
            mediaType = DbItemType.Manga,
            title = "Candidate",
            description = "Description",
        )

        assertEquals(
            setOf(LocalMetadataField.Title, LocalMetadataField.Description),
            selectedLocalMetadataFields(
                setOf(LocalMetadataField.Title, LocalMetadataField.Description, LocalMetadataField.Cover),
                candidate,
            ),
        )
    }

    @Test
    fun emptySelectionCannotWriteAnything() {
        val candidate = MetadataMedia("1", "metadata", DbItemType.Manga, "Candidate")
        assertEquals(emptySet(), selectedLocalMetadataFields(emptySet(), candidate))
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/AnilistTrackerProfileTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines AnilistTrackerProfileTest, readsViewerNameAndMediumAvatarWithBearerToken.

Read the setup, action and assertions in these cases before implementing their production paths:

  • readsViewerNameAndMediumAvatarWithBearerToken

Cross-chapter imports used by this file: DbTrackPreference, InMemoryYokanDatabase, seedDatabaseSnapshot, HttpResponse, RecordingHttpService. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.test.runTest

class AnilistTrackerProfileTest {
    @Test
    fun readsViewerNameAndMediumAvatarWithBearerToken() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot()).also {
            it.upsertTrackPreference(DbTrackPreference(syncId = 2, oauth = "secret-token"))
        }
        val http = RecordingHttpService { HttpResponse(statusCode = 200, body = """{"data":{"Viewer":{"name":"Yoko","avatar":{"medium":"https://img.test/a"}}}}""") }

        val profile = AnilistTrackerService(2, database, http).accountProfile()

        assertEquals(TrackerAccountProfile("Yoko", "https://img.test/a"), profile)
        assertEquals("Bearer secret-token", http.requests.single().headers["Authorization"])
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/BangumiTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines BangumiTrackerServiceTest, loggedIn, loginWithPersonalTokenValidatesViaMe, loginWithOAuthCodeExchangesToken, searchesByIdAndText, bindAdoptsExistingCollection, bindCreatesMissingCollection, updatePatchesAndFallsBackToCreate, refreshAndNoOpUnbind, unauthorizedRefreshesOAuthTokenOnce and 2 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginWithPersonalTokenValidatesViaMe
  • loginWithOAuthCodeExchangesToken
  • searchesByIdAndText
  • bindAdoptsExistingCollection
  • bindCreatesMissingCollection
  • updatePatchesAndFallsBackToCreate
  • refreshAndNoOpUnbind
  • unauthorizedRefreshesOAuthTokenOnce
  • unauthorizedPersonalTokenThrows
  • expiredOAuthTokenRefreshesWithRedirectUriBeforeTheCall

Cross-chapter imports used by this file: DbItemType, DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class BangumiTrackerServiceTest {
    private val me = """{"id":1001,"username":"sai","nickname":"Sai","avatar":{"large":"https://lain.bgm.tv/pic/user/l/1001.jpg"}}"""
    private val collection = """{"subject_id":42,"subject_type":1,"rate":8,"type":3,"ep_status":12,"vol_status":2,"private":false,"subject":{"id":42,"eps":30,"volumes":5}}"""

    private fun loggedIn(token: String = "tok", refresh: String? = null) = InMemoryYokanDatabase().also {
        it.upsertTrackPreference(
            DbTrackPreference(
                syncId = 12,
                username = "sai",
                oauth = token,
                prefs = TrackerCredentials(clientId = "cid", clientSecret = "sec", refreshToken = refresh).encode(),
            ),
        )
    }

    private val track = DbTrack(id = 3, mangaId = 9, syncId = 12, mediaId = 42, status = DbTrackStatus.PlanToRead, lastChapterRead = 0, itemType = DbItemType.Manga)

    @Test
    fun loginWithPersonalTokenValidatesViaMe() = runTest {
        val mock = MockTrackerHttp { 200 to me }
        val pref = BangumiTrackerService(12, InMemoryYokanDatabase(), mock.http).login(mapOf(TrackerLoginField.ApiKey to " pat "))

        assertEquals("pat", pref.oauth)
        assertEquals("sai", pref.username)
        assertEquals("Sai", pref.accountName)
        assertEquals(null, pref.credentials().refreshToken)
        val request = mock.requests.single()
        assertTrue(request.url.endsWith("/v0/me"))
        assertEquals("Bearer pat", request.headers["Authorization"])
        assertEquals("Yokan", request.headers["User-Agent"])
    }

    @Test
    fun loginWithOAuthCodeExchangesToken() = runTest {
        val mock = MockTrackerHttp { req ->
            if (req.url == "https://bgm.tv/oauth/access_token") {
                200 to """{"access_token":"A","expires_in":604800,"token_type":"Bearer","scope":null,"refresh_token":"R","user_id":1001}"""
            } else {
                200 to me
            }
        }
        val service = BangumiTrackerService(12, InMemoryYokanDatabase(), mock.http)
        val pref = service.login(
            mapOf(
                TrackerLoginField.ClientId to "cid",
                TrackerLoginField.ClientSecret to "sec",
                TrackerLoginField.AuthorizationCode to "yokan://tracker/bangumi?code=xyz",
            ),
        )

        assertEquals("A", pref.oauth)
        assertEquals("R", pref.credentials().refreshToken)
        assertEquals("1001", pref.credentials().userId)
        val exchange = mock.requests.first()
        assertEquals("POST", exchange.method)
        assertTrue("grant_type=authorization_code" in exchange.body && "code=xyz" in exchange.body && "redirect_uri=yokan%3A%2F%2Ftracker%2Fbangumi" in exchange.body)
        assertEquals("Bearer A", mock.requests[1].headers["Authorization"])
        assertTrue(service.authorizeUrl(mapOf(TrackerLoginField.ClientId to "cid")).startsWith("https://bgm.tv/oauth/authorize?client_id=cid&response_type=code"))
        assertEquals("https://next.bgm.tv/demo/access-token", service.authorizeUrl(emptyMap()))
    }

    @Test
    fun searchesByIdAndText() = runTest {
        val subject = """{"id":42,"name":"ベルセルク","name_cn":"剑风传奇","summary":" Guts ","date":"1990-11-26","platform":"漫画","images":{"common":"https://lain.bgm.tv/pic/cover/c/42.jpg"},"volumes":41,"eps":0,"rating":{"score":8.9}}"""
        val mock = MockTrackerHttp { req ->
            when {
                req.url.endsWith("/v0/subjects/42") -> 200 to subject
                req.url.endsWith("/v0/subjects/1") -> 404 to """{"title":"Not Found"}"""
                "/v0/search/subjects" in req.url -> 200 to """{"total":1,"limit":20,"offset":0,"data":[$subject]}"""
                else -> 404 to ""
            }
        }
        val service = BangumiTrackerService(12, loggedIn(), mock.http)

        val byId = service.search("id:42", isManga = true).single()
        assertEquals(42L, byId.mediaId)
        assertEquals("剑风传奇", byId.title)
        assertEquals("https://bgm.tv/subject/42", byId.trackingUrl)
        assertEquals(8.9, byId.score)
        assertEquals("1990-11-26", byId.startDate)
        assertEquals(emptyList(), service.search("id:1", isManga = true))

        assertEquals(1, service.search("berserk", isManga = false).size)
        val search = mock.requests.last()
        assertEquals("POST", search.method)
        val body = trackerJson.parseToJsonElement(search.body).jsonObject
        assertEquals("berserk", body["keyword"]!!.jsonPrimitive.content)
        assertEquals(2, body["filter"]!!.jsonObject["type"]!!.jsonArray.single().jsonPrimitive.int)
    }

    @Test
    fun bindAdoptsExistingCollection() = runTest {
        val mock = MockTrackerHttp { 200 to collection }
        val bound = BangumiTrackerService(12, loggedIn(), mock.http).bind(track, isManga = true)

        assertEquals(DbTrackStatus.Reading, bound.status)
        assertEquals(12, bound.lastChapterRead)
        assertEquals(8, bound.score)
        assertEquals(30, bound.totalChapter)
        assertEquals(3, bound.id)
        assertTrue(mock.requests.single().url.endsWith("/v0/users/sai/collections/42"))
    }

    @Test
    fun bindCreatesMissingCollection() = runTest {
        val mock = MockTrackerHttp { req -> if (req.method == "GET") 404 to """{"title":"Not Found"}""" else 202 to "" }
        val bound = BangumiTrackerService(12, loggedIn(), mock.http)
            .bind(track.copy(status = DbTrackStatus.PlanToWatch, itemType = DbItemType.Anime), isManga = false)

        assertEquals(DbTrackStatus.PlanToWatch, bound.status)
        val post = mock.requests.last()
        assertEquals("POST", post.method)
        assertTrue(post.url.endsWith("/v0/users/-/collections/42"))
        val body = trackerJson.parseToJsonElement(post.body).jsonObject
        assertEquals(1, body["type"]!!.jsonPrimitive.int)
        assertEquals(0, body["rate"]!!.jsonPrimitive.int)
        assertEquals(0, body["ep_status"]!!.jsonPrimitive.int)
    }

    @Test
    fun updatePatchesAndFallsBackToCreate() = runTest {
        val mock = MockTrackerHttp { 204 to "" }
        val updated = BangumiTrackerService(12, loggedIn(), mock.http)
            .update(track.copy(lastChapterRead = 5, score = 7), isManga = true)

        assertEquals(DbTrackStatus.Reading, updated.status)
        val patch = mock.requests.single()
        assertEquals("PATCH", patch.method)
        val body = trackerJson.parseToJsonElement(patch.body).jsonObject
        assertEquals(3, body["type"]!!.jsonPrimitive.int)
        assertEquals(7, body["rate"]!!.jsonPrimitive.int)
        assertEquals(5, body["ep_status"]!!.jsonPrimitive.int)

        val missing = MockTrackerHttp { req -> if (req.method == "PATCH") 404 to """{"title":"Not Found"}""" else 202 to "" }
        BangumiTrackerService(12, loggedIn(), missing.http).update(track.copy(status = DbTrackStatus.Completed), isManga = true)
        assertEquals(listOf("PATCH", "POST"), missing.requests.map { it.method })
        assertEquals(2, trackerJson.parseToJsonElement(missing.requests.last().body).jsonObject["type"]!!.jsonPrimitive.int)
    }

    @Test
    fun refreshAndNoOpUnbind() = runTest {
        val mock = MockTrackerHttp { 200 to collection }
        val service = BangumiTrackerService(12, loggedIn(), mock.http)
        assertEquals(12, service.refresh(track, isManga = true).lastChapterRead)
        service.unbind(track, isManga = true)
        assertEquals(1, mock.requests.size)

        val none = MockTrackerHttp { 404 to """{"title":"Not Found"}""" }
        assertEquals(track, BangumiTrackerService(12, loggedIn(), none.http).refresh(track, isManga = true))
    }

    @Test
    fun unauthorizedRefreshesOAuthTokenOnce() = runTest {
        val mock = MockTrackerHttp { req ->
            when {
                req.url == "https://bgm.tv/oauth/access_token" -> 200 to """{"access_token":"new","expires_in":604800,"token_type":"Bearer","refresh_token":"R2","user_id":1001}"""
                req.headers["Authorization"] == "Bearer old" -> 401 to """{"title":"Unauthorized"}"""
                else -> 200 to collection
            }
        }
        val database = loggedIn(token = "old", refresh = "R1")

        assertEquals(12, BangumiTrackerService(12, database, mock.http).refresh(track, isManga = true).lastChapterRead)
        assertTrue("grant_type=refresh_token" in mock.requests[1].body && "refresh_token=R1" in mock.requests[1].body)
        val stored = database.trackPreferences().single { it.syncId == 12L }
        assertEquals("new", stored.oauth)
        assertEquals("R2", stored.credentials().refreshToken)
    }

    @Test
    fun unauthorizedPersonalTokenThrows() = runTest {
        val mock = MockTrackerHttp { 401 to """{"title":"Unauthorized"}""" }
        val error = runCatching { BangumiTrackerService(12, loggedIn(), mock.http).refresh(track, isManga = true) }.exceptionOrNull()
        assertEquals(401, (error as TrackerHttpException).status)
        assertEquals(1, mock.requests.size)
    }

    @Test
    fun expiredOAuthTokenRefreshesWithRedirectUriBeforeTheCall() = runTest {
        val mock = MockTrackerHttp { req ->
            if (req.url == "https://bgm.tv/oauth/access_token") {
                200 to """{"access_token":"new","expires_in":604800,"token_type":"Bearer","refresh_token":"R2"}"""
            } else {
                200 to collection
            }
        }
        val database = InMemoryYokanDatabase().also {
            it.upsertTrackPreference(
                DbTrackPreference(
                    syncId = 12,
                    username = "sai",
                    oauth = "old",
                    prefs = TrackerCredentials(clientId = "cid", clientSecret = "sec", refreshToken = "R1", expiresAt = 1).encode(),
                ),
            )
        }

        BangumiTrackerService(12, database, mock.http).refresh(track, isManga = true)

        assertEquals(2, mock.requests.size)
        assertTrue("grant_type=refresh_token" in mock.requests[0].body && "redirect_uri=yokan%3A%2F%2Ftracker%2Fbangumi" in mock.requests[0].body)
        assertEquals("Bearer new", mock.requests[1].headers["Authorization"])
        assertEquals("new", database.trackPreference(12)?.oauth)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/ExistingTrackerIdSearchTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines ExistingTrackerIdSearchTest, anilistIdQueriesMedia, anilistMissingIdIsEmpty, malIdUsesBearerWhenLoggedIn, malIdUsesClientIdOrJikan, kitsuIdFetchesSingleResource, simklIdFetchesAnime, traktIdAcceptsSlug.

Read the setup, action and assertions in these cases before implementing their production paths:

  • anilistIdQueriesMedia
  • anilistMissingIdIsEmpty
  • malIdUsesBearerWhenLoggedIn
  • malIdUsesClientIdOrJikan
  • kitsuIdFetchesSingleResource
  • simklIdFetchesAnime
  • traktIdAcceptsSlug

Cross-chapter imports used by this file: DbTrackPreference, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class ExistingTrackerIdSearchTest {
    @Test
    fun anilistIdQueriesMedia() = runTest {
        val mock = MockTrackerHttp {
            200 to """{"data":{"Media":{"id":30013,"title":{"romaji":"One Piece","english":null},"coverImage":{"large":"c.jpg"},"chapters":1100,"siteUrl":"https://anilist.co/manga/30013"}}}"""
        }
        val result = AnilistTrackerService(2, InMemoryYokanDatabase(), mock.http).search("id:30013", isManga = true)
        assertEquals(listOf(30013L), result.map { it.mediaId })
        assertEquals("One Piece", result.single().title)
        val req = mock.requests.single()
        assertEquals("POST", req.method)
        assertTrue("Media(id:" in req.body && "\"id\":30013" in req.body && "\"type\":\"MANGA\"" in req.body, req.body)
    }

    @Test
    fun anilistMissingIdIsEmpty() = runTest {
        val mock = MockTrackerHttp { 404 to """{"errors":[{"message":"Not Found.","status":404}],"data":{"Media":null}}""" }
        assertEquals(emptyList(), AnilistTrackerService(2, InMemoryYokanDatabase(), mock.http).search("id:1", true))
        assertEquals(emptyList(), AnilistTrackerService(2, InMemoryYokanDatabase(), mock.http).search("id:abc", true))
        assertEquals(1, mock.requests.size)
    }

    @Test
    fun malIdUsesBearerWhenLoggedIn() = runTest {
        val db = InMemoryYokanDatabase()
        db.upsertTrackPreference(DbTrackPreference(syncId = 1, oauth = "tok"))
        val mock = MockTrackerHttp {
            200 to """{"id":2,"title":"Berserk","main_picture":{"large":"b.jpg"},"num_chapters":380,"status":"currently_publishing","mean":9.4}"""
        }
        val result = MalTrackerService(1, db, mock.http).search("id:2", isManga = true)
        assertEquals(2L, result.single().mediaId)
        assertEquals(380, result.single().totalChapter)
        val req = mock.requests.single()
        assertTrue(req.url.startsWith("https://api.myanimelist.net/v2/manga/2?fields="), req.url)
        assertEquals("Bearer tok", req.headers["Authorization"])
    }

    @Test
    fun malIdUsesClientIdOrJikan() = runTest {
        val db = InMemoryYokanDatabase()
        db.upsertTrackPreference(DbTrackPreference(syncId = 1, prefs = TrackerCredentials(clientId = "cid").encode()))
        val mock = MockTrackerHttp { 200 to """{"id":21,"title":"One Punch","num_episodes":12}""" }
        MalTrackerService(1, db, mock.http).search("id:21", isManga = false)
        assertTrue(mock.requests.single().url.startsWith("https://api.myanimelist.net/v2/anime/21?"))
        assertEquals("cid", mock.requests.single().headers["X-MAL-CLIENT-ID"])

        val jikan = MockTrackerHttp { 200 to """{"data":{"mal_id":21,"title":"One Punch","episodes":12,"url":"https://myanimelist.net/anime/21"}}""" }
        val result = MalTrackerService(1, InMemoryYokanDatabase(), jikan.http).search("id:21", isManga = false)
        assertEquals("https://api.jikan.moe/v4/anime/21", jikan.requests.single().url)
        assertEquals(12, result.single().totalChapter)
    }

    @Test
    fun kitsuIdFetchesSingleResource() = runTest {
        val mock = MockTrackerHttp { req ->
            if (req.url.endsWith("/manga/9")) {
                200 to """{"data":{"id":"9","type":"manga","attributes":{"canonicalTitle":"Naruto","chapterCount":700,"slug":"naruto"}}}"""
            } else {
                404 to """{"errors":[{"status":"404"}]}"""
            }
        }
        val service = KitsuTrackerService(3, InMemoryYokanDatabase(), mock.http)
        assertEquals(listOf(9L), service.search("id:9", true).map { it.mediaId })
        assertEquals("https://kitsu.io/api/edge/manga/9", mock.requests.first().url)
        assertEquals(emptyList(), service.search("id:10", true))
    }

    @Test
    fun simklIdFetchesAnime() = runTest {
        val db = InMemoryYokanDatabase()
        db.upsertTrackPreference(DbTrackPreference(syncId = 4, username = "key"))
        val mock = MockTrackerHttp { 200 to """{"title":"Frieren","ids":{"simkl":2114},"total_episodes":28}""" }
        val service = SimklTrackerService(4, db, mock.http)
        val result = service.search("id:2114", isManga = false)
        assertEquals(2114L, result.single().mediaId)
        assertEquals("https://api.simkl.com/anime/2114?extended=full&client_id=key", mock.requests.single().url)
        assertEquals(emptyList(), service.search("id:frieren", isManga = false))
        assertEquals(1, mock.requests.size)
    }

    @Test
    fun traktIdAcceptsSlug() = runTest {
        val mock = MockTrackerHttp { req ->
            if ("/shows/" in req.url) {
                200 to """{"title":"Breaking Bad","year":2008,"ids":{"trakt":1388,"slug":"breaking-bad"},"aired_episodes":62}"""
            } else {
                404 to ""
            }
        }
        val service = TraktTrackerService(5, InMemoryYokanDatabase(), mock.http)
        val result = service.search("id:breaking-bad", isManga = false)
        assertEquals(1388L, result.single().mediaId)
        assertEquals("https://trakt.tv/shows/breaking-bad", result.single().trackingUrl)
        val req = mock.requests.single()
        assertEquals("https://api.trakt.tv/shows/breaking-bad?extended=full", req.url)
        assertEquals("2", req.headers["trakt-api-version"])
        assertEquals(emptyList(), service.search("id:1", isManga = true))
        assertEquals(1, mock.requests.size) // Trakt tracks shows only
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/HikkaTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines HikkaTrackerServiceTest, read, service, loginExchangesReferenceAndStoresSession, searchByIdAndText, bindAdoptsExistingEntry, bindCreatesMissingEntryAndUpdateMapsWireFormat, animeUsesWatchEndpoint, refreshWithoutEntryKeepsTrackAndUnbindDeletes, expiredOrRejectedSessionThrows.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginExchangesReferenceAndStoresSession
  • searchByIdAndText
  • bindAdoptsExistingEntry
  • bindCreatesMissingEntryAndUpdateMapsWireFormat
  • animeUsesWatchEndpoint
  • refreshWithoutEntryKeepsTrackAndUnbindDeletes
  • expiredOrRejectedSessionThrows

Cross-chapter imports used by this file: DbItemType, DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertTrue

class HikkaTrackerServiceTest {
    private val manga = """{"data_type":"manga","title_original":"Berserk","title_en":"Berserk EN","title_ua":null,
        "media_type":"manga","chapters":380,"volumes":42,"translated_ua":false,"status":"ongoing","image":"https://cdn/b.jpg",
        "year":1989,"scored_by":100,"score":9.4,"slug":"berserk-abc"}"""

    private fun read(status: String, chapters: Int, score: Int, rereads: Int = 0) =
        """{"reference":"r1","note":null,"updated":1,"created":1,"status":"$status","chapters":$chapters,"volumes":0,
        "rereads":$rereads,"score":$score,"start_date":1700000000,"end_date":null,"manga":$manga}"""

    private fun service(route: (RecordedRequest) -> Pair<Int, String>, expiresAt: Long? = null): Pair<HikkaTrackerService, MockTrackerHttp> {
        val db = InMemoryYokanDatabase()
        db.upsertTrackPreference(
            DbTrackPreference(syncId = 13, oauth = "sess", prefs = TrackerCredentials(expiresAt = expiresAt).encode()),
        )
        val mock = MockTrackerHttp(route)
        return HikkaTrackerService(13, db, mock.http) to mock
    }

    private val track = DbTrack(id = 5, mangaId = 7, syncId = 13, status = DbTrackStatus.PlanToRead, lastChapterRead = 3, score = 8,
        trackingUrl = "https://hikka.io/manga/berserk-abc", libraryId = 7, itemType = DbItemType.Manga)

    @Test
    fun loginExchangesReferenceAndStoresSession() = runTest {
        val mock = MockTrackerHttp { req ->
            when {
                req.url.endsWith("/auth/token") -> 200 to """{"secret":"tok","expiration":2000000000,"created":1}"""
                req.url.endsWith("/user/me") -> 200 to """{"reference":"u-1","username":"neo"}"""
                else -> 404 to ""
            }
        }
        val service = HikkaTrackerService(13, InMemoryYokanDatabase(), mock.http)
        assertEquals(
            "https://hikka.io/oauth?reference=client-ref&scope=readlist%2Cwatchlist%2Cread%3Auser-details",
            service.authorizeUrl(mapOf(TrackerLoginField.ClientId to "client-ref")),
        )
        val pref = service.login(
            mapOf(
                TrackerLoginField.ClientId to "client-ref",
                TrackerLoginField.ClientSecret to "shh",
                TrackerLoginField.AuthorizationCode to "yokan://tracker/hikka?reference=req-9",
            ),
        )
        val token = trackerJson.parseToJsonElement(mock.requests[0].body).jsonObject
        assertEquals("req-9", token["request_reference"]!!.jsonPrimitive.content)
        assertEquals("shh", token["client_secret"]!!.jsonPrimitive.content)
        assertEquals("tok", mock.requests[1].headers["auth"])
        assertEquals("tok", pref.oauth)
        assertEquals("neo", pref.username)
        assertEquals(2_000_000_000_000L, pref.credentials().expiresAt)
        assertEquals("u-1", pref.credentials().userId)
    }

    @Test
    fun searchByIdAndText() = runTest {
        val (service, mock) = service({ req ->
            when {
                req.url == "https://api.hikka.io/manga/berserk-abc" -> 200 to manga
                req.url.endsWith("/manga/missing") -> 404 to """{"message":"not found"}"""
                req.method == "POST" -> 200 to """{"pagination":{"total":1,"pages":1,"page":1},"list":[$manga]}"""
                else -> 404 to ""
            }
        })
        val byId = service.search("id:berserk-abc", true).single()
        assertEquals("https://hikka.io/manga/berserk-abc", byId.trackingUrl)
        assertEquals("Berserk EN", byId.title)
        assertEquals(380, byId.totalChapter)
        assertNull(byId.mediaId)
        assertTrue(service.search("id:missing", true).isEmpty())
        val text = service.search("berserk", true)
        assertEquals(1, text.size)
        val post = mock.requests.last()
        assertEquals("https://api.hikka.io/manga?page=1&size=50", post.url)
        assertEquals("berserk", trackerJson.parseToJsonElement(post.body).jsonObject["query"]!!.jsonPrimitive.content)
        assertEquals("sess", post.headers["auth"])
    }

    @Test
    fun bindAdoptsExistingEntry() = runTest {
        val (service, mock) = service({ req -> if (req.method == "GET") 200 to read("on_hold", 50, 9) else 400 to "" })
        val bound = service.bind(track, true)
        assertEquals(DbTrackStatus.OnHold, bound.status)
        assertEquals(50, bound.lastChapterRead)
        assertEquals(9, bound.score)
        assertEquals(1_700_000_000_000L, bound.startedReadingDate)
        assertEquals(5, bound.id)
        assertEquals(1, mock.requests.size)
        assertEquals("https://api.hikka.io/read/manga/berserk-abc", mock.requests[0].url)
    }

    @Test
    fun bindCreatesMissingEntryAndUpdateMapsWireFormat() = runTest {
        val (service, mock) = service({ req ->
            when (req.method) {
                "GET" -> 404 to """{"message":"not found"}"""
                "PUT" -> 200 to read("reading", 3, 8)
                else -> 400 to ""
            }
        })
        val bound = service.bind(track, true)
        assertEquals(DbTrackStatus.Reading, bound.status)
        val put = mock.requests.last()
        assertEquals("PUT", put.method)
        assertEquals("https://api.hikka.io/read/manga/berserk-abc", put.url)
        val body = trackerJson.parseToJsonElement(put.body).jsonObject
        assertEquals("reading", body["status"]!!.jsonPrimitive.content) // PlanToRead + progress → reading
        assertEquals(3, body["chapters"]!!.jsonPrimitive.int)
        assertEquals(8, body["score"]!!.jsonPrimitive.int)
        assertEquals(0, body["rereads"]!!.jsonPrimitive.int)
    }

    @Test
    fun animeUsesWatchEndpoint() = runTest {
        val (service, mock) = service({ req ->
            when (req.method) {
                "GET" -> 200 to """{"status":"watching","episodes":4,"rewatches":0,"score":7}"""
                "PUT" -> 200 to """{"status":"planned","episodes":0,"rewatches":0,"score":0}"""
                else -> 400 to ""
            }
        })
        val anime = track.copy(trackingUrl = "https://hikka.io/anime/frieren", status = DbTrackStatus.PlanToWatch, lastChapterRead = 0,
            score = 0, itemType = DbItemType.Anime)
        assertEquals(DbTrackStatus.Watching, service.refresh(anime, false).status)
        assertEquals(DbTrackStatus.PlanToWatch, service.update(anime, false).status)
        val put = mock.requests.last()
        assertEquals("https://api.hikka.io/watch/frieren", put.url)
        val body = trackerJson.parseToJsonElement(put.body).jsonObject
        assertEquals("planned", body["status"]!!.jsonPrimitive.content)
        assertEquals(0, body["episodes"]!!.jsonPrimitive.int)
    }

    @Test
    fun refreshWithoutEntryKeepsTrackAndUnbindDeletes() = runTest {
        val (service, mock) = service({ req -> if (req.method == "DELETE") 200 to "{}" else 404 to "{}" })
        assertEquals(track, service.refresh(track, true))
        service.unbind(track, true)
        assertEquals("DELETE", mock.requests.last().method)
        assertEquals("https://api.hikka.io/read/manga/berserk-abc", mock.requests.last().url)
    }

    @Test
    fun expiredOrRejectedSessionThrows() = runTest {
        val (expired, expiredMock) = service({ 200 to "{}" }, expiresAt = 1L)
        assertEquals(401, assertFailsWith<TrackerHttpException> { expired.refresh(track, true) }.status)
        assertTrue(expiredMock.requests.isEmpty())
        val (rejected, _) = service({ 401 to """{"message":"auth"}""" })
        assertTrue(assertFailsWith<TrackerHttpException> { rejected.refresh(track, true) }.unauthorized)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/JellyfinTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines JellyfinTrackerServiceTest, episode, route, loggedIn, loginAuthenticatesByName, wrongPasswordThrows, matchesSeasonLinks, movieCountsAsOneEpisode, acceptsByNameOrHost, updateMarksEpisodesUpToProgressPlayed and 2 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginAuthenticatesByName
  • wrongPasswordThrows
  • matchesSeasonLinks
  • movieCountsAsOneEpisode
  • acceptsByNameOrHost
  • updateMarksEpisodesUpToProgressPlayed
  • updateMovieMarksPlayed
  • revokedTokenFails

Cross-chapter imports used by this file: DbManga, DbSource, DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

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.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class JellyfinTrackerServiceTest {
    private val server = "https://jf.example"
    private val user = "u1"

    private fun episode(id: String, index: Int, played: Boolean) =
        """{"Name":"Ep $index","Id":"$id","Type":"Episode","IndexNumber":$index,"UserData":{"Played":$played}}"""

    private fun route(request: RecordedRequest): Pair<Int, String> = when {
        request.url.endsWith("/Users/AuthenticateByName") ->
            if (request.body.contains("\"Pw\":\"secret\"")) 200 to """{"User":{"Name":"Ann","Id":"$user"},"AccessToken":"tok","ServerId":"s"}"""
            else 401 to ""
        request.serverHeader("X-Emby-Token") != "tok" -> 401 to ""
        request.url == "$server/Items/season1?userId=$user" ->
            200 to """{"Name":"Season 1","Id":"season1","Type":"Season","SeriesId":"show1","UserData":{"Played":false}}"""
        request.url == "$server/Items/movie1?userId=$user" ->
            200 to """{"Name":"Akira","Id":"movie1","Type":"Movie","UserData":{"Played":false}}"""
        request.url.startsWith("$server/Shows/show1/Episodes?") && request.url.contains("seasonId=season1") ->
            200 to """{"Items":[${episode("e1", 1, true)},${episode("e2", 2, false)},${episode("e3", 3, false)}],"TotalRecordCount":3}"""
        request.url.contains("/UserPlayedItems/") -> 200 to """{"Played":true}"""
        else -> 404 to ""
    }

    private fun loggedIn(http: MockTrackerHttp): JellyfinTrackerService {
        val db = InMemoryYokanDatabase()
        db.upsertTrackPreference(DbTrackPreference(syncId = 23, oauth = "tok", prefs = TrackerCredentials(serverUrl = server, userId = user).encode()))
        return JellyfinTrackerService(23, db, http.http)
    }

    @Test
    fun loginAuthenticatesByName() = runTest {
        val http = MockTrackerHttp(::route)
        val preference = JellyfinTrackerService(23, InMemoryYokanDatabase(), http.http).login(
            mapOf(TrackerLoginField.ServerUrl to "$server/", TrackerLoginField.Username to "ann", TrackerLoginField.Password to "secret"),
        )
        assertEquals("tok", preference.oauth)
        assertEquals("Ann", preference.username)
        assertEquals(user, preference.credentials().userId)
        assertEquals(server, preference.credentials().serverUrl)
        val auth = http.requests.single()
        assertEquals("POST", auth.method)
        assertTrue(auth.serverHeader("X-Emby-Authorization").orEmpty().contains("Client=\"Yokan\""))
        val body = trackerJson.parseToJsonElement(auth.body).jsonObject
        assertEquals("ann", body["Username"]?.jsonPrimitive?.contentOrNull)
    }

    @Test
    fun wrongPasswordThrows() = runTest {
        val service = JellyfinTrackerService(23, InMemoryYokanDatabase(), MockTrackerHttp(::route).http)
        val error = assertFailsWith<TrackerHttpException> {
            service.login(mapOf(TrackerLoginField.ServerUrl to server, TrackerLoginField.Username to "ann", TrackerLoginField.Password to "x"))
        }
        assertEquals(401, error.status)
    }

    @Test
    fun matchesSeasonLinks() = runTest {
        val service = loggedIn(MockTrackerHttp(::route))
        for (link in listOf("https://jf.lan/Users/other/Items/season1#seriesId,show1", "/Items/season1", "item?Id=season1")) {
            val match = service.match(DbManga(link = link))!!
            assertEquals("Season 1", match.title)
            assertEquals("$server/Items/season1", match.trackingUrl)
            assertEquals(3, match.totalChapter)
            assertEquals(1, match.lastChapterRead)
            assertEquals(DbTrackStatus.Watching.name, match.status)
        }
        assertNull(service.match(DbManga(link = "/Items/gone")))
        assertEquals(listOf("Akira"), service.search("id:movie1", false).map { it.title })
    }

    @Test
    fun movieCountsAsOneEpisode() = runTest {
        val service = loggedIn(MockTrackerHttp(::route))
        val movie = service.match(DbManga(link = "$server/Users/$user/Items/movie1#movie"))!!
        assertEquals(1, movie.totalChapter)
        assertEquals(0, movie.lastChapterRead)
        assertEquals(DbTrackStatus.PlanToWatch.name, movie.status)
        assertFalse(service.supports(true))
        assertTrue(service.supports(false))
    }

    @Test
    fun acceptsByNameOrHost() {
        val service = loggedIn(MockTrackerHttp(::route))
        assertTrue(service.accept(DbSource(name = "Jellyfin (2)")))
        assertTrue(service.accept(DbSource(name = "Home media", baseUrl = "https://jf.example")))
        assertFalse(service.accept(DbSource(name = "Gogoanime", baseUrl = "https://gogo.example")))
    }

    @Test
    fun updateMarksEpisodesUpToProgressPlayed() = runTest {
        val http = MockTrackerHttp(::route)
        loggedIn(http).update(
            DbTrack(status = DbTrackStatus.Watching, lastChapterRead = 3, trackingUrl = "$server/Users/$user/Items/season1"),
            false,
        )
        val posts = http.requests.filter { it.method == "POST" }.map { it.url }
        assertEquals(listOf("$server/UserPlayedItems/e2?userId=$user", "$server/UserPlayedItems/e3?userId=$user"), posts)
    }

    @Test
    fun updateMovieMarksPlayed() = runTest {
        val http = MockTrackerHttp(::route)
        loggedIn(http).update(DbTrack(status = DbTrackStatus.Watching, lastChapterRead = 1, trackingUrl = "$server/Users/$user/Items/movie1"), false)
        assertEquals(listOf("$server/UserPlayedItems/movie1?userId=$user"), http.requests.filter { it.method == "POST" }.map { it.url })
    }

    @Test
    fun revokedTokenFails() = runTest {
        val db = InMemoryYokanDatabase()
        db.upsertTrackPreference(DbTrackPreference(syncId = 23, oauth = "old", prefs = TrackerCredentials(serverUrl = server, userId = user).encode()))
        val service = JellyfinTrackerService(23, db, MockTrackerHttp(::route).http)
        val error = assertFailsWith<TrackerHttpException> {
            service.refresh(DbTrack(status = DbTrackStatus.Watching, trackingUrl = "$server/Users/$user/Items/season1"), false)
        }
        assertTrue(error.unauthorized)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/KavitaTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines KavitaTrackerServiceTest, route, loggedIn, loginExchangesApiKeyForToken, rejectedApiKeyThrows, expiredTokenIsRenewedOnceAndPersisted, matchParsesLinkShapesAndProgress, noReadChapterMeansZeroProgress, acceptsByNameOrHost, updateMarksChaptersUntilProgress and 1 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginExchangesApiKeyForToken
  • rejectedApiKeyThrows
  • expiredTokenIsRenewedOnceAndPersisted
  • matchParsesLinkShapesAndProgress
  • noReadChapterMeansZeroProgress
  • acceptsByNameOrHost
  • updateMarksChaptersUntilProgress
  • revokedApiKeyFails

Cross-chapter imports used by this file: DbManga, DbSource, DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

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.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class KavitaTrackerServiceTest {
    private val server = "https://kavita.example"

    private val volumes = """
        [{"id":1,"number":1,"name":"1","pages":40,"pagesRead":40,"lastModified":"","created":"","seriesId":7,
          "chapters":[{"id":10,"number":"1"},{"id":11,"number":"2"}]},
         {"id":2,"number":0,"name":"0","pages":40,"pagesRead":0,"lastModified":"","created":"","seriesId":7,
          "chapters":[{"id":12,"number":"12"},{"id":13,"number":"12,5"}]}]
    """

    private fun route(token: String = "jwt-1", latest: Pair<Int, String> = 200 to """{"id":11,"number":"2"}""") =
        { request: RecordedRequest ->
            when {
                request.url.contains("/api/Plugin/authenticate") ->
                    200 to """{"username":"reader","token":"$token","refreshToken":"r","apiKey":"key"}"""
                request.serverHeader("Authorization") != "Bearer $token" -> 401 to ""
                request.url.endsWith("/api/Series/7") ->
                    200 to """{"id":7,"name":"Berserk","pages":200,"pagesRead":80,"format":1,"libraryId":1}"""
                request.url.endsWith("/api/Series/volumes?seriesId=7") -> 200 to volumes
                request.url.contains("/api/Tachiyomi/latest-chapter?seriesId=7") -> latest
                request.url.contains("/api/Tachiyomi/mark-chapter-until-as-read") -> 200 to ""
                else -> 404 to ""
            }
        }

    private fun loggedIn(http: MockTrackerHttp, db: InMemoryYokanDatabase = InMemoryYokanDatabase()): KavitaTrackerService {
        db.upsertTrackPreference(
            DbTrackPreference(syncId = 21, oauth = "jwt-old", prefs = TrackerCredentials(serverUrl = server, apiKey = "key").encode()),
        )
        return KavitaTrackerService(21, db, http.http)
    }

    @Test
    fun loginExchangesApiKeyForToken() = runTest {
        val http = MockTrackerHttp(route())
        val preference = KavitaTrackerService(21, InMemoryYokanDatabase(), http.http)
            .login(mapOf(TrackerLoginField.ServerUrl to "$server/api/opds/key", TrackerLoginField.ApiKey to "key"))
        assertEquals("jwt-1", preference.oauth)
        assertEquals("reader", preference.username)
        assertEquals(server, preference.credentials().serverUrl)
        assertEquals("key", preference.credentials().apiKey)
        val auth = http.requests.single()
        assertEquals("POST", auth.method)
        assertEquals("$server/api/Plugin/authenticate?apiKey=key&pluginName=Yokan", auth.url)
    }

    @Test
    fun rejectedApiKeyThrows() = runTest {
        val service = KavitaTrackerService(21, InMemoryYokanDatabase(), MockTrackerHttp { 401 to "" }.http)
        assertFailsWith<TrackerHttpException> {
            service.login(mapOf(TrackerLoginField.ServerUrl to server, TrackerLoginField.ApiKey to "bad"))
        }
    }

    @Test
    fun expiredTokenIsRenewedOnceAndPersisted() = runTest {
        val db = InMemoryYokanDatabase()
        val http = MockTrackerHttp(route())
        val match = loggedIn(http, db).match(DbManga(link = "https://elsewhere/api/Series/7"))!!
        assertEquals("Berserk", match.title)
        assertEquals("jwt-1", db.trackPreferences().single { it.syncId == 21L }.oauth)
        assertEquals(1, http.requests.count { it.url.contains("/Plugin/authenticate") })
    }

    @Test
    fun matchParsesLinkShapesAndProgress() = runTest {
        val service = loggedIn(MockTrackerHttp(route()))
        for (link in listOf("/api/Series/7", "$server/library/1/series/7", "https://x/api/series?seriesId=7")) {
            val match = service.match(DbManga(link = link))!!
            assertEquals("$server/api/Series/7", match.trackingUrl)
            assertEquals(7L, match.mediaId)
            assertEquals(12, match.totalChapter)
            assertEquals(2, match.lastChapterRead)
            assertEquals(DbTrackStatus.Reading.name, match.status)
        }
        assertNull(service.match(DbManga(link = "/api/Series/8")))
        assertNull(service.match(DbManga(link = "/library/abc")))
        assertEquals(listOf("Berserk"), service.search("id:7", true).map { it.title })
    }

    @Test
    fun noReadChapterMeansZeroProgress() = runTest {
        val service = loggedIn(MockTrackerHttp(route(latest = 204 to "")))
        assertEquals(0, service.refresh(DbTrack(status = DbTrackStatus.Reading, trackingUrl = "$server/api/Series/7"), true).lastChapterRead)
    }

    @Test
    fun acceptsByNameOrHost() {
        val service = loggedIn(MockTrackerHttp(route()))
        assertTrue(service.accept(DbSource(name = "Kavita")))
        assertTrue(service.accept(DbSource(name = "Home", apiUrl = "https://kavita.example/api")))
        assertFalse(service.accept(DbSource(name = "Komga", baseUrl = "https://komga.example")))
    }

    @Test
    fun updateMarksChaptersUntilProgress() = runTest {
        val http = MockTrackerHttp(route())
        val updated = loggedIn(http).update(
            DbTrack(id = 3, syncId = 21, status = DbTrackStatus.PlanToRead, lastChapterRead = 5, trackingUrl = "$server/api/Series/7"),
            true,
        )
        // The stored token is stale: the first mark is rejected, Kavita re-authenticates and the retry carries the new token.
        val mark = http.requests.last { it.url.contains("mark-chapter-until-as-read") }
        assertEquals("Bearer jwt-1", mark.serverHeader("Authorization"))
        assertEquals("POST", mark.method)
        assertEquals("$server/api/Tachiyomi/mark-chapter-until-as-read?seriesId=7&chapterNumber=5", mark.url)
        assertEquals(DbTrackStatus.Reading, updated.status)
        assertEquals(3, updated.id)
    }

    @Test
    fun revokedApiKeyFails() = runTest {
        val http = MockTrackerHttp { 401 to "" }
        assertFailsWith<TrackerHttpException> {
            loggedIn(http).refresh(DbTrack(status = DbTrackStatus.Reading, trackingUrl = "$server/api/Series/7"), true)
        }
        assertEquals(2, http.requests.size)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/KomgaTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines KomgaTrackerServiceTest, route, loggedIn, loginWithApiKeyValidatesAndStoresServer, loginWithPasswordUsesBasicAuth, rejectedLoginThrows, matchesSeriesAndReadListLinks, notLoggedInMatchesNothing, acceptsByNameOrHost, refreshAndUpdateSeriesProgress and 3 further declarations.

The source describes its contract as:

Case-insensitive header lookup shared by the server tracker tests.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginWithApiKeyValidatesAndStoresServer
  • loginWithPasswordUsesBasicAuth
  • rejectedLoginThrows
  • matchesSeriesAndReadListLinks
  • notLoggedInMatchesNothing
  • acceptsByNameOrHost
  • refreshAndUpdateSeriesProgress
  • updateReadListUsesV1Payload
  • revokedKeyFailsRefresh

Cross-chapter imports used by this file: DbManga, DbSource, DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

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.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.double
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class KomgaTrackerServiceTest {
    private val server = "https://komga.example"

    private val series = """
        {"id":"0A1B","libraryId":"L1","name":"Blame!","booksCount":10,"booksReadCount":3,"booksUnreadCount":7,
         "booksInProgressCount":0,"metadata":{"status":"ENDED","title":"BLAME!","titleSort":"BLAME!","summary":"Cyberpunk"}}
    """
    private val progress = """
        {"booksCount":10,"booksReadCount":3,"booksUnreadCount":7,"booksInProgressCount":0,
         "lastReadContinuousNumberSort":3.0,"maxNumberSort":10.0}
    """

    private fun route(request: RecordedRequest): Pair<Int, String> = when {
        request.url.endsWith("/api/v2/users/me") -> 200 to """{"id":"u1","email":"reader@example.com","roles":["USER"]}"""
        request.url.endsWith("/api/v1/series/0A1B") -> 200 to series
        request.url.endsWith("/api/v2/series/0A1B/read-progress/tachiyomi") -> 200 to (if (request.method == "PUT") "" else progress)
        request.url.endsWith("/api/v1/readlists/RL9") ->
            200 to """{"id":"RL9","name":"Arc","bookIds":["b1","b2"],"createdDate":"","lastModifiedDate":"","filtered":false}"""
        request.url.endsWith("/api/v1/readlists/RL9/read-progress/tachiyomi") ->
            200 to """{"booksCount":2,"booksReadCount":2,"booksUnreadCount":0,"booksInProgressCount":0,"lastReadContinuousIndex":2}"""
        else -> 404 to """{"error":"not found"}"""
    }

    private fun loggedIn(http: MockTrackerHttp, apiKey: String = "key-1"): KomgaTrackerService {
        val db = InMemoryYokanDatabase()
        db.upsertTrackPreference(
            DbTrackPreference(syncId = 20, oauth = apiKey, prefs = TrackerCredentials(serverUrl = server, apiKey = apiKey).encode()),
        )
        return KomgaTrackerService(20, db, http.http)
    }

    @Test
    fun loginWithApiKeyValidatesAndStoresServer() = runTest {
        val http = MockTrackerHttp(::route)
        val service = KomgaTrackerService(20, InMemoryYokanDatabase(), http.http)
        val preference = service.login(mapOf(TrackerLoginField.ServerUrl to "komga.example/", TrackerLoginField.ApiKey to "key-1"))
        assertEquals("key-1", preference.oauth)
        assertEquals("reader@example.com", preference.username)
        assertEquals(server, preference.credentials().serverUrl)
        assertEquals("key-1", http.requests.single().serverHeader("X-API-Key"))
    }

    @Test
    fun loginWithPasswordUsesBasicAuth() = runTest {
        val http = MockTrackerHttp(::route)
        val service = KomgaTrackerService(20, InMemoryYokanDatabase(), http.http)
        val preference = service.login(
            mapOf(TrackerLoginField.ServerUrl to server, TrackerLoginField.Username to "user", TrackerLoginField.Password to "pass"),
        )
        assertEquals("basic", preference.oauth)
        assertEquals("Basic dXNlcjpwYXNz", http.requests.single().serverHeader("Authorization"))
    }

    @Test
    fun rejectedLoginThrows() = runTest {
        val service = KomgaTrackerService(20, InMemoryYokanDatabase(), MockTrackerHttp { 401 to "" }.http)
        val error = assertFailsWith<TrackerHttpException> {
            service.login(mapOf(TrackerLoginField.ServerUrl to server, TrackerLoginField.ApiKey to "bad"))
        }
        assertTrue(error.unauthorized)
    }

    @Test
    fun matchesSeriesAndReadListLinks() = runTest {
        val service = loggedIn(MockTrackerHttp(::route))
        for (link in listOf("https://other.host/api/v1/series/0A1B", "/api/v1/series/0A1B", "$server/series/0A1B?tab=books")) {
            val match = service.match(DbManga(link = link))!!
            assertEquals("BLAME!", match.title)
            assertEquals("$server/api/v1/series/0A1B", match.trackingUrl)
            assertEquals(10, match.totalChapter)
            assertEquals(3, match.lastChapterRead)
            assertEquals(DbTrackStatus.Reading.name, match.status)
        }
        val readList = service.match(DbManga(link = "/api/v1/readlists/RL9"))!!
        assertEquals("Arc", readList.title)
        assertEquals(2, readList.lastChapterRead)
        assertEquals(DbTrackStatus.Completed.name, readList.status)
        assertNull(service.match(DbManga(link = "/api/v1/series/missing")))
        assertNull(service.match(DbManga(link = "https://komga.example/")))
        assertEquals(listOf("BLAME!"), service.search("id:0A1B", true).map { it.title })
        assertTrue(service.search("blame", true).isEmpty())
    }

    @Test
    fun notLoggedInMatchesNothing() = runTest {
        val http = MockTrackerHttp(::route)
        assertNull(KomgaTrackerService(20, InMemoryYokanDatabase(), http.http).match(DbManga(link = "/api/v1/series/0A1B")))
        assertTrue(http.requests.isEmpty())
    }

    @Test
    fun acceptsByNameOrHost() {
        val service = loggedIn(MockTrackerHttp(::route))
        assertTrue(service.accept(DbSource(name = "Komga (Home)")))
        assertTrue(service.accept(DbSource(name = "My comics", baseUrl = "https://KOMGA.example/api")))
        assertFalse(service.accept(DbSource(name = "MangaDex", baseUrl = "https://mangadex.org")))
    }

    @Test
    fun refreshAndUpdateSeriesProgress() = runTest {
        val http = MockTrackerHttp(::route)
        val service = loggedIn(http)
        val track = DbTrack(id = 5, mangaId = 9, syncId = 20, status = DbTrackStatus.PlanToRead, lastChapterRead = 4, trackingUrl = "$server/api/v1/series/0A1B")
        val refreshed = service.refresh(track, true)
        assertEquals(3, refreshed.lastChapterRead)
        assertEquals(DbTrackStatus.Reading, refreshed.status)
        assertEquals(5, refreshed.id)

        service.update(track, true)
        val put = http.requests.single { it.method == "PUT" }
        assertEquals("$server/api/v2/series/0A1B/read-progress/tachiyomi", put.url)
        assertEquals(4.0, trackerJson.parseToJsonElement(put.body).jsonObject["lastBookNumberSortRead"]?.jsonPrimitive?.double)
        assertEquals("key-1", put.serverHeader("X-API-Key"))
    }

    @Test
    fun updateReadListUsesV1Payload() = runTest {
        val http = MockTrackerHttp(::route)
        loggedIn(http).update(DbTrack(status = DbTrackStatus.Reading, lastChapterRead = 2, trackingUrl = "$server/api/v1/readlists/RL9"), true)
        val put = http.requests.single { it.method == "PUT" }
        assertTrue(put.url.endsWith("/api/v1/readlists/RL9/read-progress/tachiyomi"))
        assertEquals("""{"lastBookRead":2}""", put.body)
    }

    @Test
    fun revokedKeyFailsRefresh() = runTest {
        val service = loggedIn(MockTrackerHttp { 401 to "" })
        val error = assertFailsWith<TrackerHttpException> {
            service.refresh(DbTrack(status = DbTrackStatus.Reading, trackingUrl = "$server/api/v1/series/0A1B"), true)
        }
        assertEquals(401, error.status)
    }
}

/** Case-insensitive header lookup shared by the server tracker tests. */
internal fun RecordedRequest.serverHeader(name: String): String? =
    headers.entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/MangaBakaTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines MangaBakaTrackerServiceTest, loggedIn, loginValidatesTokenWithProfile, loginRejected, searchByIdAndText, bindAdoptsExistingEntry, bindCreatesMissingEntry, updatePatchesEntry, updateAutoStartsReading, refreshAndUnbind and 1 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginValidatesTokenWithProfile
  • loginRejected
  • searchByIdAndText
  • bindAdoptsExistingEntry
  • bindCreatesMissingEntry
  • updatePatchesEntry
  • updateAutoStartsReading
  • refreshAndUnbind
  • revokedTokenThrows

Cross-chapter imports used by this file: DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class MangaBakaTrackerServiceTest {
    private val base = "https://api.mangabaka.org/v1"
    private val series = """{"id":42,"state":"active","titles":[
        {"language":"ja","traits":["native"],"title":"ベルセルク","is_primary":false},
        {"language":"en","traits":["official"],"title":"Berserk","is_primary":true}],
        "cover":{"x250":{"x1":"https://cdn/b.jpg"}},"authors":["Miura"],"artists":["Miura"],"description":" Guts ",
        "published":{"start_date":"1989-08-25"},"status":"releasing","type":"manga","rating":91.5}"""
    private val track = DbTrack(id = 5, mangaId = 7, syncId = 14, mediaId = 42, status = DbTrackStatus.PlanToRead)

    private fun loggedIn() = InMemoryYokanDatabase().apply {
        upsertTrackPreference(DbTrackPreference(syncId = 14, oauth = "mb-key"))
    }

    @Test
    fun loginValidatesTokenWithProfile() = runTest {
        val mock = MockTrackerHttp {
            200 to """{"status":200,"data":{"id":"u1","nickname":"Guts","preferred_username":"guts","picture":null,"auth_type":"pat"}}"""
        }
        val pref = MangaBakaTrackerService(14, InMemoryYokanDatabase(), mock.http).login(mapOf(TrackerLoginField.ApiKey to " mb-key "))
        val req = mock.requests.single()
        assertEquals("$base/my/profile", req.url)
        assertEquals("mb-key", req.headers["x-api-key"])
        assertEquals("mb-key", pref.oauth)
        assertEquals("guts", pref.username)
        assertEquals("Guts", pref.accountName)
        assertEquals("u1", trackerJson.decodeFromString(TrackerCredentials.serializer(), pref.prefs!!).userId)
    }

    @Test
    fun loginRejected() = runTest {
        val mock = MockTrackerHttp { 401 to """{"status":401,"message":"Unauthorized"}""" }
        assertFailsWith<TrackerHttpException> {
            MangaBakaTrackerService(14, InMemoryYokanDatabase(), mock.http).login(mapOf(TrackerLoginField.ApiKey to "bad"))
        }
    }

    @Test
    fun searchByIdAndText() = runTest {
        val mock = MockTrackerHttp { r ->
            when {
                r.url == "$base/series/42" -> 200 to """{"status":200,"data":$series}"""
                r.url.startsWith("$base/series/search") -> 200 to """{"status":200,"data":[$series]}"""
                else -> 404 to """{"status":404}"""
            }
        }
        val service = MangaBakaTrackerService(14, InMemoryYokanDatabase(), mock.http)
        val byId = service.search("id:42", true).single()
        assertEquals(42L, byId.mediaId)
        assertEquals("Berserk", byId.title)
        assertEquals("https://mangabaka.org/42", byId.trackingUrl)
        assertEquals("https://cdn/b.jpg", byId.coverUrl)
        assertEquals("Manga", byId.publishingType)
        assertEquals("1989-08-25", byId.startDate)
        assertTrue(service.search("id:7", true).isEmpty())
        assertEquals("Berserk", service.search("dark fantasy", true).single().title)
        assertEquals("$base/series/search?q=dark%20fantasy", mock.requests.last().url)
    }

    @Test
    fun bindAdoptsExistingEntry() = runTest {
        val mock = MockTrackerHttp {
            200 to """{"status":200,"data":{"state":"paused","progress_chapter":30,"rating":85,"is_private":false,
                "start_date":"2024-01-02T00:00:00.000Z","finish_date":null}}"""
        }
        val bound = MangaBakaTrackerService(14, loggedIn(), mock.http).bind(track, true)
        assertEquals("$base/my/library/42", mock.requests.single().url)
        assertEquals("mb-key", mock.requests.single().headers["x-api-key"])
        assertEquals(DbTrackStatus.OnHold, bound.status)
        assertEquals(30, bound.lastChapterRead)
        assertEquals(9, bound.score)
        assertEquals(1704153600000L, bound.startedReadingDate)
        assertEquals(null, bound.finishedReadingDate)
        assertEquals(5, bound.id)
    }

    @Test
    fun bindCreatesMissingEntry() = runTest {
        val mock = MockTrackerHttp { r ->
            if (r.method == "GET") 404 to """{"status":404}""" else 201 to """{"status":201,"data":true}"""
        }
        val bound = MangaBakaTrackerService(14, loggedIn(), mock.http).bind(track.copy(score = 6), true)
        val post = mock.requests.last()
        assertEquals("POST", post.method)
        assertEquals("$base/my/library/42", post.url)
        val body = trackerJson.parseToJsonElement(post.body).jsonObject
        assertEquals("plan_to_read", body["state"]!!.jsonPrimitive.content)
        assertEquals(60, body["rating"]!!.jsonPrimitive.int)
        assertEquals(DbTrackStatus.PlanToRead, bound.status)
    }

    @Test
    fun updatePatchesEntry() = runTest {
        val mock = MockTrackerHttp { 200 to """{"status":200,"data":true}""" }
        val updated = MangaBakaTrackerService(14, loggedIn(), mock.http)
            .update(track.copy(status = DbTrackStatus.Reading, lastChapterRead = 12, score = 0, startedReadingDate = 1704153600000L), true)
        val req = mock.requests.single()
        assertEquals("PATCH", req.method)
        assertEquals("$base/my/library/42", req.url)
        val body = trackerJson.parseToJsonElement(req.body).jsonObject
        assertEquals("reading", body["state"]!!.jsonPrimitive.content)
        assertEquals(12, body["progress_chapter"]!!.jsonPrimitive.int)
        assertEquals(JsonNull, body["rating"])
        assertEquals("2024-01-02", body["start_date"]!!.jsonPrimitive.content)
        assertEquals(DbTrackStatus.Reading, updated.status)
    }

    @Test
    fun updateAutoStartsReading() = runTest {
        val mock = MockTrackerHttp { 200 to """{"status":200,"data":true}""" }
        val updated = MangaBakaTrackerService(14, loggedIn(), mock.http).update(track.copy(lastChapterRead = 1), true)
        assertEquals(DbTrackStatus.Reading, updated.status)
        assertTrue((updated.startedReadingDate ?: 0) > 0)
    }

    @Test
    fun refreshAndUnbind() = runTest {
        val mock = MockTrackerHttp { r ->
            when (r.method) {
                "GET" -> 200 to """{"status":200,"data":{"state":"considering","progress_chapter":null,"rating":null,"is_private":false}}"""
                else -> 200 to """{"status":200,"data":true}"""
            }
        }
        val service = MangaBakaTrackerService(14, loggedIn(), mock.http)
        val refreshed = service.refresh(track.copy(status = DbTrackStatus.Reading), true)
        assertEquals(DbTrackStatus.PlanToRead, refreshed.status)
        assertEquals(0, refreshed.lastChapterRead)
        service.unbind(track, true)
        assertEquals("DELETE", mock.requests.last().method)
        assertEquals("$base/my/library/42", mock.requests.last().url)
    }

    @Test
    fun revokedTokenThrows() = runTest {
        val mock = MockTrackerHttp { 401 to """{"status":401}""" }
        val error = assertFailsWith<TrackerHttpException> { MangaBakaTrackerService(14, loggedIn(), mock.http).refresh(track, true) }
        assertTrue(error.unauthorized)
        assertEquals(1, mock.requests.size)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/MangaUpdatesTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines MangaUpdatesTrackerServiceTest, loggedIn, loginStoresSessionAndUsername, loginRejected, searchByIdAndText, bindAdoptsExistingEntry, bindCreatesMissingEntry, updatePushesListAndRating, refreshAndUnbind, expiredSessionThrows.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginStoresSessionAndUsername
  • loginRejected
  • searchByIdAndText
  • bindAdoptsExistingEntry
  • bindCreatesMissingEntry
  • updatePushesListAndRating
  • refreshAndUnbind
  • expiredSessionThrows

Cross-chapter imports used by this file: DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.int
import kotlinx.serialization.json.long

class MangaUpdatesTrackerServiceTest {
    private val base = "https://api.mangaupdates.com/v1"
    private val record = """{"series_id":123456,"title":"Berserk","url":"https://www.mangaupdates.com/series/abc/berserk",
        "description":"Guts","image":{"url":{"original":"https://cdn/b.jpg","thumb":"t"}},"type":"Manga","year":"1989",
        "bayesian_rating":9.1}"""
    private val track = DbTrack(id = 5, mangaId = 7, syncId = 10, mediaId = 123456, status = DbTrackStatus.PlanToRead)

    private fun loggedIn() = InMemoryYokanDatabase().apply {
        upsertTrackPreference(DbTrackPreference(syncId = 10, oauth = "sess"))
    }

    @Test
    fun loginStoresSessionAndUsername() = runTest {
        val mock = MockTrackerHttp { r ->
            when {
                r.url == "$base/account/login" -> 200 to """{"status":"success","context":{"session_token":"sess","uid":42}}"""
                r.url == "$base/account/profile" -> 200 to """{"user_id":42,"username":"guts"}"""
                else -> 404 to "{}"
            }
        }
        val pref = MangaUpdatesTrackerService(10, InMemoryYokanDatabase(), mock.http).login(
            mapOf(TrackerLoginField.Username to "guts", TrackerLoginField.Password to "pw"),
        )
        assertEquals("PUT", mock.requests[0].method)
        val body = trackerJson.parseToJsonElement(mock.requests[0].body).jsonObject
        assertEquals("guts", body["username"]!!.jsonPrimitive.content)
        assertEquals("pw", body["password"]!!.jsonPrimitive.content)
        assertEquals("Bearer sess", mock.requests[1].headers["Authorization"])
        assertEquals("sess", pref.oauth)
        assertEquals("guts", pref.username)
        assertEquals("42", trackerJson.decodeFromString(TrackerCredentials.serializer(), pref.prefs!!).userId)
    }

    @Test
    fun loginRejected() = runTest {
        val mock = MockTrackerHttp { 401 to """{"status":"exception","reason":"Invalid credentials"}""" }
        val error = assertFailsWith<TrackerHttpException> {
            MangaUpdatesTrackerService(10, InMemoryYokanDatabase(), mock.http)
                .login(mapOf(TrackerLoginField.Username to "a", TrackerLoginField.Password to "b"))
        }
        assertEquals(401, error.status)
    }

    @Test
    fun searchByIdAndText() = runTest {
        val mock = MockTrackerHttp { r ->
            when (r.url) {
                "$base/series/123456" -> 200 to record
                "$base/series/9" -> 404 to "{}"
                "$base/series/search" -> 200 to """{"total_hits":1,"results":[{"record":$record,"hit_title":"Berserk"}]}"""
                else -> 404 to "{}"
            }
        }
        val service = MangaUpdatesTrackerService(10, InMemoryYokanDatabase(), mock.http)
        val byId = service.search("id:123456", true).single()
        assertEquals(123456L, byId.mediaId)
        assertEquals("Berserk", byId.title)
        assertEquals("https://www.mangaupdates.com/series/abc/berserk", byId.trackingUrl)
        assertEquals("https://cdn/b.jpg", byId.coverUrl)
        assertTrue(service.search("id:9", true).isEmpty())
        val text = service.search("berserk", true).single()
        assertEquals(10, text.syncId)
        val req = mock.requests.last()
        assertEquals("POST", req.method)
        assertEquals("berserk", trackerJson.parseToJsonElement(req.body).jsonObject["search"]!!.jsonPrimitive.content)
    }

    @Test
    fun bindAdoptsExistingEntry() = runTest {
        val mock = MockTrackerHttp { r ->
            when (r.url) {
                "$base/lists/series/123456" -> 200 to """{"series":{"id":123456,"title":"Berserk"},"list_id":4,"status":{"volume":2,"chapter":30},"priority":0}"""
                "$base/series/123456/rating" -> 200 to """{"rating":8.6}"""
                else -> 404 to "{}"
            }
        }
        val bound = MangaUpdatesTrackerService(10, loggedIn(), mock.http).bind(track, true)
        assertEquals(DbTrackStatus.OnHold, bound.status)
        assertEquals(30, bound.lastChapterRead)
        assertEquals(9, bound.score)
        assertEquals(5, bound.id)
        assertEquals(2, mock.requests.size)
    }

    @Test
    fun bindCreatesMissingEntry() = runTest {
        val mock = MockTrackerHttp { r ->
            when {
                r.method == "GET" -> 404 to """{"status":"exception","reason":"Series not in list"}"""
                else -> 200 to """{"status":"success"}"""
            }
        }
        val bound = MangaUpdatesTrackerService(10, loggedIn(), mock.http).bind(track.copy(lastChapterRead = 3), true)
        val add = mock.requests.first { it.method == "POST" }
        assertEquals("$base/lists/series", add.url)
        val item = trackerJson.parseToJsonElement(add.body).jsonArray.single().jsonObject
        assertEquals(123456L, item["series"]!!.jsonObject["id"]!!.jsonPrimitive.long)
        assertEquals(1, item["list_id"]!!.jsonPrimitive.int)
        assertEquals(3, item["status"]!!.jsonObject["chapter"]!!.jsonPrimitive.int)
        assertEquals(DbTrackStatus.PlanToRead, bound.status)
        assertEquals("DELETE", mock.requests.last().method)
    }

    @Test
    fun updatePushesListAndRating() = runTest {
        val mock = MockTrackerHttp { 200 to """{"status":"success"}""" }
        val updated = MangaUpdatesTrackerService(10, loggedIn(), mock.http)
            .update(track.copy(lastChapterRead = 12, score = 7, totalChapter = 12), true)
        assertEquals(DbTrackStatus.Completed, updated.status)
        val list = mock.requests[0]
        assertEquals("$base/lists/series/update", list.url)
        assertEquals("Bearer sess", list.headers["Authorization"])
        val item = trackerJson.parseToJsonElement(list.body).jsonArray.single().jsonObject
        assertEquals(2, item["list_id"]!!.jsonPrimitive.int)
        assertEquals(12, item["status"]!!.jsonObject["chapter"]!!.jsonPrimitive.int)
        val rating = mock.requests[1]
        assertEquals("PUT", rating.method)
        assertEquals("$base/series/123456/rating", rating.url)
        assertEquals(7, trackerJson.parseToJsonElement(rating.body).jsonObject["rating"]!!.jsonPrimitive.int)
    }

    @Test
    fun refreshAndUnbind() = runTest {
        val mock = MockTrackerHttp { r ->
            when (r.url) {
                "$base/lists/series/123456" -> 200 to """{"series":{"id":123456},"list_id":0,"status":{"chapter":5}}"""
                "$base/series/123456/rating" -> 404 to "{}"
                else -> 200 to """{"status":"success"}"""
            }
        }
        val service = MangaUpdatesTrackerService(10, loggedIn(), mock.http)
        val refreshed = service.refresh(track, true)
        assertEquals(DbTrackStatus.Reading, refreshed.status)
        assertEquals(5, refreshed.lastChapterRead)
        assertEquals(0, refreshed.score)
        service.unbind(track, true)
        val delete = mock.requests.last()
        assertEquals("$base/lists/series/delete", delete.url)
        assertEquals(123456L, trackerJson.parseToJsonElement(delete.body).jsonArray.single().jsonPrimitive.long)
    }

    @Test
    fun expiredSessionThrows() = runTest {
        val mock = MockTrackerHttp { 401 to """{"status":"exception","reason":"Unauthorized"}""" }
        val error = assertFailsWith<TrackerHttpException> {
            MangaUpdatesTrackerService(10, loggedIn(), mock.http).update(track, true)
        }
        assertTrue(error.unauthorized)
        assertEquals(1, mock.requests.size)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/ShikimoriTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines ShikimoriTrackerServiceTest, loggedIn, loginExchangesCodeAndStoresCredentials, searchesByIdAndText, bindAdoptsExistingRate, bindCreatesMissingRate, updatePatchesRateAndAutoCompletes, refreshAndUnbind, unauthorizedRefreshesTokenOnceAndRetries, unauthorizedWithoutRefreshTokenThrows.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginExchangesCodeAndStoresCredentials
  • searchesByIdAndText
  • bindAdoptsExistingRate
  • bindCreatesMissingRate
  • updatePatchesRateAndAutoCompletes
  • refreshAndUnbind
  • unauthorizedRefreshesTokenOnceAndRetries
  • unauthorizedWithoutRefreshTokenThrows

Cross-chapter imports used by this file: DbItemType, DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.int
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive

class ShikimoriTrackerServiceTest {
    private val rate = """{"id":77,"user_id":5,"target_id":42,"target_type":"Manga","score":8,"status":"watching","chapters":12,"episodes":0}"""

    private fun loggedIn(token: String = "tok", refresh: String? = "ref") = InMemoryYokanDatabase().also {
        it.upsertTrackPreference(
            DbTrackPreference(
                syncId = 11,
                username = "neko",
                oauth = token,
                prefs = TrackerCredentials(clientId = "cid", clientSecret = "sec", refreshToken = refresh, userId = "5").encode(),
            ),
        )
    }

    private val track = DbTrack(id = 3, mangaId = 9, syncId = 11, mediaId = 42, status = DbTrackStatus.PlanToRead, lastChapterRead = 0, itemType = DbItemType.Manga)

    @Test
    fun loginExchangesCodeAndStoresCredentials() = runTest {
        val mock = MockTrackerHttp { req ->
            when {
                req.url.endsWith("/oauth/token") -> 200 to """{"access_token":"A","token_type":"Bearer","expires_in":86400,"refresh_token":"R","created_at":1700000000}"""
                req.url.endsWith("/api/users/whoami") -> 200 to """{"id":5,"nickname":"neko"}"""
                else -> 404 to ""
            }
        }
        val service = ShikimoriTrackerService(11, InMemoryYokanDatabase(), mock.http)

        val pref = service.login(
            mapOf(
                TrackerLoginField.ClientId to "cid",
                TrackerLoginField.ClientSecret to "sec",
                TrackerLoginField.AuthorizationCode to "yokan://tracker/shikimori?code=abc",
            ),
        )

        assertEquals("A", pref.oauth)
        assertEquals("neko", pref.username)
        val creds = pref.credentials()
        assertEquals("R", creds.refreshToken)
        assertEquals("5", creds.userId)
        assertEquals("cid", creds.clientId)
        assertTrue(creds.expiresAt != null)
        val token = mock.requests.first()
        assertEquals("POST", token.method)
        assertTrue("grant_type=authorization_code" in token.body && "code=abc" in token.body && "client_secret=sec" in token.body)
        assertTrue("redirect_uri=yokan%3A%2F%2Ftracker%2Fshikimori" in token.body)
        assertEquals("Bearer A", mock.requests[1].headers["Authorization"])
        assertEquals("Yokan", mock.requests[1].headers["User-Agent"])
        val url = service.authorizeUrl(mapOf(TrackerLoginField.ClientId to "cid"))
        assertTrue(url.startsWith("https://shikimori.io/oauth/authorize?client_id=cid") && "scope=user_rates" in url)
    }

    @Test
    fun searchesByIdAndText() = runTest {
        val mock = MockTrackerHttp { req ->
            when {
                "/api/mangas/42" in req.url -> 200 to """{"id":42,"name":"Berserk","russian":"Берсерк","image":{"original":"/system/mangas/original/42.jpg"},"url":"/mangas/42-berserk","kind":"manga","score":"9.4","status":"ongoing","chapters":0,"aired_on":"1989-08-25","description":"Guts"}"""
                "/api/mangas/1" in req.url -> 404 to """{"message":"not found"}"""
                "/api/animes?" in req.url -> 200 to """[{"id":1,"name":"Cowboy Bebop","image":{"original":"/a.jpg"},"kind":"tv","score":"8.75","status":"released","episodes":26,"aired_on":"1998-04-03"}]"""
                else -> 404 to ""
            }
        }
        val service = ShikimoriTrackerService(11, loggedIn(), mock.http)

        val byId = service.search("id:42", isManga = true).single()
        assertEquals(42L, byId.mediaId)
        assertEquals("Berserk", byId.title)
        assertEquals("https://shikimori.io/system/mangas/original/42.jpg", byId.coverUrl)
        assertEquals("https://shikimori.io/mangas/42", byId.trackingUrl)
        assertEquals(9.4, byId.score)
        assertEquals(emptyList(), service.search("id:1", isManga = true))

        val text = service.search("bebop", isManga = false).single()
        assertEquals(26, text.totalChapter)
        assertEquals("https://shikimori.io/animes/1", text.trackingUrl)
        assertTrue("search=bebop" in mock.requests.last().url && "limit=20" in mock.requests.last().url)
    }

    @Test
    fun bindAdoptsExistingRate() = runTest {
        val mock = MockTrackerHttp { 200 to "[$rate]" }
        val bound = ShikimoriTrackerService(11, loggedIn(), mock.http).bind(track, isManga = true)

        assertEquals(DbTrackStatus.Reading, bound.status)
        assertEquals(12, bound.lastChapterRead)
        assertEquals(8, bound.score)
        assertEquals(3, bound.id)
        val url = mock.requests.single().url
        assertTrue("/api/v2/user_rates?" in url && "user_id=5" in url && "target_id=42" in url && "target_type=Manga" in url)
    }

    @Test
    fun bindCreatesMissingRate() = runTest {
        val mock = MockTrackerHttp { req ->
            if (req.method == "GET") 200 to "[]"
            else 201 to """{"id":78,"user_id":5,"target_id":42,"target_type":"Anime","score":0,"status":"planned","episodes":0}"""
        }
        val bound = ShikimoriTrackerService(11, loggedIn(), mock.http)
            .bind(track.copy(status = DbTrackStatus.PlanToWatch, itemType = DbItemType.Anime), isManga = false)

        assertEquals(DbTrackStatus.PlanToWatch, bound.status)
        val post = mock.requests.last()
        assertEquals("POST", post.method)
        assertTrue(post.url.endsWith("/api/v2/user_rates"))
        val body = trackerJson.parseToJsonElement(post.body).jsonObject["user_rate"]!!.jsonObject
        assertEquals("Anime", body["target_type"]!!.jsonPrimitive.content)
        assertEquals(42, body["target_id"]!!.jsonPrimitive.int)
        assertEquals("planned", body["status"]!!.jsonPrimitive.content)
        assertEquals(0, body["episodes"]!!.jsonPrimitive.int)
    }

    @Test
    fun updatePatchesRateAndAutoCompletes() = runTest {
        val mock = MockTrackerHttp { req ->
            if (req.method == "GET") 200 to "[$rate]"
            else 200 to """{"id":77,"score":7,"status":"completed","chapters":20}"""
        }
        val updated = ShikimoriTrackerService(11, loggedIn(), mock.http)
            .update(track.copy(status = DbTrackStatus.Reading, lastChapterRead = 20, totalChapter = 20, score = 7), isManga = true)

        assertEquals(DbTrackStatus.Completed, updated.status)
        assertEquals(20, updated.lastChapterRead)
        val patch = mock.requests.last()
        assertEquals("PATCH", patch.method)
        assertTrue(patch.url.endsWith("/api/v2/user_rates/77"))
        val body = trackerJson.parseToJsonElement(patch.body).jsonObject["user_rate"]!!.jsonObject
        assertEquals("completed", body["status"]!!.jsonPrimitive.content)
        assertEquals(7, body["score"]!!.jsonPrimitive.int)
        assertEquals(20, body["chapters"]!!.jsonPrimitive.int)
    }

    @Test
    fun refreshAndUnbind() = runTest {
        val mock = MockTrackerHttp { req -> if (req.method == "GET") 200 to "[$rate]" else 204 to "" }
        val service = ShikimoriTrackerService(11, loggedIn(), mock.http)

        assertEquals(12, service.refresh(track, isManga = true).lastChapterRead)
        service.unbind(track, isManga = true)
        assertEquals("DELETE", mock.requests.last().method)
        assertTrue(mock.requests.last().url.endsWith("/api/v2/user_rates/77"))

        val empty = MockTrackerHttp { 200 to "[]" }
        assertEquals(track, ShikimoriTrackerService(11, loggedIn(), empty.http).refresh(track, isManga = true))
    }

    @Test
    fun unauthorizedRefreshesTokenOnceAndRetries() = runTest {
        val mock = MockTrackerHttp { req ->
            when {
                req.url.endsWith("/oauth/token") -> 200 to """{"access_token":"new","token_type":"Bearer","expires_in":86400,"refresh_token":"ref2","created_at":1700000000}"""
                req.headers["Authorization"] == "Bearer old" -> 401 to """{"error":"invalid_token"}"""
                else -> 200 to "[$rate]"
            }
        }
        val database = loggedIn(token = "old")

        val refreshed = ShikimoriTrackerService(11, database, mock.http).refresh(track, isManga = true)

        assertEquals(12, refreshed.lastChapterRead)
        assertTrue("grant_type=refresh_token" in mock.requests[1].body && "refresh_token=ref" in mock.requests[1].body)
        val stored = database.trackPreferences().single { it.syncId == 11L }
        assertEquals("new", stored.oauth)
        assertEquals("ref2", stored.credentials().refreshToken)
        assertEquals("neko", stored.username)
    }

    @Test
    fun unauthorizedWithoutRefreshTokenThrows() = runTest {
        val mock = MockTrackerHttp { 401 to """{"error":"invalid_token"}""" }
        val error = runCatching { ShikimoriTrackerService(11, loggedIn(refresh = null), mock.http).refresh(track, isManga = true) }
            .exceptionOrNull()
        assertEquals(401, (error as TrackerHttpException).status)
        assertEquals(1, mock.requests.size)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/SuwayomiTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines SuwayomiTrackerServiceTest, chapter, route, loggedIn, loginWithAndWithoutBasicAuth, wrongPasswordThrows, matchParsesLinkShapes, acceptsByNameOrHost, updateMarksChapterAndPrevious, updateToUnknownChapterFails.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginWithAndWithoutBasicAuth
  • wrongPasswordThrows
  • matchParsesLinkShapes
  • acceptsByNameOrHost
  • updateMarksChapterAndPrevious
  • updateToUnknownChapterFails

Cross-chapter imports used by this file: DbManga, DbSource, DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

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.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class SuwayomiTrackerServiceTest {
    private val server = "http://192.168.1.5:4567"

    private fun chapter(index: Int, number: Double, read: Boolean) =
        """{"id":${100 + index},"url":"/c/$index","name":"Ch. $number","uploadDate":0,"chapterNumber":$number,"scanlator":null,
            "mangaId":42,"read":$read,"bookmarked":false,"lastPageRead":0,"lastReadAt":0,"index":$index,"fetchedAt":0,
            "downloaded":false,"pageCount":0,"chapterCount":3,"meta":{}}"""

    private val manga = """
        {"id":42,"sourceId":"1","url":"/m/42","title":"Vagabond","thumbnailUrl":null,"initialized":true,"artist":null,
         "author":null,"description":"Swords","genre":[],"status":"ONGOING","inLibrary":true,"inLibraryAt":0,"source":null,
         "meta":{},"realUrl":null,"lastFetchedAt":0,"chaptersLastFetchedAt":0,"freshData":false,"unreadCount":2,
         "downloadCount":0,"chapterCount":3,"lastChapterRead":${chapter(1, 1.0, true)},"age":0,"chaptersAge":0}
    """

    private fun route(request: RecordedRequest): Pair<Int, String> = when {
        request.serverHeader("Authorization") != null && request.serverHeader("Authorization") != "Basic dXNlcjpwYXNz" -> 401 to ""
        request.url.endsWith("/api/v1/settings/about") -> 200 to """{"name":"Suwayomi-Server","version":"v2.1.1867"}"""
        request.url.endsWith("/api/v1/manga/42/full") -> 200 to manga
        request.url.endsWith("/api/v1/manga/42/chapters") ->
            200 to "[${chapter(1, 1.0, true)},${chapter(2, 2.0, false)},${chapter(3, 2.5, false)}]"
        request.url.contains("/api/v1/manga/42/chapter/") -> 200 to ""
        else -> 404 to ""
    }

    private fun loggedIn(http: MockTrackerHttp, basic: Boolean = false): SuwayomiTrackerService {
        val db = InMemoryYokanDatabase()
        db.upsertTrackPreference(
            DbTrackPreference(
                syncId = 22,
                oauth = if (basic) "basic" else "anonymous",
                prefs = TrackerCredentials(serverUrl = server, apiKey = if (basic) "Basic dXNlcjpwYXNz" else null).encode(),
            ),
        )
        return SuwayomiTrackerService(22, db, http.http)
    }

    @Test
    fun loginWithAndWithoutBasicAuth() = runTest {
        val http = MockTrackerHttp(::route)
        val service = SuwayomiTrackerService(22, InMemoryYokanDatabase(), http.http)
        val open = service.login(mapOf(TrackerLoginField.ServerUrl to server))
        assertEquals("anonymous", open.oauth)
        assertEquals("Suwayomi-Server", open.accountName)
        assertNull(http.requests.last().serverHeader("Authorization"))

        val basic = service.login(
            mapOf(TrackerLoginField.ServerUrl to server, TrackerLoginField.Username to "user", TrackerLoginField.Password to "pass"),
        )
        assertEquals("basic", basic.oauth)
        assertEquals("user", basic.username)
        assertEquals("Basic dXNlcjpwYXNz", http.requests.last().serverHeader("Authorization"))
    }

    @Test
    fun wrongPasswordThrows() = runTest {
        val service = SuwayomiTrackerService(22, InMemoryYokanDatabase(), MockTrackerHttp(::route).http)
        val error = assertFailsWith<TrackerHttpException> {
            service.login(mapOf(TrackerLoginField.ServerUrl to server, TrackerLoginField.Username to "user", TrackerLoginField.Password to "nope"))
        }
        assertTrue(error.unauthorized)
    }

    @Test
    fun matchParsesLinkShapes() = runTest {
        val service = loggedIn(MockTrackerHttp(::route), basic = true)
        for (link in listOf("42", "/manga/42", "https://other:4567/api/v1/manga/42")) {
            val match = service.match(DbManga(link = link))!!
            assertEquals("Vagabond", match.title)
            assertEquals("$server/api/v1/manga/42", match.trackingUrl)
            assertEquals(42L, match.mediaId)
            assertEquals(3, match.totalChapter)
            assertEquals(1, match.lastChapterRead)
            assertEquals(DbTrackStatus.Reading.name, match.status)
        }
        assertNull(service.match(DbManga(link = "/manga/7")))
        assertNull(service.match(DbManga(link = "/manga/abc")))
        assertEquals(1, service.search("id:42", true).size)
    }

    @Test
    fun acceptsByNameOrHost() {
        val service = loggedIn(MockTrackerHttp(::route))
        assertTrue(service.accept(DbSource(name = "Tachidesk")))
        assertTrue(service.accept(DbSource(name = "Suwayomi")))
        assertTrue(service.accept(DbSource(name = "Server", baseUrl = "http://192.168.1.5:4567")))
        assertFalse(service.accept(DbSource(name = "Kavita", baseUrl = "http://192.168.1.6")))
    }

    @Test
    fun updateMarksChapterAndPrevious() = runTest {
        val http = MockTrackerHttp(::route)
        val updated = loggedIn(http).update(
            DbTrack(id = 1, syncId = 22, status = DbTrackStatus.Reading, lastChapterRead = 2, trackingUrl = "$server/api/v1/manga/42"),
            true,
        )
        val put = http.requests.single { it.method == "PUT" }
        assertEquals("$server/api/v1/manga/42/chapter/2", put.url)
        assertEquals("markPrevRead=true&read=true", put.body)
        assertTrue(put.serverHeader("Content-Type").orEmpty().startsWith("application/x-www-form-urlencoded"))
        assertEquals(1, updated.lastChapterRead)
    }

    @Test
    fun updateToUnknownChapterFails() = runTest {
        val http = MockTrackerHttp(::route)
        assertFailsWith<IllegalArgumentException> {
            loggedIn(http).update(DbTrack(status = DbTrackStatus.Reading, lastChapterRead = 9, trackingUrl = "$server/api/v1/manga/42"), true)
        }
        assertTrue(http.requests.none { it.method == "PUT" })
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/TmdbTrackerServiceTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines TmdbTrackerServiceTest, service, loginRequiresApprovalThenCreatesSession, searchByIdTriesTvThenMovieAndText, bindAdoptsAccountStates, bindWithoutRemoteStateAddsToWatchlist, updatePushesWatchlistAndRating, refreshAndUnbind, rejectedSessionThrows.

Read the setup, action and assertions in these cases before implementing their production paths:

  • loginRequiresApprovalThenCreatesSession
  • searchByIdTriesTvThenMovieAndText
  • bindAdoptsAccountStates
  • bindWithoutRemoteStateAddsToWatchlist
  • updatePushesWatchlistAndRating
  • refreshAndUnbind
  • rejectedSessionThrows

Cross-chapter imports used by this file: DbItemType, DbTrack, DbTrackPreference, DbTrackStatus, InMemoryYokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.boolean
import kotlinx.serialization.json.double
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class TmdbTrackerServiceTest {
    private val auth = "api_key=key&session_id=sess"
    private val tv = """{"id":1399,"name":"Game of Thrones","overview":"Dragons","poster_path":"/p.jpg","first_air_date":"2011-04-17",
        "number_of_episodes":73,"status":"Ended","vote_average":8.4}"""

    private fun service(route: (RecordedRequest) -> Pair<Int, String>): Pair<TmdbTrackerService, MockTrackerHttp> {
        val db = InMemoryYokanDatabase()
        db.upsertTrackPreference(
            DbTrackPreference(syncId = 15, oauth = "sess", prefs = TrackerCredentials(apiKey = "key", userId = "42").encode()),
        )
        val mock = MockTrackerHttp(route)
        return TmdbTrackerService(15, db, mock.http) to mock
    }

    private val track = DbTrack(id = 5, mangaId = 7, syncId = 15, mediaId = 550, status = DbTrackStatus.Watching, lastChapterRead = 1,
        score = 8, trackingUrl = "https://www.themoviedb.org/movie/550", itemType = DbItemType.Anime)

    @Test
    fun loginRequiresApprovalThenCreatesSession() = runTest {
        val mock = MockTrackerHttp { req ->
            when {
                "/authentication/token/new" in req.url -> 200 to """{"success":true,"expires_at":"x","request_token":"rt"}"""
                "/authentication/session/new" in req.url -> 200 to """{"success":true,"session_id":"sess"}"""
                "/account?" in req.url -> 200 to """{"id":42,"name":"","username":"neo"}"""
                else -> 404 to ""
            }
        }
        val service = TmdbTrackerService(15, InMemoryYokanDatabase(), mock.http)
        val values = mapOf(TrackerLoginField.ApiKey to "key")
        assertFailsWith<IllegalStateException> { service.login(values) }
        assertEquals(
            "https://www.themoviedb.org/authenticate/rt?redirect_to=yokan%3A%2F%2Ftracker%2Ftmdb",
            service.authorizeUrl(values),
        )
        val pref = service.login(values)
        val session = mock.requests[1]
        assertEquals("POST", session.method)
        assertEquals("https://api.themoviedb.org/3/authentication/session/new?api_key=key", session.url)
        assertEquals("rt", trackerJson.parseToJsonElement(session.body).jsonObject["request_token"]!!.jsonPrimitive.content)
        assertEquals("https://api.themoviedb.org/3/account?api_key=key&session_id=sess", mock.requests[2].url)
        assertEquals("sess", pref.oauth)
        assertEquals("neo", pref.username)
        assertEquals("key", pref.credentials().apiKey)
        assertEquals("42", pref.credentials().userId)
        assertFalse(service.supports(true))
        assertTrue(service.supports(false))
    }

    @Test
    fun searchByIdTriesTvThenMovieAndText() = runTest {
        val (service, mock) = service({ req ->
            when {
                "/tv/1399?" in req.url -> 200 to tv
                "/tv/550?" in req.url -> 404 to """{"status_code":34}"""
                "/movie/550?" in req.url -> 200 to """{"id":550,"title":"Fight Club","release_date":"1999-10-15"}"""
                "/search/multi" in req.url -> 200 to """{"page":1,"results":[{"id":550,"media_type":"movie","title":"Fight Club"},
                    {"id":1,"media_type":"person","name":"Someone"},$tv]}""".replace("\"id\":1399,", "\"id\":1399,\"media_type\":\"tv\",")
                else -> 404 to ""
            }
        })
        val show = service.search("id:tv/1399", false).single()
        assertEquals("https://www.themoviedb.org/tv/1399", show.trackingUrl)
        assertEquals(73, show.totalChapter)
        assertEquals("https://image.tmdb.org/t/p/w500/p.jpg", show.coverUrl)
        val movie = service.search("id:550", false).single()
        assertEquals("https://www.themoviedb.org/movie/550", movie.trackingUrl)
        assertEquals(550L, movie.mediaId)
        assertEquals(listOf("Fight Club", "Game of Thrones"), service.search("fight club", false).map { it.title })
        assertEquals("https://api.themoviedb.org/3/search/multi?$auth&query=fight%20club", mock.requests.last().url)
    }

    @Test
    fun bindAdoptsAccountStates() = runTest {
        val (service, mock) = service({ 200 to """{"id":550,"favorite":false,"rated":{"value":6.5},"watchlist":true}""" })
        val bound = service.bind(track, false)
        assertEquals(DbTrackStatus.PlanToWatch, bound.status)
        assertEquals(7, bound.score)
        assertEquals(1, bound.lastChapterRead)
        assertEquals(1, mock.requests.size)
        assertEquals("https://api.themoviedb.org/3/movie/550/account_states?$auth", mock.requests[0].url)
    }

    @Test
    fun bindWithoutRemoteStateAddsToWatchlist() = runTest {
        val (service, mock) = service({ req ->
            if ("account_states" in req.url) 200 to """{"id":550,"favorite":false,"rated":false,"watchlist":false}"""
            else 200 to """{"status_code":1}"""
        })
        val bound = service.bind(track.copy(status = DbTrackStatus.PlanToWatch, score = 0), false)
        assertEquals(DbTrackStatus.PlanToWatch, bound.status)
        val watchlist = mock.requests[1]
        assertEquals("POST", watchlist.method)
        assertEquals("https://api.themoviedb.org/3/account/42/watchlist?$auth", watchlist.url)
        val body = trackerJson.parseToJsonElement(watchlist.body).jsonObject
        assertEquals("movie", body["media_type"]!!.jsonPrimitive.content)
        assertEquals(550, body["media_id"]!!.jsonPrimitive.content.toInt())
        assertTrue(body["watchlist"]!!.jsonPrimitive.boolean)
        assertEquals("DELETE", mock.requests[2].method)
    }

    @Test
    fun updatePushesWatchlistAndRating() = runTest {
        val (service, mock) = service({ 201 to """{"status_code":1}""" })
        val show = track.copy(trackingUrl = "https://www.themoviedb.org/tv/1399", mediaId = 1399, lastChapterRead = 12)
        val updated = service.update(show, false)
        assertEquals(12, updated.lastChapterRead)
        assertFalse(trackerJson.parseToJsonElement(mock.requests[0].body).jsonObject["watchlist"]!!.jsonPrimitive.boolean)
        val rating = mock.requests[1]
        assertEquals("POST", rating.method)
        assertEquals("https://api.themoviedb.org/3/tv/1399/rating?$auth", rating.url)
        assertEquals(8.0, trackerJson.parseToJsonElement(rating.body).jsonObject["value"]!!.jsonPrimitive.double)
    }

    @Test
    fun refreshAndUnbind() = runTest {
        val (service, mock) = service({ req ->
            when {
                "account_states" in req.url -> 200 to """{"id":550,"rated":{"value":10.0},"watchlist":false}"""
                req.method == "DELETE" -> 404 to """{"status_code":34}"""
                else -> 201 to """{"status_code":13}"""
            }
        })
        val refreshed = service.refresh(track, false)
        assertEquals(10, refreshed.score)
        assertEquals(DbTrackStatus.Watching, refreshed.status)
        service.unbind(track, false)
        assertEquals(listOf("POST", "DELETE"), mock.requests.drop(1).map { it.method })
        assertEquals("https://api.themoviedb.org/3/movie/550/rating?$auth", mock.requests.last().url)
    }

    @Test
    fun rejectedSessionThrows() = runTest {
        val (service, _) = service({ 401 to """{"status_code":3,"status_message":"Authentication failed"}""" })
        assertTrue(assertFailsWith<TrackerHttpException> { service.refresh(track, false) }.unauthorized)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerAccountTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines TrackerAccountTest, anilistAccountKeepsIdAndNameApart, anilistAccountSurvivesNoAvatar, malAccountIdIsName, malAccountReadsEmptyPictureAsNull, simklAccountTakesIdFromAccountAndNameFromUser, simklAccountStillWorksWhenUserBlockMissing, kitsuAccountFallsBackToSlugWhenNameNull, kitsuAccountPrefersNameWhenPresent, traktAccountExtractsUsernameNameAndAvatar and 6 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • anilistAccountKeepsIdAndNameApart
  • anilistAccountSurvivesNoAvatar
  • malAccountIdIsName
  • malAccountReadsEmptyPictureAsNull
  • simklAccountTakesIdFromAccountAndNameFromUser
  • simklAccountStillWorksWhenUserBlockMissing
  • kitsuAccountFallsBackToSlugWhenNameNull
  • kitsuAccountPrefersNameWhenPresent
  • traktAccountExtractsUsernameNameAndAvatar
  • noServiceReportsEmptyId
  • trackPreferenceAccountLabelHandlesNumericUsername
  • malTrackerServiceAccountProfile
  • simklTrackerServiceAccountProfile
  • kitsuTrackerServiceAccountProfile
  • traktTrackerServiceAccountProfile

Cross-chapter imports used by this file: DbTrackPreference, InMemoryYokanDatabase, seedDatabaseSnapshot, HttpResponse, RecordingHttpService. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.DbTrackPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonObject

class TrackerAccountTest {

    private val json = Json { ignoreUnknownKeys = true; isLenient = true }

    @Test
    fun anilistAccountKeepsIdAndNameApart() {
        val viewer = json.parseToJsonElement("""
            {
              "id": 123456,
              "name": "RyanYuuki",
              "avatar": {"large": "https://s4.anilist.co/file/avatar/123456.png"},
              "mediaListOptions": {"scoreFormat": "POINT_10"}
            }
        """).jsonObject

        val account = anilistAccount(viewer)
        assertEquals("123456", account.id)
        assertEquals("RyanYuuki", account.name)
        assertTrue(account.avatarUrl?.endsWith("123456.png") == true)
    }

    @Test
    fun anilistAccountSurvivesNoAvatar() {
        val viewer = json.parseToJsonElement("""
            {
              "id": 7,
              "name": "someone",
              "avatar": null
            }
        """).jsonObject

        val account = anilistAccount(viewer)
        assertEquals("7", account.id)
        assertEquals("someone", account.name)
        assertNull(account.avatarUrl)
    }

    @Test
    fun malAccountIdIsName() {
        val user = json.parseToJsonElement("""
            {
              "id": 999,
              "name": "someone",
              "picture": "https://api-cdn.myanimelist.net/images/userimages/1.jpg"
            }
        """).jsonObject

        val account = malAccount(user)
        assertEquals("someone", account.id)
        assertEquals("someone", account.name)
        assertTrue(account.avatarUrl?.contains("userimages") == true)
    }

    @Test
    fun malAccountReadsEmptyPictureAsNull() {
        val userWithEmpty = json.parseToJsonElement("""{"name":"someone","picture":""}""").jsonObject
        val userWithoutPic = json.parseToJsonElement("""{"name":"someone"}""").jsonObject

        assertNull(malAccount(userWithEmpty).avatarUrl)
        assertNull(malAccount(userWithoutPic).avatarUrl)
    }

    @Test
    fun simklAccountTakesIdFromAccountAndNameFromUser() {
        val settings = json.parseToJsonElement("""
            {
              "user": {
                "name": "Someone",
                "joined_at": "2020-01-01T00:00:00Z",
                "avatar": "1_male.jpg"
              },
              "account": {"id": 4242, "timezone": "Europe/Paris", "type": "free"}
            }
        """).jsonObject

        val account = simklAccount(settings)
        assertEquals("4242", account.id)
        assertEquals("Someone", account.name)
        assertEquals("https://simkl.in/avatars/1_male.jpg", account.avatarUrl)
    }

    @Test
    fun simklAccountStillWorksWhenUserBlockMissing() {
        val settings = json.parseToJsonElement("""{"account":{"id":1}}""").jsonObject
        val account = simklAccount(settings)
        assertEquals("1", account.id)
        assertNull(account.name)
        assertNull(account.avatarUrl)
    }

    @Test
    fun kitsuAccountFallsBackToSlugWhenNameNull() {
        val data = json.parseToJsonElement("""
            {
              "id": "55555",
              "attributes": {
                "slug": "some-one",
                "name": null,
                "ratingSystem": "simple",
                "avatar": {"original": "https://media.kitsu.io/users/avatars/1.png"}
              }
            }
        """).jsonObject

        val account = kitsuAccount(data)
        assertEquals("55555", account.id)
        assertEquals("some-one", account.name)
        assertTrue(account.avatarUrl?.contains("kitsu.io") == true)
    }

    @Test
    fun kitsuAccountPrefersNameWhenPresent() {
        val data = json.parseToJsonElement("""
            {
              "id": "1",
              "attributes": {"slug": "some-one", "name": "Some One"}
            }
        """).jsonObject

        val account = kitsuAccount(data)
        assertEquals("Some One", account.name)
        assertNull(account.avatarUrl)
    }

    @Test
    fun traktAccountExtractsUsernameNameAndAvatar() {
        val settings = json.parseToJsonElement("""
            {
              "user": {
                "username": "traktuser",
                "name": "Trakt User",
                "images": {
                  "avatar": {"full": "https://trakt.tv/assets/avatar.png"}
                }
              }
            }
        """).jsonObject

        val account = traktAccount(settings)
        assertEquals("traktuser", account.id)
        assertEquals("Trakt User", account.name)
        assertEquals("https://trakt.tv/assets/avatar.png", account.avatarUrl)
    }

    @Test
    fun noServiceReportsEmptyId() {
        val anilist = anilistAccount(json.parseToJsonElement("""{"id": 1, "name": "a"}""").jsonObject)
        val mal = malAccount(json.parseToJsonElement("""{"name": "b"}""").jsonObject)
        val simkl = simklAccount(json.parseToJsonElement("""{"account": {"id": 2}}""").jsonObject)
        val kitsu = kitsuAccount(json.parseToJsonElement("""{"id": "3", "attributes": {"slug": "c"}}""").jsonObject)
        val trakt = traktAccount(json.parseToJsonElement("""{"user": {"username": "d"}}""").jsonObject)

        assertTrue(anilist.id.isNotEmpty())
        assertTrue(mal.id.isNotEmpty())
        assertTrue(simkl.id.isNotEmpty())
        assertTrue(kitsu.id.isNotEmpty())
        assertTrue(trakt.id.isNotEmpty())
    }

    @Test
    fun trackPreferenceAccountLabelHandlesNumericUsername() {
        val prefWithAccountName = DbTrackPreference(syncId = 1, username = "123456", accountName = "Alice")
        assertEquals("Alice", prefWithAccountName.accountLabel)

        val prefWithAlphabeticUsername = DbTrackPreference(syncId = 1, username = "alice_dev")
        assertEquals("alice_dev", prefWithAlphabeticUsername.accountLabel)

        val prefWithNumericIdOnly = DbTrackPreference(syncId = 2, username = "123456")
        assertNull(prefWithNumericIdOnly.accountLabel)
    }

    @Test
    fun malTrackerServiceAccountProfile() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot()).also {
            it.upsertTrackPreference(DbTrackPreference(syncId = 1, oauth = "token"))
        }
        val http = RecordingHttpService { HttpResponse(statusCode = 200, body = """{"name":"mal_user","picture":"https://cdn.myanimelist.net/pic.jpg"}""") }
        val profile = MalTrackerService(1, database, http).accountProfile()

        assertNotNull(profile)
        assertEquals("mal_user", profile.name)
        assertEquals("https://cdn.myanimelist.net/pic.jpg", profile.avatarUrl)
        assertEquals("Bearer token", http.requests.single().headers["Authorization"])
    }

    @Test
    fun simklTrackerServiceAccountProfile() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot()).also {
            it.upsertTrackPreference(DbTrackPreference(syncId = 4, oauth = "simkl_token"))
        }
        val http = RecordingHttpService { HttpResponse(statusCode = 200, body = """{"account":{"id":123},"user":{"name":"SimklUser","avatar":"avatar.jpg"}}""") }
        val profile = SimklTrackerService(4, database, http).accountProfile()

        assertNotNull(profile)
        assertEquals("SimklUser", profile.name)
        assertEquals("https://simkl.in/avatars/avatar.jpg", profile.avatarUrl)
    }

    @Test
    fun kitsuTrackerServiceAccountProfile() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot()).also {
            it.upsertTrackPreference(DbTrackPreference(syncId = 3, oauth = "kitsu_token"))
        }
        val http = RecordingHttpService { HttpResponse(statusCode = 200, body = """{"data":[{"id":"77","attributes":{"slug":"kitsu_user","name":"Kitsu User","avatar":{"original":"https://kitsu.io/pic.png"}}}]}""") }
        val profile = KitsuTrackerService(3, database, http).accountProfile()

        assertNotNull(profile)
        assertEquals("Kitsu User", profile.name)
        assertEquals("https://kitsu.io/pic.png", profile.avatarUrl)
    }

    @Test
    fun traktTrackerServiceAccountProfile() = runTest {
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot()).also {
            it.upsertTrackPreference(DbTrackPreference(syncId = 5, oauth = "trakt_token"))
        }
        val http = RecordingHttpService { HttpResponse(statusCode = 200, body = """{"user":{"username":"trakt_hero","name":"Trakt Hero","images":{"avatar":{"full":"https://trakt.tv/avatar.png"}}}}""") }
        val profile = TraktTrackerService(5, database, http).accountProfile()

        assertNotNull(profile)
        assertEquals("Trakt Hero", profile.name)
        assertEquals("https://trakt.tv/avatar.png", profile.avatarUrl)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerAccountsTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines TrackerAccountsTest, FakeTracker, checkRefresh, findLibraryItem, update, bind, refresh, unbind, statusList, search and 19 further declarations.

The source describes its contract as:

The remote side of tracking as driven by the repository's local writes.

Read the setup, action and assertions in these cases before implementing their production paths:

  • bindCreatesRemoteEntryAsPlannedWithoutReadsAndAdoptsExistingRemoteProgress
  • localProgressAheadOfProviderIsPushedOnBindAndReadingPushesWhenEnabled
  • editsPushAndRemoteRemovalIsOptIn
  • signedOutRemoteTrackersStayLocalAndOriginalAdaptersKeepLocalUpdates
  • enhancedTrackerAutoBindsOnAddAndSyncsProgressBothWays
  • enhancedTrackerIgnoresOtherSourcesAndOptInAutoBindNeedsOneExactTitle
  • loginStoresTheAdapterPreferenceAndRejectsMissingFields
  • idQueriesAndCallbackParametersParse

Cross-chapter imports used by this file: DefaultYokanRepository, DbChapter, DbItemType, DbManga, DbSource, DbTrack. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
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.InMemoryYokanDatabase
import eu.friedcutlet.yokan.domain.ItemType
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

/** The remote side of tracking as driven by the repository's local writes. */
@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class TrackerAccountsTest {
    private val mangaId = 9001L

    private open class FakeTracker(override val syncId: Int, remote: Boolean = true) : TrackerService {
        override val name = "Fake$syncId"
        override val loginFields: List<TrackerLoginField> = if (remote) listOf(TrackerLoginField.ApiKey) else emptyList()
        val calls = mutableListOf<String>()
        var remoteState: DbTrack? = null
        var searchResults: List<DbTrackSearch> = emptyList()

        override suspend fun checkRefresh() = true
        override suspend fun findLibraryItem(track: DbTrack, isManga: Boolean): DbTrack? = null
        override suspend fun update(track: DbTrack, isManga: Boolean): DbTrack {
            calls += "update:${track.lastChapterRead}:${track.status}:${track.score}"
            return track.also { remoteState = it }
        }
        override suspend fun bind(track: DbTrack, isManga: Boolean): DbTrack {
            calls += "bind:${track.lastChapterRead}:${track.status}"
            return remoteState?.let { track.copy(lastChapterRead = it.lastChapterRead, status = it.status, score = it.score) } ?: track
        }
        override suspend fun refresh(track: DbTrack, isManga: Boolean): DbTrack {
            calls += "refresh"
            return remoteState?.let { track.copy(lastChapterRead = it.lastChapterRead, status = it.status) } ?: track
        }
        override suspend fun unbind(track: DbTrack, isManga: Boolean) { calls += "unbind:${track.mediaId}" }
        override fun statusList(isManga: Boolean) = emptyList<DbTrackStatus>()
        override suspend fun search(query: String, isManga: Boolean) = searchResults.also { calls += "search:$query" }
        override suspend fun fetchGeneralData(isManga: Boolean, rankingType: String) = emptyList<DbTrackSearch>()
        override suspend fun fetchUserData(isManga: Boolean) = emptyList<DbTrackSearch>()
        override fun scoreValue() = 0 to 10
        override fun displayScore(score: Int) = "$score"
        override suspend fun login(values: Map<TrackerLoginField, String>) =
            DbTrackPreference(syncId = syncId.toLong(), oauth = values.required(TrackerLoginField.ApiKey))
    }

    private class FakeServer(syncId: Int) : FakeTracker(syncId), EnhancedTracker {
        override fun accept(source: DbSource) = source.name.contains("Komga")
        override suspend fun match(manga: DbManga) =
            DbTrackSearch(syncId = syncId, mediaId = 77, title = manga.name, trackingUrl = "https://komga.test/api/v1/series/77", lastChapterRead = remoteState?.lastChapterRead)
    }

    private fun TestScope.setup(vararg trackers: TrackerService, readChapters: Int = 0, chapters: Int = 6): Triple<InMemoryYokanDatabase, DefaultYokanRepository, TrackerAccounts> {
        val database = InMemoryYokanDatabase()
        database.upsertSource(DbSource(id = 501, name = "Komga (Home)", lang = "all", isAdded = true))
        database.upsertManga(DbManga(id = mangaId, name = "Blue Box", link = "https://komga.test/api/v1/series/77", sourceId = 501))
        (1..chapters).forEach { n ->
            database.upsertChapter(DbChapter(id = 9100L + n, mangaId = mangaId, url = "/c$n", name = "Chapter $n", number = n.toDouble(), isRead = n <= readChapters))
        }
        val accounts = TrackerAccounts(database, trackers.toList(), this)
        return Triple(database, DefaultYokanRepository(database, trackerAccounts = accounts), accounts)
    }

    private fun InMemoryYokanDatabase.signIn(syncId: Int) = upsertTrackPreference(DbTrackPreference(syncId = syncId.toLong(), oauth = "token"))

    private fun InMemoryYokanDatabase.track(syncId: Int) = tracks(mangaId).single { it.syncId == syncId }

    @Test
    fun bindCreatesRemoteEntryAsPlannedWithoutReadsAndAdoptsExistingRemoteProgress() = runTest {
        val tracker = FakeTracker(10)
        val (database, repository) = setup(tracker)
        database.signIn(10)
        repository.bindTrack(mangaId, DbTrackSearch(syncId = 10, mediaId = 5, title = "Blue Box"), ItemType.Manga)
        advanceUntilIdle()
        assertEquals(listOf("bind:0:PlanToRead"), tracker.calls)
        assertEquals(DbTrackStatus.PlanToRead, database.track(10).status)

        // An existing remote entry ahead of local progress wins; local is not pushed backwards.
        repository.removeTrack(database.track(10).id)
        tracker.calls.clear()
        tracker.remoteState = DbTrack(status = DbTrackStatus.Reading, lastChapterRead = 12, score = 8)
        repository.bindTrack(mangaId, DbTrackSearch(syncId = 10, mediaId = 5, title = "Blue Box"), ItemType.Manga)
        advanceUntilIdle()
        assertEquals(listOf("bind:0:PlanToRead"), tracker.calls)
        assertEquals(Triple(12, DbTrackStatus.Reading, 8), database.track(10).let { Triple(it.lastChapterRead, it.status, it.score) })
    }

    @Test
    fun localProgressAheadOfProviderIsPushedOnBindAndReadingPushesWhenEnabled() = runTest {
        val tracker = FakeTracker(10)
        val (database, repository) = setup(tracker, readChapters = 3)
        database.signIn(10)
        tracker.remoteState = DbTrack(status = DbTrackStatus.Reading, lastChapterRead = 1)
        repository.bindTrack(mangaId, DbTrackSearch(syncId = 10, mediaId = 5), ItemType.Manga)
        advanceUntilIdle()
        assertEquals(listOf("bind:3:Reading", "update:3:Reading:null"), tracker.calls)
        assertEquals(3, database.track(10).lastChapterRead)

        tracker.calls.clear()
        repository.setChaptersRead(setOf(9104L), isRead = true)
        advanceUntilIdle()
        assertEquals(listOf("update:4:Reading:null"), tracker.calls)

        tracker.calls.clear()
        database.updateSettings(database.settings().copy(updateProgressAfterReading = false))
        repository.setChaptersRead(setOf(9105L), isRead = true)
        advanceUntilIdle()
        assertEquals(emptyList(), tracker.calls)
        assertEquals(5, database.track(10).lastChapterRead)
    }

    @Test
    fun editsPushAndRemoteRemovalIsOptIn() = runTest {
        val tracker = FakeTracker(10)
        val (database, repository) = setup(tracker)
        database.signIn(10)
        repository.bindTrack(mangaId, DbTrackSearch(syncId = 10, mediaId = 5), ItemType.Manga)
        advanceUntilIdle()
        tracker.calls.clear()
        repository.updateTrack(database.track(10).id, progress = 4, status = DbTrackStatus.OnHold, score = 7)
        advanceUntilIdle()
        assertEquals(listOf("update:4:OnHold:7"), tracker.calls)

        tracker.calls.clear()
        repository.removeTrack(database.track(10).id)
        advanceUntilIdle()
        assertEquals(emptyList(), tracker.calls)
        repository.bindTrack(mangaId, DbTrackSearch(syncId = 10, mediaId = 5), ItemType.Manga)
        advanceUntilIdle()
        tracker.calls.clear()
        repository.removeTrack(database.track(10).id, removeRemote = true)
        advanceUntilIdle()
        assertEquals(listOf("unbind:5"), tracker.calls)
    }

    @Test
    fun signedOutRemoteTrackersStayLocalAndOriginalAdaptersKeepLocalUpdates() = runTest {
        val remote = FakeTracker(10)
        val original = FakeTracker(2, remote = false)
        val (database, repository) = setup(remote, original)
        repository.bindTrack(mangaId, DbTrackSearch(syncId = 10, mediaId = 5), ItemType.Manga)
        repository.bindTrack(mangaId, DbTrackSearch(syncId = 2, mediaId = 6), ItemType.Manga)
        advanceUntilIdle()
        assertEquals(emptyList(), remote.calls)
        assertEquals(emptyList(), original.calls) // no remote bind for the local-only adapters
        repository.updateTrack(database.track(2).id, progress = 2, status = DbTrackStatus.Reading, score = 0)
        repository.updateTrack(database.track(10).id, progress = 2, status = DbTrackStatus.Reading, score = 0)
        advanceUntilIdle()
        assertEquals(listOf("update:2:Reading:0"), original.calls)
        assertEquals(emptyList(), remote.calls)
    }

    @Test
    fun enhancedTrackerAutoBindsOnAddAndSyncsProgressBothWays() = runTest {
        val server = FakeServer(20)
        val (database, repository) = setup(server, readChapters = 2)
        database.signIn(20)
        server.remoteState = DbTrack(status = DbTrackStatus.Reading, lastChapterRead = 4)
        repository.setMangaFavorite(mangaId, true)
        advanceUntilIdle()
        val track = database.track(20)
        assertEquals("https://komga.test/api/v1/series/77", track.trackingUrl)
        assertEquals(4, track.lastChapterRead)
        // Remote progress marks local chapters read up to chapter 4.
        assertEquals(listOf(9101L, 9102L, 9103L, 9104L), database.chapters(mangaId).filter { it.isRead }.map { it.id }.sorted())

        // Reading locally pushes the continuous chapter number.
        server.calls.clear()
        repository.setChaptersRead(setOf(9105L), isRead = true)
        advanceUntilIdle()
        assertEquals(listOf("update:5:Reading:null"), server.calls)

        // A detail refresh pulls progress made on the server.
        server.calls.clear()
        server.remoteState = DbTrack(status = DbTrackStatus.Completed, lastChapterRead = 6)
        repository.refreshTracks(mangaId)
        advanceUntilIdle()
        assertEquals(listOf("refresh"), server.calls)
        assertTrue(database.chapters(mangaId).all { it.isRead })
        assertEquals(DbTrackStatus.Completed, database.track(20).status)
    }

    @Test
    fun enhancedTrackerIgnoresOtherSourcesAndOptInAutoBindNeedsOneExactTitle() = runTest {
        val server = FakeServer(20)
        val account = FakeTracker(10)
        val (database, repository) = setup(server, account)
        database.signIn(20)
        database.signIn(10)
        database.upsertSource(DbSource(id = 501, name = "Other", lang = "all", isAdded = true))
        account.searchResults = listOf(DbTrackSearch(syncId = 10, mediaId = 1, title = "Blue Box"), DbTrackSearch(syncId = 10, mediaId = 2, title = "Blue Box!"))
        repository.setMangaFavorite(mangaId, true)
        advanceUntilIdle()
        assertTrue(database.tracks(mangaId).isEmpty()) // pref off; source not accepted
        assertEquals(emptyList(), account.calls)

        repository.setMangaFavorite(mangaId, false)
        database.updateSettings(database.settings().let { it.copy(features = it.features.copy(tracking = it.features.tracking.copy(autoBindOnAdd = true))) })
        repository.setMangaFavorite(mangaId, true)
        advanceUntilIdle()
        assertTrue(database.tracks(mangaId).isEmpty()) // both normalize to "bluebox": ambiguous

        repository.setMangaFavorite(mangaId, false)
        account.searchResults = listOf(DbTrackSearch(syncId = 10, mediaId = 1, title = "Blue Box"), DbTrackSearch(syncId = 10, mediaId = 2, title = "Blue Box 2"))
        repository.setMangaFavorite(mangaId, true)
        advanceUntilIdle()
        assertEquals(1L, database.track(10).mediaId)
        assertTrue(account.calls.any { it.startsWith("bind:") })
    }

    @Test
    fun loginStoresTheAdapterPreferenceAndRejectsMissingFields() = runTest {
        val tracker = FakeTracker(10)
        val (database, _, accounts) = setup(tracker)
        val error = runCatching { accounts.login(10L, emptyMap()) }.exceptionOrNull()
        assertEquals("API key / access token is required", error?.message)
        accounts.login(10L, mapOf(TrackerLoginField.ApiKey to " key "))
        assertEquals("key", database.trackPreferences().single { it.syncId == 10L }.oauth)
    }

    @Test
    fun idQueriesAndCallbackParametersParse() {
        assertEquals("12345", trackerSearchId("id:12345"))
        assertEquals("one-piece", trackerSearchId("  ID: one-piece "))
        assertEquals(null, trackerSearchId("Blue Box"))
        assertEquals(null, trackerSearchId("id:"))
        assertEquals("a b/c", callbackParameter("yokan://tracker/shikimori?code=a+b%2Fc&state=x", "code"))
        assertEquals("ref", callbackParameter("yokan://tracker/hikka#reference=ref", "reference"))
        assertEquals("raw-code", callbackParameter(" raw-code ", "code"))
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerOAuthTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines TrackerOAuthTest, parsesAccessTokenFromFragment, parsesAuthorizationCodeFromQuery, returnsErrorOnRejection, authorizeUrlAdvertisesRedirect.

Read the setup, action and assertions in these cases before implementing their production paths:

  • parsesAccessTokenFromFragment
  • parsesAuthorizationCodeFromQuery
  • returnsErrorOnRejection
  • authorizeUrlAdvertisesRedirect
package eu.friedcutlet.yokan.services.tracking

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class TrackerOAuthTest {
    @Test
    fun parsesAccessTokenFromFragment() {
        val result = TrackerOAuth.parseCallback("yokan://tracker/anilist#access_token=abc&state=xyz")
        assertEquals("abc", result.accessToken)
        assertEquals("xyz", result.state)
        assertNull(result.error)
    }

    @Test
    fun parsesAuthorizationCodeFromQuery() {
        val result = TrackerOAuth.parseCallback("yokan://tracker/myanimelist?code=12345&state=safe")
        assertEquals("12345", result.authorizationCode)
        assertEquals("safe", result.state)
    }

    @Test
    fun returnsErrorOnRejection() {
        val result = TrackerOAuth.parseCallback("yokan://tracker/anilist?error=access_denied")
        assertEquals("access_denied", result.error)
    }

    @Test
    fun authorizeUrlAdvertisesRedirect() {
        val url = TrackerOAuth.authorizeUrl(2, "client123")
        assertEquals(true, url?.contains("yokan://tracker/anilist"))
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerSearchEncodingTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines TrackerSearchEncodingTest, searchedUrl, malSearchEncodesReservedCharacters, kitsuSearchEncodesReservedCharacters, simklSearchEncodesReservedCharacters, traktSearchEncodesReservedCharacters.

Read the setup, action and assertions in these cases before implementing their production paths:

  • malSearchEncodesReservedCharacters
  • kitsuSearchEncodesReservedCharacters
  • simklSearchEncodesReservedCharacters
  • traktSearchEncodesReservedCharacters

Cross-chapter imports used by this file: InMemoryYokanDatabase. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import kotlin.test.Test
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class TrackerSearchEncodingTest {
    private val query = "A&B #1+"
    private val encoded = "=A%26B%20%231%2B&"

    private suspend fun searchedUrl(search: suspend (MockTrackerHttp) -> Unit): String {
        val mock = MockTrackerHttp { 200 to """{"data":[]}""" }
        search(mock)
        return mock.requests.single().url
    }

    @Test
    fun malSearchEncodesReservedCharacters() = runTest {
        val url = searchedUrl { MalTrackerService(1, InMemoryYokanDatabase(), it.http).search(query, isManga = true) }

        assertTrue(encoded in url, url)
    }

    @Test
    fun kitsuSearchEncodesReservedCharacters() = runTest {
        val url = searchedUrl { KitsuTrackerService(3, InMemoryYokanDatabase(), it.http).search(query, isManga = true) }

        assertTrue(encoded in url, url)
    }

    @Test
    fun simklSearchEncodesReservedCharacters() = runTest {
        val url = searchedUrl { SimklTrackerService(5, InMemoryYokanDatabase(), it.http).search(query, isManga = false) }

        assertTrue(encoded in url, url)
    }

    @Test
    fun traktSearchEncodesReservedCharacters() = runTest {
        val url = searchedUrl { TraktTrackerService(8, InMemoryYokanDatabase(), it.http).search(query, isManga = false) }

        assertTrue(encoded in url, url)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerTestHttp.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines RecordedRequest, MockTrackerHttp, HttpRequestData.recorded.

The source describes its contract as:

One request as it reached the Ktor engine: the real HTTP boundary of the adapters.

Cross-chapter imports used by this file: KtorHttpService. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.tracking

import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.KtorHttpService
import io.ktor.client.engine.mock.MockEngine
import io.ktor.client.engine.mock.respond
import io.ktor.client.request.HttpRequestData
import io.ktor.http.HttpStatusCode
import io.ktor.http.content.OutgoingContent
import io.ktor.http.headersOf

/** One request as it reached the Ktor engine: the real HTTP boundary of the adapters. */
data class RecordedRequest(val method: String, val url: String, val headers: Map<String, String>, val body: String)

/**
 * A [KtorHttpService] over a [MockEngine] whose [route] returns `status to body` (JSON) for each request.
 * Every request is appended to [requests]. Use 4xx for failures: KtorHttpService retries 5xx.
 */
class MockTrackerHttp(private val route: (RecordedRequest) -> Pair<Int, String>) {
    val requests = mutableListOf<RecordedRequest>()

    val http: HttpService = KtorHttpService(
        MockEngine { data ->
            val recorded = data.recorded()
            requests += recorded
            val (status, body) = route(recorded)
            respond(body, HttpStatusCode.fromValue(status), headersOf("Content-Type", "application/json"))
        },
    )

    private fun HttpRequestData.recorded(): RecordedRequest = RecordedRequest(
        method = method.value,
        url = url.toString(),
        headers = headers.entries().associate { (k, v) -> k to v.joinToString(",") } +
            (body.contentType?.let { mapOf("Content-Type" to it.toString()) } ?: emptyMap()),
        body = when (val content = body) {
            is OutgoingContent.ByteArrayContent -> content.bytes().decodeToString()
            else -> ""
        },
    )
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/RecommendationsRouteTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines RecommendationsRouteTest, localRecommendationOpensLocalDetail, recommendationWithoutLocalMatchUsesGlobalSearch.

Read the setup, action and assertions in these cases before implementing their production paths:

  • localRecommendationOpensLocalDetail
  • recommendationWithoutLocalMatchUsesGlobalSearch

Cross-chapter imports used by this file: DefaultYokanRepository, DbItemType, DbManga, InMemoryYokanDatabase, seedDatabaseSnapshot, ItemType. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.discovery

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.metadata.RecommendationResult
import eu.friedcutlet.yokan.ui.navigation.Route
import kotlin.test.Test
import kotlin.test.assertEquals

class RecommendationsRouteTest {
    private val repository = DefaultYokanRepository(
        InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(DbManga(id = 7, name = "Local", favorite = true)))),
    )
    private val routes = mutableListOf<Route>()

    @Test
    fun localRecommendationOpensLocalDetail() {
        openRecommendationResult(repository, { routes += it }, RecommendationResult("Local", 100, "", DbItemType.Manga, mangaId = 7))

        assertEquals(listOf<Route>(Route.Detail(7)), routes)
    }

    @Test
    fun recommendationWithoutLocalMatchUsesGlobalSearch() {
        openRecommendationResult(repository, { routes += it }, RecommendationResult("Remote", 100, "", DbItemType.Anime, mangaId = 99))

        assertEquals(listOf<Route>(Route.GlobalSearch(ItemType.Anime, "Remote")), routes)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/SourceRelatedViewModelTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines SourceRelatedViewModelTest, Owner, database, Owner.vm, create, related.

Read the setup, action and assertions in these cases before implementing their production paths:

  • opensSameSourceEntryPreservingFavouritesNotesAndCreditsAndRejectsUnlistedRows
  • retriesKeepUsableGroupsAndDoNotStartDuplicateRequests
  • clearingTheScreenCancelsTheRuntimeRequestAndRemovedSourcesCannotCreateEntries
  • aLateResponseCannotAttachToAReboundTitle
  • sameNameSourcesWithTheSameUrlDoNotShareSavedEntries

Cross-chapter imports used by this file: DefaultYokanRepository. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.discovery

import androidx.lifecycle.*
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.extensions.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.*
import kotlin.test.*

@OptIn(ExperimentalCoroutinesApi::class)
class SourceRelatedViewModelTest {
    private val dispatcher = UnconfinedTestDispatcher()
    @BeforeTest fun before() { Dispatchers.setMain(dispatcher) }
    @AfterTest fun after() { Dispatchers.resetMain() }
    private class Owner : ViewModelStoreOwner { override val viewModelStore = ViewModelStore() }
    private val item = RemoteManga("Sequel", "/sequel")
    private val relations = SourceRelations(true, listOf(SourceRelatedGroup("Sequel", listOf(item))))
    private fun database() = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
        mangas = listOf(
            DbManga(id = 1, name = "Parent", link = "/parent", sourceId = 42, source = "Same name", itemType = DbItemType.Anime),
            DbManga(id = 2, name = "Saved sequel", link = "/sequel", sourceId = 42, source = "Same name", itemType = DbItemType.Anime,
                favorite = true, privateNote = "Private", cast = listOf(eu.friedcutlet.yokan.domain.TitleCredit("Actor"))),
            DbManga(id = 3, name = "Other source sequel", link = "/sequel", sourceId = 43, source = "Same name", itemType = DbItemType.Anime),
        ),
        sources = listOf(DbSource(id = 42, name = "Same name", itemType = DbItemType.Anime, isAdded = true)),
    ))
    private fun Owner.vm(db: InMemoryYokanDatabase, load: suspend () -> SourceRelations): SourceRelatedViewModel {
        val factory = object : ExtensionRuntimeFactory {
            override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, db) {
                override suspend fun related(url: String): SourceRelations { assertEquals("/parent", url); return load() }
            }
        }
        return ViewModelProvider.create(this, viewModelFactory { initializer {
            SourceRelatedViewModel(1, DefaultYokanRepository(db), db, factory, dispatcher)
        } })[SourceRelatedViewModel::class]
    }

    @Test fun opensSameSourceEntryPreservingFavouritesNotesAndCreditsAndRejectsUnlistedRows() = runTest(dispatcher) {
        val db = database()
        val owner = Owner()
        try {
            val vm = owner.vm(db) { relations }
            vm.state.first { !it.loading }
            vm.open(RemoteManga("Forged", "/forged"))
            assertNull(vm.state.value.openedTitleId)
            vm.open(item)
            assertEquals(2L, vm.state.first { it.openedTitleId != null }.openedTitleId)
            val saved = requireNotNull(db.manga(2))
            assertTrue(saved.favorite)
            assertEquals("Private", saved.privateNote)
            assertEquals("Actor", saved.cast.single().name)
            assertEquals("Other source sequel", db.manga(3)?.name)
            vm.opened()
            assertNull(vm.state.value.openedTitleId)
        } finally { owner.viewModelStore.clear() }
    }

    @Test fun retriesKeepUsableGroupsAndDoNotStartDuplicateRequests() = runTest(dispatcher) {
        val db = database()
        val owner = Owner()
        val pending = CompletableDeferred<Unit>()
        var calls = 0
        try {
            val vm = owner.vm(db) { calls++; if (calls == 2) { pending.await(); error("Temporary failure") }; relations }
            vm.state.first { !it.loading }
            vm.refresh(); vm.refresh()
            assertEquals(2, calls)
            assertEquals(relations.groups, vm.state.value.groups)
            pending.complete(Unit)
            assertEquals("Temporary failure", vm.state.first { !it.loading && it.error != null }.error)
            assertEquals(relations.groups, vm.state.value.groups)
            vm.refresh()
            vm.state.first { !it.loading && it.error == null }
            assertEquals(3, calls)
        } finally { owner.viewModelStore.clear() }
    }

    @Test fun clearingTheScreenCancelsTheRuntimeRequestAndRemovedSourcesCannotCreateEntries() = runTest(dispatcher) {
        val db = database()
        val owner = Owner()
        var cancelled = false
        owner.vm(db) { try { awaitCancellation() } finally { cancelled = true } }
        owner.viewModelStore.clear()
        assertTrue(cancelled)
        val next = Owner()
        try {
            val vm = next.vm(db) { relations }
            vm.state.first { !it.loading }
            db.removeSource(42)
            vm.open(item)
            vm.state.first { it.error != null }
            assertNull(vm.state.value.openedTitleId)
            assertEquals("Saved sequel", db.manga(2)?.name)
        } finally { next.viewModelStore.clear() }
    }

    @Test fun aLateResponseCannotAttachToAReboundTitle() = runTest(dispatcher) {
        val db = database()
        val owner = Owner()
        val pending = CompletableDeferred<SourceRelations>()
        try {
            val vm = owner.vm(db) { pending.await() }
            db.upsertManga(requireNotNull(db.manga(1)).copy(sourceId = 43))
            pending.complete(relations)
            val state = vm.state.first { !it.loading }
            assertNotNull(state.error)
            assertTrue(state.groups.isEmpty())
            assertNull(state.sourceId)
        } finally { owner.viewModelStore.clear() }
    }

    @Test fun sameNameSourcesWithTheSameUrlDoNotShareSavedEntries() {
        val db = database()
        db.removeManga(2)
        val repo = DefaultYokanRepository(db)
        val source = requireNotNull(repo.source(42))
        val saved = repo.upsertRemoteTitle(source, item)
        assertNotEquals(3L, saved.id)
        assertEquals(42L, saved.sourceId)
        assertEquals("Other source sequel", db.manga(3)?.name)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeFeedHidingTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines HomeFeedHidingTest, cards.

Read the setup, action and assertions in these cases before implementing their production paths:

  • sourceFeedsHideLibraryEntriesOfEnabledTypeOnly
package eu.friedcutlet.yokan.ui.screens.home

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.discovery.*
import kotlin.test.*

class HomeFeedHidingTest {
    private val local = projectHomeLocal(emptySnapshot().copy(
        mangas = listOf(DbManga(id = 1, name = "Fav", favorite = true, sourceId = 10, link = "/one")),
    ))
    private val items = listOf(
        DiscoveryMedia("source:10:/one", "Fav", HomeMediaFilter.Manga, sourceId = 10, sourceUrl = "/one"),
        DiscoveryMedia("source:10:/two", "New", HomeMediaFilter.Manga, sourceId = 10, sourceUrl = "/two"),
    )
    private val remote = listOf(
        HomeRemoteShelf("feed:a", HomeSection.Sources, items, sourceName = "Src"),
        HomeRemoteShelf("PopularManga", HomeSection.PopularManga, items),
    )

    private fun cards(browse: DbBrowsePreferences, shelf: String) =
        buildHomeState(local, remote, DbSettings(features = DbFeaturePreferences(browse = browse)))
            .shelves.single { it.id == shelf }.cards.map { it.media.key }

    @Test fun sourceFeedsHideLibraryEntriesOfEnabledTypeOnly() {
        assertEquals(listOf("source:10:/one", "source:10:/two"), cards(DbBrowsePreferences(), "feed:a"))
        assertEquals(listOf("source:10:/two"), cards(DbBrowsePreferences(hideLibraryManga = true), "feed:a"))
        assertEquals(listOf("source:10:/one", "source:10:/two"), cards(DbBrowsePreferences(hideLibraryAnime = true), "feed:a"))
        // Catalog shelves are not source feeds.
        assertEquals(2, cards(DbBrowsePreferences(hideLibraryManga = true), "PopularManga").size)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeModelsTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines HomeModelsTest, snapshot.

Read the setup, action and assertions in these cases before implementing their production paths:

  • resumesAllThreeMediaWithoutConfusingTheirProgressUnits
  • completedAndDeletedHistoryCannotLaunchAnInvalidReader
  • readChapterAdvancesToNextUnreadInReaderOrder
  • hiddenMediaAndNsfwSourcesStayOutOfResumeAndRecommendations
  • catalogMatchesLocalTitleButSourceCardsRequireExactSourceAndUrl
  • selectedFilterAlsoHidesUnrelatedLoadingAndErrorShelves
  • completedLibraryCardsCanBeHiddenAndScoresUseTrackerScales
package eu.friedcutlet.yokan.ui.screens.home

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.discovery.*
import kotlin.test.*

class HomeModelsTest {
    private fun snapshot() = emptySnapshot().copy(
        mangas = listOf(
            DbManga(id = 1, name = "Manga", favorite = true, sourceId = 10, link = "/one"),
            DbManga(id = 2, name = "Anime", itemType = DbItemType.Anime, favorite = true),
            DbManga(id = 3, name = "Novel", itemType = DbItemType.Novel, favorite = true),
        ),
        chapters = listOf(
            DbChapter(id = 11, mangaId = 1, name = "Chapter 1", lastPageRead = "4"),
            DbChapter(id = 21, mangaId = 2, name = "Episode 1", lastPageRead = "125000"),
            DbChapter(id = 31, mangaId = 3, name = "Chapter 1", lastPageRead = "0.65"),
        ),
        histories = listOf(
            DbHistory(id = 1, mangaId = 1, chapterId = 11, itemType = DbItemType.Manga, updatedAt = 100),
            DbHistory(id = 2, mangaId = 2, chapterId = 21, itemType = DbItemType.Anime, updatedAt = 200),
            DbHistory(id = 3, mangaId = 3, chapterId = 31, itemType = DbItemType.Novel, updatedAt = 300),
        ),
        pageCache = listOf(DbChapterPageUrls(chapterId = 11, urls = List(10) { "/$it.jpg" })),
    )

    @Test fun resumesAllThreeMediaWithoutConfusingTheirProgressUnits() {
        val data = projectHomeLocal(snapshot())
        assertEquals(listOf(3L, 2L, 1L), data.resume.map { it.mangaId })
        val manga = data.resume.single { it.mangaId == 1L }
        assertEquals(4L, manga.position)
        assertEquals(0.5f, manga.progress)
        assertEquals(125000L, data.resume.single { it.mangaId == 2L }.position)
        val novel = data.resume.single { it.mangaId == 3L }
        assertEquals(0.65f, novel.novelProgress)
        assertEquals(0.65f, novel.progress)
    }

    @Test fun completedAndDeletedHistoryCannotLaunchAnInvalidReader() {
        val snapshot = snapshot()
        val data = projectHomeLocal(snapshot.copy(chapters = snapshot.chapters.filterNot { it.id == 21L }
            .map { it.copy(isRead = it.id == 11L) }))
        assertEquals(listOf(3L), data.resume.map { it.mangaId })
    }

    @Test fun readChapterAdvancesToNextUnreadInReaderOrder() {
        val base = snapshot()
        val data = projectHomeLocal(base.copy(
            chapters = listOf(DbChapter(id = 12, mangaId = 1, name = "Chapter 2"),
                DbChapter(id = 11, mangaId = 1, name = "Chapter 1", isRead = true)),
            histories = base.histories.take(1),
        ))
        assertEquals(12L, data.resume.single().chapterId)
    }

    @Test fun hiddenMediaAndNsfwSourcesStayOutOfResumeAndRecommendations() {
        val base = snapshot()
        val settings = base.settings.copy(hideItems = listOf("AnimeLibrary"), showNsfw = false)
        val data = projectHomeLocal(base.copy(settings = settings,
            sources = listOf(DbSource(id = 10, name = "Adult source", isNsfw = true, isAdded = true))))
        assertEquals(listOf(3L), data.resume.map { it.mangaId })
        val state = buildHomeState(data, listOf(HomeRemoteShelf("anime", HomeSection.PopularAnime,
            loading = true, issue = DiscoveryIssue.Network)), settings)
        assertTrue(state.shelves.none { it.section == HomeSection.PopularAnime })
    }

    @Test fun catalogMatchesLocalTitleButSourceCardsRequireExactSourceAndUrl() {
        val data = projectHomeLocal(snapshot())
        val remote = listOf(HomeRemoteShelf("catalog", HomeSection.PopularManga, listOf(
            DiscoveryMedia("anilist:1", "  MANGA  ", HomeMediaFilter.Manga),
            DiscoveryMedia("source:10:/one", "Renamed", HomeMediaFilter.Manga, sourceId = 10, sourceUrl = "/one"),
            DiscoveryMedia("source:99:/one", "Manga", HomeMediaFilter.Manga, sourceId = 99, sourceUrl = "/one"),
        )))
        val cards = buildHomeState(data, remote, DbSettings()).shelves.single { it.id == "catalog" }.cards
        assertEquals(2, cards.size)
        assertEquals(1L, cards.first().mangaId)
        assertNull(cards.last().mangaId)
    }

    @Test fun selectedFilterAlsoHidesUnrelatedLoadingAndErrorShelves() {
        val rows = listOf(HomeRemoteShelf("anime", HomeSection.PopularAnime, loading = true),
            HomeRemoteShelf("movies", HomeSection.PopularMovies, issue = DiscoveryIssue.Credentials))
        val state = buildHomeState(HomeLocalData(), rows, DbSettings(features = DbFeaturePreferences(home = DbHomePreferences(filter = HomeMediaFilter.Movie))))
        assertEquals(listOf("continue", "recommended", "movies"), state.shelves.map { it.id })
    }

    @Test fun completedLibraryCardsCanBeHiddenAndScoresUseTrackerScales() {
        val base = snapshot()
        val data = projectHomeLocal(base.copy(chapters = base.chapters.map { it.copy(isRead = true) },
            tracks = listOf(DbTrack(id = 1, mangaId = 1, syncId = 2, score = 85, status = DbTrackStatus.Reading),
                DbTrack(id = 2, mangaId = 2, syncId = 3, score = 70, status = DbTrackStatus.Watching))))
        assertEquals(8.5, data.library.single { it.mangaId == 1L }.media.rating)
        assertEquals(7.0, data.library.single { it.mangaId == 2L }.media.rating)
        val state = buildHomeState(data, emptyList(), DbSettings(features = DbFeaturePreferences(home = DbHomePreferences(hideCompleted = true))))
        assertTrue(state.featured.isEmpty())
        assertTrue(state.shelves.all { it.cards.isEmpty() })
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeTmdbRecommendationsTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines HomeTmdbRecommendationsTest, track, snapshot, state, shelf, popular, recommendations, sourceFeed, tmdbRecommendations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • seedsAreRecentlyWatchedTmdbTracksAndEveryTrackedTitleIsKnown
  • shelfExcludesTrackedAndLibraryTitlesAndRespectsLimitFilterAndHiding
  • viewModelRequestsTrackedSeedsOnlyWhenEnabledAndCancelsWhenHidden
package eu.friedcutlet.yokan.ui.screens.home

import eu.friedcutlet.yokan.data.*
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.discovery.*
import eu.friedcutlet.yokan.services.tracking.TmdbTrackerSyncId
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

@OptIn(ExperimentalCoroutinesApi::class)
class HomeTmdbRecommendationsTest {
    private val dispatcher = UnconfinedTestDispatcher()
    @BeforeTest fun before() { Dispatchers.setMain(dispatcher) }
    @AfterTest fun after() { Dispatchers.resetMain() }

    private fun track(id: Long, mangaId: Long, url: String, updatedAt: Long, syncId: Int = TmdbTrackerSyncId) =
        DbTrack(id = id, mangaId = mangaId, syncId = syncId, status = DbTrackStatus.Watching, trackingUrl = url, updatedAt = updatedAt)

    private fun snapshot() = emptySnapshot().copy(
        mangas = listOf(
            DbManga(id = 1, name = "Show", itemType = DbItemType.Anime, favorite = true),
            DbManga(id = 2, name = "Film", itemType = DbItemType.Anime, favorite = true),
            DbManga(id = 3, name = "Owned", itemType = DbItemType.Anime, favorite = true),
        ),
        histories = listOf(DbHistory(id = 1, mangaId = 1, itemType = DbItemType.Anime, updatedAt = 50)),
        tracks = listOf(
            track(1, 1, "https://www.themoviedb.org/tv/100", 10),
            track(2, 2, "https://www.themoviedb.org/movie/200-film", 20),
            track(3, 99, "https://www.themoviedb.org/movie/300", 30),
            track(4, 1, "https://anilist.co/anime/5", 40, syncId = 2),
        ),
    )

    @Test fun seedsAreRecentlyWatchedTmdbTracksAndEveryTrackedTitleIsKnown() {
        val data = projectHomeLocal(snapshot())
        assertEquals(listOf(TmdbSeed("tv", 100), TmdbSeed("movie", 200)), data.tmdbSeeds)
        assertEquals(setOf("tmdb:tv:100", "tmdb:movie:200", "tmdb:movie:300"), data.tmdbTracked)
    }

    @Test fun shelfExcludesTrackedAndLibraryTitlesAndRespectsLimitFilterAndHiding() {
        val data = projectHomeLocal(snapshot())
        val items = listOf(
            DiscoveryMedia("tmdb:movie:300", "Tracked", HomeMediaFilter.Movie),
            DiscoveryMedia("tmdb:tv:400", "Owned", HomeMediaFilter.Series),
        ) + (1..8).map { DiscoveryMedia("tmdb:${if (it % 2 == 0) "movie" else "tv"}:$it", "Fresh $it",
            if (it % 2 == 0) HomeMediaFilter.Movie else HomeMediaFilter.Series) }
        val remote = listOf(HomeRemoteShelf("tmdb-recommended", HomeSection.TmdbRecommended, items))
        fun state(prefs: DbHomePreferences) = buildHomeState(data, remote, DbSettings(features = DbFeaturePreferences(home = prefs)))
        fun shelf(prefs: DbHomePreferences) = state(prefs).shelves.singleOrNull { it.section == HomeSection.TmdbRecommended }

        val all = shelf(DbHomePreferences(itemsPerShelf = 6))!!
        assertEquals((1..6).map { "Fresh $it" }, all.cards.map { it.media.title })
        assertEquals(listOf("Fresh 2", "Fresh 4", "Fresh 6", "Fresh 8"),
            shelf(DbHomePreferences(filter = HomeMediaFilter.Movie))!!.cards.map { it.media.title })
        assertNull(shelf(DbHomePreferences(filter = HomeMediaFilter.Anime)))
        assertNull(shelf(DbHomePreferences(hiddenSections = setOf(HomeSection.TmdbRecommended))))
    }

    @Test fun viewModelRequestsTrackedSeedsOnlyWhenEnabledAndCancelsWhenHidden() = runTest(dispatcher) {
        val repo = DefaultYokanRepository(InMemoryYokanDatabase(snapshot()))
        val settings = SettingsStore(repo, backgroundScope) {}
        val seen = mutableListOf<List<TmdbSeed>>()
        var running = 0
        val discovery = object : DiscoveryService {
            override suspend fun popular(kind: HomeMediaFilter, token: String, includeAdult: Boolean, refresh: Boolean) = emptyList<DiscoveryMedia>()
            override suspend fun recommendations(title: String, kind: HomeMediaFilter, includeAdult: Boolean, refresh: Boolean) = emptyList<DiscoveryMedia>()
            override suspend fun sourceFeed(feed: DbHomeSourceFeed, includeAdult: Boolean, refresh: Boolean) = emptyList<DiscoveryMedia>()
            override suspend fun tmdbRecommendations(seeds: List<TmdbSeed>, token: String, includeAdult: Boolean, refresh: Boolean): List<DiscoveryMedia> {
                seen += seeds
                running++
                try { awaitCancellation() } finally { running-- }
            }
        }
        val vm = HomeViewModel(repo, settings, discovery, dispatcher)
        try {
            vm.setActive(true)
            runCurrent()
            assertTrue(seen.isEmpty(), "TMDB disabled: no recommendation requests")
            vm.updatePreferences { it.copy(enableTmdb = true) }
            runCurrent()
            assertEquals(listOf(setOf(TmdbSeed("tv", 100), TmdbSeed("movie", 200))), seen.map { it.toSet() })
            assertEquals(1, running)
            assertTrue(vm.state.value.shelves.single { it.section == HomeSection.TmdbRecommended }.loading)
            vm.updatePreferences { it.copy(hiddenSections = setOf(HomeSection.TmdbRecommended)) }
            runCurrent()
            assertEquals(0, running, "the in-flight load is cancelled with the superseded request")
            assertEquals(1, seen.size)
            assertTrue(vm.state.value.shelves.none { it.section == HomeSection.TmdbRecommended })
        } finally { vm.awaitCleanup() }
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeViewModelTest.kt

Create this path in your reconstruction project. Source set: commonTest. Exact file download.

The implementation below defines HomeViewModelTest, Discovery, recommendations, sourceFeed, tmdbRecommendations, popular.

Read the setup, action and assertions in these cases before implementing their production paths:

  • localResumeAppearsWithoutWaitingForProvidersAndDeactivationCancelsThem
  • providerFailureAndTimeoutFinishTheirShelfWithoutBlockingOthers
  • disablingProviderRejectsLateResponsesAndCustomizationSurvivesContentUpdates
  • cleanupJoinsRetiredRequestGenerationsBeforeReleasingProfile
package eu.friedcutlet.yokan.ui.screens.home

import eu.friedcutlet.yokan.data.*
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.discovery.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*

@OptIn(ExperimentalCoroutinesApi::class)
class HomeViewModelTest {
    private val dispatcher = UnconfinedTestDispatcher()
    @BeforeTest fun before() { Dispatchers.setMain(dispatcher) }
    @AfterTest fun after() { Dispatchers.resetMain() }
    private abstract class Discovery : DiscoveryService {
        override suspend fun recommendations(title: String, kind: HomeMediaFilter, includeAdult: Boolean, refresh: Boolean) = emptyList<DiscoveryMedia>()
        override suspend fun sourceFeed(feed: DbHomeSourceFeed, includeAdult: Boolean, refresh: Boolean) = emptyList<DiscoveryMedia>()
        override suspend fun tmdbRecommendations(seeds: List<TmdbSeed>, token: String, includeAdult: Boolean, refresh: Boolean) = emptyList<DiscoveryMedia>()
    }

    @Test fun localResumeAppearsWithoutWaitingForProvidersAndDeactivationCancelsThem() = runTest(dispatcher) {
        val repo = DefaultYokanRepository(InMemoryYokanDatabase(emptySnapshot().copy(
            mangas = listOf(DbManga(id = 1, name = "Offline manga", favorite = true)),
            chapters = listOf(DbChapter(id = 11, mangaId = 1, name = "Chapter 1")),
            histories = listOf(DbHistory(id = 1, mangaId = 1, chapterId = 11, itemType = DbItemType.Manga)),
        )))
        val settings = SettingsStore(repo, backgroundScope) {}
        var running = 0
        val discovery = object : Discovery() {
            override suspend fun popular(kind: HomeMediaFilter, token: String, includeAdult: Boolean, refresh: Boolean): List<DiscoveryMedia> {
                running++
                try { awaitCancellation() } finally { running-- }
            }
        }
        val vm = HomeViewModel(repo, settings, discovery, dispatcher)
        try {
            vm.setActive(true)
            runCurrent()
            assertEquals(11L, vm.state.value.shelves.single { it.section == HomeSection.Continue }.cards.single().chapterId)
            assertTrue(running in 1..3)
            vm.setActive(false)
            runCurrent()
            assertEquals(0, running)
        } finally { vm.awaitCleanup() }
    }

    @Test fun providerFailureAndTimeoutFinishTheirShelfWithoutBlockingOthers() = runTest(dispatcher) {
        val repo = DefaultYokanRepository(InMemoryYokanDatabase(emptySnapshot()))
        val settings = SettingsStore(repo, backgroundScope) {}
        val discovery = object : Discovery() {
            override suspend fun popular(kind: HomeMediaFilter, token: String, includeAdult: Boolean, refresh: Boolean): List<DiscoveryMedia> = when (kind) {
                HomeMediaFilter.Anime -> listOf(DiscoveryMedia("anime", "Anime", kind))
                HomeMediaFilter.Manga -> throw DiscoveryException(DiscoveryIssue.RateLimited)
                else -> withTimeout(100) { delay(200); emptyList() }
            }
        }
        val vm = HomeViewModel(repo, settings, discovery, dispatcher)
        try {
            vm.setActive(true)
            advanceUntilIdle()
            val shelves = vm.state.value.shelves
            assertEquals(1, shelves.single { it.section == HomeSection.PopularAnime }.cards.size)
            assertEquals(DiscoveryIssue.RateLimited, shelves.single { it.section == HomeSection.PopularManga }.issue)
            assertEquals(DiscoveryIssue.Network, shelves.single { it.section == HomeSection.PopularNovels }.issue)
            assertFalse(vm.state.value.refreshing)
        } finally { vm.awaitCleanup() }
    }

    @Test fun disablingProviderRejectsLateResponsesAndCustomizationSurvivesContentUpdates() = runTest(dispatcher) {
        val repo = DefaultYokanRepository(InMemoryYokanDatabase(emptySnapshot()))
        val settings = SettingsStore(repo, backgroundScope) {}
        val release = CompletableDeferred<Unit>()
        val discovery = object : Discovery() {
            override suspend fun popular(kind: HomeMediaFilter, token: String, includeAdult: Boolean, refresh: Boolean): List<DiscoveryMedia> {
                withContext(NonCancellable) { release.await() }
                return listOf(DiscoveryMedia("late:$kind", "Late title", kind))
            }
        }
        val vm = HomeViewModel(repo, settings, discovery, dispatcher)
        try {
            vm.setActive(true)
            runCurrent()
            vm.customize(true)
            vm.updatePreferences { it.copy(enableAniList = false) }
            runCurrent()
            release.complete(Unit)
            advanceUntilIdle()
            assertTrue(vm.state.value.shelves.all { it.cards.isEmpty() })
            assertTrue(vm.state.value.customizeOpen)
            assertFalse(vm.state.value.refreshing)
            assertFalse(repo.dbSettings().home.enableAniList)
        } finally { release.complete(Unit); vm.awaitCleanup() }
    }

    @Test fun cleanupJoinsRetiredRequestGenerationsBeforeReleasingProfile() = runTest(dispatcher) {
        val repo = DefaultYokanRepository(InMemoryYokanDatabase(emptySnapshot()))
        val settings = SettingsStore(repo, backgroundScope) {}
        val release = CompletableDeferred<Unit>()
        val discovery = object : Discovery() {
            override suspend fun popular(kind: HomeMediaFilter, token: String, includeAdult: Boolean, refresh: Boolean): List<DiscoveryMedia> {
                try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }
            }
        }
        val vm = HomeViewModel(repo, settings, discovery, dispatcher)
        try {
            vm.setActive(true)
            runCurrent()
            vm.updatePreferences { it.copy(enableAniList = false) }
            runCurrent()
            val cleanup = async { vm.awaitCleanup() }
            runCurrent()
            assertFalse(cleanup.isCompleted, "Retired request finalizers still own profile resources")
            release.complete(Unit)
            cleanup.await()
        } finally { release.complete(Unit); vm.awaitCleanup() }
    }
}

Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/discovery/SourceRelatedScreenRenderTest.kt

Create this path in your reconstruction project. Source set: desktopTest. Exact file download.

The implementation below defines SourceRelatedScreenRenderTest, onUi.

The source describes its contract as:

Synthetic source data; renders the shared layout and exercises opening an actual row.

Read the setup, action and assertions in these cases before implementing their production paths:

  • groupedResultsAndRecoveryStatesRenderAtCompactAndWideSizes

Cross-chapter imports used by this file: RemoteManga, SourceRelatedGroup, YokanTheme. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.discovery

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.use
import androidx.lifecycle.*
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceRelatedGroup
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import java.io.File
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlin.test.*

/** Synthetic source data; renders the shared layout and exercises opening an actual row. */
class SourceRelatedScreenRenderTest {
    @Test fun groupedResultsAndRecoveryStatesRenderAtCompactAndWideSizes() {
        val owner = object : LifecycleOwner { override val lifecycle = LifecycleRegistry.createUnsafe(this) }
        onUi { owner.lifecycle.currentState = Lifecycle.State.RESUMED }
        val loaded = SourceRelatedState(title = "Sample journey", supported = true, groups = listOf(
            SourceRelatedGroup("Sequel", listOf(
                RemoteManga("Sample journey: The next season", "/next", description = "The story continues with familiar characters and a new destination."),
                RemoteManga("A related title with a longer name that should remain readable on a compact screen", "/long"),
            )),
            SourceRelatedGroup("Adaptation", listOf(RemoteManga("Sample journey — original manga", "/manga"))),
        ))
        try {
            listOf(Triple(360, 900, true), Triple(1024, 800, false)).forEach { (width, height, dark) ->
                listOf("groups" to loaded, "error" to SourceRelatedState(error = "The source could not be reached. Check your connection and try again."),
                    "unsupported" to SourceRelatedState(supported = false)).forEach { (name, state) ->
                    val opened = mutableListOf<RemoteManga>()
                    val scene = onUi { ImageComposeScene(width, height) {
                        CompositionLocalProvider(LocalLifecycleOwner provides owner) {
                            YokanTheme(darkTheme = dark) { Surface(Modifier.fillMaxSize()) {
                                SourceRelatedScreen(state, onOpen = { opened += it }, onRefresh = {}, onBack = {})
                            } }
                        }
                    } }
                    try {
                        repeat(10) { onUi { scene.render(it * 100_000_000L).close() } }
                        onUi { scene.render(1_100_000_000L).use { image ->
                            assertEquals(width, image.width)
                            val output = File("build/reports/source-related-ui/$name-$width.png")
                            output.parentFile.mkdirs()
                            checkNotNull(image.encodeToData()).use { output.writeBytes(it.bytes) }
                        } }
                        if (name == "groups") {
                            onUi {
                                scene.sendPointerEvent(PointerEventType.Press, Offset(200f, 210f))
                                scene.sendPointerEvent(PointerEventType.Release, Offset(200f, 210f))
                            }
                            assertEquals("/next", opened.single().url)
                        }
                    } finally { onUi { scene.close() } }
                }
            }
        } finally { onUi { owner.lifecycle.currentState = Lifecycle.State.DESTROYED } }
    }

    private fun <T> onUi(block: () -> T): T {
        if (SwingUtilities.isEventDispatchThread()) return block()
        val task = FutureTask(block)
        SwingUtilities.invokeAndWait(task)
        return task.get()
    }
}

Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/home/HomeScreenRenderTest.kt

Create this path in your reconstruction project. Source set: desktopTest. Exact file download.

The implementation below defines HomeScreenRenderTest, render, settle, save, onUi.

The source describes its contract as:

Shared Compose layout evidence; these are desktop renders, not device screenshots.

Read the setup, action and assertions in these cases before implementing their production paths:

  • rendersResponsiveContentEmptyErrorsAndCustomization

Cross-chapter imports used by this file: YokanTheme. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.home

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Density
import androidx.compose.ui.use
import androidx.lifecycle.*
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.discovery.*
import eu.friedcutlet.yokan.ui.theme.YokanTheme
import java.io.File
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlin.test.*

/** Shared Compose layout evidence; these are desktop renders, not device screenshots. */
class HomeScreenRenderTest {
    @Test fun rendersResponsiveContentEmptyErrorsAndCustomization() {
        val cover = System.getenv("YOKAN_HOME_UI_COVER")?.let(::File)?.takeIf { it.exists() }?.readBytes()
        val banner = System.getenv("YOKAN_HOME_UI_BANNER")?.let(::File)?.takeIf { it.exists() }?.absolutePath
        val attack = HomeCard(DiscoveryMedia("library:1", "Attack on Titan", HomeMediaFilter.Anime,
            backdropUrl = banner, description = "Humanity fights to survive behind enormous walls as a young soldier uncovers the secrets beyond them.", rating = 8.5),
            mangaId = 1, chapterId = 11, coverBytes = cover, chapterName = "Episode 12", position = 125000)
        val novel = HomeCard(DiscoveryMedia("library:2", "Ascendance of a Bookworm", HomeMediaFilter.Novel),
            mangaId = 2, chapterId = 21, chapterName = "Chapter 8", novelProgress = 0.65f, progress = 0.65f)
        val manga = HomeCard(DiscoveryMedia("library:3", "Witch Hat Atelier", HomeMediaFilter.Manga, rating = 8.7),
            mangaId = 3, chapterId = 31, chapterName = "Chapter 14", position = 7, progress = 0.4f)
        val content = HomeState(featured = listOf(attack, novel, manga), shelves = listOf(
            HomeShelf("continue", HomeSection.Continue, listOf(attack, novel, manga)),
            HomeShelf("recommended", HomeSection.Recommended, listOf(manga, attack, novel)),
            HomeShelf("anime", HomeSection.PopularAnime, listOf(attack)),
        ))
        render("home-phone", 390, 1000, 1f, true, content, interact = true)
        render("home-large-text", 390, 1000, 1.5f, true, content)
        render("home-tablet", 768, 1024, 1f, false, content)
        render("home-desktop", 1280, 900, 1f, false, content)
        render("home-empty", 390, 900, 1f, true, HomeState(preferences = DbHomePreferences(enableAniList = false)))
        render("home-errors", 390, 1000, 1f, true, HomeState(shelves = listOf(
            HomeShelf("continue", HomeSection.Continue, emptyList()),
            HomeShelf("anime", HomeSection.PopularAnime, emptyList(), issue = DiscoveryIssue.Network),
            HomeShelf("movies", HomeSection.PopularMovies, emptyList(), issue = DiscoveryIssue.Credentials),
        )))
    }

    private fun render(name: String, width: Int, height: Int, fontScale: Float, dark: Boolean, initial: HomeState, interact: Boolean = false) {
        val owner = object : LifecycleOwner { override val lifecycle = LifecycleRegistry.createUnsafe(this) }
        var state by mutableStateOf(initial)
        onUi { owner.lifecycle.currentState = Lifecycle.State.RESUMED }
        val scene = onUi { ImageComposeScene(width, height) {
            CompositionLocalProvider(LocalLifecycleOwner provides owner, LocalDensity provides Density(1f, fontScale)) {
                YokanTheme(darkTheme = dark) { Surface(Modifier.fillMaxSize()) {
                    HomeScreen(state, {}, {}, { state = state.copy(customizeOpen = it) },
                        { state = state.copy(searchOpen = it) }, { state = state.copy(searchQuery = it) }, {},
                        { state = state.copy(preferences = it(state.preferences)) }, {}, {}, {}, { _, _ -> }, {})
                } }
            }
        } }
        var time = 0L
        fun settle() { repeat(12) { time += 100_000_000L; onUi { scene.render(time).close() } } }
        fun save(suffix: String) {
            settle()
            onUi { scene.render(time).use { image ->
                assertEquals(width, image.width)
                val output = File("build/reports/home-ui/$suffix.png")
                output.parentFile.mkdirs()
                checkNotNull(image.encodeToData()).use { output.writeBytes(it.bytes) }
            } }
        }
        try {
            save(name)
            if (interact) {
                onUi {
                    scene.sendPointerEvent(PointerEventType.Press, Offset(width - 24f, 32f))
                    scene.sendPointerEvent(PointerEventType.Release, Offset(width - 24f, 32f))
                }
                settle()
                assertTrue(state.customizeOpen, "Home toolbar must open customization")
                save("home-customize")
            }
        } finally {
            onUi { scene.close(); owner.lifecycle.currentState = Lifecycle.State.DESTROYED }
        }
    }

    private fun <T> onUi(block: () -> T): T {
        val task = FutureTask<T> { block() }
        SwingUtilities.invokeAndWait(task)
        return task.get()
    }
}

Completion record

  • [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
  • [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
  • [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
  • [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry. [chapter-content-end]: #

Gate: fixture tests pass for every implemented provider and supported operation, including account-change races, exact ID search and score normalization. Home resume matches reader ordering, deleted history is ignored and failed shelves do not erase healthy ones. Real service credentials/live protocol compatibility need explicit integration runs; fake HTTP tests are not live certification.

Ready to move on?

Check the chapter’s verification gate before marking it complete.

Search chapters, reference and source filenames.