Yokan / rebuild
Course 1 8624561

Files, archives and local library

284 min read + implementationSnapshot 8624561Markdown

Prerequisites: database/repository and profile paths. This chapter supplies offline content to all readers. File workbook.

How to write this chapter

Supply an owned file/archive boundary and a local-library pipeline for manga, EPUB and video. Scanning extracts source facts; reconciliation decides how those facts can update current user state.

The 88 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 files, archive entries, pickers and deterministic ordering.
  • Step 2: Implement JVM, SAF, iOS and browser storage adapters.
  • Step 3: Classify inputs and assemble local scan/import candidates.
  • Step 4: Reconcile current state, sidecars, seasons and managed entry changes.
  • Step 5: Connect local-library overview, browsing and metadata review UI.
  • Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #

Step 1: define file and archive contracts

Recreate LocalFileService/LocalArchiveService, media selection and pickers, path helpers, bounded cache, natural page order and EPUB manifest parsing. Distinguish app-owned storage, externally granted folders, virtual archive entries and browser handles. Keep URI schemes meaningful; content:// is not a normal filesystem path.

Implement asynchronous bounded reads and preparation. Cancellation propagates. Extract to owned caches with safe entry paths, bounded work and deterministic cleanup. Natural page ordering must put page 2 before page 10 and preserve ties consistently. EPUB uses container/OPF manifest/spine order and resolves relative links/media against each document's location.

Follow the code

Start with file references and readable archive/media contracts before platform paths. Local storage, external grants and virtual archive entries have different capabilities. Natural ordering makes page 2 precede page 10; EPUB ordering comes from the container/OPF spine rather than alphabetical ZIP order. Bounded reads/caches keep a malformed input from allocating unbounded memory. Pickers return references that must be prepared under the owner.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/LocalLibraryPaths.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/NaturalPageOrder.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/EpubManifest.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/BoundedCache.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.kt

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.kt

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

The implementation below defines LocalArchiveService, listEpubChaptersAsync, readEpubChapterAsync, readEpubResourceAsync, listPagesAsync, zipDirectoryToCbzAsync, invalidateIndexCache, listPages, listPagesStrict, listEpubChapters and 36 further declarations.

The source describes its contract as:

One readable-file definition for native filesystems and browser inventory listings.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.database.DbPageUrl

/** One readable-file definition for native filesystems and browser inventory listings. */
internal val readableLocalFileExtensions: Set<String> =
    setOf("cbz", "zip", "cbt", "tar", "epub", "cbr", "rar") +
        setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif") +
        setOf("mp4", "mkv", "mov", "webm", "avi", "m4v", "ts", "m3u8") +
        setOf("txt", "html", "xhtml", "md")

interface LocalArchiveService {
    suspend fun listEpubChaptersAsync(archivePath: String): List<LocalEpubChapter> = listEpubChapters(archivePath)
    suspend fun readEpubChapterAsync(archivePath: String, index: Int): String = readEpubChapter(archivePath, index)
    suspend fun readEpubResourceAsync(archivePath: String, resourcePath: String): ByteArray? = readEpubResource(archivePath, resourcePath)
    suspend fun listPagesAsync(archivePath: String): List<DbPageUrl> = listPages(archivePath)
    suspend fun zipDirectoryToCbzAsync(directoryPath: String, deleteSource: Boolean = true): String? = zipDirectoryToCbz(directoryPath, deleteSource)
    fun invalidateIndexCache() = Unit
    fun listPages(archivePath: String): List<DbPageUrl>
    /** Fresh, complete inventory for queue cloning; throws if any supported archive image is unreadable. */
    fun listPagesStrict(archivePath: String): List<DbPageUrl> =
        throw UnsupportedOperationException("Strict archive page inventory is unavailable")
    fun listEpubChapters(archivePath: String): List<LocalEpubChapter>
    fun readEpubChapter(archivePath: String, index: Int): String
    fun readEpubResource(archivePath: String, resourcePath: String): ByteArray?
    /** Zips the folder's images plus its [CHAPTER_METADATA_FILE] into `<folder>.cbz`; null when it is not a folder. */
    fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean = true): String?
}

/** Metadata a downloaded chapter folder keeps next to its pages, and carries into its CBZ. */
internal const val CHAPTER_METADATA_FILE = "metadata.json"

data class LocalEpubChapter(
    val title: String,
    val href: String,
)

data class LocalEntry(
    val path: String,
    val name: String,
    val isArchive: Boolean,
)

/** One immediate child; [name] includes the file extension and [path] may be an opaque provider URI. */
@kotlinx.serialization.Serializable
data class LocalDirectoryEntry(val path: String, val name: String, val isDirectory: Boolean)

interface LocalFileService {
    val downloadRoot: String
    val backupRoot: String
    val cacheRoot: String

    /** Browser files use asynchronous disk APIs; native implementations are immediately ready. */
    suspend fun prepare() = Unit
    suspend fun awaitPersistence() = Unit
    suspend fun close() { awaitPersistence() }
    suspend fun writeBytesAsync(path: String, bytes: ByteArray) = writeBytes(path, bytes)
    suspend fun readBytesAsync(path: String, maxBytes: Long = Long.MAX_VALUE): ByteArray =
        if (maxBytes == Long.MAX_VALUE) readBytes(path) else readBytesBounded(path, maxBytes)
    suspend fun deleteRecursivelyAsync(path: String): Boolean = deleteRecursively(path)
    suspend fun promoteAsync(sourcePath: String, targetPath: String): Boolean = promote(sourcePath, targetPath)
    suspend fun readableUrl(path: String): String =
        if (path.startsWith("file://") || path.startsWith("content://") || path.startsWith("http://") || path.startsWith("https://") || path.startsWith("blob:")) path else "file://$path"

    fun writeBytes(path: String, bytes: ByteArray)
    fun appendBytes(path: String, bytes: ByteArray) = writeBytes(path, readBytes(path) + bytes)
    /** Append without buffering the existing file; native implementations keep one handle open. */
    suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T =
        block { bytes -> if (exists(path)) appendBytes(path, bytes) else writeBytes(path, bytes) }
    /**
     * Replaces [path] with the chunks [block] writes. Platform implementations keep the file open
     * for the whole block; nothing may be created if [block] writes no chunk.
     */
    suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {
        var first = true
        return block { bytes ->
            if (first) writeBytes(path, bytes) else appendBytes(path, bytes)
            first = false
        }
    }
    /** Promote a fully written temporary file to its final name. */
    fun promote(sourcePath: String, targetPath: String): Boolean {
        if (!exists(sourcePath)) return false
        writeBytes(targetPath, readBytes(sourcePath))
        return exists(targetPath) && deleteRecursively(sourcePath) && !exists(sourcePath)
    }
    /** Atomically replace an existing file with a staged sibling file; unsupported by default. */
    fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean = false
    /** Publish a complete staged sibling directory only when its destination is absent. */
    fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean = false
    fun readBytes(path: String): ByteArray
    fun mimeType(path: String): String? = null
    /** Reads at most [maxBytes], throwing if the source exceeds the limit or cannot be read. */
    fun readBytesBounded(path: String, maxBytes: Long): ByteArray {
        require(maxBytes >= 0)
        val bytes = readBytes(path)
        require(bytes.size.toLong() <= maxBytes) { "File exceeds $maxBytes bytes" }
        return bytes
    }
    fun canonicalPath(path: String): String?
    fun exists(path: String): Boolean
    fun deleteRecursively(path: String): Boolean
    fun directorySize(path: String): Long
    fun openLocation(path: String): Boolean
    /** Null means the root could not be read; an empty list is a readable empty root. */
    fun listLocalEntries(root: String): List<LocalEntry>?
    /** Immediate children without recursive flattening. Null means unavailable/unsupported. */
    fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? = null
    fun listFiles(root: String): List<LocalFileEntry>
}

data class LocalFileEntry(
    val path: String,
    val name: String,
    val sizeBytes: Long,
    val lastModified: Long,
)

expect fun createPlatformLocalArchiveService(profileId: eu.friedcutlet.yokan.domain.ProfileId = eu.friedcutlet.yokan.domain.ProfileId.Default): LocalArchiveService

expect fun createPlatformLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId = eu.friedcutlet.yokan.domain.ProfileId.Default): LocalFileService

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.kt

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

The implementation below defines LocalMediaInput, readChunks, LocalMediaSelection, close, pickLocalMedia.

The source describes its contract as:

A picker-owned read grant. Only selected files are read; callers never inspect their parent.

package eu.friedcutlet.yokan.services.files

/** A picker-owned read grant. Only selected files are read; callers never inspect their parent. */
interface LocalMediaInput {
    val relativePath: String
    val sizeBytes: Long?
    /** Backpressure is mandatory; each chunk is at most [LOCAL_IMPORT_CHUNK_BYTES]. */
    suspend fun readChunks(consume: suspend (ByteArray) -> Unit)
}

class LocalMediaSelection(
    val files: List<LocalMediaInput>,
    private val release: () -> Unit = {},
) {
    fun close() = release()
}

internal const val LOCAL_IMPORT_CHUNK_BYTES = 64 * 1024
internal const val LOCAL_IMPORT_MAX_FILES = 10_000
internal val localImportExtensions = readableLocalFileExtensions +
    setOf("json", "nfo", "srt", "ass", "ssa", "vtt", "ttf", "otf", "key")

/** Folder selections preserve their top-level name and relative structure. Never buffers media. */
expect suspend fun pickLocalMedia(directory: Boolean = false): LocalMediaSelection?

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/LocalLibraryPaths.kt

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

The implementation below defines defaultLocalFolder, effectiveLocalLibraryFolders, resolveConfiguredLocalArchivePath, resolveLocalEpisodeVideo, downloadItemTypeFolder, downloadItemTypeFromFolder.

The source describes its contract as:

The file a local or downloaded episode plays: the stored video itself, or the first video in its folder.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DefaultLocalFolderName
import eu.friedcutlet.yokan.database.resolveLocalArchivePath
import eu.friedcutlet.yokan.database.effectiveLocalFolders
import eu.friedcutlet.yokan.database.DbItemType

fun defaultLocalFolder(files: LocalFileService): DbLocalFolder =
    DbLocalFolder(name = DefaultLocalFolderName, path = "${files.downloadRoot.trimEnd('/')}/local")

fun effectiveLocalLibraryFolders(settings: DbSettings, files: LocalFileService): List<DbLocalFolder> =
    settings.effectiveLocalFolders(defaultLocalFolder(files))

fun resolveConfiguredLocalArchivePath(storedPath: String, files: LocalFileService, settings: DbSettings): String {
    if (storedPath.isBlank()) return storedPath
    val separator = storedPath.indexOf('#')
    val base = if (separator >= 0) storedPath.substring(0, separator) else storedPath
    val suffix = if (separator >= 0) storedPath.substring(separator) else ""
    return resolveLocalArchivePath(base, effectiveLocalLibraryFolders(settings, files)) + suffix
}

internal val LocalVideoExtensions = setOf("mp4", "mkv", "mov", "webm", "avi", "m4v", "ts", "m3u8")

/** The file a local or downloaded episode plays: the stored video itself, or the first video in its folder. */
fun resolveLocalEpisodeVideo(storedPath: String, files: LocalFileService, settings: DbSettings): String? {
    val resolved = resolveConfiguredLocalArchivePath(storedPath, files, settings)
    return if (resolved.substringAfterLast('.').lowercase() in LocalVideoExtensions) resolved.takeIf(files::exists)
    else files.listFiles(resolved).filter { it.name.substringAfterLast('.').lowercase() in LocalVideoExtensions }
        .minByOrNull { it.name }?.path
}

fun downloadItemTypeFolder(itemType: DbItemType): String = when (itemType) {
    DbItemType.Anime -> "Anime"
    DbItemType.Novel -> "Novel"
    else -> "Manga"
}

fun downloadItemTypeFromFolder(name: String): DbItemType? = when {
    name.equals("Anime", ignoreCase = true) -> DbItemType.Anime
    name.equals("Novel", ignoreCase = true) -> DbItemType.Novel
    name.equals("Manga", ignoreCase = true) -> DbItemType.Manga
    else -> null
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/NaturalPageOrder.kt

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

package eu.friedcutlet.yokan.services.files

internal val naturalPageNameComparator: Comparator<String> = Comparator { left, right ->
    var leftIndex = 0
    var rightIndex = 0

    while (leftIndex < left.length && rightIndex < right.length) {
        val leftChar = left[leftIndex]
        val rightChar = right[rightIndex]
        if (leftChar in '0'..'9' && rightChar in '0'..'9') {
            val leftStart = leftIndex
            val rightStart = rightIndex
            while (leftIndex < left.length && left[leftIndex] in '0'..'9') leftIndex++
            while (rightIndex < right.length && right[rightIndex] in '0'..'9') rightIndex++

            var leftSignificant = leftStart
            var rightSignificant = rightStart
            while (leftSignificant < leftIndex && left[leftSignificant] == '0') leftSignificant++
            while (rightSignificant < rightIndex && right[rightSignificant] == '0') rightSignificant++

            val leftDigits = leftIndex - leftSignificant
            val rightDigits = rightIndex - rightSignificant
            if (leftDigits != rightDigits) return@Comparator leftDigits.compareTo(rightDigits)
            for (offset in 0 until leftDigits) {
                val comparison = left[leftSignificant + offset].compareTo(right[rightSignificant + offset])
                if (comparison != 0) return@Comparator comparison
            }
        } else {
            val comparison = leftChar.lowercaseChar().compareTo(rightChar.lowercaseChar())
            if (comparison != 0) return@Comparator comparison
            leftIndex++
            rightIndex++
        }
    }

    val lengthComparison = (left.length - leftIndex).compareTo(right.length - rightIndex)
    if (lengthComparison != 0) lengthComparison else left.compareTo(right)
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/EpubManifest.kt

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

Read container/OPF parsing and relative path resolution together. The reading spine determines chapter order, while the manifest supplies media references.

The implementation below defines readEpubManifest, readEpubManifestAsync, epubPackagePath, epubSpine, epubChapter, normalizeArchivePath.

The source describes its contract as:

Reads an EPUB's chapters in spine order (META-INF/container.xml → OPF → spine → manifest). Manifest hrefs resolve against the OPF directory and are normalised with [normalizeArchivePath]. [readEntry] returns the bytes of an archive entry at a normalised path, or null when it is missing. Chapters without a \<title\> are named "Chapter N" after their spine position.

package eu.friedcutlet.yokan.services.files

private val containerRootfilePath = Regex("full-path=\"([^\"]+)\"")
private val manifestItem = Regex("<item\\s+([^>]+)/?>")
private val itemId = Regex("id=\"([^\"]+)\"")
private val itemHref = Regex("href=\"([^\"]+)\"")
private val spineItemRef = Regex("<itemref\\s+[^>]*?idref=\"([^\"]+)\"")
private val titleElement = Regex("<title[^>]*>(.*?)</title>", RegexOption.DOT_MATCHES_ALL)
private val markupTag = Regex("<[^>]+>")

/**
 * Reads an EPUB's chapters in spine order (`META-INF/container.xml` → OPF → spine → manifest).
 * Manifest hrefs resolve against the OPF directory and are normalised with [normalizeArchivePath].
 * [readEntry] returns the bytes of an archive entry at a normalised path, or null when it is missing.
 * Chapters without a `<title>` are named "Chapter N" after their spine position.
 */
internal fun readEpubManifest(readEntry: (String) -> ByteArray?): List<LocalEpubChapter> {
    val opfPath = epubPackagePath(readEntry("META-INF/container.xml")) ?: return emptyList()
    val opfXml = readEntry(opfPath)?.decodeToString() ?: return emptyList()
    return epubSpine(opfPath, opfXml).mapNotNull { (index, href) ->
        readEntry(href)?.let { epubChapter(index, href, it) }
    }
}

/** Same manifest interpretation for asynchronous file backends, without buffering a whole book. */
internal suspend fun readEpubManifestAsync(readEntry: suspend (String) -> ByteArray?): List<LocalEpubChapter> {
    val opfPath = epubPackagePath(readEntry("META-INF/container.xml")) ?: return emptyList()
    val opfXml = readEntry(opfPath)?.decodeToString() ?: return emptyList()
    return epubSpine(opfPath, opfXml).mapNotNull { (index, href) ->
        readEntry(href)?.let { epubChapter(index, href, it) }
    }
}

private fun epubPackagePath(container: ByteArray?): String? = container?.decodeToString()?.let { xml ->
    containerRootfilePath.find(xml)?.groupValues?.get(1)?.let(::normalizeArchivePath)?.takeIf(String::isNotEmpty)
}

private fun epubSpine(opfPath: String, opfXml: String): List<Pair<Int, String>> {
    val opfDir = opfPath.substringBeforeLast('/', "").let { if (it.isEmpty()) "" else "$it/" }
    val manifest = manifestItem.findAll(opfXml).associate { match ->
        val attributes = match.groupValues[1]
        itemId.find(attributes)?.groupValues?.get(1).orEmpty() to
            itemHref.find(attributes)?.groupValues?.get(1).orEmpty()
    }.filterValues(String::isNotBlank)
    return spineItemRef.findAll(opfXml).mapIndexedNotNull { index, match ->
        val href = manifest[match.groupValues[1]] ?: return@mapIndexedNotNull null
        normalizeArchivePath(if (href.startsWith('/')) href else opfDir + href)
            .takeIf(String::isNotEmpty)
            ?.let { index to it }
    }.toList()
}

private fun epubChapter(index: Int, href: String, bytes: ByteArray): LocalEpubChapter {
    val title = titleElement.find(bytes.decodeToString())?.groupValues?.get(1)
        ?.replace(markupTag, "")?.trim()?.takeIf(String::isNotBlank)
    return LocalEpubChapter(title ?: "Chapter ${index + 1}", href)
}

/** Archive-relative path; EPUB hrefs decode `%20`, but literal ZIP entry names must not. */
internal fun normalizeArchivePath(path: String, decodePercentSpaces: Boolean = true): String {
    val output = ArrayDeque<String>()
    path.replace('\\', '/').split('/').forEach { part ->
        when (part) {
            "", "." -> Unit
            ".." -> output.removeLastOrNull()
            else -> output.addLast(if (decodePercentSpaces) part.replace("%20", " ") else part)
        }
    }
    return output.joinToString("/")
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/BoundedCache.kt

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

The implementation below defines BoundedCache, get, clear, set.

The source describes its contract as:

Thread-safe LRU for archive metadata (page lists, chapter lists). Bounded by entry count and total weight; oversized values are returned by callers but not retained.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.util.PlatformLock

/**
 * Thread-safe LRU for archive metadata (page lists, chapter lists). Bounded by entry count and total
 * weight; oversized values are returned by callers but not retained.
 */
internal class BoundedCache<K, V>(
    private val maxEntries: Int,
    private val maxWeight: Int,
    private val weightOf: (V) -> Int,
) {
    private val lock = PlatformLock()
    private val values = LinkedHashMap<K, V>()
    private var weight = 0L

    init {
        require(maxEntries > 0 && maxWeight > 0)
    }

    operator fun get(key: K): V? = lock.withLock {
        values.remove(key)?.also { values[key] = it }
    }

    fun clear() = lock.withLock {
        values.clear()
        weight = 0L
    }

    operator fun set(key: K, value: V) {
        val valueWeight = weightOf(value)
        require(valueWeight >= 0)
        lock.withLock {
            values.remove(key)?.let { weight -= weightOf(it) }
            if (valueWeight > maxWeight) return@withLock
            values[key] = value
            weight += valueWeight
            while (values.size > maxEntries || weight > maxWeight) {
                val oldest = values.entries.first()
                weight -= weightOf(oldest.value)
                values.remove(oldest.key)
            }
        }
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.kt

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

The implementation below defines pickFolder, pickFile, exportFile.

The source describes its contract as:

Pick a single file matching the provided extension list. Returns null on cancel.

package eu.friedcutlet.yokan.services.files

expect suspend fun pickFolder(initial: String? = null): String?

/** Pick a single file matching the provided extension list. Returns null on cancel. */
expect suspend fun pickFile(extensions: List<String>, initial: String? = null): String?

/**
 * Exports bytes using the platform save UI. Android/desktop prompt for a
 * destination; iOS writes to its dedicated app backup directory.
 */
expect suspend fun exportFile(
    bytes: ByteArray,
    suggestedName: String,
    mimeType: String,
    initial: String? = null,
): String?

Check your understanding

List a CBZ containing pages 1, 2 and 10 and an EPUB whose spine differs from filename order. Confirm each reader receives the correct sequence. [chapter-content-end]: #

Step 2: implement each storage adapter

JVM adapters handle local files, supported ZIP/CBZ/EPUB/RAR/archive paths and extraction caches. Android adds SAF document/tree grants and archive/input adapters; the existing SAF read path is not a general writable download directory. iOS handles document inputs and scoped file access through its actuals. Browser storage uses its prepared inventory/OPFS and asynchronous interop, with a service worker for media URLs where implemented.

Recreate browser file persistence, readable listings, folder traversal and byte streaming from its tests. Keep immediate-child indexes so every traversal step does not rescan all paths. An empty folder is still a folder. Browser capabilities in this source are broader than the older README's blanket “filesystem downloads unavailable” statement; native paths remain unavailable.

Follow the code

Map the common contract onto real platform capabilities. A SAF content URI is not a java.io.File; a browser handle/OPFS path is not a native writable directory. Archive extraction uses owned caches and safe entry paths. Browser traversal retains immediate-child indexes and empty directories; its media service worker exposes only the prepared storage paths. Preserve granted access and release resources on cancellation/retirement.

Write these files in this order:

  • composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/AndroidSafLocalArchiveService.kt
  • composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/AndroidSafLocalFileService.kt
  • composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.android.kt
  • composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.android.kt
  • composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.android.kt
  • composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/SafDocumentPath.android.kt
  • composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/DesktopDataRoot.kt
  • composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.desktop.kt
  • composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.desktop.kt
  • composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.desktop.kt
  • composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/IosLocalFileService.ios.kt
  • composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/IosSecurityScopedBookmarks.ios.kt
  • composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/IosZipArchive.ios.kt
  • composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.ios.kt
  • composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.ios.kt
  • composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.ios.kt
  • composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/JvmLocalArchiveService.kt
  • composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/JvmLocalFileService.kt
  • composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaInput.jvm.kt
  • composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/RarArchiveExtractor.kt
  • composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/TarStreams.kt
  • composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.wasm.kt
  • composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.wasm.kt
  • composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.wasm.kt

Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/AndroidSafLocalArchiveService.kt

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

The implementation below defines AndroidSafLocalArchiveService, ContentMetadata, invalidateIndexCache, withArchiveFile, withFreshArchiveFile, stage, contentDocumentUri, queryContentMetadata, String.cacheKey.

The source describes its contract as:

[JvmLocalArchiveService] plus SAF content:// documents. ZipFile needs a filesystem path while SAF only promises a readable stream, so each document is copied once to cacheRoot/archive-staging/\<cacheKey\> (uri + name + size + mtime) and reused until it falls out of the [MAX_STAGED_ARCHIVES] most recently used copies; the provider URI is never opened for writing.

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

package eu.friedcutlet.yokan.services.files

import android.content.ContentResolver
import android.net.Uri
import android.provider.DocumentsContract
import eu.friedcutlet.yokan.AndroidAppContext
import eu.friedcutlet.yokan.util.PlatformLock
import java.io.File
import java.io.InputStream
import java.security.MessageDigest

/**
 * [JvmLocalArchiveService] plus SAF `content://` documents. ZipFile needs a filesystem path while
 * SAF only promises a readable stream, so each document is copied once to
 * `cacheRoot/archive-staging/<cacheKey>` (uri + name + size + mtime) and reused until it falls out of
 * the [MAX_STAGED_ARCHIVES] most recently used copies; the provider URI is never opened for writing.
 */
internal class AndroidSafLocalArchiveService(
    cacheRoot: String,
    private val contentResolver: ContentResolver? = null,
    private val contentStreamOpener: ((String) -> InputStream?)? = null,
) : JvmLocalArchiveService(cacheRoot) {
    private data class ContentMetadata(
        val name: String,
        val mimeType: String?,
        val size: Long,
        val lastModified: Long,
    )

    private val stagingRoot = File(cacheRoot, "archive-staging")
    private val stagingLock = PlatformLock()
    private var stagingGeneration = 0L

    override fun invalidateIndexCache() {
        super.invalidateIndexCache()
        // A full scan must also bypass copies from providers with unchanged or missing timestamps.
        stagingLock.withLock { stagingGeneration = kotlin.random.Random.nextLong() }
    }

    override fun <T> withArchiveFile(path: String, block: (ArchiveFile) -> T): T? =
        withArchiveFile(path, fresh = false, block = block)

    override fun <T> withFreshArchiveFile(path: String, block: (ArchiveFile) -> T): T? =
        withArchiveFile(path, fresh = true, block = block)

    private fun <T> withArchiveFile(path: String, fresh: Boolean, block: (ArchiveFile) -> T): T? {
        if (!path.startsWith("content://")) return super.withArchiveFile(path, block)
        contentStreamOpener?.let { opener ->
            val cacheKey = path.cacheKey(null)
            val staged = stage(cacheKey, fresh) { opener(path) } ?: return null
            val name = path.substringAfterLast('/').ifBlank { "archive" }
            return runCatching { block(ArchiveFile(staged, name, mimeType = null, cacheKey = cacheKey)) }.getOrNull()
        }
        val uri = runCatching { Uri.parse(path) }.getOrNull() ?: return null
        val documentUri = contentDocumentUri(uri)
        val resolver = contentResolver ?: AndroidAppContext.appContext?.contentResolver ?: return null
        val metadata = queryContentMetadata(resolver, documentUri)
        val cacheKey = path.cacheKey(metadata)
        val staged = stage(cacheKey, fresh) { resolver.openInputStream(documentUri) } ?: return null
        val name = metadata?.name?.takeIf(String::isNotBlank) ?: uri.lastPathSegment.orEmpty().ifBlank { "archive" }
        return runCatching { block(ArchiveFile(staged, name, metadata?.mimeType, cacheKey)) }.getOrNull()
    }

    /**
     * The staged copy for [cacheKey]: reused (and marked used) when present, else copied from
     * [openStream] through a temp file so a failed copy never looks staged. Null when the copy fails.
     */
    // ponytail: pruning can delete a copy between another reader's touch and open once >3 documents are
    // read concurrently (that read returns null); add per-key refcounts if that shows up.
    private fun stage(cacheKey: String, fresh: Boolean, openStream: () -> InputStream?): File? {
        val target = File(stagingRoot, cacheKey)
        if (fresh) stagingLock.withLock { target.delete() }
        val reused = stagingLock.withLock {
            target.isFile.also { present -> if (present) target.setLastModified(System.currentTimeMillis()) }
        }
        if (reused) return target
        if (!stagingRoot.exists() && !stagingRoot.mkdirs()) return null
        val partial = runCatching { File.createTempFile("archive-", ".tmp", stagingRoot) }.getOrNull() ?: return null
        val copied = runCatching {
            openStream()?.use { input -> partial.outputStream().use { output -> input.copyTo(output) } } != null
        }.getOrDefault(false)
        return stagingLock.withLock {
            // A concurrent read may have staged the same document meanwhile; both copies are current.
            val staged = copied && (target.isFile || partial.renameTo(target))
            partial.delete()
            if (!staged) return@withLock null
            pruneLeastRecentlyUsed(stagingRoot, keep = target, maxBytes = Long.MAX_VALUE, maxEntries = MAX_STAGED_ARCHIVES)
            target
        }
    }

    private fun contentDocumentUri(uri: Uri): Uri = runCatching {
        if (DocumentsContract.isTreeUri(uri)) {
            val documentId = if (uri.pathSegments.getOrNull(2) == "document") {
                DocumentsContract.getDocumentId(uri)
            } else {
                DocumentsContract.getTreeDocumentId(uri)
            }
            DocumentsContract.buildDocumentUriUsingTree(uri, documentId)
        } else {
            uri
        }
    }.getOrDefault(uri)

    private fun queryContentMetadata(resolver: ContentResolver, uri: Uri): ContentMetadata? = runCatching {
        resolver.query(
            uri,
            arrayOf(
                DocumentsContract.Document.COLUMN_DISPLAY_NAME,
                DocumentsContract.Document.COLUMN_MIME_TYPE,
                DocumentsContract.Document.COLUMN_SIZE,
                DocumentsContract.Document.COLUMN_LAST_MODIFIED,
            ),
            null,
            null,
            null,
        )?.use { cursor ->
            if (!cursor.moveToFirst()) return@use null
            ContentMetadata(
                name = cursor.stringColumn(DocumentsContract.Document.COLUMN_DISPLAY_NAME),
                mimeType = cursor.stringColumn(DocumentsContract.Document.COLUMN_MIME_TYPE).takeIf(String::isNotBlank),
                size = cursor.longColumn(DocumentsContract.Document.COLUMN_SIZE),
                lastModified = cursor.longColumn(DocumentsContract.Document.COLUMN_LAST_MODIFIED),
            )
        }
    }.getOrNull()

    private fun String.cacheKey(metadata: ContentMetadata?): String {
        val digest = MessageDigest.getInstance("SHA-1")
        digest.update(encodeToByteArray())
        digest.update(stagingLock.withLock { stagingGeneration }.toString().encodeToByteArray())
        metadata?.let {
            digest.update(it.name.encodeToByteArray())
            digest.update(it.size.toString().encodeToByteArray())
            digest.update(it.lastModified.toString().encodeToByteArray())
        }
        return digest.digest().toHexString()
    }

    private companion object {
        // ponytail: count-only cap (3 copies, any size); add a byte budget if huge archives crowd the cache.
        const val MAX_STAGED_ARCHIVES = 3
    }
}

Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/AndroidSafLocalFileService.kt

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

The implementation below defines AndroidSafLocalFileService, writeBytes, appendBytes, writeChunks, appendChunks, promote, atomicReplaceFile, publishDirectoryIfAbsent, canonicalPath, readBytes and 24 further declarations.

The source describes its contract as:

[JvmLocalFileService] plus SAF content:// paths. Persisted tree grants are read-only local folders: they can be listed, read and opened, never written or deleted. A separately picked content:// document (not under a tree) keeps write support.

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

package eu.friedcutlet.yokan.services.files

import android.content.ContentResolver
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.provider.DocumentsContract
import eu.friedcutlet.yokan.AndroidAppContext

/**
 * [JvmLocalFileService] plus SAF `content://` paths. Persisted tree grants are read-only local
 * folders: they can be listed, read and opened, never written or deleted. A separately picked
 * `content://` document (not under a tree) keeps write support.
 */
internal class AndroidSafLocalFileService(
    private val files: JvmLocalFileService,
) : LocalFileService by files {
    override fun writeBytes(path: String, bytes: ByteArray) {
        if (!path.startsWith("content://")) return files.writeBytes(path, bytes)
        if (treeUri(path) != null) return
        val context = AndroidAppContext.appContext ?: return
        context.contentResolver.openOutputStream(Uri.parse(path), "wt")?.use { it.write(bytes) }
    }

    override fun appendBytes(path: String, bytes: ByteArray) {
        if (!path.startsWith("content://")) return files.appendBytes(path, bytes)
        if (treeUri(path) != null) return
        val context = AndroidAppContext.appContext ?: return
        context.contentResolver.openOutputStream(Uri.parse(path), "wa")?.use { it.write(bytes) }
    }

    override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T =
        if (path.startsWith("content://")) super.writeChunks(path, block) else files.writeChunks(path, block)

    override suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T =
        if (path.startsWith("content://")) super.appendChunks(path, block) else files.appendChunks(path, block)

    override fun promote(sourcePath: String, targetPath: String): Boolean =
        if (sourcePath.startsWith("content://") || targetPath.startsWith("content://")) {
            // Provider documents cannot be moved atomically; copy through the resolver instead.
            super.promote(sourcePath, targetPath)
        } else {
            files.promote(sourcePath, targetPath)
        }

    override fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean =
        if (tempPath.startsWith("content://") || finalPath.startsWith("content://")) false
        else files.atomicReplaceFile(tempPath, finalPath)

    override fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean =
        if (stagedPath.startsWith("content://") || finalPath.startsWith("content://")) false
        else files.publishDirectoryIfAbsent(stagedPath, finalPath)

    override fun canonicalPath(path: String): String? =
        if (path.startsWith("content://")) null else files.canonicalPath(path)

    override fun readBytes(path: String): ByteArray {
        if (!path.startsWith("content://")) return files.readBytes(path)
        val context = AndroidAppContext.appContext ?: return ByteArray(0)
        return runCatching {
            val uri = Uri.parse(path)
            if (treeUri(path) != null && !hasPersistedReadGrant(context.contentResolver, uri)) return@runCatching null
            val documentUri = safDocumentUri(context.contentResolver, uri) ?: uri
            context.contentResolver.openInputStream(documentUri)?.use { it.readBytes() }
        }.getOrNull() ?: ByteArray(0)
    }

    override fun mimeType(path: String): String? {
        if (!path.startsWith("content://")) return files.mimeType(path)
        val context = AndroidAppContext.appContext ?: return null
        return runCatching { context.contentResolver.getType(Uri.parse(path)) }.getOrNull()
    }

    override fun readBytesBounded(path: String, maxBytes: Long): ByteArray {
        require(maxBytes >= 0) { "maxBytes must not be negative" }
        if (!path.startsWith("content://")) return files.readBytesBounded(path, maxBytes)
        require(maxBytes < Int.MAX_VALUE) { "Bound exceeds ByteArray capacity" }
        val context = AndroidAppContext.appContext ?: error("Content resolver is unavailable")
        val uri = Uri.parse(path)
        if (treeUri(path) != null) require(hasPersistedReadGrant(context.contentResolver, uri)) { "No SAF read grant" }
        val documentUri = safDocumentUri(context.contentResolver, uri) ?: uri
        val input = context.contentResolver.openInputStream(documentUri) ?: error("Cannot open $path")
        input.use {
            val output = java.io.ByteArrayOutputStream()
            val buffer = ByteArray(16 * 1024)
            var total = 0L
            while (total <= maxBytes) {
                val count = it.read(buffer, 0, minOf(buffer.size.toLong(), maxBytes + 1 - total).toInt())
                if (count < 0) break
                output.write(buffer, 0, count)
                total += count
            }
            require(total <= maxBytes) { "File exceeds $maxBytes bytes" }
            return output.toByteArray()
        }
    }

    override fun listFiles(root: String): List<LocalFileEntry> {
        val context = AndroidAppContext.appContext
        if (context != null && root.startsWith("content://") && treeUri(root) != null) {
            return listSafFiles(context.contentResolver, Uri.parse(root)).orEmpty()
        }
        return files.listFiles(root)
    }

    override fun exists(path: String): Boolean {
        if (!path.startsWith("content://")) return files.exists(path)
        val context = AndroidAppContext.appContext ?: return false
        val uri = Uri.parse(path)
        return if (treeUri(path) != null) {
            hasPersistedReadGrant(context.contentResolver, uri) &&
                querySafDocument(context.contentResolver, uri) != null
        } else {
            runCatching {
                context.contentResolver.openInputStream(uri)?.use { true } ?: false
            }.getOrDefault(false)
        }
    }

    override fun deleteRecursively(path: String): Boolean =
        if (path.startsWith("content://")) false else files.deleteRecursively(path)

    override fun directorySize(path: String): Long {
        val context = AndroidAppContext.appContext
        if (context != null && path.startsWith("content://") && treeUri(path) != null) {
            return directorySizeSaf(context.contentResolver, Uri.parse(path))
        }
        return files.directorySize(path)
    }

    override fun openLocation(path: String): Boolean {
        if (!path.startsWith("content://")) return files.openLocation(path)
        val context = AndroidAppContext.appContext ?: return false
        val uri = Uri.parse(path)
        if (treeUri(path) == null || !hasPersistedReadGrant(context.contentResolver, uri)) return false
        return runCatching {
            context.startActivity(Intent(Intent.ACTION_VIEW).apply {
                data = uri
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
            })
            true
        }.getOrDefault(false)
    }

    override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? {
        if (!root.startsWith("content://")) return files.listDirectoryEntries(root)
        val resolver = AndroidAppContext.appContext?.contentResolver ?: return null
        val uri = Uri.parse(root)
        if (treeUri(root) == null || !hasPersistedReadGrant(resolver, uri)) return null
        val document = querySafDocument(resolver, uri)?.takeIf { it.isDirectory } ?: return null
        return querySafChildren(resolver, document.uri)?.map { LocalDirectoryEntry(it.uri.toString(), it.name, it.isDirectory) }
            ?.sortedBy { it.name.lowercase() }
    }

    override fun listLocalEntries(root: String): List<LocalEntry>? {
        val context = AndroidAppContext.appContext
        if (context != null && root.startsWith("content://") && treeUri(root) != null) {
            return listSafLocalEntries(context.contentResolver, Uri.parse(root))
        }
        return files.listLocalEntries(root)
    }

    private data class SafDocument(
        val uri: Uri,
        val name: String,
        val mimeType: String,
        val size: Long,
        val lastModified: Long,
    ) {
        val isDirectory: Boolean get() = mimeType == DocumentsContract.Document.MIME_TYPE_DIR
        val isReadableFile: Boolean
            get() = !isDirectory && name.substringAfterLast('.', "").lowercase() in readableLocalFileExtensions
    }

    private fun listSafLocalEntries(resolver: ContentResolver, root: Uri): List<LocalEntry>? {
        if (!hasPersistedReadGrant(resolver, root)) return null
        val rootDocument = querySafDocument(resolver, root) ?: return null
        if (!rootDocument.isDirectory) return null
        return collectSafLocalEntries(resolver, rootDocument.uri, mutableSetOf())
    }

    private fun collectSafLocalEntries(
        resolver: ContentResolver,
        directory: Uri,
        visited: MutableSet<String>,
    ): List<LocalEntry>? {
        val documentId = runCatching { DocumentsContract.getDocumentId(directory) }.getOrNull() ?: return null
        if (!visited.add(documentId)) return null
        val children = querySafChildren(resolver, directory) ?: return null
        val entries = mutableListOf<LocalEntry>()
        for (child in children.sortedBy { it.name.lowercase() }) {
            if (child.isDirectory) {
                val containsReadableFile = querySafChildren(resolver, child.uri)?.any { it.isReadableFile } ?: return null
                if (containsReadableFile) {
                    entries += LocalEntry(child.uri.toString(), child.name, isArchive = false)
                } else {
                    entries += collectSafLocalEntries(resolver, child.uri, visited) ?: return null
                }
            } else if (child.isReadableFile) {
                entries += LocalEntry(child.uri.toString(), child.name.substringBeforeLast('.'), isArchive = true)
            }
        }
        return entries
    }

    private fun listSafFiles(resolver: ContentResolver, root: Uri): List<LocalFileEntry>? {
        if (!hasPersistedReadGrant(resolver, root)) return null
        val rootDocument = querySafDocument(resolver, root) ?: return null
        if (!rootDocument.isDirectory) return null
        return querySafChildren(resolver, rootDocument.uri)?.filterNot { it.isDirectory }
            ?.sortedByDescending { it.lastModified }
            ?.map { LocalFileEntry(it.uri.toString(), it.name, it.size, it.lastModified) }
    }

    private fun directorySizeSaf(resolver: ContentResolver, root: Uri): Long {
        if (!hasPersistedReadGrant(resolver, root)) return 0L
        val document = querySafDocument(resolver, root) ?: return 0L
        if (!document.isDirectory) return document.size
        return directorySizeSafChildren(resolver, document.uri, mutableSetOf())
    }

    private fun directorySizeSafChildren(
        resolver: ContentResolver,
        directory: Uri,
        visited: MutableSet<String>,
    ): Long {
        val id = runCatching { DocumentsContract.getDocumentId(directory) }.getOrNull() ?: return 0L
        if (!visited.add(id)) return 0L
        return querySafChildren(resolver, directory)?.sumOf { child ->
            if (child.isDirectory) directorySizeSafChildren(resolver, child.uri, visited) else child.size.coerceAtLeast(0L)
        } ?: 0L
    }

    private fun querySafDocument(resolver: ContentResolver, path: Uri): SafDocument? = runCatching {
        val uri = safDocumentUri(resolver, path) ?: return@runCatching null
        resolver.query(uri, documentProjection, null, null, null)?.use { cursor ->
            if (!cursor.moveToFirst()) return@use null
            readSafDocument(uri, cursor)
        }
    }.getOrNull()

    private fun querySafChildren(resolver: ContentResolver, directory: Uri): List<SafDocument>? = runCatching {
        val tree = treeUri(directory.toString()) ?: return@runCatching null
        val directoryId = DocumentsContract.getDocumentId(safDocumentUri(resolver, directory) ?: return@runCatching null)
        val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(tree, directoryId)
        resolver.query(childrenUri, documentProjection, null, null, null)?.use { cursor ->
            buildList<SafDocument> {
                while (cursor.moveToNext()) add(readSafDocument(
                    DocumentsContract.buildDocumentUriUsingTree(tree, cursor.stringColumn(DocumentsContract.Document.COLUMN_DOCUMENT_ID)),
                    cursor,
                ))
            }
        }
    }.getOrNull()

    private fun readSafDocument(uri: Uri, cursor: Cursor): SafDocument {
        check(cursor.stringColumn(DocumentsContract.Document.COLUMN_DOCUMENT_ID).isNotBlank()) {
            "SAF provider returned a document without an id"
        }
        val name = cursor.stringColumn(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
        val mimeType = cursor.stringColumn(DocumentsContract.Document.COLUMN_MIME_TYPE)
        check(name.isNotBlank() && mimeType.isNotBlank()) { "SAF provider returned an invalid document" }
        val size = cursor.longColumn(DocumentsContract.Document.COLUMN_SIZE)
        val lastModified = cursor.longColumn(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
        return SafDocument(uri, name, mimeType, size, lastModified)
    }

    private fun safDocumentUri(resolver: ContentResolver, uri: Uri): Uri? = runCatching {
        val tree = treeUri(uri.toString()) ?: return@runCatching null
        val path = safDocumentPath(uri.pathSegments) ?: return@runCatching null
        var current = DocumentsContract.buildDocumentUriUsingTree(tree, path.documentId)
        for (name in path.children) {
            current = querySafChildren(resolver, current)
                ?.firstOrNull { child -> child.name == name }
                ?.uri
                ?: return@runCatching null
        }
        current
    }.getOrNull()

    private fun treeUri(path: String): Uri? = runCatching {
        val uri = Uri.parse(path)
        if (uri.scheme != "content") return@runCatching null
        DocumentsContract.buildTreeDocumentUri(uri.authority, DocumentsContract.getTreeDocumentId(uri))
    }.getOrNull()

    private fun hasPersistedReadGrant(resolver: ContentResolver, path: Uri): Boolean {
        val tree = treeUri(path.toString()) ?: return false
        val granted = resolver.persistedUriPermissions.any {
            it.uri == tree && it.isReadPermission
        }
        if (!granted) {
            runCatching {
                resolver.releasePersistableUriPermission(
                    tree,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
                )
            }
        }
        return granted
    }

    private companion object {
        val documentProjection = arrayOf(
            DocumentsContract.Document.COLUMN_DOCUMENT_ID,
            DocumentsContract.Document.COLUMN_DISPLAY_NAME,
            DocumentsContract.Document.COLUMN_MIME_TYPE,
            DocumentsContract.Document.COLUMN_SIZE,
            DocumentsContract.Document.COLUMN_LAST_MODIFIED,
        )
    }
}

/** Opens a local directory in the system file manager. */
internal fun openAndroidDirectory(directory: java.io.File): Boolean {
    val context = AndroidAppContext.appContext ?: return false
    context.startActivity(Intent(Intent.ACTION_VIEW).apply {
        setDataAndType(Uri.fromFile(directory), "resource/folder")
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    })
    return true
}

internal fun Cursor.stringColumn(name: String): String {
    val index = getColumnIndex(name)
    return if (index >= 0 && !isNull(index)) getString(index) else ""
}

internal fun Cursor.longColumn(name: String): Long {
    val index = getColumnIndex(name)
    return if (index >= 0 && !isNull(index)) getLong(index) else 0L
}

Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.android.kt

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

The implementation below defines createPlatformLocalArchiveService, createPlatformLocalFileService.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.AndroidAppContext

actual fun createPlatformLocalArchiveService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalArchiveService = AndroidSafLocalArchiveService(
    cacheRoot = createPlatformLocalFileService(profileId).cacheRoot,
)

actual fun createPlatformLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalFileService {
    val context = AndroidAppContext.appContext
    val namespace = eu.friedcutlet.yokan.domain.ProfileStorageNamespace(profileId)
    if (profileId != eu.friedcutlet.yokan.domain.ProfileId.Default) checkNotNull(context) { "Android context unavailable" }
    val filesDir = context?.filesDir?.absolutePath ?: System.getProperty("java.io.tmpdir").orEmpty()
    return AndroidSafLocalFileService(
        JvmLocalFileService(
            downloadRoot = "${namespace.ownedRoot(filesDir)}/downloads",
            backupRoot = "${namespace.ownedRoot(filesDir)}/backups",
            cacheRoot = if (namespace.relativeRoot == null) context?.cacheDir?.absolutePath ?: "$filesDir/cache"
                else "${namespace.ownedRoot(checkNotNull(context).cacheDir.absolutePath)}/cache",
            openDirectory = ::openAndroidDirectory,
        ),
    )
}

Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.android.kt

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

The implementation below defines pickLocalMedia, add.

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

package eu.friedcutlet.yokan.services.files

import android.net.Uri
import android.provider.DocumentsContract
import android.provider.OpenableColumns
import eu.friedcutlet.yokan.AndroidAppContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext

actual suspend fun pickLocalMedia(directory: Boolean): LocalMediaSelection? {
    val chosen = if (directory) pickFolder() else pickFile(readableLocalFileExtensions.toList())
    if (chosen == null) return null
    val resolver = checkNotNull(AndroidAppContext.appContext).contentResolver
    return withContext(Dispatchers.IO) {
        val inputs = mutableListOf<LocalMediaInput>()
        fun add(uri: Uri, name: String, size: Long?) {
            if (name.split('/').any { it.startsWith('.') } || name.substringAfterLast('.', "").lowercase() !in localImportExtensions) return
            check(inputs.size < LOCAL_IMPORT_MAX_FILES) { "Too many selected files" }
            inputs += JvmLocalMediaInput(name, size?.takeIf { it >= 0 }) {
                resolver.openInputStream(uri) ?: error("Selected file is no longer readable")
            }
        }
        val uri = Uri.parse(chosen)
        if (!directory) {
            resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { cursor ->
                check(cursor.moveToFirst()) { "Selected file is unavailable" }
                add(uri, cursor.getString(0), if (cursor.isNull(1)) null else cursor.getLong(1))
            } ?: error("Cannot read selected file metadata")
        } else {
            val rootId = DocumentsContract.getTreeDocumentId(uri)
            val rootUri = DocumentsContract.buildDocumentUriUsingTree(uri, rootId)
            val rootName = resolver.query(rootUri, arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME), null, null, null)?.use {
                check(it.moveToFirst()); it.getString(0)
            } ?: error("Cannot read selected folder")
            val pending = ArrayDeque<Pair<String, String>>().apply { add(rootId to rootName) }
            val seen = mutableSetOf<String>()
            var visited = 0
            while (pending.isNotEmpty()) {
                currentCoroutineContext().ensureActive()
                val (id, relative) = pending.removeFirst()
                check(seen.add(id) && relative.count { it == '/' } < 64) { "Cyclic or excessively deep folder" }
                val children = DocumentsContract.buildChildDocumentsUriUsingTree(uri, id)
                resolver.query(children, arrayOf(DocumentsContract.Document.COLUMN_DOCUMENT_ID,
                    DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE,
                    DocumentsContract.Document.COLUMN_SIZE), null, null, null)?.use { cursor ->
                    while (cursor.moveToNext()) {
                        currentCoroutineContext().ensureActive()
                        check(++visited <= 50_000) { "Selected folder is too large" }
                        val childId = cursor.getString(0)
                        val name = cursor.getString(1)
                        if (name.startsWith('.')) continue
                        val path = "$relative/$name"
                        if (cursor.getString(2) == DocumentsContract.Document.MIME_TYPE_DIR) pending.add(childId to path)
                        else add(DocumentsContract.buildDocumentUriUsingTree(uri, childId), path, if (cursor.isNull(3)) null else cursor.getLong(3))
                    }
                } ?: error("Cannot read selected folder")
            }
        }
        LocalMediaSelection(inputs)
    }
}

Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.android.kt

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

The implementation below defines AndroidFolderPickerBridge, registerFolderPickerLauncher, pickFolder, persistReadOnlyTreePermission, pickFile, exportFile.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.AndroidAppContext
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.provider.DocumentsContract
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import kotlinx.coroutines.CompletableDeferred

object AndroidFolderPickerBridge {
    @Volatile var launcher: ((String?, CompletableDeferred<String?>) -> Unit)? = null
    @Volatile var fileLauncher: ((Array<String>, CompletableDeferred<String?>) -> Unit)? = null
    @Volatile var exportLauncher: ((String, CompletableDeferred<String?>) -> Unit)? = null
}

internal fun registerFolderPickerLauncher(activity: ComponentActivity) {
    val folderLauncher = activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        val uri = result.data?.data?.takeIf { result.resultCode == Activity.RESULT_OK }
        pendingResult?.complete(uri?.let(::persistReadOnlyTreePermission))
        pendingResult = null
    }
    AndroidFolderPickerBridge.launcher = { initial, pending ->
        pendingResult = pending
        runCatching {
            folderLauncher.launch(Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
                initial?.takeIf { it.startsWith("content://") }
                    ?.let { putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.parse(it)) }
                // Local folders are intentionally read-only. Persist only the
                // read grant; write/delete are not part of the local library API.
                addFlags(
                    Intent.FLAG_GRANT_READ_URI_PERMISSION or
                        Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION or
                        Intent.FLAG_GRANT_PREFIX_URI_PERMISSION,
                )
            })
        }.onFailure {
            pending.complete(null)
            pendingResult = null
        }
    }
    val fileLauncher = activity.registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
        pendingFileResult?.complete(uri?.toString())
        pendingFileResult = null
    }
    AndroidFolderPickerBridge.fileLauncher = { mimes, pending ->
        pendingFileResult = pending
        runCatching { fileLauncher.launch(mimes) }.onFailure {
            pending.complete(null)
            pendingFileResult = null
        }
    }
    val exportLauncher = activity.registerForActivityResult(
        ActivityResultContracts.CreateDocument("application/octet-stream"),
    ) { uri ->
        pendingExportResult?.complete(uri?.toString())
        pendingExportResult = null
    }
    AndroidFolderPickerBridge.exportLauncher = { suggestedName, pending ->
        pendingExportResult = pending
        runCatching { exportLauncher.launch(suggestedName) }.onFailure {
            pending.complete(null)
            pendingExportResult = null
        }
    }
}

private var pendingResult: CompletableDeferred<String?>? = null
private var pendingFileResult: CompletableDeferred<String?>? = null
private var pendingExportResult: CompletableDeferred<String?>? = null

actual suspend fun pickFolder(initial: String?): String? {
    val launcher = AndroidFolderPickerBridge.launcher ?: return null
    val pending = CompletableDeferred<String?>()
    launcher(initial, pending)
    return pending.await()
}

private fun persistReadOnlyTreePermission(uri: Uri): String? {
    val context = AndroidAppContext.appContext ?: return null
    if (!DocumentsContract.isTreeUri(uri)) return null
    val resolver = context.contentResolver
    return runCatching {
        resolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
        if (resolver.persistedUriPermissions.none { permission ->
                permission.uri == uri && permission.isReadPermission
            }
        ) {
            error("The selected folder did not grant persistent read access")
        }
        uri.toString()
    }.getOrElse {
        // Providers can reject persistence, and a stale grant can disappear
        // while the app is relaunched. Releasing is best effort and idempotent.
        runCatching {
            resolver.releasePersistableUriPermission(
                uri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
            )
        }
        null
    }
}

actual suspend fun pickFile(extensions: List<String>, initial: String?): String? {
    val launcher = AndroidFolderPickerBridge.fileLauncher ?: return null
    val mimes = if (extensions.isEmpty()) arrayOf("*/*") else extensions.flatMap { ext ->
        when (ext.lowercase()) {
            "torrent" -> listOf("application/x-bittorrent")
            "epub" -> listOf("application/epub+zip")
            "zip", "cbz" -> listOf("application/zip")
            "tar", "cbt" -> listOf("application/x-tar")
            "json" -> listOf("application/json")
            // Providers disagree on gzip's mime; accept both spellings.
            "gz" -> listOf("application/gzip", "application/x-gzip")
            "apk" -> listOf("application/vnd.android.package-archive")
            else -> listOf("*/*")
        }
    }.distinct().toTypedArray()
    val pending = CompletableDeferred<String?>()
    launcher(mimes, pending)
    return pending.await()
}

actual suspend fun exportFile(
    bytes: ByteArray,
    suggestedName: String,
    mimeType: String,
    initial: String?,
): String? {
    val launcher = AndroidFolderPickerBridge.exportLauncher ?: return null
    val pending = CompletableDeferred<String?>()
    launcher(suggestedName, pending)
    val target = pending.await() ?: return null
    val context = AndroidAppContext.appContext ?: return null
    return runCatching {
        context.contentResolver.openOutputStream(Uri.parse(target), "wt")?.use { output ->
            output.write(bytes)
        } ?: error("Unable to open backup destination")
        target
    }.getOrNull()
}

Write composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/SafDocumentPath.android.kt

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

The implementation below defines SafDocumentPath, safDocumentPath.

The source describes its contract as:

URI pathSegments have already decoded opaque document IDs; never split those IDs as paths.

package eu.friedcutlet.yokan.services.files

internal data class SafDocumentPath(val documentId: String, val children: List<String>)

/** URI pathSegments have already decoded opaque document IDs; never split those IDs as paths. */
internal fun safDocumentPath(segments: List<String>): SafDocumentPath? {
    if (segments.getOrNull(0) != "tree" || segments.getOrNull(1).isNullOrBlank()) return null
    val explicitDocument = segments.getOrNull(2) == "document"
    val id = segments.getOrNull(if (explicitDocument) 3 else 1)?.takeIf(String::isNotBlank) ?: return null
    val children = segments.drop(if (explicitDocument) 4 else 2)
    if (children.size > 64 || children.any { it.isBlank() || it == "." || it == ".." || '/' in it || '\\' in it || '\u0000' in it }) return null
    return SafDocumentPath(id, children)
}

Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/DesktopDataRoot.kt

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

The source describes its contract as:

Root for every desktop data file (Room, legacy snapshot, downloads, cache, extension server): $XDG_DATA_HOME/yokan, else ~/.local/share/yokan. Not created eagerly; writers mkdirs() what they need.

package eu.friedcutlet.yokan.services.files

import java.io.File

/**
 * Root for every desktop data file (Room, legacy snapshot, downloads, cache,
 * extension server): `$XDG_DATA_HOME/yokan`, else `~/.local/share/yokan`.
 * Not created eagerly; writers `mkdirs()` what they need.
 */
internal val desktopDataRoot: File by lazy {
    System.getenv("XDG_DATA_HOME")?.takeIf(String::isNotBlank)?.let { File(it, "yokan") }
        ?: File(System.getProperty("user.home").orEmpty().ifBlank { "." }, ".local/share/yokan")
}

Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.desktop.kt

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

The implementation below defines createPlatformLocalArchiveService, createPlatformLocalFileService, createDesktopProfileFileService, openInDesktopShell.

package eu.friedcutlet.yokan.services.files

import java.awt.Desktop
import java.io.File

actual fun createPlatformLocalArchiveService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalArchiveService = JvmLocalArchiveService(
    cacheRoot = createPlatformLocalFileService(profileId).cacheRoot,
)

actual fun createPlatformLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalFileService =
    createDesktopProfileFileService(desktopDataRoot, profileId, ::openInDesktopShell)

internal fun createDesktopProfileFileService(dataRoot: File, profileId: eu.friedcutlet.yokan.domain.ProfileId,
    openDirectory: (File) -> Boolean = { false }): LocalFileService {
    val namespace = eu.friedcutlet.yokan.domain.ProfileStorageNamespace(profileId)
    val root = File(namespace.ownedRoot(dataRoot.path))
    return JvmLocalFileService(
        downloadRoot = File(root, if (namespace.relativeRoot == null) "Yokan/downloads" else "downloads").path,
        backupRoot = File(root, if (namespace.relativeRoot == null) "Yokan/backups" else "backups").path,
        cacheRoot = File(root, "cache").path,
        openDirectory = openDirectory,
    )
}

private fun openInDesktopShell(directory: File): Boolean {
    if (!Desktop.isDesktopSupported() || !Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) return false
    Desktop.getDesktop().open(directory)
    return true
}

Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.desktop.kt

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

The implementation below defines pickLocalMedia.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.services.scheduling.DesktopSession
import java.nio.file.Files
import javax.swing.JFileChooser
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.swing.Swing
import kotlinx.coroutines.withContext

actual suspend fun pickLocalMedia(directory: Boolean): LocalMediaSelection? {
    val selected = withContext(Dispatchers.Swing) {
        val chooser = JFileChooser().apply {
            fileSelectionMode = if (directory) JFileChooser.DIRECTORIES_ONLY else JFileChooser.FILES_ONLY
            isMultiSelectionEnabled = !directory
        }
        if (chooser.showOpenDialog(DesktopSession.frame) != JFileChooser.APPROVE_OPTION) null
        else if (directory) listOf(chooser.selectedFile.toPath()) else chooser.selectedFiles.map { it.toPath() }
    } ?: return null
    return withContext(Dispatchers.IO) {
        val inputs = mutableListOf<LocalMediaInput>()
        for (root in selected) {
            val paths = if (directory) Files.walk(root) else java.util.stream.Stream.of(root)
            paths.use { walk ->
                val iterator = walk.iterator()
                var visited = 0
                while (iterator.hasNext()) {
                    currentCoroutineContext().ensureActive()
                    check(++visited <= 50_000) { "Selected folder is too large" }
                    val path = iterator.next()
                    if (!Files.isRegularFile(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) continue
                    val relative = if (directory) "${root.fileName}/${root.relativize(path).toString().replace('\\', '/')}" else path.fileName.toString()
                    if (relative.split('/').any { it.startsWith('.') } || relative.substringAfterLast('.', "").lowercase() !in localImportExtensions) continue
                    check(inputs.size < LOCAL_IMPORT_MAX_FILES) { "Too many selected files" }
                    inputs += JvmLocalMediaInput(relative, Files.size(path)) { Files.newInputStream(path) }
                }
            }
        }
        LocalMediaSelection(inputs)
    }
}

Write composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.desktop.kt

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

The implementation below defines pickFolder, pickFile, accept, getDescription, exportFile.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.services.scheduling.DesktopSession
import javax.swing.JFileChooser
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.swing.Swing
import kotlinx.coroutines.withContext

// Swing components must be created and shown on the EDT; the modal dialog keeps pumping events.
actual suspend fun pickFolder(initial: String?): String? = withContext(Dispatchers.Swing) {
    runCatching {
        val chooser = JFileChooser().apply {
            fileSelectionMode = JFileChooser.DIRECTORIES_ONLY
            isMultiSelectionEnabled = false
            initial?.takeIf { it.isNotBlank() }?.let { path ->
                currentDirectory = java.io.File(path.removePrefix("file://"))
            }
        }
        val result = chooser.showOpenDialog(DesktopSession.frame)
        if (result == JFileChooser.APPROVE_OPTION) chooser.selectedFile.absolutePath else null
    }.getOrNull()
}

actual suspend fun pickFile(extensions: List<String>, initial: String?): String? = withContext(Dispatchers.Swing) {
    runCatching {
        val chooser = JFileChooser().apply {
            fileSelectionMode = JFileChooser.FILES_ONLY
            isMultiSelectionEnabled = false
            initial?.takeIf { it.isNotBlank() }?.let { path ->
                currentDirectory = java.io.File(path.removePrefix("file://"))
            }
            if (extensions.isNotEmpty()) {
                fileFilter = object : javax.swing.filechooser.FileFilter() {
                    override fun accept(file: java.io.File): Boolean =
                        file.isDirectory || extensions.any { ext -> file.name.endsWith(".$ext", ignoreCase = true) }
                    override fun getDescription(): String = extensions.joinToString(", ") { "*.$it" }
                }
            }
        }
        val result = chooser.showOpenDialog(DesktopSession.frame)
        if (result == JFileChooser.APPROVE_OPTION) chooser.selectedFile.absolutePath else null
    }.getOrNull()
}

actual suspend fun exportFile(
    bytes: ByteArray,
    suggestedName: String,
    mimeType: String,
    initial: String?,
): String? {
    val target = withContext(Dispatchers.Swing) {
        runCatching {
            val chooser = JFileChooser().apply {
                fileSelectionMode = JFileChooser.FILES_ONLY
                isMultiSelectionEnabled = false
                dialogTitle = "Export backup"
                val initialDirectory = initial
                    ?.takeIf { it.isNotBlank() }
                    ?.let { java.io.File(it.removePrefix("file://")) }
                    ?.takeIf { it.isDirectory }
                if (initialDirectory != null) currentDirectory = initialDirectory
                selectedFile = java.io.File(initialDirectory ?: currentDirectory, suggestedName)
            }
            if (chooser.showSaveDialog(DesktopSession.frame) == JFileChooser.APPROVE_OPTION) chooser.selectedFile else null
        }.getOrNull()
    } ?: return null
    // Keep the (possibly large) backup write off the EDT.
    return withContext(Dispatchers.IO) {
        runCatching {
            target.parentFile?.mkdirs()
            target.writeBytes(bytes)
            target.absolutePath
        }.getOrNull()
    }
}

Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/IosLocalFileService.ios.kt

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

The implementation below defines IosLocalFileService, IosProfileLocalFileService, writeBytes, appendBytes, writeChunks, appendChunks, promote, atomicReplaceFile, publishDirectoryIfAbsent, readBytes and 17 further declarations.

The source describes its contract as:

iOS filesystem service: app Documents/Caches roots plus user folders reached through [IosSecurityScopedBookmarks]. Paths may carry a file:// prefix.

package eu.friedcutlet.yokan.services.files

import kotlinx.cinterop.BetaInteropApi
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.autoreleasepool
import kotlinx.cinterop.usePinned
import platform.Foundation.NSDate
import platform.Foundation.NSFileModificationDate
import platform.Foundation.NSCachesDirectory
import platform.Foundation.NSData
import platform.Foundation.NSDataReadingMappedIfSafe
import platform.Foundation.NSDocumentDirectory
import platform.Foundation.NSFileManager
import platform.Foundation.NSFileType
import platform.Foundation.NSFileTypeDirectory
import platform.Foundation.NSFileTypeRegular
import platform.Foundation.NSHomeDirectory
import platform.Foundation.NSSearchPathForDirectoriesInDomains
import platform.Foundation.NSURL
import platform.Foundation.NSUserDomainMask
import platform.Foundation.create
import platform.Foundation.dataWithContentsOfFile
import platform.Foundation.timeIntervalSince1970
import platform.Foundation.writeToFile
import platform.posix.fclose
import platform.posix.fopen
import platform.posix.fwrite
import platform.posix.rename

/**
 * iOS filesystem service: app Documents/Caches roots plus user folders reached through
 * [IosSecurityScopedBookmarks]. Paths may carry a `file://` prefix.
 */
@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)
internal object IosLocalFileService : LocalFileService by IosProfileLocalFileService(eu.friedcutlet.yokan.domain.ProfileId.Default)

@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)
internal class IosProfileLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId) : LocalFileService {
    private val namespace = eu.friedcutlet.yokan.domain.ProfileStorageNamespace(profileId)
    private val fm get() = NSFileManager.defaultManager
    private val documentsDir: String = NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory,
        NSUserDomainMask,
        true,
    ).firstOrNull()?.toString() ?: "${NSHomeDirectory()}/Documents"
    private val cachesDir: String = NSSearchPathForDirectoriesInDomains(
        NSCachesDirectory,
        NSUserDomainMask,
        true,
    ).firstOrNull()?.toString() ?: "${NSHomeDirectory()}/Library/Caches"

    override val downloadRoot: String = ensureDirectory(if (namespace.relativeRoot == null) "$documentsDir/Yokan/downloads" else "${namespace.ownedRoot(documentsDir)}/downloads")
    override val backupRoot: String = ensureDirectory(if (namespace.relativeRoot == null) "$documentsDir/Yokan/backups" else "${namespace.ownedRoot(documentsDir)}/backups")
    override val cacheRoot: String = ensureDirectory(if (namespace.relativeRoot == null) "$cachesDir/Yokan" else "${namespace.ownedRoot(cachesDir)}/cache")

    override fun writeBytes(path: String, bytes: ByteArray) {
        val resolved = path.removePrefix("file://")
        val parent = resolved.substringBeforeLast('/', missingDelimiterValue = "")
        if (parent.isNotEmpty()) ensureDirectory(parent)
        // Borrow the pinned array instead of copying it into NSData; the write finishes before unpinning.
        val written = autoreleasepool {
            if (bytes.isEmpty()) {
                NSData.create(bytes = null, length = 0uL).writeToFile(resolved, atomically = true)
            } else {
                bytes.usePinned { pinned ->
                    NSData.create(bytesNoCopy = pinned.addressOf(0), length = bytes.size.toULong(), freeWhenDone = false)
                        .writeToFile(resolved, atomically = true)
                }
            }
        }
        check(written) {
            "Failed to write file: $resolved"
        }
    }

    override fun appendBytes(path: String, bytes: ByteArray) {
        if (bytes.isEmpty()) return
        val resolved = path.removePrefix("file://")
        if (!fm.fileExistsAtPath(resolved)) {
            writeBytes(resolved, bytes)
            return
        }
        val handle = fopen(resolved, "ab") ?: error("Failed to open file for append: $resolved")
        try {
            val written = bytes.usePinned { pinned ->
                fwrite(pinned.addressOf(0), 1uL, bytes.size.toULong(), handle)
            }
            check(written == bytes.size.toULong()) {
                "Short write while appending file: $resolved"
            }
        } finally {
            check(fclose(handle) == 0) { "Failed to close file after append: $resolved" }
        }
    }

    override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {
        val resolved = path.removePrefix("file://")
        val parent = resolved.substringBeforeLast('/', missingDelimiterValue = "")
        if (parent.isNotEmpty()) ensureDirectory(parent)
        val handle = fopen(resolved, "wb") ?: error("Failed to open file for writing: $resolved")
        val result = try {
            block { bytes ->
                if (bytes.isNotEmpty()) {
                    val written = bytes.usePinned { pinned ->
                        fwrite(pinned.addressOf(0), 1uL, bytes.size.toULong(), handle)
                    }
                    check(written == bytes.size.toULong()) { "Short write while writing file: $resolved" }
                }
            }
        } catch (error: Throwable) {
            fclose(handle)
            throw error
        }
        check(fclose(handle) == 0) { "Failed to close file after writing: $resolved" }
        return result
    }

    override suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {
        val resolved = path.removePrefix("file://")
        val parent = resolved.substringBeforeLast('/', missingDelimiterValue = "")
        if (parent.isNotEmpty()) ensureDirectory(parent)
        val handle = fopen(resolved, "ab") ?: error("Failed to open file for writing: $resolved")
        val result = try {
            block { bytes ->
                if (bytes.isNotEmpty()) {
                    val written = bytes.usePinned { pinned ->
                        fwrite(pinned.addressOf(0), 1uL, bytes.size.toULong(), handle)
                    }
                    check(written == bytes.size.toULong()) { "Short write while writing file: $resolved" }
                }
            }
        } catch (error: Throwable) {
            fclose(handle)
            throw error
        }
        check(fclose(handle) == 0) { "Failed to close file after writing: $resolved" }
        return result
    }

    override fun promote(sourcePath: String, targetPath: String): Boolean =
        IosSecurityScopedBookmarks.withAccess(sourcePath) { source ->
            IosSecurityScopedBookmarks.withAccess(targetPath) { target ->
                if (!fm.fileExistsAtPath(source)) return@withAccess false
                val parent = target.substringBeforeLast('/', missingDelimiterValue = "")
                if (parent.isNotEmpty()) ensureDirectory(parent)
                if (fm.fileExistsAtPath(target) && !fm.removeItemAtPath(target, error = null)) {
                    return@withAccess false
                }
                if (!fm.moveItemAtPath(source, toPath = target, error = null)) return@withAccess false
                fm.fileExistsAtPath(target) && !fm.fileExistsAtPath(source)
            }
        } ?: false

    override fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean =
        IosSecurityScopedBookmarks.withAccess(tempPath) { source ->
            IosSecurityScopedBookmarks.withAccess(finalPath) { target ->
                if (source.substringBeforeLast('/') != target.substringBeforeLast('/') ||
                    !fm.fileExistsAtPath(source) || fm.directoryExists(source)
                ) return@withAccess false
                rename(source, target) == 0
            }
        } ?: false

    override fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean =
        IosSecurityScopedBookmarks.withAccess(stagedPath) { source ->
            IosSecurityScopedBookmarks.withAccess(finalPath) { target ->
                if (source.substringBeforeLast('/') != target.substringBeforeLast('/') ||
                    !fm.directoryExists(source) || fm.fileExistsAtPath(target)
                ) return@withAccess false
                // ponytail: precheck+rename is not safe against external same-name racers; rely only on
                // the app-owned namespace with one queue writer and random IDs, or add a native RENAME_EXCL shim.
                rename(source, target) == 0
            }
        } ?: false

    override fun readBytes(path: String): ByteArray {
        return IosSecurityScopedBookmarks.withAccess(path) { raw ->
            val resolved = raw.fileSystemPath()
            // Mapped (clean, evictable) pages instead of a second heap copy; the pool unmaps them after the copy out.
            autoreleasepool {
                val data = NSData.dataWithContentsOfFile(resolved, NSDataReadingMappedIfSafe, null)
                    ?: return@autoreleasepool ByteArray(0)
                val length = data.length.toInt()
                if (length == 0) return@autoreleasepool ByteArray(0)
                val bytes = ByteArray(length)
                bytes.usePinned { pinned ->
                    platform.posix.memcpy(pinned.addressOf(0), data.bytes, length.toULong())
                }
                bytes
            }
        } ?: ByteArray(0)
    }

    override fun readBytesBounded(path: String, maxBytes: Long): ByteArray {
        require(maxBytes >= 0 && maxBytes < Int.MAX_VALUE) { "Invalid byte limit" }
        return IosSecurityScopedBookmarks.withAccess(path) { raw ->
            val resolved = raw.fileSystemPath()
            val actualSize = fm.fileSize(resolved)
            check(actualSize <= maxBytes) { "File exceeds $maxBytes bytes" }
            val file = fopen(resolved, "rb") ?: error("Cannot open file: $path")
            var bytes = ByteArray(minOf(actualSize, 64L * 1024).toInt())
            var total = 0L
            try {
                while (total <= maxBytes) {
                    if (total == bytes.size.toLong()) {
                        if (total == maxBytes) {
                            val extra = ByteArray(1)
                            val count = extra.usePinned { pinned ->
                                platform.posix.fread(pinned.addressOf(0), 1uL, 1uL, file).toInt()
                            }
                            if (count > 0) total++
                            break
                        }
                        val nextSize = minOf(maxBytes + 1, maxOf(16L * 1024, bytes.size.toLong() * 2))
                        bytes = bytes.copyOf(nextSize.toInt())
                    }
                    val count = bytes.usePinned { pinned ->
                        platform.posix.fread(
                            pinned.addressOf(total.toInt()),
                            1uL,
                            minOf(bytes.size.toLong() - total, maxBytes + 1 - total).toULong(),
                            file,
                        ).toInt()
                    }
                    if (count == 0) break
                    total += count
                }
            } finally {
                fclose(file)
            }
            check(total == actualSize) { "File changed or was truncated while reading: $path" }
            check(total <= maxBytes) { "File exceeds $maxBytes bytes" }
            bytes.copyOf(minOf(total, maxBytes).toInt())
        } ?: error("Cannot read file: $path")
    }

    override fun canonicalPath(path: String): String? =
        IosSecurityScopedBookmarks.withAccess(path) { resolved ->
            NSURL.fileURLWithPath(resolved).URLByResolvingSymlinksInPath?.path
        }

    override fun exists(path: String): Boolean =
        IosSecurityScopedBookmarks.withAccess(path) { resolved -> fm.fileExistsAtPath(resolved) } ?: false

    override fun deleteRecursively(path: String): Boolean {
        return IosSecurityScopedBookmarks.withAccess(path) { resolved ->
            if (!fm.fileExistsAtPath(resolved)) true else fm.removeItemAtPath(resolved, error = null)
        } ?: false
    }

    override fun directorySize(path: String): Long {
        return IosSecurityScopedBookmarks.withAccess(path) { resolved ->
            if (!fm.fileExistsAtPath(resolved)) 0L else walkSize(resolved)
        } ?: 0L
    }

    override fun openLocation(path: String): Boolean {
        return IosSecurityScopedBookmarks.withAccess(path) { resolved ->
            val url = NSURL.fileURLWithPath(resolved)
            platform.UIKit.UIApplication.sharedApplication.openURL(url)
        } ?: false
    }

    override fun listLocalEntries(root: String): List<LocalEntry>? {
        return IosSecurityScopedBookmarks.withAccess(root) { resolved ->
            if (!fm.directoryExists(resolved)) return@withAccess null
            listLocalEntriesRecursive(resolved, root.removePrefix("file://"))
        }
    }

    override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? =
        IosSecurityScopedBookmarks.withAccess(root) { resolved ->
            val names = fm.contentsOfDirectoryAtPath(resolved, error = null) ?: return@withAccess null
            names.filterIsInstance<String>().mapNotNull { name ->
                val type = fm.attributesOfItemAtPath("$resolved/$name", error = null)?.get(NSFileType)
                if (type != NSFileTypeDirectory && type != NSFileTypeRegular) return@mapNotNull null
                LocalDirectoryEntry("${root.removePrefix("file://").trimEnd('/')}/$name", name, type == NSFileTypeDirectory)
            }.sortedBy { it.name.lowercase() }
        }

    private fun listLocalEntriesRecursive(root: String, logicalRoot: String): List<LocalEntry>? {
        val names = fm.contentsOfDirectoryAtPath(root, error = null) ?: return null
        return names.filterIsInstance<String>()
            .sortedBy { it.lowercase() }
            .flatMap { name ->
                val full = "$root/$name"
                val logical = "$logicalRoot/$name"
                when {
                    !fm.directoryExists(full) && hasReadableExtension(name) ->
                        listOf(LocalEntry(path = logical, name = name.substringBeforeLast('.'), isArchive = true))
                    fm.directoryExists(full) && directoryContainsReadableFiles(full) ->
                        listOf(LocalEntry(path = logical, name = name, isArchive = false))
                    fm.directoryExists(full) -> listLocalEntriesRecursive(full, logical) ?: return null
                    else -> emptyList()
                }
            }
    }

    override fun listFiles(root: String): List<LocalFileEntry> {
        return IosSecurityScopedBookmarks.withAccess(root) { resolved ->
            if (!fm.directoryExists(resolved)) return@withAccess emptyList()
            fm.contentsOfDirectoryAtPath(resolved, error = null)
                ?.filterIsInstance<String>()
                ?.map { name ->
                    val full = "$resolved/$name"
                    LocalFileEntry(
                        path = "${root.removePrefix("file://").trimEnd('/')}/$name",
                        name = name,
                        sizeBytes = fm.fileSize(full),
                        lastModified = ((fm.attributesOfItemAtPath(full, error = null)?.get(NSFileModificationDate) as? NSDate)?.timeIntervalSince1970?.times(1000))?.toLong() ?: 0L,
                    )
                }
                .orEmpty()
        }.orEmpty()
    }

    private fun ensureDirectory(path: String): String {
        if (!fm.fileExistsAtPath(path)) {
            fm.createDirectoryAtPath(path, withIntermediateDirectories = true, attributes = null, error = null)
        }
        return path
    }

    private fun walkSize(path: String): Long {
        if (!fm.directoryExists(path)) return fm.fileSize(path)
        val children = fm.contentsOfDirectoryAtPath(path, error = null)?.filterIsInstance<String>().orEmpty()
        return children.sumOf { walkSize("$path/$it") }
    }

    private fun directoryContainsReadableFiles(path: String): Boolean =
        fm.contentsOfDirectoryAtPath(path, error = null)
            ?.filterIsInstance<String>()
            ?.any { name ->
                val full = "$path/$name"
                !fm.directoryExists(full) && hasReadableExtension(name)
            } == true

    private fun hasReadableExtension(name: String): Boolean {
        val lower = name.lowercase()
        return lower.endsWith(".cbz") || lower.endsWith(".zip") ||
            lower.endsWith(".cbt") || lower.endsWith(".tar") ||
            lower.endsWith(".epub") || lower.endsWith(".png") ||
            lower.endsWith(".jpg") || lower.endsWith(".jpeg") ||
            lower.endsWith(".gif") || lower.endsWith(".webp") ||
            lower.endsWith(".bmp") || lower.endsWith(".avif") ||
            lower.endsWith(".mp4") || lower.endsWith(".mkv") ||
            lower.endsWith(".mov") || lower.endsWith(".webm") ||
            lower.endsWith(".avi") || lower.endsWith(".m4v") ||
            lower.endsWith(".ts") || lower.endsWith(".m3u8") ||
            lower.endsWith(".txt") || lower.endsWith(".html") ||
            lower.endsWith(".xhtml") || lower.endsWith(".md")
    }
}

private fun String.fileSystemPath(): String =
    if (startsWith("file:")) NSURL.URLWithString(this)?.path ?: error("Invalid file URL: $this") else this

@OptIn(ExperimentalForeignApi::class)
internal fun NSFileManager.directoryExists(path: String): Boolean {
    return fileExistsAtPath(path) && contentsOfDirectoryAtPath(path, error = null) != null
}

@OptIn(ExperimentalForeignApi::class)
internal fun NSFileManager.fileSize(path: String): Long {
    val attrs = attributesOfItemAtPath(path, error = null) ?: return 0L
    val size = attrs["NSFileSize"] as? platform.Foundation.NSNumber ?: return 0L
    return size.longLongValue
}

Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/IosSecurityScopedBookmarks.ios.kt

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

The implementation below defines IosSecurityScopedBookmarks, persist, withAccess, withAccessAsync, withCoordinatedRead, refresh, matchingRoot, storedRoots, bookmarkKey.

The source describes its contract as:

Keeps security-scoped bookmark data outside the common settings model. The configured path remains the opaque path returned by the picker; this class resolves it only at the point where a filesystem operation is performed.

@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package eu.friedcutlet.yokan.services.files

import kotlinx.cinterop.BooleanVarOf
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.alloc
import kotlinx.cinterop.ObjCObjectVar
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.value
import platform.Foundation.NSData
import platform.Foundation.NSURL
import platform.Foundation.NSURLBookmarkCreationMinimalBookmark
import platform.Foundation.NSURLBookmarkResolutionWithoutImplicitStartAccessing
import platform.Foundation.NSFileCoordinator
import platform.Foundation.NSFileCoordinatorReadingWithoutChanges
import platform.Foundation.NSError
import platform.Foundation.NSUserDefaults
import eu.friedcutlet.yokan.services.blockingDispatcher
import kotlin.coroutines.ContinuationInterceptor
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext

/**
 * Keeps security-scoped bookmark data outside the common settings model. The
 * configured path remains the opaque path returned by the picker; this class
 * resolves it only at the point where a filesystem operation is performed.
 */
@OptIn(ExperimentalForeignApi::class)
internal object IosSecurityScopedBookmarks {
    private const val rootsKey = "eu.friedcutlet.yokan.securityScopedBookmarkRoots"
    private const val bookmarkKeyPrefix = "eu.friedcutlet.yokan.securityScopedBookmark."

    private val defaults: NSUserDefaults
        get() = NSUserDefaults.standardUserDefaults

    fun persist(url: NSURL): String? {
        val path = url.path?.takeIf(String::isNotBlank) ?: return null
        val started = url.startAccessingSecurityScopedResource()
        return try {
            val bookmark = url.bookmarkDataWithOptions(
                options = NSURLBookmarkCreationMinimalBookmark,
                includingResourceValuesForKeys = null,
                relativeToURL = null,
                error = null,
            ) ?: return null
            defaults.setObject(bookmark, forKey = bookmarkKey(path))
            val roots = storedRoots()
            if (path !in roots) defaults.setObject(roots + path, forKey = rootsKey)
            path
        } finally {
            if (started) url.stopAccessingSecurityScopedResource()
        }
    }

    /**
     * Resolves the bookmark for [path], refreshes stale data, and holds the
     * security scope for exactly the duration of [block]. A path without a
     * bookmark is treated as an app-local path and is used directly.
     */
    fun <T> withAccess(path: String, block: (String) -> T): T? {
        val logicalPath = if (path.startsWith("file:")) {
            NSURL.URLWithString(path)?.path ?: return null
        } else path
        val root = matchingRoot(logicalPath)
        if (root == null) return runCatching { block(logicalPath) }.getOrNull()

        val bookmark = defaults.objectForKey(bookmarkKey(root)) as? NSData ?: return null
        return memScoped {
            val stale = alloc<BooleanVarOf<Boolean>>()
            val resolved = NSURL.URLByResolvingBookmarkData(
                bookmarkData = bookmark,
                options = NSURLBookmarkResolutionWithoutImplicitStartAccessing,
                relativeToURL = null,
                bookmarkDataIsStale = stale.ptr,
                error = null,
            ) ?: return@memScoped null
            val physicalRoot = resolved.path?.takeIf(String::isNotBlank) ?: return@memScoped null
            val started = resolved.startAccessingSecurityScopedResource()
            try {
                if (stale.value) refresh(root, resolved)
                val relative = logicalPath.removePrefix(root).trimStart('/')
                if (relative.split('/').any { it == ".." }) return@memScoped null
                val physicalPath = if (relative.isEmpty()) physicalRoot else "$physicalRoot/$relative"
                runCatching { block(physicalPath) }.getOrNull()
            } finally {
                if (started) resolved.stopAccessingSecurityScopedResource()
            }
        }
    }

    /** Holds a balanced security scope across suspended, bounded file reads. Errors propagate. */
    suspend fun <T> withAccessAsync(path: String, block: suspend (String) -> T): T {
        val logicalPath = if (path.startsWith("file:")) {
            requireNotNull(NSURL.URLWithString(path)?.path)
        } else path
        val root = matchingRoot(logicalPath) ?: return block(logicalPath)
        val bookmark = defaults.objectForKey(bookmarkKey(root)) as? NSData ?: error("Folder permission is unavailable")
        var staleBookmark = false
        val resolved = memScoped {
            val stale = alloc<BooleanVarOf<Boolean>>()
            val url = NSURL.URLByResolvingBookmarkData(bookmark, NSURLBookmarkResolutionWithoutImplicitStartAccessing, null, stale.ptr, null)
                ?: error("Folder permission could not be resolved")
            staleBookmark = stale.value
            url
        }
        val physicalRoot = requireNotNull(resolved.path)
        val started = resolved.startAccessingSecurityScopedResource()
        try {
            if (staleBookmark) refresh(root, resolved)
            val relative = logicalPath.removePrefix(root).trimStart('/')
            require(relative.split('/').none { it == ".." })
            return block(if (relative.isEmpty()) physicalRoot else "$physicalRoot/$relative")
        } finally { if (started) resolved.stopAccessingSecurityScopedResource() }
    }

    /** Keeps provider materialization and all reads inside its synchronous coordination accessor. */
    @OptIn(kotlinx.cinterop.BetaInteropApi::class)
    suspend fun <T> withCoordinatedRead(path: String, block: suspend (String) -> T): T = withContext(blockingDispatcher) {
        withAccessAsync(path) { physical ->
            coroutineScope {
                val coordinator = NSFileCoordinator(filePresenter = null)
                suspendCancellableCoroutine { continuation ->
                    continuation.invokeOnCancellation { coordinator.cancel() }
                    launch(blockingDispatcher) {
                        val outcome = runCatching {
                            val readerContext = currentCoroutineContext().minusKey(ContinuationInterceptor)
                            memScoped {
                                val failure = alloc<ObjCObjectVar<NSError?>>()
                                failure.value = null
                                var result: Result<T>? = null
                                coordinator.coordinateReadingItemAtURL(
                                    NSURL.fileURLWithPath(physical),
                                    options = NSFileCoordinatorReadingWithoutChanges,
                                    error = failure.ptr,
                                ) { coordinated ->
                                    // This bridge stays on the background thread and inherits cancellation.
                                    // The native destination writer is synchronous; no UI thread is blocked.
                                    result = runCatching { runBlocking(readerContext) { block(requireNotNull(requireNotNull(coordinated).path)) } }
                                }
                                val completed = result ?: error(failure.value?.localizedDescription ?: "Document provider could not open the file")
                                completed.getOrThrow()
                            }
                        }
                        if (continuation.isActive) continuation.resumeWith(outcome)
                    }
                }
            }
        }
    }

    private fun refresh(root: String, url: NSURL) {
        runCatching {
            url.bookmarkDataWithOptions(
                options = NSURLBookmarkCreationMinimalBookmark,
                includingResourceValuesForKeys = null,
                relativeToURL = null,
                error = null,
            )?.let { defaults.setObject(it, forKey = bookmarkKey(root)) }
        }
    }

    private fun matchingRoot(path: String): String? = storedRoots()
        .filter { root ->
            val normalizedRoot = root.trimEnd('/').ifEmpty { "/" }
            path == normalizedRoot ||
                (normalizedRoot == "/" && path.startsWith('/')) ||
                path.startsWith("$normalizedRoot/")
        }
        .maxByOrNull(String::length)

    private fun storedRoots(): List<String> =
        defaults.arrayForKey(rootsKey)?.filterIsInstance<String>().orEmpty()

    private fun bookmarkKey(root: String): String = bookmarkKeyPrefix + root
}

Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/IosZipArchive.ios.kt

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

The implementation below defines IosZipEntry, IosZipArchive, read, readImage, readEntry, open, openFile, parse, fileLength, readFileRange and 11 further declarations.

The source describes its contract as:

Minimal ZIP reader (stored + deflate) on the platform zlib binding, shared by CBZ/EPUB support ([openFile]: positioned reads of the central directory, then one entry at a time) and backup restore ([open]: bytes already in memory). Retains only the entry table. Sizes and offsets are 32-bit and read as Int, so archives over 2 GiB and ZIP64 are unsupported.

package eu.friedcutlet.yokan.services.files

import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.alloc
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.usePinned
import platform.posix.SEEK_END
import platform.posix.SEEK_SET
import platform.posix.fclose
import platform.posix.fopen
import platform.posix.fread
import platform.posix.fseek
import platform.posix.ftell
import platform.posix.fwrite
import platform.posix.remove
import platform.posix.rename
import platform.zlib.Z_FINISH
import platform.zlib.Z_OK
import platform.zlib.Z_STREAM_END
import platform.zlib.inflate
import platform.zlib.inflateEnd
import platform.zlib.inflateInit2
import platform.zlib.z_stream

private data class IosZipEntry(
    val compressionMethod: Int,
    val crc: Int,
    val compressedSize: Int,
    val uncompressedSize: Int,
    val localHeaderOffset: Int,
)

/**
 * Minimal ZIP reader (stored + deflate) on the platform zlib binding, shared by CBZ/EPUB support
 * ([openFile]: positioned reads of the central directory, then one entry at a time) and backup
 * restore ([open]: bytes already in memory). Retains only the entry table.
 *
 * Sizes and offsets are 32-bit and read as Int, so archives over 2 GiB and ZIP64 are unsupported.
 */
internal class IosZipArchive private constructor(
    private val readAt: (offset: Long, length: Int) -> ByteArray?,
    private val entries: Map<String, IosZipEntry>,
) {
    val entryNames: List<String> get() = entries.keys.toList()

    fun read(path: String): ByteArray? = readEntry(path, maxBytes = null)

    fun readImage(path: String, maxBytes: Long): ByteArray? = readEntry(path, maxBytes)

    private fun readEntry(path: String, maxBytes: Long?): ByteArray? {
        val normalized = normalizeArchivePath(path, decodePercentSpaces = false).takeIf(String::isNotEmpty) ?: return null
        val entry = entries[normalized]
            ?: entries.entries.firstOrNull { it.key.endsWith(normalized) }?.value
            ?: return null
        if (maxBytes != null && (entry.uncompressedSize <= 0 || entry.compressedSize < 0 ||
                entry.uncompressedSize.toLong() > maxBytes || entry.compressedSize.toLong() > maxBytes)
        ) return null
        val offset = entry.localHeaderOffset.toLong()
        val header = readAt(offset, LOCAL_HEADER_SIZE) ?: return null
        if (header.u32(0) != LOCAL_FILE_HEADER) return null
        val dataStart = offset + LOCAL_HEADER_SIZE + header.u16(26) + header.u16(28)
        val compressed = readAt(dataStart, entry.compressedSize) ?: return null
        val data = when (entry.compressionMethod) {
            0 -> compressed
            8 -> inflateRaw(compressed, entry.uncompressedSize)
            else -> null
        } ?: return null
        return data.takeIf { it.size == entry.uncompressedSize && crc32Of(it) == entry.crc }
    }

    companion object {
        private const val END_OF_CENTRAL_DIRECTORY = 0x06054B50
        private const val CENTRAL_DIRECTORY_HEADER = 0x02014B50
        private const val LOCAL_FILE_HEADER = 0x04034B50
        private const val LOCAL_HEADER_SIZE = 30
        private const val END_RECORD_SIZE = 22

        /** The end record plus the longest ZIP comment. */
        private const val MAX_END_RECORD_SEARCH = END_RECORD_SIZE + 65_535L

        fun open(bytes: ByteArray): IosZipArchive? = parse(bytes.size.toLong()) { offset, length ->
            bytes.copyOfRange(offset.toInt(), (offset + length).toInt())
        }

        /** Reads [path] with positioned file reads; callers hold any security scope around each call. */
        fun openFile(path: String, strict: Boolean = false): IosZipArchive? {
            val size = fileLength(path) ?: return null
            return parse(size, strict) { offset, length -> readFileRange(path, offset, length) }
        }

        /** [readRange] only sees in-bounds ranges, so a corrupt size never allocates past the archive. */
        private fun parse(
            size: Long,
            strict: Boolean = false,
            readRange: (offset: Long, length: Int) -> ByteArray?,
        ): IosZipArchive? {
            val readAt = { offset: Long, length: Int ->
                if (offset < 0 || length < 0 || offset + length > size) null else readRange(offset, length)
            }
            if (size < END_RECORD_SIZE) return null
            val tailLength = minOf(size, MAX_END_RECORD_SEARCH).toInt()
            val tail = readAt(size - tailLength, tailLength) ?: return null
            val eocd = (tail.size - END_RECORD_SIZE downTo 0)
                .firstOrNull { tail.u32(it) == END_OF_CENTRAL_DIRECTORY }
                ?: return null
            val diskNumber = tail.u16(eocd + 4)
            val directoryDiskNumber = tail.u16(eocd + 6)
            val entriesOnDisk = tail.u16(eocd + 8)
            val entryCount = tail.u16(eocd + 10)
            val directoryOffset = tail.u32(eocd + 16)
            val directorySize = tail.u32(eocd + 12)
            val commentLength = tail.u16(eocd + 20)
            val eocdAbsoluteOffset = size - tailLength + eocd
            if (strict) {
                if (diskNumber != 0 || directoryDiskNumber != 0 || entriesOnDisk != entryCount ||
                    entryCount < 0 || entryCount == 0xffff || directoryOffset < 0 || directoryOffset == -1 ||
                    directorySize < 0 || directorySize == -1 || commentLength < 0 ||
                    eocd + END_RECORD_SIZE + commentLength != tail.size ||
                    directoryOffset.toLong() + directorySize.toLong() != eocdAbsoluteOffset
                ) return null
            }
            val directory = readAt(directoryOffset.toLong(), directorySize) ?: return null
            var cursor = 0
            val entries = LinkedHashMap<String, IosZipEntry>(entryCount)
            repeat(entryCount) {
                if (cursor < 0 || cursor + 46 > directory.size || directory.u32(cursor) != CENTRAL_DIRECTORY_HEADER) {
                    if (strict) return null
                    return@repeat
                }
                val method = directory.u16(cursor + 10)
                val compressedSize = directory.u32(cursor + 20)
                val uncompressedSize = directory.u32(cursor + 24)
                val nameLength = directory.u16(cursor + 28)
                val extraLength = directory.u16(cursor + 30)
                val commentLength = directory.u16(cursor + 32)
                val localOffset = directory.u32(cursor + 42)
                val nameStart = cursor + 46
                val nameEnd = nameStart + nameLength
                val recordEnd = nameEnd + extraLength + commentLength
                if (nameLength <= 0 || extraLength < 0 || commentLength < 0 || recordEnd < nameEnd || recordEnd > directory.size) {
                    if (strict) return null
                    return@repeat
                }
                val name = runCatching { directory.copyOfRange(nameStart, nameEnd).decodeToString() }.getOrNull()
                if (name.isNullOrBlank()) {
                    if (strict) return null
                } else {
                    if (strict && (compressedSize < 0 || uncompressedSize < 0 || localOffset < 0)) return null
                    entries[normalizeArchivePath(name, decodePercentSpaces = false)] = IosZipEntry(
                        compressionMethod = method,
                        crc = directory.u32(cursor + 16),
                        compressedSize = compressedSize,
                        uncompressedSize = uncompressedSize,
                        localHeaderOffset = localOffset,
                    )
                }
                cursor = recordEnd
            }
            if (strict && (entries.size != entryCount || cursor != directory.size)) return null
            return IosZipArchive(readAt, entries).takeIf { entries.isNotEmpty() }
        }
    }
}

@OptIn(ExperimentalForeignApi::class)
private fun fileLength(path: String): Long? {
    val file = fopen(path, "rb") ?: return null
    return try {
        if (fseek(file, 0, SEEK_END) == 0) ftell(file).takeIf { it >= 0 } else null
    } finally {
        fclose(file)
    }
}

@OptIn(ExperimentalForeignApi::class)
private fun readFileRange(path: String, offset: Long, length: Int): ByteArray? {
    if (length == 0) return ByteArray(0)
    val file = fopen(path, "rb") ?: return null
    return try {
        if (fseek(file, offset, SEEK_SET) != 0) return null
        val buffer = ByteArray(length)
        val read = buffer.usePinned { pinned -> fread(pinned.addressOf(0), 1uL, length.toULong(), file) }
        buffer.takeIf { read == length.toULong() }
    } finally {
        fclose(file)
    }
}

/** Builds a stored (method 0) ZIP in memory; backups use it for their single entry. */
internal fun buildStoredZip(entries: List<Pair<String, ByteArray>>): ByteArray {
    val chunks = mutableListOf<ByteArray>()
    check(writeStoredZip(entries.asSequence()) { chunk -> chunks += chunk; true })
    val result = ByteArray(chunks.sumOf { it.size })
    var cursor = 0
    chunks.forEach { chunk ->
        chunk.copyInto(result, cursor)
        cursor += chunk.size
    }
    return result
}

/**
 * Streams a stored ZIP of [entries] into [targetPath], holding one entry in memory at a time. Writes
 * `<target>.part` first so a failed write never looks complete; false when writing failed.
 */
@OptIn(ExperimentalForeignApi::class)
internal fun writeStoredZipFile(targetPath: String, entries: Sequence<Pair<String, ByteArray>>): Boolean {
    val partial = "$targetPath.part"
    val file = fopen(partial, "wb") ?: return false
    var written = false
    try {
        written = writeStoredZip(entries) { chunk ->
            chunk.isEmpty() || chunk.usePinned { pinned ->
                fwrite(pinned.addressOf(0), 1uL, chunk.size.toULong(), file) == chunk.size.toULong()
            }
        }
    } finally {
        if (fclose(file) != 0) written = false
    }
    if (written && rename(partial, targetPath) == 0) return true
    remove(partial)
    return false
}

private class StoredZipEntry(val name: ByteArray, val crc: Int, val size: Int, val headerOffset: Int)

/**
 * Emits a stored (method 0) ZIP of [entries] chunk by chunk through [emit], so archive creation needs
 * no deflate encoder. False when [emit] fails or the archive outgrows the offsets [IosZipArchive] reads.
 */
private fun writeStoredZip(entries: Sequence<Pair<String, ByteArray>>, emit: (ByteArray) -> Boolean): Boolean {
    var offset = 0L
    fun put(bytes: ByteArray): Boolean {
        offset += bytes.size
        return offset <= Int.MAX_VALUE && emit(bytes)
    }
    val central = mutableListOf<StoredZipEntry>()
    for ((name, data) in entries) {
        val entry = StoredZipEntry(name.encodeToByteArray(), crc32Of(data), data.size, offset.toInt())
        val header = ByteArray(30)
        header.putU32(0, 0x04034B50)
        header.putU16(4, 20) // version needed
        header.putU16(8, 0) // method: stored
        header.putU32(14, entry.crc)
        header.putU32(18, entry.size)
        header.putU32(22, entry.size)
        header.putU16(26, entry.name.size)
        if (!put(header) || !put(entry.name) || !put(data)) return false
        central += entry
    }
    val centralStart = offset.toInt()
    for (entry in central) {
        val record = ByteArray(46)
        record.putU32(0, 0x02014B50)
        record.putU16(4, 20) // version made by
        record.putU16(6, 20) // version needed
        record.putU16(10, 0) // method: stored
        record.putU32(16, entry.crc)
        record.putU32(20, entry.size)
        record.putU32(24, entry.size)
        record.putU16(28, entry.name.size)
        record.putU32(42, entry.headerOffset)
        if (!put(record) || !put(entry.name)) return false
    }
    val centralSize = offset.toInt() - centralStart
    val eocd = ByteArray(22)
    eocd.putU32(0, 0x06054B50)
    eocd.putU16(8, central.size)
    eocd.putU16(10, central.size)
    eocd.putU32(12, centralSize)
    eocd.putU32(16, centralStart)
    return put(eocd)
}

private fun ByteArray.putU16(offset: Int, value: Int) {
    this[offset] = (value and 0xFF).toByte()
    this[offset + 1] = ((value ushr 8) and 0xFF).toByte()
}

private fun ByteArray.putU32(offset: Int, value: Int) {
    this[offset] = (value and 0xFF).toByte()
    this[offset + 1] = ((value ushr 8) and 0xFF).toByte()
    this[offset + 2] = ((value ushr 16) and 0xFF).toByte()
    this[offset + 3] = ((value ushr 24) and 0xFF).toByte()
}

@OptIn(ExperimentalForeignApi::class)
private fun crc32Of(data: ByteArray): Int {
    if (data.isEmpty()) return 0
    return data.usePinned { pinned ->
        platform.zlib.crc32(0uL, pinned.addressOf(0).reinterpret(), data.size.toUInt()).toInt()
    }
}

private fun ByteArray.u16(offset: Int): Int {
    if (offset < 0 || offset + 2 > size) return -1
    return (this[offset].toInt() and 0xFF) or ((this[offset + 1].toInt() and 0xFF) shl 8)
}

private fun ByteArray.u32(offset: Int): Int {
    if (offset < 0 || offset + 4 > size) return -1
    return (this[offset].toInt() and 0xFF) or
        ((this[offset + 1].toInt() and 0xFF) shl 8) or
        ((this[offset + 2].toInt() and 0xFF) shl 16) or
        ((this[offset + 3].toInt() and 0xFF) shl 24)
}

@OptIn(ExperimentalForeignApi::class)
private fun inflateRaw(compressed: ByteArray, expectedSize: Int): ByteArray? {
    if (expectedSize < 0) return null
    if (expectedSize == 0) return ByteArray(0)
    val output = ByteArray(expectedSize)
    return compressed.usePinned { inputPinned ->
        output.usePinned { outputPinned ->
            memScoped {
                val stream = alloc<z_stream>()
                stream.next_in = inputPinned.addressOf(0).reinterpret()
                stream.avail_in = compressed.size.toUInt()
                stream.next_out = outputPinned.addressOf(0).reinterpret()
                stream.avail_out = output.size.toUInt()
                if (inflateInit2(stream.ptr, -15) != Z_OK) return@memScoped null
                try {
                    output.takeIf { inflate(stream.ptr, Z_FINISH) == Z_STREAM_END }
                } finally {
                    inflateEnd(stream.ptr)
                }
            }
        }
    }
}

Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.ios.kt

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

The implementation below defines createPlatformLocalArchiveService, createPlatformLocalFileService, IosLocalArchiveService, listPages, listPagesStrict, listDirectoryPages, extractZipPages, extractTarPages, CPointer, isImageName and 18 further declarations.

The source describes its contract as:

iOS archive support. Image directories list directly through NSFileManager; CBZ/ZIP pages and EPUB chapters read through a file-backed [IosZipArchive]; CBT/TAR pages stream entry by entry. Pages extract into cacheRoot/archives/\<key\> like the JVM implementation, kept least-recently-used within [extractedPagesBudgetBytes]; zipDirectoryToCbz streams a stored ZIP. Memory ceiling: TAR uses one 512 B header and one 64 KiB copy buffer. ZIP reads keep the entry tables of 8 archives and hold one entry at a time; plus 8 page lists and 8 chapter lists.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.util.PlatformLock
import kotlinx.cinterop.BetaInteropApi
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import platform.Foundation.NSDate
import platform.Foundation.NSFileManager
import platform.Foundation.NSFileModificationDate
import platform.Foundation.NSURL
import platform.Foundation.timeIntervalSince1970
import platform.posix.FILE
import platform.posix.SEEK_CUR
import platform.posix.fclose
import platform.posix.fopen
import platform.posix.fread
import platform.posix.fseek
import platform.posix.fwrite
import platform.posix.remove
import platform.posix.rename
import kotlin.random.Random

actual fun createPlatformLocalArchiveService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalArchiveService = IosLocalArchiveService(files = createPlatformLocalFileService(profileId))

actual fun createPlatformLocalFileService(profileId: eu.friedcutlet.yokan.domain.ProfileId): LocalFileService = if (profileId == eu.friedcutlet.yokan.domain.ProfileId.Default) IosLocalFileService else IosProfileLocalFileService(profileId)

/**
 * iOS archive support. Image directories list directly through NSFileManager; CBZ/ZIP pages and
 * EPUB chapters read through a file-backed [IosZipArchive]; CBT/TAR pages stream entry by entry. Pages
 * extract into `cacheRoot/archives/<key>` like the JVM implementation, kept least-recently-used within
 * [extractedPagesBudgetBytes]; zipDirectoryToCbz streams a stored ZIP.
 *
 * Memory ceiling: TAR uses one 512 B header and one 64 KiB copy buffer. ZIP reads keep the entry
 * tables of 8 archives and hold one entry at a time; plus 8 page lists and 8 chapter lists.
 */
@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)
internal class IosLocalArchiveService(
    // ponytail: fixed 1 GiB of extracted pages; make it a storage setting if users want a bigger offline cache.
    private val files: LocalFileService = IosLocalFileService,
    private val extractedPagesBudgetBytes: Long = 1L shl 30,
) : LocalArchiveService {
    private val imageExtensions = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif")
    private val zipArchives = LinkedHashMap<String, IosZipArchive>()
    private val epubChapterCache = LinkedHashMap<String, List<LocalEpubChapter>>()
    private val extractedPages = LinkedHashMap<String, List<DbPageUrl>>()
    private val cacheLock = PlatformLock()
    private val extractionRoot = "${files.cacheRoot}/archives"
    private val maxStrictZipPageBytes = 25L * 1024 * 1024

    override fun listPages(archivePath: String): List<DbPageUrl> {
        if (archivePath.isBlank()) return emptyList()
        cacheLock.withLock { extractedPages[archivePath] }?.takeIf { touchExtraction(it) }?.let { return it }
        val pages = IosSecurityScopedBookmarks.withAccess(archivePath) { path ->
            val fm = NSFileManager.defaultManager
            if (!fm.fileExistsAtPath(path)) return@withAccess emptyList()
            val lower = path.lowercase()
            when {
                fm.directoryExists(path) -> listDirectoryPages(path, archivePath)
                isImageName(path) -> listOf(DbPageUrl(filePageUrl(path), path.substringAfterLast('/')))
                lower.endsWith(".cbz") || lower.endsWith(".zip") -> extractZipPages(path)
                lower.endsWith(".cbt") || lower.endsWith(".tar") -> extractTarPages(path)
                else -> emptyList()
            }
        }.orEmpty()
        cacheLock.withLock { extractedPages.putBounded(archivePath, pages) }
        return pages
    }

    override fun listPagesStrict(archivePath: String): List<DbPageUrl> {
        require(archivePath.isNotBlank()) { "Archive path is blank" }
        return IosSecurityScopedBookmarks.withAccess(archivePath) { path ->
            val fm = NSFileManager.defaultManager
            check(fm.fileExistsAtPath(path)) { "Archive is not readable: $archivePath" }
            when {
                fm.directoryExists(path) -> {
                    val names = fm.contentsOfDirectoryAtPath(path, error = null)
                        ?.filterIsInstance<String>() ?: error("Cannot read image directory: $archivePath")
                    names.filter(::isImageName).sortedWith(naturalPageNameComparator).map { name ->
                        val full = "$path/$name"
                        val input = fopen(full, "rb") ?: error("Unreadable image: $name")
                        check(fclose(input) == 0) { "Unreadable image: $name" }
                        DbPageUrl(filePageUrl(full), name)
                    }
                }
                path.endsWith(".cbz", true) || path.endsWith(".zip", true) -> extractZipPages(path, strict = true)
                isImageName(path) -> {
                    val input = fopen(path, "rb") ?: error("Unreadable image")
                    check(fclose(input) == 0) { "Unreadable image" }
                    listOf(DbPageUrl(filePageUrl(path), path.substringAfterLast('/')))
                }
                path.endsWith(".cbt", true) || path.endsWith(".tar", true) -> extractTarPages(path, strict = true)
                path.endsWith(".cbr", true) || path.endsWith(".rar", true) -> error("Strict RAR inventory is not supported on iOS")
                else -> error("Unsupported image archive: $archivePath")
            }
        } ?: error("Archive is not readable: $archivePath")
    }

    private fun listDirectoryPages(path: String, logicalRoot: String): List<DbPageUrl> {
        val children = NSFileManager.defaultManager.contentsOfDirectoryAtPath(path, error = null)
            ?.filterIsInstance<String>()
            ?.filter { name -> isImageName(name) }
            ?.sortedWith(naturalPageNameComparator)
            .orEmpty()
        val root = (if (logicalRoot.startsWith("file:")) NSURL.URLWithString(logicalRoot)?.path else logicalRoot)
            ?.trimEnd('/') ?: return emptyList()
        return children.map { name ->
            DbPageUrl(url = filePageUrl("$root/$name"), fileName = name)
        }
    }

    private fun extractZipPages(path: String, strict: Boolean = false): List<DbPageUrl> {
        val archive = (if (strict) IosZipArchive.openFile(path, strict = true) else zipArchive(path))
            ?: if (strict) error("Unreadable ZIP archive: $path") else return emptyList()
        val names = archive.entryNames
            .filter { name -> !name.startsWith(".") && !name.contains("/.") && isImageName(name) }
            .sortedWith(naturalPageNameComparator)
        if (names.isEmpty()) return emptyList()
        val target = if (strict) freshPagesCacheDir(path) else pagesCacheDir(path)
        val pages = names.mapIndexedNotNull { index, name ->
            val safeName = indexedPageName(index, name)
            val output = "$target/$safeName"
            if (strict || !NSFileManager.defaultManager.fileExistsAtPath(output)) {
                val data = (if (strict) archive.readImage(name, maxStrictZipPageBytes) else archive.read(name))
                    ?: if (strict) error("Unreadable ZIP image: $name") else return@mapIndexedNotNull null
                val partial = "$output.part"
                try {
                    IosLocalFileService.writeBytes(partial, data)
                    check(rename(partial, output) == 0) { "Cannot promote ZIP image: $name" }
                } catch (failure: Throwable) {
                    remove(partial)
                    remove(output)
                    throw failure
                }
            }
            DbPageUrl(url = filePageUrl(output), fileName = safeName)
        }
        pruneExtractedPages(keep = target)
        return pages
    }

    /** Streams the TAR; a truncated entry ends extraction and keeps the pages read so far. */
    private fun extractTarPages(path: String, strict: Boolean = false): List<DbPageUrl> {
        val input = fopen(path, "rb") ?: return emptyList()
        val target = if (strict) freshPagesCacheDir(path) else pagesCacheDir(path)
        val entries = mutableListOf<Pair<String, DbPageUrl>>()
        try {
            val header = ByteArray(TAR_BLOCK)
            val buffer = ByteArray(TAR_COPY_BUFFER)
            var index = 0
            while (true) {
                val headerRead = input.readBlock(header, header.size)
                if (headerRead == 0) {
                    if (strict) error("Missing TAR end marker")
                    break
                }
                if (headerRead != header.size) {
                    if (strict) error("Truncated TAR header")
                    break
                }
                if (header.all { it == 0.toByte() }) {
                    if (strict) {
                        val end = ByteArray(TAR_BLOCK)
                        check(input.readBlock(end, end.size) == end.size && end.all { it == 0.toByte() }) {
                            "Malformed TAR end marker"
                        }
                    }
                    break
                }
                val name = header.tarString(0, 100)
                if (name.isEmpty()) {
                    if (strict) error("Malformed TAR entry name")
                    break
                }
                val parsedSize = header.tarString(124, 12).toLongOrNull(8)
                if (strict) {
                    check(name.isNotBlank()) { "Malformed TAR entry name" }
                    checkTarHeader(header, parsedSize)
                }
                val size = parsedSize ?: 0L
                if (size < 0) {
                    if (strict) error("Malformed TAR entry size: $name")
                    break
                }
                val padding = (TAR_BLOCK - size % TAR_BLOCK) % TAR_BLOCK
                val type = header[156].toInt().toChar()
                val isPage = (type == '0' || type == 0.toChar()) &&
                    !name.startsWith(".") && !name.contains("/.") && isImageName(name)
                if (!isPage) {
                    val skipped = if (strict) input.skipExactly(size + padding, buffer) else fseek(input, size + padding, SEEK_CUR) == 0
                    if (!skipped) {
                        if (strict) error("Truncated TAR entry: $name")
                        break
                    }
                    continue
                }
                val safeName = indexedPageName(index++, name)
                val output = "$target/$safeName"
                val stored = if (!strict && NSFileManager.defaultManager.fileExistsAtPath(output)) {
                    fseek(input, size, SEEK_CUR) == 0
                } else {
                    input.copyEntryTo(output, size, buffer)
                }
                val paddingSkipped = if (stored && strict) input.skipExactly(padding, buffer) else stored && fseek(input, padding, SEEK_CUR) == 0
                if (!stored || !paddingSkipped) {
                    if (strict) error("Truncated TAR image: $name")
                    break
                }
                entries += name to DbPageUrl(url = filePageUrl(output), fileName = safeName)
            }
        } finally {
            fclose(input)
        }
        pruneExtractedPages(keep = target)
        return entries.sortedWith { left, right -> naturalPageNameComparator.compare(left.first, right.first) }
            .map { it.second }
    }

    /** Copies [size] bytes to [output] via a temp file so an interrupted copy never looks extracted. */
    private fun CPointer<FILE>.copyEntryTo(output: String, size: Long, buffer: ByteArray): Boolean {
        val partial = "$output.part"
        val file = fopen(partial, "wb") ?: return false
        var remaining = size
        var closed = false
        try {
            while (remaining > 0) {
                val wanted = minOf(remaining, buffer.size.toLong()).toInt()
                val read = readBlock(buffer, wanted)
                if (read <= 0) break
                val written = buffer.usePinned { pinned ->
                    fwrite(pinned.addressOf(0), 1uL, read.toULong(), file)
                }
                if (written != read.toULong()) break
                remaining -= read
            }
        } finally {
            closed = fclose(file) == 0
        }
        if (remaining == 0L && closed && rename(partial, output) == 0) return true
        remove(partial)
        return false
    }

    private fun CPointer<FILE>.readBlock(buffer: ByteArray, count: Int): Int =
        buffer.usePinned { pinned -> fread(pinned.addressOf(0), 1uL, count.toULong(), this).toInt() }

    private fun CPointer<FILE>.skipExactly(size: Long, buffer: ByteArray): Boolean {
        var remaining = size
        while (remaining > 0) {
            val read = readBlock(buffer, minOf(remaining, buffer.size.toLong()).toInt())
            if (read <= 0) return false
            remaining -= read
        }
        return true
    }

    private fun isImageName(name: String): Boolean =
        imageExtensions.any { name.lowercase().endsWith(".$it") }

    private fun indexedPageName(index: Int, entryName: String): String =
        index.toString().padStart(4, '0') + "_" + entryName.substringAfterLast('/')

    private fun pagesCacheDir(path: String): String {
        val fm = NSFileManager.defaultManager
        val key = ((path.hashCode().toLong() shl 32) xor fm.fileSize(path)).toULong().toString(16)
        val dir = "$extractionRoot/$key"
        fm.createDirectoryAtPath(dir, withIntermediateDirectories = true, attributes = null, error = null)
        markUsed(dir)
        return dir
    }

    private fun freshPagesCacheDir(path: String): String {
        val dir = "$extractionRoot/strict-${Random.nextLong().toULong()}-${path.hashCode()}"
        check(NSFileManager.defaultManager.createDirectoryAtPath(dir, withIntermediateDirectories = true, attributes = null, error = null)) {
            "Cannot create archive extraction directory"
        }
        markUsed(dir)
        return dir
    }

    /** Marks the extraction directory behind cached [pages] used; false once it was pruned (re-extract). */
    private fun touchExtraction(pages: List<DbPageUrl>): Boolean {
        val directory = pages.firstOrNull()?.url?.removePrefix("file://")?.substringBeforeLast('/') ?: return true
        if (directory.substringBeforeLast('/') != extractionRoot) return true // image folders list their own files
        return markUsed(directory)
    }

    /** Deletes the least recently used extraction directories (never [keep]) beyond [extractedPagesBudgetBytes]. */
    private fun pruneExtractedPages(keep: String) {
        val fm = NSFileManager.defaultManager
        val directories = fm.contentsOfDirectoryAtPath(extractionRoot, error = null).orEmpty()
            .filterIsInstance<String>()
            .map { name -> "$extractionRoot/$name" }
            .map { directory -> Triple(directory, fm.modifiedAt(directory), IosLocalFileService.directorySize(directory)) }
            .sortedBy { it.second }
        var bytes = directories.sumOf { it.third }
        for ((directory, _, size) in directories) {
            if (bytes <= extractedPagesBudgetBytes) break
            if (directory == keep) continue
            fm.removeItemAtPath(directory, error = null)
            bytes -= size
        }
    }

    override fun invalidateIndexCache() = cacheLock.withLock {
        epubChapterCache.clear()
        zipArchives.clear()
    }

    override fun listEpubChapters(archivePath: String): List<LocalEpubChapter> {
        if (archivePath.isBlank()) return emptyList()
        return IosSecurityScopedBookmarks.withAccess(archivePath) { path ->
            val key = archiveFingerprint(path)
            cacheLock.withLock { epubChapterCache[key] }?.let { return@withAccess it }
            val chapters = zipArchive(path)?.let { archive ->
                runCatching { readEpubManifest(archive::read) }.getOrDefault(emptyList())
            } ?: return@withAccess emptyList()
            cacheLock.withLock { epubChapterCache.putBounded(key, chapters) }
            chapters
        } ?: emptyList()
    }

    override fun readEpubChapter(archivePath: String, index: Int): String {
        val href = listEpubChapters(archivePath).getOrNull(index)?.href ?: return ""
        return readEpubResource(archivePath, href)?.decodeToString().orEmpty()
    }

    override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? =
        IosSecurityScopedBookmarks.withAccess(archivePath) { path -> zipArchive(path)?.read(resourcePath) }

    override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? {
        val source = directoryPath.removePrefix("file://")
        val fm = NSFileManager.defaultManager
        if (!fm.directoryExists(source)) return null
        val names = fm.contentsOfDirectoryAtPath(source, error = null)
            ?.filterIsInstance<String>()
            ?.filter { name ->
                !fm.directoryExists("$source/$name") && !name.startsWith(".") && (isImageName(name) || name == CHAPTER_METADATA_FILE)
            }
            ?.sortedWith(naturalPageNameComparator)
            .orEmpty()
        if (names.isEmpty()) return null
        val targetPath = "$source.cbz"
        val pages = names.asSequence().map { name -> name to files.readBytes("$source/$name") }
        check(writeStoredZipFile(targetPath, pages)) { "Failed to write file: $targetPath" }
        if (deleteSource) fm.removeItemAtPath(source, error = null)
        return targetPath
    }

    /** Entry table of the already resolved [path], cached by path and size so a rewritten file reopens. */
    private fun archiveFingerprint(path: String): String =
        "$path:${NSFileManager.defaultManager.fileSize(path)}:${NSFileManager.defaultManager.modifiedAt(path)}"

    private fun zipArchive(path: String): IosZipArchive? {
        val key = archiveFingerprint(path)
        cacheLock.withLock { zipArchives.remove(key)?.also { zipArchives[key] = it } }?.let { return it }
        val archive = IosZipArchive.openFile(path) ?: return null
        cacheLock.withLock { zipArchives.putBounded(key, archive) }
        return archive
    }

    private fun <V> LinkedHashMap<String, V>.putBounded(key: String, value: V) {
        remove(key)
        put(key, value)
        while (size > MAX_METADATA_CACHE_ENTRIES) remove(keys.first())
    }

    private companion object {
        const val MAX_METADATA_CACHE_ENTRIES = 8
        const val TAR_BLOCK = 512
        const val TAR_COPY_BUFFER = 64 * 1024
    }
}

/** Encode the actual path bytes once; NSURL.fileURLWithPath treats literal "%20" as an escape. */
private fun filePageUrl(path: String): String = buildString {
    append("file://")
    val hex = "0123456789ABCDEF"
    path.encodeToByteArray().forEach { byte ->
        val value = byte.toInt() and 255
        if (value in 'A'.code..'Z'.code || value in 'a'.code..'z'.code ||
            value in '0'.code..'9'.code || value == '/'.code || value == '-'.code ||
            value == '.'.code || value == '_'.code || value == '~'.code
        ) append(value.toChar()) else {
            append('%')
            append(hex[value ushr 4])
            append(hex[value and 15])
        }
    }
}

/** Bumps [path]'s modification time, the LRU clock for extraction directories; false when it is gone. */
@OptIn(ExperimentalForeignApi::class)
private fun markUsed(path: String): Boolean =
    NSFileManager.defaultManager.setAttributes(mapOf<Any?, Any?>(NSFileModificationDate to NSDate()), ofItemAtPath = path, error = null)

@OptIn(ExperimentalForeignApi::class)
private fun NSFileManager.modifiedAt(path: String): Double =
    (attributesOfItemAtPath(path, error = null)?.get(NSFileModificationDate) as? NSDate)?.timeIntervalSince1970 ?: 0.0

private fun ByteArray.tarString(start: Int, length: Int): String {
    val end = (start + length).coerceAtMost(size)
    if (start >= end) return ""
    return sliceArray(start until end).takeWhile { it != 0.toByte() }.toByteArray().decodeToString().trim()
}

private fun checkTarHeader(header: ByteArray, size: Long?) {
    check(size != null && size >= 0) { "Malformed TAR entry size" }
    val storedChecksum = header.tarString(148, 8).toLongOrNull(8)
    check(storedChecksum != null) { "Malformed TAR checksum" }
    val checksum = header.indices.sumOf { index ->
        if (index in 148..155) 32 else header[index].toInt() and 0xff
    }
    check(checksum.toLong() == storedChecksum) { "TAR header checksum mismatch" }
}

Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.ios.kt

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

The implementation below defines pickLocalMedia, IosLocalMediaInput, readChunks.

@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.services.blockingDispatcher
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield
import platform.Foundation.NSFileManager
import platform.Foundation.NSFileSize
import platform.Foundation.NSFileType
import platform.Foundation.NSFileTypeDirectory
import platform.Foundation.NSFileTypeRegular
import platform.Foundation.NSNumber
import platform.posix.fclose
import platform.posix.ferror
import platform.posix.fopen
import platform.posix.fread

actual suspend fun pickLocalMedia(directory: Boolean): LocalMediaSelection? {
    val chosen = if (directory) pickFolder() else pickScopedMediaFile()
    if (chosen == null) return null
    return withContext(blockingDispatcher) {
        IosSecurityScopedBookmarks.withCoordinatedRead(chosen) { root ->
            val fm = NSFileManager.defaultManager
            val inputs = mutableListOf<LocalMediaInput>()
            val pending = ArrayDeque<Pair<String, String>>().apply { add(root to root.substringAfterLast('/')) }
            var visited = 0
            while (pending.isNotEmpty()) {
                currentCoroutineContext().ensureActive()
                check(++visited <= 50_000) { "Selected folder is too large" }
                val (path, relative) = pending.removeFirst()
                check(relative.count { it == '/' } < 64) { "Selected folder is too deep" }
                val attrs = fm.attributesOfItemAtPath(path, error = null) ?: error("Selected file is unavailable")
                when (attrs[NSFileType]) {
                    NSFileTypeDirectory -> {
                        check(directory) { "Select a media file" }
                        val names = fm.contentsOfDirectoryAtPath(path, error = null)?.filterIsInstance<String>()
                            ?: error("Selected folder is unreadable")
                        for (name in names) if (!name.startsWith('.')) pending.add("$path/$name" to "$relative/$name")
                    }
                    NSFileTypeRegular -> {
                        if (relative.substringAfterLast('.', "").lowercase() !in localImportExtensions) continue
                        check(inputs.size < LOCAL_IMPORT_MAX_FILES) { "Too many selected files" }
                        val logical = if (directory) "$chosen/${path.removePrefix("$root/")}" else chosen
                        inputs += IosLocalMediaInput(relative, (attrs[NSFileSize] as? NSNumber)?.longLongValue, logical)
                    }
                    // Symlinks and special files are never followed out of the selected tree.
                    else -> Unit
                }
            }
            LocalMediaSelection(inputs)
        }
    }
}

internal class IosLocalMediaInput(
    override val relativePath: String,
    override val sizeBytes: Long?,
    private val path: String,
) : LocalMediaInput {
    override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) = withContext(blockingDispatcher) {
        IosSecurityScopedBookmarks.withCoordinatedRead(path) { physical ->
            val input = fopen(physical, "rb") ?: error("Selected file is no longer readable")
            try {
                val buffer = ByteArray(LOCAL_IMPORT_CHUNK_BYTES)
                while (true) {
                    currentCoroutineContext().ensureActive()
                    val count = buffer.usePinned { fread(it.addressOf(0), 1uL, buffer.size.toULong(), input).toInt() }
                    if (count == 0) { check(ferror(input) == 0) { "Could not read selected file" }; break }
                    consume(buffer.copyOf(count))
                    yield()
                }
            } finally { fclose(input) }
        }
    }
}

Write composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.ios.kt

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

The implementation below defines pickFolder, pickFile, pickScopedMediaFile, exportFile, IosDocumentPickerDelegate, documentPicker, documentPickerWasCancelled, documentTypesFor, topViewController.

The source describes its contract as:

Reads the selected original through a scoped URL instead of first duplicating it into Inbox.

@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package eu.friedcutlet.yokan.services.files

import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import platform.darwin.NSObject
import platform.Foundation.NSURL
import platform.UIKit.UIApplication
import platform.UIKit.UIDocumentPickerDelegateProtocol
import platform.UIKit.UIDocumentPickerMode
import platform.UIKit.UIDocumentPickerViewController
import platform.UIKit.UIViewController
import platform.UIKit.UISceneActivationStateForegroundActive
import platform.UIKit.UIWindow
import platform.UIKit.UIWindowScene

actual suspend fun pickFolder(initial: String?): String? =
    documentPickerLock.withLock {
        val presenter = topViewController() ?: return@withLock null
        val pending = CompletableDeferred<String?>()
        val delegate = IosDocumentPickerDelegate(pending, emptySet(), persistReadAccess = true)
        val picker = UIDocumentPickerViewController(
            documentTypes = listOf("public.folder"),
            inMode = UIDocumentPickerMode.UIDocumentPickerModeOpen,
        )
        activeDocumentPickerDelegate = delegate
        picker.delegate = delegate
        picker.allowsMultipleSelection = false
        presenter.presentViewController(picker, animated = true, completion = null)
        try {
            pending.await()
        } finally {
            if (activeDocumentPickerDelegate === delegate) activeDocumentPickerDelegate = null
        }
    }

actual suspend fun pickFile(extensions: List<String>, initial: String?): String? =
    documentPickerLock.withLock {
        val presenter = topViewController() ?: return@withLock null
        val pending = CompletableDeferred<String?>()
        val allowedExtensions = extensions.map(String::lowercase).toSet()
        val delegate = IosDocumentPickerDelegate(pending, allowedExtensions)
        val picker = UIDocumentPickerViewController(
            documentTypes = documentTypesFor(allowedExtensions),
            inMode = UIDocumentPickerMode.UIDocumentPickerModeImport,
        )
        activeDocumentPickerDelegate = delegate
        picker.delegate = delegate
        picker.allowsMultipleSelection = false
        presenter.presentViewController(picker, animated = true, completion = null)
        try {
            pending.await()
        } finally {
            if (activeDocumentPickerDelegate === delegate) activeDocumentPickerDelegate = null
        }
    }

/** Reads the selected original through a scoped URL instead of first duplicating it into Inbox. */
internal suspend fun pickScopedMediaFile(): String? = documentPickerLock.withLock {
    val presenter = topViewController() ?: return@withLock null
    val pending = CompletableDeferred<String?>()
    val extensions = readableLocalFileExtensions
    val delegate = IosDocumentPickerDelegate(pending, extensions, persistReadAccess = true)
    val picker = UIDocumentPickerViewController(
        documentTypes = documentTypesFor(extensions),
        inMode = UIDocumentPickerMode.UIDocumentPickerModeOpen,
    )
    activeDocumentPickerDelegate = delegate
    picker.delegate = delegate
    picker.allowsMultipleSelection = false
    presenter.presentViewController(picker, animated = true, completion = null)
    try { pending.await() }
    finally { if (activeDocumentPickerDelegate === delegate) activeDocumentPickerDelegate = null }
}

actual suspend fun exportFile(
    bytes: ByteArray,
    suggestedName: String,
    mimeType: String,
    initial: String?,
): String? = runCatching {
    val files = createPlatformLocalFileService()
    val path = "${files.backupRoot.trimEnd('/')}/$suggestedName"
    files.writeBytes(path, bytes)
    path
}.getOrNull()

private val documentPickerLock = Mutex()

private var activeDocumentPickerDelegate: IosDocumentPickerDelegate? = null

private class IosDocumentPickerDelegate(
    private val pending: CompletableDeferred<String?>,
    private val allowedExtensions: Set<String>,
    private val persistReadAccess: Boolean = false,
) : NSObject(), UIDocumentPickerDelegateProtocol {
    override fun documentPicker(
        controller: UIDocumentPickerViewController,
        didPickDocumentsAtURLs: List<*>,
    ) {
        val url = didPickDocumentsAtURLs.firstOrNull() as? NSURL
        val path = if (persistReadAccess) {
            url?.let { selected -> runCatching { IosSecurityScopedBookmarks.persist(selected) }.getOrNull() }
        } else {
            url?.path
        }
        val accepted = path?.takeIf { selected ->
            allowedExtensions.isEmpty() || selected.substringAfterLast('.', "").lowercase() in allowedExtensions
        }
        pending.complete(accepted)
        controller.dismissViewControllerAnimated(true, completion = null)
    }

    override fun documentPickerWasCancelled(controller: UIDocumentPickerViewController) {
        pending.complete(null)
        controller.dismissViewControllerAnimated(true, completion = null)
    }
}

private val wellKnownUtis = mapOf(
    "jar" to "com.sun.java-archive",
    "json" to "public.json",
    "epub" to "org.idpf.epub-container",
    "zip" to "public.zip-archive",
    "cbz" to "public.zip-archive",
)

/**
 * Union of UTIs for every requested extension — a first-match-wins mapping
 * made e.g. `.backup` unselectable whenever `json` was also in the list.
 * Unknown extensions get a dynamic UTI (`dyn.*`) so the picker still filters
 * by extension; only if that fails do we fall back to `public.data`.
 */
internal fun documentTypesFor(extensions: Set<String>): List<String> {
    if (extensions.isEmpty()) return listOf("public.data")
    val types = mutableListOf<String>()
    var unknown = false
    extensions.forEach { ext ->
        val uti = wellKnownUtis[ext]
            ?: platform.UniformTypeIdentifiers.UTType.typeWithFilenameExtension(ext)?.identifier
        if (uti != null) types += uti else unknown = true
    }
    if (unknown || types.isEmpty()) types += "public.data"
    return types.distinct()
}

private fun topViewController(): UIViewController? {
    val activeWindows = UIApplication.sharedApplication.connectedScenes
        .filterIsInstance<UIWindowScene>()
        .filter { scene -> scene.activationState == UISceneActivationStateForegroundActive }
        .flatMap { scene -> scene.windows }
        .filterIsInstance<UIWindow>()
    val window = activeWindows.firstOrNull { candidate -> candidate.isKeyWindow() }
        ?: activeWindows.firstOrNull()
        ?: return null
    var current = window.rootViewController
    while (current?.presentedViewController != null) current = current.presentedViewController
    return current
}

Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/JvmLocalArchiveService.kt

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

The implementation below defines LocalArchiveType, localArchiveType, JvmLocalArchiveService, ArchiveFile, invalidateIndexCache, withArchiveFile, withFreshArchiveFile, listEpubChapters, readEpubChapter, readEpubResource and 21 further declarations.

The source describes its contract as:

Archive kind from the display name, else the provider MIME type (SAF names can be opaque).

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.util.PlatformLock
import java.io.File
import java.io.InputStream
import java.net.URI
import java.security.MessageDigest
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
import java.util.zip.CRC32

internal enum class LocalArchiveType { Epub, Zip, Tar, Rar, Unknown }

/** Archive kind from the display name, else the provider MIME type (SAF names can be opaque). */
internal fun localArchiveType(name: String, mimeType: String?): LocalArchiveType {
    val lowerName = name.lowercase()
    return when {
        lowerName.endsWith(".epub") || mimeType.equals("application/epub+zip", ignoreCase = true) ->
            LocalArchiveType.Epub
        lowerName.endsWith(".cbz") || lowerName.endsWith(".zip") ||
            mimeType.equals("application/zip", ignoreCase = true) -> LocalArchiveType.Zip
        lowerName.endsWith(".cbt") || lowerName.endsWith(".tar") ||
            mimeType.equals("application/x-tar", ignoreCase = true) ||
            mimeType.equals("application/tar", ignoreCase = true) -> LocalArchiveType.Tar
        lowerName.endsWith(".cbr") || lowerName.endsWith(".rar") ||
            mimeType.equals("application/x-rar-compressed", ignoreCase = true) ||
            mimeType.equals("application/x-rar", ignoreCase = true) ||
            mimeType.equals("application/vnd.rar", ignoreCase = true) ||
            mimeType.equals("application/rar", ignoreCase = true) -> LocalArchiveType.Rar
        else -> LocalArchiveType.Unknown
    }
}

/**
 * File-backed archive support shared by desktop and Android: image folders, CBZ/ZIP, CBT/TAR
 * (streamed), CBR/RAR and EPUB. Pages extract once into `cacheRoot/archives/<key>`; those
 * directories are kept least-recently-used within [extractedPagesBudgetBytes].
 *
 * Memory ceiling: archive payloads are streamed and never retained; the metadata caches hold at
 * most 32 archives / 10k page URLs and 32 books / 2k chapters, and the last [MAX_OPEN_EPUBS] EPUBs
 * stay open. Android's SAF subclass overrides [withArchiveFile] to stage `content://` documents.
 */
internal open class JvmLocalArchiveService(
    protected val cacheRoot: String,
    // ponytail: fixed 1 GiB of extracted pages; make it a storage setting if users want a bigger offline cache.
    private val extractedPagesBudgetBytes: Long = 1L shl 30,
) : LocalArchiveService {
    /** An archive readable from disk. [name]/[mimeType] pick the kind because staged copies have temp names. */
    protected class ArchiveFile(
        val file: File,
        val name: String,
        val mimeType: String?,
        val cacheKey: String,
    ) {
        val type: LocalArchiveType get() = localArchiveType(name, mimeType)
    }

    private val imageExtensions = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif")
    private val extracted = BoundedCache<String, List<DbPageUrl>>(maxEntries = 32, maxWeight = 10_000) { it.size }
    private val epubChapterCache = BoundedCache<String, List<LocalEpubChapter>>(maxEntries = 32, maxWeight = 2_000) { it.size }
    private val extractionRoot = File(cacheRoot, "archives").absoluteFile
    private val openEpubsLock = PlatformLock()
    private val openEpubs = LinkedHashMap<String, ZipFile>()

    override fun invalidateIndexCache() = epubChapterCache.clear()

    /** Runs [block] against the on-disk archive for [path]; null when it is not a readable file. */
    protected open fun <T> withArchiveFile(path: String, block: (ArchiveFile) -> T): T? {
        val file = path.toUriFile()
        if (!file.isFile) return null
        return block(ArchiveFile(file, file.name, null, file.cacheKey()))
    }

    protected open fun <T> withFreshArchiveFile(path: String, block: (ArchiveFile) -> T): T? =
        withArchiveFile(path, block)

    override fun listEpubChapters(archivePath: String): List<LocalEpubChapter> {
        if (archivePath.isBlank()) return emptyList()
        return withArchiveFile(archivePath) { archive ->
            epubChapterCache[archive.cacheKey]?.let { return@withArchiveFile it }
            if (archive.type != LocalArchiveType.Epub) return@withArchiveFile emptyList()
            val chapters = runCatching { ZipFile(archive.file).use { zip -> readEpubManifest(zip::readEntry) } }
                .getOrDefault(emptyList())
            epubChapterCache[archive.cacheKey] = chapters
            chapters
        } ?: emptyList()
    }

    override fun readEpubChapter(archivePath: String, index: Int): String {
        val href = listEpubChapters(archivePath).getOrNull(index)?.href ?: return ""
        return readEpubResource(archivePath, href)?.decodeToString().orEmpty()
    }

    override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? {
        if (archivePath.isBlank() || resourcePath.isBlank()) return null
        return withArchiveFile(archivePath) { archive ->
            runCatching { openEpub(archive).readEntry(resourcePath) }.getOrNull()
        }
    }

    /**
     * The book's ZipFile, kept open (LRU by [ArchiveFile.cacheKey]) so each chapter and image read of a
     * reading session skips reopening it. Library scans list chapters with a transient ZipFile instead.
     */
    // ponytail: the last 4 books read stay open, so Windows refuses to delete/rename them until evicted,
    // and closing an evicted book fails a read still running on it (null). Add idle closing if either bites.
    private fun openEpub(archive: ArchiveFile): ZipFile = openEpubsLock.withLock {
        openEpubs.remove(archive.cacheKey)?.let { open ->
            openEpubs[archive.cacheKey] = open
            return@withLock open
        }
        ZipFile(archive.file).also { zip ->
            openEpubs[archive.cacheKey] = zip
            while (openEpubs.size > MAX_OPEN_EPUBS) openEpubs.remove(openEpubs.keys.first())?.close()
        }
    }

    override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? {
        val source = File(directoryPath.removePrefix("file://"))
        if (!source.exists() || !source.isDirectory) return null
        val targetPath = "${source.absolutePath}.cbz"
        val target = File(targetPath)
        target.parentFile?.mkdirs()
        ZipOutputStream(target.outputStream().buffered()).use { zos ->
            val entries = source.walkTopDown()
                .filter { it.isFile && (it.extension.isImageExtension() || it.name == CHAPTER_METADATA_FILE) }
                .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }
                .toList()
            entries.forEach { file ->
                val entry = ZipEntry(file.name)
                entry.time = file.lastModified()
                zos.putNextEntry(entry)
                file.inputStream().use { it.copyTo(zos) }
                zos.closeEntry()
            }
        }
        if (deleteSource) source.deleteRecursively()
        return targetPath
    }

    override fun listPages(archivePath: String): List<DbPageUrl> {
        if (archivePath.isBlank()) return emptyList()
        extracted[archivePath]?.takeIf { it.touchExtraction() }?.let { return it }
        val directory = archivePath.toUriFile()
        val pages = if (directory.isDirectory) {
            directory.listImageFiles().map { it.toPageUrl() }
        } else if (directory.isFile && directory.extension.isImageExtension()) {
            listOf(directory.toPageUrl())
        } else {
            withArchiveFile(archivePath) { archive ->
                val extractedPages = when (archive.type) {
                    LocalArchiveType.Zip -> extractZip(archive)
                    LocalArchiveType.Tar -> extractTar(archive)
                    LocalArchiveType.Rar -> extractRar(archive)
                    LocalArchiveType.Epub, LocalArchiveType.Unknown -> emptyList()
                }
                if (extractedPages.isNotEmpty()) {
                    pruneLeastRecentlyUsed(extractionRoot, keep = File(extractionRoot, archive.cacheKey), maxBytes = extractedPagesBudgetBytes)
                }
                extractedPages
            } ?: return emptyList()
        }
        extracted[archivePath] = pages
        return pages
    }

    override fun listPagesStrict(archivePath: String): List<DbPageUrl> {
        require(archivePath.isNotBlank()) { "Archive path is blank" }
        val directory = archivePath.toUriFile()
        if (directory.isFile && directory.extension.isImageExtension()) {
            directory.validateStrictImage()
            return listOf(directory.toPageUrl())
        }
        if (directory.isDirectory) {
            val files = directory.listFiles() ?: error("Cannot read image directory: $archivePath")
            val images = files.filter { it.isFile && it.extension.isImageExtension() }
                .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }
            images.forEach { image ->
                image.validateStrictImage()
            }
            return images.map { it.toPageUrl() }
        }
        return withFreshArchiveFile(archivePath) { archive ->
            val fresh = File(extractionRoot, "strict-${System.nanoTime()}-${archive.cacheKey}")
            check(fresh.mkdirs()) { "Cannot create archive extraction directory" }
            try {
                val pages = when (archive.type) {
                    LocalArchiveType.Zip -> extractZip(archive, fresh, strict = true)
                    LocalArchiveType.Tar -> extractTar(archive, fresh, strict = true)
                    LocalArchiveType.Rar -> error("Strict RAR inventory is not supported")
                    LocalArchiveType.Epub, LocalArchiveType.Unknown -> error("Unsupported image archive: ${archive.name}")
                }
                pruneLeastRecentlyUsed(extractionRoot, keep = fresh, maxBytes = extractedPagesBudgetBytes)
                pages
            } catch (failure: Throwable) {
                fresh.deleteRecursively()
                throw failure
            }
        } ?: error("Archive is not readable: $archivePath")
    }

    /** Marks the extraction directory behind cached [DbPageUrl]s used; false once it was pruned (re-extract). */
    private fun List<DbPageUrl>.touchExtraction(): Boolean {
        val directory = firstOrNull()?.let { page -> runCatching { File(URI(page.url)).parentFile }.getOrNull() } ?: return true
        if (directory.parentFile != extractionRoot) return true // image folders list their own files
        return directory.setLastModified(System.currentTimeMillis())
    }

    private fun ArchiveFile.extractionDirectory(): File =
        File(extractionRoot, cacheKey).apply {
            mkdirs()
            setLastModified(System.currentTimeMillis())
        }

    private fun extractRar(archive: ArchiveFile): List<DbPageUrl> =
        RarArchiveExtractor.extract(archive.file, archive.extractionDirectory()).map { it.toPageUrl() }

    private fun extractZip(archive: ArchiveFile, target: File = archive.extractionDirectory(), strict: Boolean = false): List<DbPageUrl> {
        ZipFile(archive.file).use { zip ->
            val entries = zip.entries().asSequence()
                .filter { !it.isDirectory && File(it.name).extension.isImageExtension() }
                .filterNot { it.name.startsWith(".") || it.name.contains("/.") }
                .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }
                .toList()
            return entries.mapIndexed { index, entry ->
                val output = File(target, "%04d_%s".format(index, File(entry.name).name))
                if (strict || !output.exists()) {
                    val partial = File(output.path + ".part")
                    try {
                        zip.getInputStream(entry).use { input ->
                            partial.outputStream().use { output ->
                                if (strict) input.copyZipEntryStrict(entry, output) else input.copyTo(output)
                            }
                        }
                        check(partial.renameTo(output)) { "Cannot promote extracted image ${entry.name}" }
                        if (strict) output.validateStrictImage()
                    } catch (failure: Throwable) {
                        partial.delete()
                        output.delete()
                        throw failure
                    }
                }
                output.toPageUrl()
            }
        }
    }

    private fun extractTar(archive: ArchiveFile, target: File = archive.extractionDirectory(), strict: Boolean = false): List<DbPageUrl> {
        val entries = mutableListOf<Pair<String, File>>()
        archive.file.inputStream().buffered().use { stream ->
            var index = 0
            while (true) {
                val header = readTarHeader(stream, strict)
                if (header == null) break
                val (entryName, size, type) = header
                val isImage = (type == '0' || type == 0.toChar()) &&
                    !entryName.startsWith(".") && !entryName.contains("/.") &&
                    File(entryName).extension.isImageExtension()
                val output = if (isImage) File(target, "%04d_%s".format(index++, File(entryName).name)) else null
                if (output != null && (strict || !output.exists())) {
                    try {
                        val partial = File(output.path + ".part")
                        partial.outputStream().buffered().use { stream.transferTarEntry(size, it) }
                        check(partial.renameTo(output)) { "Cannot promote extracted image $entryName" }
                        if (strict) output.validateStrictImage()
                    } catch (failure: Throwable) {
                        output.delete()
                        File(output.path + ".part").delete()
                        throw failure
                    }
                } else {
                    stream.transferTarEntry(size)
                }
                if (strict && isImage && output != null && !output.isFile) error("Truncated TAR image $entryName")
                try {
                    stream.transferTarEntry((512L - size % 512L) % 512L)
                } catch (failure: Throwable) {
                    if (strict) throw failure
                    break
                }
                if (output != null) entries += entryName to output
            }
        }
        return entries.sortedWith { left, right -> naturalPageNameComparator.compare(left.first, right.first) }
            .map { it.second.toPageUrl() }
    }

    private fun File.listImageFiles(): List<File> =
        listFiles()?.filter { it.isFile && it.extension.isImageExtension() }
            ?.sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }
            .orEmpty()

    private fun File.cacheKey(): String {
        val digest = MessageDigest.getInstance("SHA-1")
        digest.update(absolutePath.encodeToByteArray())
        digest.update(lastModified().toString().encodeToByteArray())
        return digest.digest().toHexString()
    }

    private fun String.isImageExtension(): Boolean = lowercase() in imageExtensions

    private fun File.toPageUrl(): DbPageUrl = DbPageUrl(url = toURI().toString(), fileName = name)

    private companion object {
        const val MAX_OPEN_EPUBS = 4
    }
}

private fun InputStream.copyZipEntryStrict(entry: ZipEntry, output: java.io.OutputStream) {
    require(entry.size >= 0 && entry.crc >= 0) { "ZIP image metadata is invalid: ${entry.name}" }
    val crc = CRC32()
    val buffer = ByteArray(64 * 1024)
    var copied = 0L
    while (true) {
        val count = read(buffer)
        if (count < 0) break
        output.write(buffer, 0, count)
        crc.update(buffer, 0, count)
        copied += count
    }
    check(copied == entry.size && crc.value == entry.crc) { "ZIP image is truncated or has a CRC mismatch: ${entry.name}" }
}

/** Decode with a pixel ceiling so corrupt entries and hostile dimensions cannot pass strict inventory. */
private fun File.validateStrictImage() {
    val maxPixels = 16_000_000L
    // Android host-JVM tests have an unmocked BitmapFactory stub; prefer real ImageIO there.
    val androidOptions = if (runCatching { Class.forName("javax.imageio.ImageIO") }.isSuccess) null
        else runCatching { Class.forName("android.graphics.BitmapFactory\$Options") }.getOrNull()
    if (androidOptions != null) {
        val factory = Class.forName("android.graphics.BitmapFactory")
        val options = androidOptions.getDeclaredConstructor().newInstance()
        androidOptions.getField("inJustDecodeBounds").setBoolean(options, true)
        val decodeFile = factory.getMethod("decodeFile", String::class.java, androidOptions)
        decodeFile.invoke(null, absolutePath, options)
        val width = androidOptions.getField("outWidth").getInt(options)
        val height = androidOptions.getField("outHeight").getInt(options)
        require(width > 0 && height > 0 && width.toLong() * height <= maxPixels) { "Unreadable or oversized image: $name" }
        androidOptions.getField("inJustDecodeBounds").setBoolean(options, false)
        androidOptions.getField("inSampleSize").setInt(options, maxOf(1, kotlin.math.ceil(kotlin.math.sqrt(width.toDouble() * height / maxPixels)).toInt()))
        val bitmap = checkNotNull(decodeFile.invoke(null, absolutePath, options)) { "Undecodable image: $name" }
        bitmap.javaClass.getMethod("recycle").invoke(bitmap)
        return
    }

    val imageIo = Class.forName("javax.imageio.ImageIO")
    val imageInput = imageIo.getMethod("createImageInputStream", Any::class.java).invoke(null, this)
        ?: error("Cannot inspect image: $name")
    try {
        val readers = imageIo.getMethod("getImageReaders", Any::class.java).invoke(null, imageInput) as Iterator<*>
        require(readers.hasNext()) { "Undecodable image: $name" }
        val reader = checkNotNull(readers.next())
        val readerApi = Class.forName("javax.imageio.ImageReader")
        try {
            readerApi.getMethod("setInput", Any::class.java).invoke(reader, imageInput)
            val intClass = Int::class.javaPrimitiveType ?: error("Primitive int class is unavailable")
            val width = readerApi.getMethod("getWidth", intClass).invoke(reader, 0) as Int
            val height = readerApi.getMethod("getHeight", intClass).invoke(reader, 0) as Int
            require(width > 0 && height > 0 && width.toLong() * height <= maxPixels) { "Unreadable or oversized image: $name" }
            val bitmap = checkNotNull(readerApi.getMethod("read", intClass).invoke(reader, 0)) { "Undecodable image: $name" }
            bitmap.javaClass.getMethod("flush").invoke(bitmap)
        } finally {
            readerApi.getMethod("dispose").invoke(reader)
        }
    } finally {
        Class.forName("javax.imageio.stream.ImageInputStream").getMethod("close").invoke(imageInput)
    }
}

/** Exact entry first, then the first entry whose name ends with the path (EPUB hrefs are often partial). */
private fun ZipFile.readEntry(path: String): ByteArray? {
    val normalized = normalizeArchivePath(path).takeIf(String::isNotEmpty) ?: return null
    val entry = getEntry(normalized)
        ?: entries().asSequence().firstOrNull { it.name.replace('\\', '/').endsWith(normalized) }
        ?: return null
    return getInputStream(entry).use { it.readBytes() }
}

/**
 * Deletes the least recently modified children of [root] (never [keep]) until at most [maxEntries]
 * remain within [maxBytes]. Callers bump an entry's mtime on use, which makes this an LRU.
 */
internal fun pruneLeastRecentlyUsed(root: File, keep: File, maxBytes: Long, maxEntries: Int = Int.MAX_VALUE) {
    val entries = root.listFiles().orEmpty()
        .map { entry -> Triple(entry, entry.lastModified(), entry.walkTopDown().filter(File::isFile).sumOf(File::length)) }
        .sortedBy { it.second }
    var count = entries.size
    var bytes = entries.sumOf { it.third }
    for ((entry, _, size) in entries) {
        if (count <= maxEntries && bytes <= maxBytes) break
        if (entry == keep) continue
        entry.deleteRecursively()
        count--
        bytes -= size
    }
}

private data class TarHeader(val name: String, val size: Long, val type: Char)

private fun readTarHeader(stream: InputStream, strict: Boolean = false): TarHeader? {
    val header = ByteArray(512)
    if (!stream.readFully(header)) {
        if (strict) throw java.io.EOFException("Truncated TAR header")
        return null
    }
    if (header.all { it == 0.toByte() }) return null
    val name = header.sliceToString(0, 100)
    if (name.isEmpty()) return null
    val size = header.sliceToString(124, 12).toLongOrNull(8) ?: 0L
    return TarHeader(name, size, header[156].toInt().toChar())
}

private fun ByteArray.sliceToString(start: Int, length: Int): String {
    val end = (start + length).coerceAtMost(size)
    val trimmed = sliceArray(start until end).takeWhile { it != 0.toByte() }.toByteArray()
    return trimmed.decodeToString().trim()
}

private fun InputStream.readFully(buffer: ByteArray): Boolean {
    var offset = 0
    while (offset < buffer.size) {
        val read = read(buffer, offset, buffer.size - offset)
        if (read == -1) return false
        offset += read
    }
    return true
}

Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/JvmLocalFileService.kt

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

The implementation below defines JvmLocalFileService, writeBytes, appendBytes, writeChunks, appendChunks, promote, atomicReplaceFile, publishDirectoryIfAbsent, File.isSiblingOf, readBytes and 12 further declarations.

The source describes its contract as:

Plain-filesystem [LocalFileService] shared by desktop and Android (file:// prefixes are accepted). [openDirectory] is the platform shell integration behind [openLocation]; callers without one (tests, headless use) get false. Android wraps this for content:// SAF paths.

package eu.friedcutlet.yokan.services.files

import java.io.File
import java.net.URI
import java.nio.file.AtomicMoveNotSupportedException
import java.nio.file.Files
import java.nio.file.StandardCopyOption.ATOMIC_MOVE
import java.nio.file.StandardCopyOption

/**
 * Plain-filesystem [LocalFileService] shared by desktop and Android (`file://` prefixes are
 * accepted). [openDirectory] is the platform shell integration behind [openLocation]; callers
 * without one (tests, headless use) get `false`. Android wraps this for `content://` SAF paths.
 */
internal class JvmLocalFileService(
    override val downloadRoot: String,
    override val backupRoot: String,
    override val cacheRoot: String,
    private val openDirectory: (File) -> Boolean = { false },
) : LocalFileService {
    override fun writeBytes(path: String, bytes: ByteArray) {
        val file = File(path.removePrefix("file://"))
        file.parentFile?.mkdirs()
        file.writeBytes(bytes)
    }

    override fun appendBytes(path: String, bytes: ByteArray) {
        val file = File(path.removePrefix("file://"))
        file.parentFile?.mkdirs()
        file.appendBytes(bytes)
    }

    override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {
        val file = File(path.removePrefix("file://"))
        file.parentFile?.mkdirs()
        return file.outputStream().use { out -> block { out.write(it) } }
    }

    override suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {
        val file = File(path.removePrefix("file://"))
        file.parentFile?.mkdirs()
        return java.io.FileOutputStream(file, true).use { out -> block { out.write(it) } }
    }

    override fun promote(sourcePath: String, targetPath: String): Boolean {
        val source = File(sourcePath.removePrefix("file://"))
        val target = File(targetPath.removePrefix("file://"))
        if (!source.isFile) return false
        target.parentFile?.mkdirs()
        return runCatching {
            try {
                Files.move(
                    source.toPath(),
                    target.toPath(),
                    StandardCopyOption.ATOMIC_MOVE,
                    StandardCopyOption.REPLACE_EXISTING,
                )
            } catch (_: AtomicMoveNotSupportedException) {
                Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING)
            }
            target.isFile && !source.exists()
        }.getOrDefault(false)
    }

    override fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean {
        val source = File(tempPath.removePrefix("file://"))
        val target = File(finalPath.removePrefix("file://"))
        if (!source.isFile || !source.isSiblingOf(target)) return false
        return runCatching {
            Files.move(source.toPath(), target.toPath(), ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
            target.isFile && !source.exists()
        }.getOrDefault(false)
    }

    override fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean {
        val source = File(stagedPath.removePrefix("file://"))
        val target = File(finalPath.removePrefix("file://"))
        if (!source.isDirectory || !source.isSiblingOf(target) || target.exists()) return false
        return runCatching {
            // ATOMIC_MOVE cannot universally guarantee no-clobber against an adversarial race;
            // callers use unpredictable app-owned job IDs, and the preflight rejects existing targets.
            Files.move(source.toPath(), target.toPath(), ATOMIC_MOVE)
            target.isDirectory && !source.exists()
        }.getOrDefault(false)
    }

    private fun File.isSiblingOf(other: File): Boolean =
        toPath().toAbsolutePath().normalize().parent == other.toPath().toAbsolutePath().normalize().parent

    override fun readBytes(path: String): ByteArray {
        val file = path.toUriFile()
        if (!file.isFile) return ByteArray(0)
        return file.readBytes()
    }

    override fun readBytesBounded(path: String, maxBytes: Long): ByteArray {
        require(maxBytes >= 0) { "maxBytes must not be negative" }
        val file = path.toUriFile()
        require(file.isFile) { "File is not readable: $path" }
        require(maxBytes < Int.MAX_VALUE) { "Bound exceeds ByteArray capacity" }
        file.inputStream().buffered().use { input ->
            val output = java.io.ByteArrayOutputStream(minOf(file.length(), maxBytes).toInt())
            val buffer = ByteArray(16 * 1024)
            var remaining = maxBytes + 1
            while (remaining > 0) {
                val count = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())
                if (count < 0) break
                output.write(buffer, 0, count)
                remaining -= count
            }
            val bytes = output.toByteArray()
            require(bytes.size.toLong() <= maxBytes) { "File exceeds $maxBytes bytes" }
            return bytes
        }
    }

    override fun canonicalPath(path: String): String? =
        runCatching { File(path.removePrefix("file://")).canonicalPath }.getOrNull()

    override fun listFiles(root: String): List<LocalFileEntry> {
        val dir = File(root.removePrefix("file://"))
        if (!dir.isDirectory) return emptyList()
        return dir.listFiles()
            ?.filter { it.isFile }
            ?.sortedByDescending { it.lastModified() }
            ?.map { LocalFileEntry(it.absolutePath, it.name, it.length(), it.lastModified()) }
            .orEmpty()
    }

    override fun exists(path: String): Boolean =
        File(path.removePrefix("file://")).exists()

    override fun deleteRecursively(path: String): Boolean {
        val file = File(path.removePrefix("file://"))
        if (!file.exists()) return true
        return file.deleteRecursively()
    }

    override fun directorySize(path: String): Long {
        val file = File(path.removePrefix("file://"))
        if (!file.exists()) return 0L
        if (file.isFile) return file.length()
        return file.walkTopDown().filter { it.isFile }.sumOf { it.length() }
    }

    override fun openLocation(path: String): Boolean {
        val file = File(path.removePrefix("file://"))
        if (!file.exists()) return false
        return runCatching { openDirectory(if (file.isFile) file.parentFile else file) }.getOrDefault(false)
    }

    override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? =
        File(root.removePrefix("file://")).listFiles()?.asSequence()
            ?.filterNot { Files.isSymbolicLink(it.toPath()) }
            ?.filter { it.isDirectory || it.isFile }
            ?.map { LocalDirectoryEntry(it.absolutePath, it.name, it.isDirectory) }
            ?.sortedBy { it.name.lowercase() }?.toList()

    override fun listLocalEntries(root: String): List<LocalEntry>? {
        val dir = File(root.removePrefix("file://"))
        if (!dir.isDirectory) return null
        val children = dir.listFiles() ?: return null
        val entries = mutableListOf<LocalEntry>()
        children.sortedBy { it.name.lowercase() }.forEach { child ->
            when {
                child.isFile && child.hasReadableExtension() ->
                    entries += LocalEntry(child.absolutePath, child.nameWithoutExtension, isArchive = true)
                child.isDirectory && child.containsReadableFiles() ->
                    entries += LocalEntry(child.absolutePath, child.name, isArchive = false)
                child.isDirectory -> entries += listLocalEntries(child.absolutePath) ?: return null
            }
        }
        return entries
    }

    private fun File.hasReadableExtension(): Boolean = extension.lowercase() in readableLocalFileExtensions

    private fun File.containsReadableFiles(): Boolean =
        listFiles()?.any { it.isFile && it.hasReadableExtension() } == true
}

internal fun String.toUriFile(): File =
    if (startsWith("file:")) File(URI(this)) else File(this)

Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaInput.jvm.kt

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

The implementation below defines JvmLocalMediaInput, readChunks.

package eu.friedcutlet.yokan.services.files

import java.io.InputStream
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.withContext
import kotlinx.coroutines.yield

internal class JvmLocalMediaInput(
    override val relativePath: String,
    override val sizeBytes: Long?,
    private val open: () -> InputStream,
) : LocalMediaInput {
    override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) = withContext(Dispatchers.IO) {
        open().use { input ->
            val buffer = ByteArray(LOCAL_IMPORT_CHUNK_BYTES)
            while (true) {
                currentCoroutineContext().ensureActive()
                val count = runInterruptible { input.read(buffer) }
                if (count < 0) break
                if (count > 0) consume(buffer.copyOf(count))
                else yield()
            }
        }
    }
}

Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/RarArchiveExtractor.kt

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

The implementation below defines RarArchiveExtractor, isImageFile, isZipFile, isRar4, isRar5, extract, extractDisguisedZip, extractRar4, extractRar5, extractViaCli and 3 further declarations.

The source describes its contract as:

Robust RAR archive (RAR4 & RAR5) extractor for CBR and RAR comic archives. Capabilities: - Detects and extracts CBR archives that are actually renamed ZIP files. - Parses RAR4 (Rar!\x1a\x07\x00) store/uncompressed image entries directly in pure Kotlin. - Parses RAR5 (Rar!\x1a\x07\x01\x00) store/uncompressed image entries with vint headers. - CLI fallback (unrar / 7z) for proprietary compressed RAR streams when available.

package eu.friedcutlet.yokan.services.files

import java.io.File
import java.io.RandomAccessFile
import java.util.zip.ZipFile

/**
 * Robust RAR archive (RAR4 & RAR5) extractor for CBR and RAR comic archives.
 *
 * Capabilities:
 * - Detects and extracts CBR archives that are actually renamed ZIP files.
 * - Parses RAR4 (Rar!\x1a\x07\x00) store/uncompressed image entries directly in pure Kotlin.
 * - Parses RAR5 (Rar!\x1a\x07\x01\x00) store/uncompressed image entries with vint headers.
 * - CLI fallback (unrar / 7z) for proprietary compressed RAR streams when available.
 */
object RarArchiveExtractor {
    private val imageExtensions = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif")

    fun isImageFile(name: String): Boolean =
        File(name).extension.lowercase() in imageExtensions

    fun isZipFile(file: File): Boolean {
        if (!file.exists() || file.length() < 4) return false
        return runCatching {
            file.inputStream().use { input ->
                val b0 = input.read()
                val b1 = input.read()
                val b2 = input.read()
                val b3 = input.read()
                b0 == 0x50 && b1 == 0x4B && ((b2 == 0x03 && b3 == 0x04) || (b2 == 0x05 && b3 == 0x06))
            }
        }.getOrDefault(false)
    }

    fun isRar4(magic: ByteArray): Boolean =
        magic.size >= 7 &&
            magic[0] == 0x52.toByte() &&
            magic[1] == 0x61.toByte() &&
            magic[2] == 0x72.toByte() &&
            magic[3] == 0x21.toByte() &&
            magic[4] == 0x1A.toByte() &&
            magic[5] == 0x07.toByte() &&
            magic[6] == 0x00.toByte()

    fun isRar5(magic: ByteArray): Boolean =
        magic.size >= 8 &&
            magic[0] == 0x52.toByte() &&
            magic[1] == 0x61.toByte() &&
            magic[2] == 0x72.toByte() &&
            magic[3] == 0x21.toByte() &&
            magic[4] == 0x1A.toByte() &&
            magic[5] == 0x07.toByte() &&
            magic[6] == 0x01.toByte() &&
            magic[7] == 0x00.toByte()

    /**
     * Extracts images from a RAR or CBR archive to [targetDir].
     * Returns list of extracted image files sorted by filename.
     */
    fun extract(archiveFile: File, targetDir: File): List<File> {
        targetDir.mkdirs()
        if (!archiveFile.exists() || archiveFile.length() < 7) return emptyList()

        if (isZipFile(archiveFile)) {
            return extractDisguisedZip(archiveFile, targetDir)
        }

        val magic = ByteArray(8)
        runCatching {
            archiveFile.inputStream().use { it.read(magic) }
        }

        val entries = when {
            isRar4(magic) -> runCatching { extractRar4(archiveFile, targetDir) }.getOrDefault(emptyList())
            isRar5(magic) -> runCatching { extractRar5(archiveFile, targetDir) }.getOrDefault(emptyList())
            else -> emptyList()
        }

        if (entries.isNotEmpty()) {
            return entries.sortedWith { left, right -> naturalPageNameComparator.compare(left.first, right.first) }
                .map { it.second }
        }

        val cliExtracted = extractViaCli(archiveFile, targetDir)
        if (cliExtracted.isNotEmpty()) {
            return cliExtracted.sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }
        }

        return emptyList()
    }

    private fun extractDisguisedZip(archive: File, targetDir: File): List<File> = runCatching {
        val result = mutableListOf<File>()
        ZipFile(archive).use { zip ->
            val entries = zip.entries().toList()
                .filter { !it.isDirectory && isImageFile(it.name) }
                .filterNot { it.name.startsWith(".") || it.name.contains("/.") }
                .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }
            entries.forEachIndexed { index, entry ->
                val safeName = "%04d_%s".format(index, File(entry.name).name)
                val output = File(targetDir, safeName)
                if (!output.exists()) {
                    zip.getInputStream(entry).use { input ->
                        output.outputStream().use { input.copyTo(it) }
                    }
                }
                result += output
            }
        }
        result
    }.getOrDefault(emptyList())

    private fun extractRar4(archiveFile: File, targetDir: File): List<Pair<String, File>> {
        val extractedFiles = mutableListOf<Pair<String, File>>()
        RandomAccessFile(archiveFile, "r").use { file ->
            file.seek(7) // Skip magic bytes
            var index = 0
            while (file.filePointer + 7 <= file.length()) {
                val headerStart = file.filePointer
                file.readShortLE() // headCrc
                val headType = file.read()
                if (headType == -1) break
                val headFlags = file.readShortLE()
                val headSize = file.readShortLE()
                if (headSize < 7) break

                var addSize = 0L
                if ((headFlags and 0x8000) != 0) {
                    addSize = file.readIntLE()
                }

                if (headType == 0x74) { // FILE_HEAD
                    val packSizeLow = file.readIntLE()
                    val unpSizeLow = file.readIntLE()
                    file.read() // hostOs
                    file.readIntLE() // fileCrc
                    file.readIntLE() // fileTime
                    file.read() // unpVer
                    val method = file.read() // 0x30 = store
                    val nameSize = file.readShortLE()
                    file.readIntLE() // attr

                    val packSize = if ((headFlags and 0x0100) != 0) {
                        val highPack = file.readIntLE()
                        file.readIntLE() // highUnp
                        (highPack shl 32) or packSizeLow
                    } else {
                        packSizeLow
                    }

                    val nameBytes = ByteArray(nameSize.coerceAtLeast(0))
                    if (nameBytes.isNotEmpty()) file.readFully(nameBytes)
                    val rawName = nameBytes.decodeToString()

                    val headerEnd = headerStart + headSize
                    if (file.filePointer < headerEnd) {
                        file.seek(headerEnd)
                    }

                    if (method == 0x30 && isImageFile(rawName) && packSize > 0) {
                        val safeName = "%04d_%s".format(index++, File(rawName).name)
                        val output = File(targetDir, safeName)
                        if (!output.exists()) {
                            val buffer = ByteArray(packSize.toInt())
                            file.readFully(buffer)
                            output.writeBytes(buffer)
                        } else {
                            file.skipBytes(packSize.toInt())
                        }
                        extractedFiles += rawName to output
                    } else {
                        if (packSize > 0) file.skipBytes(packSize.toInt())
                    }
                } else if (headType == 0x7B) { // ENDARC_HEAD
                    break
                } else {
                    val headerEnd = headerStart + headSize
                    if (file.filePointer < headerEnd) file.seek(headerEnd)
                    if (addSize > 0) file.skipBytes(addSize.toInt())
                }
            }
        }
        return extractedFiles
    }

    private fun extractRar5(archiveFile: File, targetDir: File): List<Pair<String, File>> {
        val extractedFiles = mutableListOf<Pair<String, File>>()
        RandomAccessFile(archiveFile, "r").use { file ->
            file.seek(8) // Skip 8-byte RAR5 magic
            var index = 0
            while (file.filePointer < file.length()) {
                file.readIntLE() // header CRC32
                val headerSize = readVint(file)
                if (headerSize <= 0L) break
                val headerDataStart = file.filePointer
                val headerType = readVint(file)
                val headerFlags = readVint(file)

                if ((headerFlags and 0x0001L) != 0L) {
                    readVint(file) // extraSize
                }
                val dataSize = if ((headerFlags and 0x0002L) != 0L) readVint(file) else 0L

                if (headerType == 2L) { // FILE header
                    val fileFlags = readVint(file)
                    readVint(file) // unpackedSize
                    readVint(file) // attributes
                    if ((fileFlags and 0x0002L) != 0L) file.readIntLE() // mtime
                    if ((fileFlags and 0x0004L) != 0L) file.readIntLE() // data CRC32

                    val compInfo = readVint(file)
                    val method = (compInfo.toInt() shr 3) and 0x07
                    readVint(file) // hostOs
                    val nameLength = readVint(file).toInt()
                    val nameBytes = ByteArray(nameLength.coerceAtLeast(0))
                    if (nameBytes.isNotEmpty()) file.readFully(nameBytes)
                    val rawName = nameBytes.decodeToString()

                    val headerDataEnd = headerDataStart + headerSize
                    if (file.filePointer < headerDataEnd) file.seek(headerDataEnd)

                    val isDir = (fileFlags and 0x0001L) != 0L
                    if (!isDir && method == 0 && isImageFile(rawName) && dataSize > 0) {
                        val safeName = "%04d_%s".format(index++, File(rawName).name)
                        val output = File(targetDir, safeName)
                        if (!output.exists()) {
                            val buffer = ByteArray(dataSize.toInt())
                            file.readFully(buffer)
                            output.writeBytes(buffer)
                        } else {
                            file.skipBytes(dataSize.toInt())
                        }
                        extractedFiles += rawName to output
                    } else {
                        if (dataSize > 0) file.skipBytes(dataSize.toInt())
                    }
                } else if (headerType == 5L) { // ENDARC
                    break
                } else {
                    val headerDataEnd = headerDataStart + headerSize
                    if (file.filePointer < headerDataEnd) file.seek(headerDataEnd)
                    if (dataSize > 0) file.skipBytes(dataSize.toInt())
                }
            }
        }
        return extractedFiles
    }

    private fun extractViaCli(archive: File, targetDir: File): List<File> {
        val commands = listOf(
            listOf("unrar", "e", "-y", "-o+", archive.absolutePath, targetDir.absolutePath),
            listOf("7z", "e", "-y", "-o${targetDir.absolutePath}", archive.absolutePath),
            listOf("7za", "e", "-y", "-o${targetDir.absolutePath}", archive.absolutePath),
            listOf("unar", "-o", targetDir.absolutePath, "-f", archive.absolutePath),
        )
        for (cmd in commands) {
            val success = runCatching {
                val proc = ProcessBuilder(cmd)
                    .redirectErrorStream(true)
                    .start()
                val exited = proc.waitFor()
                exited == 0
            }.getOrDefault(false)

            if (success) {
                val files = targetDir.walkTopDown()
                    .filter { it.isFile && isImageFile(it.name) }
                    .toList()
                if (files.isNotEmpty()) return files
            }
        }
        return emptyList()
    }

    private fun readVint(file: RandomAccessFile): Long {
        var result = 0L
        var shift = 0
        for (i in 0 until 10) {
            val b = file.read()
            if (b == -1) break
            result = result or ((b.toLong() and 0x7f) shl shift)
            if ((b and 0x80) == 0) break
            shift += 7
        }
        return result
    }

    private fun RandomAccessFile.readShortLE(): Int {
        val b0 = read()
        val b1 = read()
        if (b0 == -1 || b1 == -1) return -1
        return (b0 and 0xff) or ((b1 and 0xff) shl 8)
    }

    private fun RandomAccessFile.readIntLE(): Long {
        val b0 = read()
        val b1 = read()
        val b2 = read()
        val b3 = read()
        if (b0 == -1 || b1 == -1 || b2 == -1 || b3 == -1) return -1L
        return ((b0.toLong() and 0xff)) or
            ((b1.toLong() and 0xff) shl 8) or
            ((b2.toLong() and 0xff) shl 16) or
            ((b3.toLong() and 0xff) shl 24)
    }
}

Write composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/TarStreams.kt

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

The implementation below defines InputStream.transferTarEntry.

The source describes its contract as:

Transfers a TAR payload with bounded memory, or skips it without materializing it.

package eu.friedcutlet.yokan.services.files

import java.io.EOFException
import java.io.InputStream
import java.io.OutputStream

/** Transfers a TAR payload with bounded memory, or skips it without materializing it. */
internal fun InputStream.transferTarEntry(size: Long, output: OutputStream? = null) {
    require(size >= 0) { "Negative TAR entry size" }
    var remaining = size
    val buffer = if (output != null) ByteArray(minOf(size, 64 * 1024L).toInt()) else null
    while (remaining > 0) {
        if (output == null) {
            val skipped = skip(remaining)
            if (skipped > 0) {
                remaining -= skipped
            } else {
                if (read() < 0) throw EOFException("Truncated TAR entry")
                remaining--
            }
        } else {
            val bytes = checkNotNull(buffer)
            val count = read(bytes, 0, minOf(remaining, bytes.size.toLong()).toInt())
            if (count < 0) throw EOFException("Truncated TAR entry")
            if (count == 0) {
                val byte = read()
                if (byte < 0) throw EOFException("Truncated TAR entry")
                output.write(byte)
                remaining--
            } else {
                output.write(bytes, 0, count)
                remaining -= count
            }
        }
    }
}

Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/files/LocalFileService.wasm.kt

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

The implementation below defines WasmSelectedFileStore, put, take, BrowserFileStores, get, createPlatformLocalFileService, createPlatformLocalArchiveService, WasmLocalArchiveService, invalidateIndexCache, listPages and 66 further declarations.

The source describes its contract as:

OPFS owns downloaded bytes; the synchronous interface is restricted to metadata and legacy backups.

Cross-chapter imports used by this file: ProfileId, ProfileStorageNamespace, DbPageUrl. Keep those contracts available as you connect this step.

@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
import eu.friedcutlet.yokan.database.DatabaseJson
import eu.friedcutlet.yokan.database.DbPageUrl
import io.ktor.http.URLBuilder
import kotlinx.browser.localStorage
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.await
import kotlinx.coroutines.withContext
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.serialization.Serializable
import kotlin.io.encoding.Base64
import kotlin.js.JsAny
import kotlin.js.JsString
import kotlin.js.Promise

internal object WasmSelectedFileStore {
    private var nextId = 0L
    private val files = mutableMapOf<String, ByteArray>()
    fun put(bytes: ByteArray, fileName: String): String {
        val path = "/yokan/selected-file/${nextId++}/${fileName.ifBlank { "selected-file" }}"
        files[path] = bytes
        return path
    }
    fun take(path: String): ByteArray? = files.remove(path)
}

private object BrowserFileStores {
    private val stores = mutableMapOf<ProfileId, WasmLocalFileService>()
    fun get(id: ProfileId): WasmLocalFileService = stores.getOrPut(id) { WasmLocalFileService(id) { stores.remove(id) } }
}

actual fun createPlatformLocalFileService(profileId: ProfileId): LocalFileService = BrowserFileStores.get(profileId)
actual fun createPlatformLocalArchiveService(profileId: ProfileId): LocalArchiveService = WasmLocalArchiveService(BrowserFileStores.get(profileId))

private class WasmLocalArchiveService(private val files: WasmLocalFileService) : LocalArchiveService {
    private val epubChapters = BoundedCache<LocalFileEntry, List<LocalEpubChapter>>(32, 2000) { it.size }
    override fun invalidateIndexCache() = epubChapters.clear()
    override fun listPages(archivePath: String): List<DbPageUrl> = emptyList()
    override suspend fun listPagesAsync(archivePath: String): List<DbPageUrl> {
        files.prepare()
        if (archivePath.substringAfterLast('.').lowercase() in ImageExtensions && files.exists(archivePath)) {
            return listOf(DbPageUrl(files.readableUrl(archivePath), archivePath.substringAfterLast('/')))
        }
        if (archivePath.substringAfterLast('.').lowercase() in setOf("cbz", "zip")) {
            val url = files.readableUrl(archivePath)
            return files.archiveEntries(archivePath).filter { it.name.substringAfterLast('.').lowercase() in ImageExtensions }
                .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }
                .map { entry -> DbPageUrl(url = URLBuilder(url).apply { parameters.append("entry", entry.name) }.buildString(), fileName = entry.name) }
        }
        return files.listFiles(archivePath).filter { it.name.substringAfterLast('.').lowercase() in ImageExtensions }
            .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }
            .map { DbPageUrl(url = files.readableUrl(it.path), fileName = it.name) }
    }
    override fun listEpubChapters(archivePath: String): List<LocalEpubChapter> = emptyList()
    override fun readEpubChapter(archivePath: String, index: Int): String = ""
    override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null
    override suspend fun listEpubChaptersAsync(archivePath: String): List<LocalEpubChapter> {
        files.prepare()
        val fingerprint = files.listFiles(archivePath.substringBeforeLast('/', "")).firstOrNull { it.path == archivePath }
        fingerprint?.let { epubChapters[it] }?.let { return it }
        val chapters = eu.friedcutlet.yokan.services.catchingNonCancellation {
            files.withArchive(archivePath) { session ->
                var remaining = 64L * 1024 * 1024
                var reads = 0
                readEpubManifestAsync { name ->
                    val maximum = if (reads++ < 2) 1024 * 1024 else 8 * 1024 * 1024
                    readArchiveSession(session, name, minOf(maximum.toLong(), remaining).toInt())?.also { remaining -= it.size }
                }
            }
        }.getOrDefault(emptyList())
        if (fingerprint != null && chapters.isNotEmpty()) epubChapters[fingerprint] = chapters
        return chapters
    }
    override suspend fun readEpubChapterAsync(archivePath: String, index: Int): String {
        val chapter = listEpubChaptersAsync(archivePath).getOrNull(index) ?: error("EPUB chapter is unavailable")
        return files.withArchive(archivePath) { session ->
            requireNotNull(readArchiveSession(session, chapter.href, 8 * 1024 * 1024)) { "EPUB chapter is missing" }.decodeToString()
        }
    }
    override suspend fun readEpubResourceAsync(archivePath: String, resourcePath: String): ByteArray? =
        eu.friedcutlet.yokan.services.catchingNonCancellation {
            files.withArchive(archivePath) { session -> readArchiveSession(session, resourcePath, 16 * 1024 * 1024) }
        }.getOrNull()
    override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? = null
    override suspend fun zipDirectoryToCbzAsync(directoryPath: String, deleteSource: Boolean): String? = files.zip(directoryPath, deleteSource)
    private companion object { val ImageExtensions = setOf("jpg", "jpeg", "png", "gif", "webp", "bmp", "avif") }
}

@Serializable
private data class BrowserStoredFile(val path: String, val name: String, val sizeBytes: Long, val lastModified: Long)

@Serializable
private data class BrowserArchiveEntry(val name: String, val size: Long)

@Serializable
private data class BrowserLocalEntry(val path: String, val name: String, val isArchive: Boolean)

/** OPFS owns downloaded bytes; the synchronous interface is restricted to metadata and legacy backups. */
private class WasmLocalFileService(profileId: ProfileId, private val onClosed: () -> Unit) : LocalFileService {
    private val root = ProfileStorageNamespace(profileId).ownedRoot("/yokan")
    override val downloadRoot = "$root/downloads"
    override val backupRoot = "$root/backups"
    override val cacheRoot = "$root/cache"
    private val store by lazy { browserStore(root) }
    private val storagePrefix = "yokan-backup-file:"

    override suspend fun prepare() { prepareStore(store).await<JsAny?>() }
    suspend fun archiveEntries(path: String): List<BrowserArchiveEntry> = DatabaseJson.decodeFromString(archiveEntriesStore(store, path).await<JsString>().toString())
    suspend fun <T> withArchive(path: String, block: suspend (JsAny) -> T): T {
        val session = withContext(NonCancellable) { openArchiveStore(store, path).await<JsAny>() }
        return try {
            currentCoroutineContext().ensureActive()
            block(session)
        } finally { withContext(NonCancellable) { closeArchiveSession(session).await<JsAny?>() } }
    }
    suspend fun zip(path: String, deleteSource: Boolean): String? = withContext(NonCancellable) { zipStore(store, path, deleteSource).await<JsString?>()?.toString() }
    override suspend fun awaitPersistence() { flushStore(store).await<JsAny?>() }
    override suspend fun close() { closeStore(store).await<JsAny?>(); onClosed() }

    override fun writeBytes(path: String, bytes: ByteArray) {
        if (path.startsWith("$backupRoot/")) localStorage.setItem(storagePrefix + path, Base64.encode(bytes))
        else writeStoreDeferred(store, path, Base64.encode(bytes))
    }
    override suspend fun writeBytesAsync(path: String, bytes: ByteArray) {
        if (path.startsWith("$backupRoot/")) writeBytes(path, bytes)
        else writeStore(store, path, Base64.encode(bytes)).await<JsAny?>()
    }
    override fun readBytes(path: String): ByteArray = WasmSelectedFileStore.take(path)
        ?: localStorage.getItem(storagePrefix + path)?.let(Base64::decode)
        ?: cachedStore(store, path)?.let(Base64::decode)
        ?: error("Use asynchronous reads for browser file content")

    override fun readBytesBounded(path: String, maxBytes: Long): ByteArray {
        val bytes = readBytes(path)
        require(bytes.size.toLong() <= maxBytes) { "File exceeds the read limit" }
        return bytes
    }
    override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray {
        WasmSelectedFileStore.take(path)?.let { require(it.size.toLong() <= maxBytes); return it }
        localStorage.getItem(storagePrefix + path)?.let { require(base64DecodedSize(it) <= maxBytes); return Base64.decode(it) }
        return Base64.decode(readStore(store, path, maxBytes.coerceAtMost(Int.MAX_VALUE.toLong()).toDouble()).await<JsString>().toString())
    }

    override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T = chunks(path, false, block)
    override suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T = chunks(path, true, block)
    private suspend fun <T> chunks(path: String, append: Boolean, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {
        // Promise cancellation cannot undo a browser writer opened after await was cancelled.
        withContext(NonCancellable) { beginStore(store, path, append).await<JsAny?>() }
        var failure: Throwable? = null
        try {
            currentCoroutineContext().ensureActive()
            return block { bytes -> chunkStore(store, path, Base64.encode(bytes)).await<JsAny?>() }
        }
        catch (error: Throwable) { failure = error; throw error }
        finally {
            // Retain partial bytes for ETag-validated resume. Join disk writes before retirement.
            withContext(NonCancellable) {
                try { endStore(store, path, true).await<JsAny?>() }
                catch (closing: Throwable) { if (failure == null) throw closing else failure.addSuppressed(closing) }
            }
        }
    }

    override fun canonicalPath(path: String): String? = path.takeIf {
        it.startsWith("$root/") && it.split('/').none { segment -> segment == "." || segment == ".." || '\\' in segment }
    }
    private fun isBackupPath(path: String): Boolean = path == backupRoot || path.startsWith("$backupRoot/")
    override fun exists(path: String): Boolean = if (isBackupPath(path)) storedBackups().any { it == path || it.startsWith("$path/") } else existsStore(store, path)
    override fun deleteRecursively(path: String): Boolean {
        if (!isBackupPath(path)) return false
        storedBackups().filter { it == path || it.startsWith("$path/") }.forEach { localStorage.removeItem(storagePrefix + it) }
        return true
    }
    override suspend fun deleteRecursivelyAsync(path: String): Boolean {
        if (isBackupPath(path)) return deleteRecursively(path)
        removeStore(store, path).await<JsAny?>()
        return true
    }
    override suspend fun promoteAsync(sourcePath: String, targetPath: String): Boolean {
        promoteStore(store, sourcePath, targetPath).await<JsAny?>()
        return true
    }
    override suspend fun readableUrl(path: String): String = urlStore(store, path.removePrefix("file://")).await<JsString>().toString()
    override fun directorySize(path: String): Long = if (isBackupPath(path)) storedBackups().filter { it == path || it.startsWith("$path/") }
        .sumOf { localStorage.getItem(storagePrefix + it)?.let(::base64DecodedSize) ?: 0L } else sizeStore(store, path).toLong()
    override fun openLocation(path: String): Boolean = false
    override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? =
        DatabaseJson.decodeFromString<List<LocalDirectoryEntry>?>(directoryEntriesStore(store, root))

    override fun listLocalEntries(root: String): List<LocalEntry>? {
        val encoded = localEntriesStore(store, root, readableLocalFileExtensions.joinToString(","))
        return DatabaseJson.decodeFromString<List<BrowserLocalEntry>?>(encoded)?.map { LocalEntry(it.path, it.name, it.isArchive) }
    }
    override fun listFiles(root: String): List<LocalFileEntry> = if (isBackupPath(root)) storedBackups().filter { it.substringBeforeLast('/') == root }
        .map { LocalFileEntry(it, it.substringAfterLast('/'), directorySize(it), 0) }
        else DatabaseJson.decodeFromString<List<BrowserStoredFile>>(listStore(store, root)).map { LocalFileEntry(it.path, it.name, it.sizeBytes, it.lastModified) }

    private fun storedBackups(): List<String> = (0 until localStorage.length).mapNotNull { index ->
        localStorage.key(index)?.takeIf { it.startsWith(storagePrefix) }?.removePrefix(storagePrefix)
    }
}

internal fun base64DecodedSize(encoded: String): Long = encoded.length * 3L / 4 - encoded.takeLast(2).count { it == '=' }

private fun browserStore(root: String): JsAny = js("globalThis.yokanBrowserFiles.open(root)")
private fun openArchiveStore(store: JsAny, path: String): Promise<JsAny> = js("store.openArchive(path)")
private fun archiveSessionRead(session: JsAny, name: String, maximum: Int): Promise<JsString?> = js("session.read(name, maximum)")
private fun closeArchiveSession(session: JsAny): Promise<JsAny?> = js("session.close().then(() => null)")
private suspend fun readArchiveSession(session: JsAny, name: String, maximum: Int): ByteArray? {
    currentCoroutineContext().ensureActive()
    // Cancelling a Promise await does not stop JS decompression. Join the bounded read
    // before its owner closes the ZIP/session or retires the profile's file storage.
    val encoded = try {
        withContext(NonCancellable) { archiveSessionRead(session, name, maximum).await<JsString?>() }
    } finally { currentCoroutineContext().ensureActive() }
    return encoded?.toString()?.let(Base64::decode)
}
private fun prepareStore(store: JsAny): Promise<JsAny?> = js("store.prepare().then(() => null)")
private fun archiveEntriesStore(store: JsAny, path: String): Promise<JsString> = js("store.archiveEntries(path)")
private fun zipStore(store: JsAny, path: String, deleteSource: Boolean): Promise<JsString?> = js("store.zip(path, deleteSource)")
private fun flushStore(store: JsAny): Promise<JsAny?> = js("store.flush().then(() => null)")
private fun closeStore(store: JsAny): Promise<JsAny?> = js("store.close().then(() => null)")
private fun writeStoreDeferred(store: JsAny, path: String, bytes: String): Unit = js("store.write(path, bytes).catch(() => {})")
private fun writeStore(store: JsAny, path: String, bytes: String): Promise<JsAny?> = js("store.write(path, bytes).then(() => null)")
private fun cachedStore(store: JsAny, path: String): String? = js("store.cached(path)")
private fun readStore(store: JsAny, path: String, maximum: Double): Promise<JsString> = js("store.read(path, maximum)")
private fun beginStore(store: JsAny, path: String, append: Boolean): Promise<JsAny?> = js("store.begin(path, append).then(() => null)")
private fun chunkStore(store: JsAny, path: String, bytes: String): Promise<JsAny?> = js("store.chunk(path, bytes).then(() => null)")
private fun endStore(store: JsAny, path: String, commit: Boolean): Promise<JsAny?> = js("store.end(path, commit).then(() => null)")
private fun removeStore(store: JsAny, path: String): Promise<JsAny?> = js("store.remove(path).then(() => null)")
private fun promoteStore(store: JsAny, source: String, target: String): Promise<JsAny?> = js("store.promote(source, target).then(() => null)")
private fun urlStore(store: JsAny, path: String): Promise<JsString> = js("store.url(path)")
private fun listStore(store: JsAny, path: String): String = js("store.list(path)")
private fun localEntriesStore(store: JsAny, path: String, extensions: String): String = js("store.localEntries(path, extensions)")
private fun directoryEntriesStore(store: JsAny, path: String): String = js("store.directoryEntries(path)")
private fun existsStore(store: JsAny, path: String): Boolean = js("store.exists(path)")
private fun sizeStore(store: JsAny, path: String): Double = js("store.size(path)")

Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/files/LocalMediaSelection.wasm.kt

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

The implementation below defines BrowserSelectedMedia, pickLocalMedia, browserMediaSelection, readChunks, createMediaPicker, mediaPickerResult, cancelMediaPicker, mediaMetadata, mediaChunk, closeMediaSelection.

@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.database.DatabaseJson
import kotlin.io.encoding.Base64
import kotlin.js.JsAny
import kotlin.js.JsString
import kotlin.js.Promise
import kotlinx.coroutines.await
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.serialization.Serializable

@Serializable
private data class BrowserSelectedMedia(val path: String, val size: Long)

actual suspend fun pickLocalMedia(directory: Boolean): LocalMediaSelection? {
    // Invoked synchronously from the click handler before the first suspension (browser activation).
    val picker = createMediaPicker(directory)
    try {
        val selection = mediaPickerResult(picker).await<JsAny?>() ?: return null
        return browserMediaSelection(selection)
    } catch (error: Throwable) {
        cancelMediaPicker(picker)
        throw error
    }
}

internal fun browserMediaSelection(selection: JsAny): LocalMediaSelection {
    val metadata = try { DatabaseJson.decodeFromString<List<BrowserSelectedMedia>>(mediaMetadata(selection)) }
        catch (error: Throwable) { closeMediaSelection(selection); throw error }
    return LocalMediaSelection(metadata.mapIndexed { index, file ->
        object : LocalMediaInput {
            override val relativePath = file.path
            override val sizeBytes = file.size
            override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) {
                var offset = 0L
                while (offset < sizeBytes) {
                    currentCoroutineContext().ensureActive()
                    val encoded = mediaChunk(selection, index, offset.toDouble()).await<JsString>().toString()
                    val bytes = Base64.decode(encoded)
                    check(bytes.isNotEmpty() && bytes.size <= LOCAL_IMPORT_CHUNK_BYTES) { "Invalid selected-file chunk" }
                    consume(bytes)
                    offset += bytes.size
                }
            }
        }
    }) { closeMediaSelection(selection) }
}

private fun createMediaPicker(directory: Boolean): JsAny = js("globalThis.yokanBrowserFiles.pickMedia(directory)")
private fun mediaPickerResult(picker: JsAny): Promise<JsAny?> = js("picker.result")
private fun cancelMediaPicker(picker: JsAny): Unit = js("picker.cancel()")
private fun mediaMetadata(selection: JsAny): String = js("selection.metadata()")
private fun mediaChunk(selection: JsAny, index: Int, offset: Double): Promise<JsString> = js("selection.chunk(index, offset)")
private fun closeMediaSelection(selection: JsAny): Unit = js("selection.close()")

Write composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.wasm.kt

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

The implementation below defines pickFolder, pickFile, cleanup, finish, exportFile.

The source describes its contract as:

Exports route through the browser's download UI instead of a save dialog.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.services.system.triggerBrowserDownload
import kotlin.coroutines.resume
import kotlinx.browser.document
import kotlinx.coroutines.suspendCancellableCoroutine
import org.khronos.webgl.ArrayBuffer
import org.khronos.webgl.Uint8Array
import org.khronos.webgl.get
import org.w3c.dom.HTMLInputElement
import org.w3c.files.FileReader

// Browsers do not expose a user-visible folder picker.
actual suspend fun pickFolder(initial: String?): String? = null

@OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
actual suspend fun pickFile(extensions: List<String>, initial: String?): String? {
    val body = document.body ?: return null
    val input = document.createElement("input") as HTMLInputElement
    input.type = "file"
    input.hidden = true
    input.accept = extensions
        .filter(String::isNotBlank)
        .joinToString(",") { if (it.startsWith(".")) it else ".$it" }
    body.appendChild(input)

    var selectedFileName = ""
    val file = suspendCancellableCoroutine<ByteArray?> { continuation ->
        val reader = FileReader()
        var finished = false

        fun cleanup() {
            input.onchange = null
            input.oncancel = null
            reader.onload = null
            reader.onerror = null
            reader.onabort = null
            input.remove()
        }

        fun finish(bytes: ByteArray?) {
            if (finished) return
            finished = true
            cleanup()
            if (continuation.isActive) continuation.resume(bytes)
        }

        input.onchange = {
            val selected = input.files?.item(0)
            if (selected == null) {
                finish(null)
            } else {
                selectedFileName = selected.name
                reader.onload = {
                    val buffer = reader.result as? ArrayBuffer
                    if (buffer == null) {
                        finish(null)
                    } else {
                        val data = Uint8Array(buffer)
                        finish(ByteArray(data.length) { data[it] })
                    }
                }
                reader.onerror = { finish(null) }
                reader.onabort = { finish(null) }
                reader.readAsArrayBuffer(selected)
            }
        }
        input.oncancel = { finish(null) }
        continuation.invokeOnCancellation {
            if (!finished) {
                finished = true
                cleanup()
                if (reader.readyState == FileReader.LOADING) reader.abort()
            }
        }
        input.click()
    }

    return file?.let { bytes ->
        WasmSelectedFileStore.put(bytes, selectedFileName)
    }
}

/** Exports route through the browser's download UI instead of a save dialog. */
actual suspend fun exportFile(
    bytes: ByteArray,
    suggestedName: String,
    mimeType: String,
    initial: String?,
): String? = if (triggerBrowserDownload(bytes, suggestedName, mimeType)) suggestedName else null

Check your understanding

Cancel a read/extraction on each adapter and check owned cache cleanup. Reopen external content after restart and distinguish a lost grant from an empty folder. [chapter-content-end]: #

Step 3: build the scan/import pipeline

Implement LocalMediaImporter, LocalLibraryService, path identity and models. Classify manga folders/archives, novels/EPUB and anime videos/folders with the original extension/structure rules. Import metadata, covers, chapters/episodes and season trees. Optional metadata errors should degrade gracefully without deleting existing user state. The existing metadata read bound is 64 KiB and cover read bound 4 MiB.

Capture a scan candidate, read files asynchronously, then reread the current database records inside the transaction before applying. Preserve concurrent progress, categories, private notes, bookmarks and cover changes; do not recreate a record deleted or rebound while scanning. Fingerprint caching is an optimization, not an excuse to ignore changed files.

Follow the code

Classification identifies loose pages, archives, EPUBs and video/season layouts. Candidate construction reads metadata and covers asynchronously with bounds, then produces proposed records. Keep that work separate from committing database changes. Optional sidecar/cover failure can degrade one candidate without deleting existing user state. Stable path identity prevents each scan from importing duplicates.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryModels.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalMediaImporter.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryController.kt

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryModels.kt

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

The implementation below defines LocalLibraryOverview, LocalMetadataSourceState, localTrackerSearchSupported, LocalMetadataSourceResult.

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.metadata.MetadataMedia

data class LocalLibraryOverview(
    val folders: List<DbLocalFolder>,
    val manga: Int,
    val anime: Int,
    val novels: Int,
    val lastScan: LocalLibraryScanResult? = null,
    val scanRunning: Boolean = false,
    val scanError: String? = null,
    val reconciliation: LocalLibraryReconciliationResult? = null,
)

enum class LocalMetadataSourceState { Results, NoResults, Offline, Error, Unsupported }

internal fun localTrackerSearchSupported(itemType: ItemType): Boolean = itemType != ItemType.Novel

data class LocalMetadataSourceResult(
    val source: String,
    val state: LocalMetadataSourceState,
    val candidates: List<MetadataMedia> = emptyList(),
    val message: String? = null,
)

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalMediaImporter.kt

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

The implementation below defines LocalImportProgress, LocalImportPhase, LocalImportFile, PendingLocalImport, LocalMediaImporter, import, report, pending, recover, discardIncomplete and 11 further declarations.

The source describes its contract as:

Journal stays outside scanned roots. A ready import survives a failed settings write/restart.

Cross-chapter imports used by this file: SettingsStore, DbItemType, DbLocalFolder, normalizeLocalFolders, SyncIds, nowMillis. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DatabaseJson
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.configuredLocalFolders
import eu.friedcutlet.yokan.database.normalizeLocalFolders
import eu.friedcutlet.yokan.database.sync.SyncIds
import eu.friedcutlet.yokan.services.files.*
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable

data class LocalImportProgress(val filesDone: Int, val filesTotal: Int, val bytesDone: Long)

@Serializable
enum class LocalImportPhase { Copying, Ready }

@Serializable
data class LocalImportFile(val path: String, val size: Long)

/** Journal stays outside scanned roots. A ready import survives a failed settings write/restart. */
@Serializable
data class PendingLocalImport(
    val id: String,
    val name: String,
    val type: DbItemType,
    val phase: LocalImportPhase = LocalImportPhase.Copying,
    val files: List<LocalImportFile> = emptyList(),
)

/** Profile-owned import. Settings membership is the publication boundary on every filesystem. */
class LocalMediaImporter(
    private val files: LocalFileService,
    private val settings: SettingsStore,
    private val persistSettings: suspend () -> Unit = {},
    private val newId: () -> String = { SyncIds.random().toString() },
    private val progressClockMillis: () -> Long = ::nowMillis,
) {
    private val mutex = Mutex()
    private val root = "${files.downloadRoot.trimEnd('/')}/local-imports"

    suspend fun import(
        selection: LocalMediaSelection,
        type: DbItemType,
        progress: (LocalImportProgress) -> Unit = {},
    ): DbLocalFolder = mutex.withLock {
        files.prepare()
        val selected = selection.files.filter { it.relativePath.substringAfterLast('.', "").lowercase() in localImportExtensions }
        require(selected.size in 1..LOCAL_IMPORT_MAX_FILES) { "Select between 1 and $LOCAL_IMPORT_MAX_FILES supported files" }
        require(selected.any { it.relativePath.substringAfterLast('.', "").lowercase() in readableLocalFileExtensions }) { "No supported media files selected" }
        validatePaths(selected.map { it.relativePath })
        require(selected.all { it.sizeBytes == null || requireNotNull(it.sizeBytes) >= 0 }) { "Invalid file size" }
        val id = newId().also(::validateId)
        checkOwnedRoot(id)
        check(!files.exists("$root/$id") && !files.exists(journalPath(id))) { "Import identity already exists" }
        var journal = PendingLocalImport(id, selectionName(selected.first().relativePath), type)
        val content = contentPath(journal)
        // Written before any content: interrupted copies cannot accidentally become scanned originals.
        writeJournal(journal)
        var ready = false
        try {
            var bytesDone = 0L
            val copied = mutableListOf<LocalImportFile>()
            var lastProgress = progressClockMillis()
            fun report(done: Int, force: Boolean = false) {
                val now = progressClockMillis()
                if (force || now < lastProgress || now - lastProgress >= 200) {
                    progress(LocalImportProgress(done, selected.size, bytesDone))
                    lastProgress = now
                }
            }
            report(0, force = true)
            selected.forEachIndexed { index, input ->
                currentCoroutineContext().ensureActive()
                checkOwnedRoot(id)
                var count = 0L
                check(!files.exists("$content/${input.relativePath}")) { "Conflicting import filenames" }
                files.writeChunks("$content/${input.relativePath}") { write ->
                    // Also creates zero-byte sidecars on implementations whose default writer is lazy.
                    write(ByteArray(0))
                    input.readChunks { chunk ->
                        currentCoroutineContext().ensureActive()
                        require(chunk.size <= LOCAL_IMPORT_CHUNK_BYTES) { "Import reader exceeded its memory bound" }
                        check(count <= Long.MAX_VALUE - chunk.size && bytesDone <= Long.MAX_VALUE - chunk.size) { "Import size overflow" }
                        count += chunk.size
                        input.sizeBytes?.let { check(count <= it) { "Selected file changed while importing" } }
                        write(chunk)
                        bytesDone += chunk.size
                        report(index)
                    }
                }
                input.sizeBytes?.let { check(count == it) { "Selected file changed while importing" } }
                copied += LocalImportFile(input.relativePath, count)
                report(index + 1, force = index == selected.lastIndex)
            }
            currentCoroutineContext().ensureActive()
            journal = journal.copy(phase = LocalImportPhase.Ready, files = copied)
            // Cancellation of a Promise does not cancel its disk write. Join before changing phase.
            withContext(NonCancellable) { writeJournal(journal); ready = true }
            currentCoroutineContext().ensureActive()
            publish(journal)
        } catch (failure: Throwable) {
            // A READY import might already be published. Never delete its content, even on a save error.
            if (!ready) withContext(NonCancellable) {
                try {
                    checkOwnedRoot(id)
                    check(files.deleteRecursivelyAsync("$root/$id")) { "Could not remove partial import" }
                    check(files.deleteRecursivelyAsync(journalPath(id))) { "Could not remove import journal" }
                } catch (cleanup: Throwable) { failure.addSuppressed(cleanup) }
            }
            throw failure
        }
    }

    suspend fun pending(): List<PendingLocalImport> = mutex.withLock { pendingUnlocked() }

    /** Explicitly finish a complete copy after restart/save failure; validates every committed file. */
    suspend fun recover(id: String): DbLocalFolder = mutex.withLock {
        val journal = pendingUnlocked().single { it.id == id }
        require(journal.phase == LocalImportPhase.Ready) { "Incomplete copies must be selected again" }
        publish(journal)
    }

    /** Only COPY journals can be discarded. READY content may already have been a user's original. */
    suspend fun discardIncomplete(id: String) = mutex.withLock {
        val journal = pendingUnlocked().single { it.id == id }
        require(journal.phase == LocalImportPhase.Copying) { "Completed imports cannot be discarded here" }
        checkOwnedRoot(id)
        require(settings.db.value.configuredLocalFolders().none { pathsOverlap(it.path, "$root/$id") }) { "Import is already in use" }
        check(files.deleteRecursivelyAsync("$root/$id")) { "Could not remove partial import" }
        check(files.deleteRecursivelyAsync(journalPath(id))) { "Could not remove import journal" }
    }

    private suspend fun publish(journal: PendingLocalImport): DbLocalFolder {
        checkOwnedRoot(journal.id)
        validatePaths(journal.files.map { it.path })
        require(journal.files.isNotEmpty() && journal.files.size <= LOCAL_IMPORT_MAX_FILES)
        val content = contentPath(journal)
        journal.files.forEach {
            check(it.size >= 0 && files.exists("$content/${it.path}") && files.directorySize("$content/${it.path}") == it.size) { "Imported file is missing or changed: ${it.path}" }
        }
        currentCoroutineContext().ensureActive()
        var published: DbLocalFolder? = null
        settings.updateDb { db ->
            val configured = db.configuredLocalFolders()
            val existing = configured.firstOrNull { it.path == content }
            val next = if (existing == null) normalizeLocalFolders(configured + DbLocalFolder(journal.name, content)) else configured
            published = existing ?: next.last()
            db.copy(namedLocalFolders = next)
        }
        // Retain READY journal until both settings and disk are durable. Recovery is idempotent.
        withContext(NonCancellable) {
            persistSettings()
            check(files.deleteRecursivelyAsync(journalPath(journal.id))) { "Could not retire import journal" }
        }
        return checkNotNull(published)
    }

    private suspend fun pendingUnlocked(): List<PendingLocalImport> {
        files.prepare()
        checkOwnedRoot()
        return files.listFiles(root).filter { it.name.endsWith(".json") }.mapNotNull { entry ->
            try {
                val journal = DatabaseJson.decodeFromString<PendingLocalImport>(files.readBytesAsync(entry.path, 2L * 1024 * 1024).decodeToString())
                validateId(journal.id)
                require(entry.path == journalPath(journal.id))
                journal
            } catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled }
            catch (_: Throwable) { null } // Corrupt journals never authorize deleting content.
        }
    }

    private suspend fun writeJournal(journal: PendingLocalImport) {
        files.writeBytesAsync(journalPath(journal.id), DatabaseJson.encodeToString(journal).encodeToByteArray())
        files.awaitPersistence()
    }

    private fun journalPath(id: String) = "$root/$id.json"
    private fun contentPath(journal: PendingLocalImport) = "$root/${journal.id}/${journal.type.name.lowercase()}"
    private fun validateId(id: String) = require(id.matches(Regex("[a-zA-Z0-9_-]{1,80}"))) { "Invalid import identity" }
    private fun checkOwnedRoot(id: String? = null) {
        fun canonical(path: String) = files.canonicalPath(path)?.replace('\\', '/')?.trimEnd('/')
        val owned = requireNotNull(canonical(files.downloadRoot)) { "Import storage is unavailable" }
        require(canonical(root) == "$owned/local-imports") { "Import storage points outside its owned directory" }
        if (id != null) {
            validateId(id)
            require(canonical("$root/$id") == "$owned/local-imports/$id") { "Import directory was redirected" }
        }
    }
    private fun selectionName(path: String) = path.substringBefore('/').substringBeforeLast('.', path.substringBefore('/')).take(120)
    private fun pathsOverlap(a: String, b: String): Boolean = a == b || a.startsWith("$b/") || b.startsWith("${a.trimEnd('/')}/")

    private fun validatePaths(paths: List<String>) {
        require(paths.size <= LOCAL_IMPORT_MAX_FILES)
        require(paths.sumOf { it.length.toLong() } <= 256L * 1024) { "Import filenames exceed the journal limit" }
        val normalized = paths.map { path ->
            require(path.length in 1..1024 && path.split('/').all { part ->
                part.isNotBlank() && part != "." && part != ".." && part.length <= 240 &&
                    part.none { it.code < 32 || it in "\\:*?\"<>|" } && !part.endsWith('.') && !part.endsWith(' ')
            }) { "Unsupported import filename: $path" }
            path.lowercase()
        }.sorted()
        normalized.zipWithNext().forEach { (a, b) ->
            require(a != b && !b.startsWith("$a/")) { "Conflicting import filenames" }
        }
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryService.kt

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

The implementation below defines LocalLibraryService, scan, scanFresh, reconcile, withOperationLock, reconcileForEntryManagement, importTorrent, DefaultLocalLibraryService, entries, children and 39 further declarations.

The source describes its contract as:

Bypass fingerprint caches for a user-requested full rescan.

Cross-chapter imports used by this file: DbChapter, DbItemType, DbLocalFolder, DbManga, DbFetchType, DbStatus. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbFetchType
import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.getLocalVirtualPath
import eu.friedcutlet.yokan.database.localVirtualPathFromStoredPath
import eu.friedcutlet.yokan.services.files.BoundedCache
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.downloadItemTypeFromFolder
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.files.LocalDirectoryEntry
import eu.friedcutlet.yokan.domain.ChapterRecognition
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import eu.friedcutlet.yokan.services.files.effectiveLocalLibraryFolders

interface LocalLibraryService {
    suspend fun scan(): LocalLibraryScanResult
    /** Bypass fingerprint caches for a user-requested full rescan. */
    suspend fun scanFresh(): LocalLibraryScanResult = scan()
    suspend fun reconcile(): LocalLibraryReconciliationResult
    suspend fun reconcile(scan: LocalLibraryScanResult): LocalLibraryReconciliationResult = reconcile()
    /** Serializes a complete scan/reconcile with entry-management apply. */
    suspend fun <T> withOperationLock(block: suspend () -> T): T = block()
    /** Called by entry management while [withOperationLock] is held. */
    suspend fun reconcileForEntryManagement(): LocalLibraryReconciliationResult = reconcile()
    /**
     * Import a torrent file or magnet URL as a local-archive [DbManga] with a single chapter that
     * carries the file path or magnet URL; playback streams it through TorrServer
     * (`services/torrent/TorrentStreams`). Returns the upserted manga id, or null on failure.
     */
    suspend fun importTorrent(pathOrMagnet: String, displayName: String? = null): Long?
}

class DefaultLocalLibraryService(
    private val database: YokanDatabase,
    private val files: LocalFileService,
    private val archives: LocalArchiveService,
) : LocalLibraryService {
    private val operationMutex = Mutex()
    private val animeChapterExtensions = setOf("mp4", "mkv", "mov", "webm", "avi", "m4v", "ts", "m3u8", "zip", "rar", "cbr", "cbz", "cbt", "tar")
    private var metadataCache = BoundedCache<LocalFileEntry, LocalMetadata>(512, 8 * 1024 * 1024) { it.weight }
    private var episodeCache = BoundedCache<LocalFileEntry, LocalEpisodeMetadataIndex>(128, 8 * 1024 * 1024) { it.weight }
    private var coverCache = BoundedCache<LocalFileEntry, ByteArray>(128, 32 * 1024 * 1024) { it.size }

    override suspend fun scanFresh(): LocalLibraryScanResult = withOperationLock {
        archives.invalidateIndexCache()
        metadataCache = BoundedCache(512, 8 * 1024 * 1024) { it.weight }
        episodeCache = BoundedCache(128, 8 * 1024 * 1024) { it.weight }
        coverCache = BoundedCache(128, 32 * 1024 * 1024) { it.size }
        scanUnlocked()
    }

    /** Listings live for one scan only: additions and removals are always discovered. */
    private inner class ScanInventory {
        private val entries = mutableMapOf<String, List<LocalEntry>?>()
        private val children = mutableMapOf<String, List<LocalFileEntry>>()
        private val directoryEntries = mutableMapOf<String, List<LocalDirectoryEntry>?>()
        val episodes = BoundedCache<String, LocalEpisodeMetadataIndex>(128, 8 * 1024 * 1024) { it.weight }
        fun entries(path: String): List<LocalEntry>? = entries.getOrPut(path) { files.listLocalEntries(path) }
        fun children(path: String): List<LocalFileEntry> = children.getOrPut(path) { files.listFiles(path) }
        fun directoryEntries(path: String): List<LocalDirectoryEntry>? = directoryEntries.getOrPut(path) { files.listDirectoryEntries(path) }
        fun fingerprint(path: String): LocalFileEntry? = children(path.substringBeforeLast('/', ""))
            .firstOrNull { it.path == path && it.lastModified > 0L }
    }

    override suspend fun <T> withOperationLock(block: suspend () -> T): T = operationMutex.withLock { block() }

    /**
     * Bundled default folder rooted at `<downloadRoot>/local`. Always scanned in
     * addition to any user-configured virtual folders so a freshly installed app
     * has a working drop-in location.
     */
    override suspend fun scan(): LocalLibraryScanResult {
        return withOperationLock { scanUnlocked() }
    }

    /** Totals and identity evidence collected over one scan. */
    private class ScanAccumulator {
        var added = 0
        var updated = 0
        var total = 0
        val addedTitleIds = mutableListOf<Long>()
        val observedTitleIds = mutableListOf<Long>()
        val addedChapterIds = mutableListOf<Long>()
        val observedChapterIds = mutableListOf<Long>()
        val healthyFolders = mutableListOf<DbLocalFolder>()
        val unavailableFolders = mutableListOf<DbLocalFolder>()
        val observedTitleIdentities = mutableListOf<LocalLibraryIdentity>()
        val observedChapterIdentities = mutableListOf<LocalLibraryIdentity>()

        fun toResult() = LocalLibraryScanResult(
            added = added,
            updated = updated,
            total = total,
            addedTitleIds = addedTitleIds.distinct(),
            observedTitleIds = observedTitleIds.distinct(),
            addedChapterIds = addedChapterIds.distinct(),
            observedChapterIds = observedChapterIds.distinct(),
            healthyFolders = healthyFolders,
            unavailableFolders = unavailableFolders,
            observedTitleIdentities = observedTitleIdentities.distinct(),
            observedChapterIdentities = observedChapterIdentities.distinct(),
        )
    }

    private suspend fun scanUnlocked(): LocalLibraryScanResult {
        files.prepare()
        val inventory = ScanInventory()
        val importArea = scanCanonicalPath("${files.downloadRoot.trimEnd('/')}/local-imports")
        val folders = effectiveLocalLibraryFolders(database.settings(), files)
        if (folders.isEmpty()) return LocalLibraryScanResult(0, 0, 0)
        val scan = ScanAccumulator()
        val existingMangas = database.mangas()
            .asSequence()
            .filter(DbManga::isLocalLibraryEntry)
            .associateByTo(mutableMapOf()) { manga ->
                manga.itemType to localVirtualPathFromStoredPath(manga.link, folders)
            }
        val existingChapters = database.chapters()
            .associateByTo(mutableMapOf()) { chapter ->
                chapter.mangaId to localVirtualPathFromStoredPath(chapter.archivePath, folders)
            }
        folders.forEach { folder ->
            val entries = listFolderEntries(folder, inventory) ?: run {
                scan.unavailableFolders += folder
                return@forEach
            }
            scan.healthyFolders += folder
            val defaultItemType = inferItemType(folder.path)
            val canonicalFolder = scanCanonicalPath(folder.path)
            val scansImportAncestor = importArea != null && canonicalFolder != null &&
                (canonicalFolder == importArea || importArea.startsWith("$canonicalFolder/"))
            fun skipped(entry: LocalEntry) = entry.isInColorizerStagingFolder(folder.path) || (scansImportAncestor &&
                scanCanonicalPath(entry.path).let { path -> path == null || path == importArea || path.startsWith("$importArea/") })
            val listedEntries = entries.filterNot(::skipped)
                .map { it.toScanEntry(folder, defaultItemType) }
                .distinctBy { it.path }
            val seasonTree = if (defaultItemType == DbItemType.Anime) animeSeasonTree(folder, inventory) else null
            val scanEntries = seasonTree?.let { tree ->
                seasonOrderedEntries(folder, tree, listedEntries) { node -> skipped(LocalEntry(node.path, node.name, false)) }
            } ?: listedEntries
            val inheritedLibrary = seasonTree?.let { inheritedLibraryState(it, existingMangas) }.orEmpty()
            val savedTitleIds = mutableMapOf<String, Long>()
            scanEntries.forEach { entry ->
                scan.total += 1
                val virtualMangaPath = getLocalVirtualPath(folder, entry.path)
                val seasonNode = seasonTree?.get(virtualMangaPath)
                val listsSeasons = seasonNode?.seasons == true
                val parentId = seasonNode?.parent?.let(savedTitleIds::get)
                val ancestorIds = generateSequence(seasonNode?.parent) { seasonTree?.get(it)?.parent }.mapNotNull(savedTitleIds::get).toSet()
                val metadata = readMetadata(entry.path, inventory, entry.itemType)
                val coverImage = readCoverImage(entry.path, inventory, metadata.cast.orEmpty().mapNotNull { it.imageUrl }.toSet())
                val observedExisting = existingMangas[entry.itemType to virtualMangaPath]
                val now = nowMillis()
                val chapters = if (listsSeasons) emptyList() else chaptersFor(entry, folder, inventory)
                val movedChapterIds = mutableSetOf<Long>()
                database.batch {
                    val savedManga = upsertScannedTitle(
                        entry = entry,
                        virtualPath = virtualMangaPath,
                        observedExisting = observedExisting,
                        folders = folders,
                        metadata = metadata,
                        coverImage = coverImage,
                        seasonTree = seasonTree,
                        seasonNode = seasonNode,
                        parentId = parentId,
                        inherited = inheritedLibrary[virtualMangaPath],
                        now = now,
                        scan = scan,
                    ) ?: return@batch
                    existingMangas[entry.itemType to virtualMangaPath] = savedManga
                    savedTitleIds[virtualMangaPath] = savedManga.id
                    chapters.forEach { chapter ->
                        upsertScannedChapter(chapter, entry.itemType, savedManga, ancestorIds, existingChapters, movedChapterIds, folders, now, scan)
                    }
                    if (movedChapterIds.isNotEmpty()) {
                        database.histories().filter { it.chapterId in movedChapterIds }
                            .forEach { database.upsertHistory(it.copy(mangaId = savedManga.id)) }
                        database.updates().filter { it.chapterId in movedChapterIds }
                            .forEach { database.upsertUpdate(it.copy(mangaId = savedManga.id)) }
                    }
                }
            }
        }
        return scan.toResult()
    }

    /** Root entries of a configured folder, or null when it is missing or cannot be listed. */
    private fun listFolderEntries(folder: DbLocalFolder, inventory: ScanInventory): List<LocalEntry>? {
        if (folder.path.isBlank() || !runCatching { files.exists(folder.path) }.getOrDefault(false)) return null
        return runCatching { inventory.entries(folder.path) }.getOrNull()
    }

    /**
     * Upserts one scanned title inside the scan batch and records it in [scan]. Null when the row
     * was deleted, retyped or relinked since the scan read it.
     */
    private fun upsertScannedTitle(
        entry: LocalScanEntry,
        virtualPath: String,
        observedExisting: DbManga?,
        folders: List<DbLocalFolder>,
        metadata: LocalMetadata,
        coverImage: ByteArray?,
        seasonTree: Map<String, SeasonNode>?,
        seasonNode: SeasonNode?,
        parentId: Long?,
        inherited: Set<Long>?,
        now: Long,
        scan: ScanAccumulator,
    ): DbManga? {
        // Browser disk reads suspend; reading progress, categories and deletion may change meanwhile.
        val existing = observedExisting?.let { database.manga(it.id) }
        if (observedExisting != null && existing == null) return null
        if (existing != null && (!existing.isLocalLibraryEntry() || existing.itemType != entry.itemType ||
                localVirtualPathFromStoredPath(existing.link, folders) != virtualPath)) return null
        val nextManga = (existing ?: DbManga()).copy(
            name = metadata.name ?: entry.name,
            link = virtualPath,
            imageUrl = metadata.imageUrl ?: existing?.imageUrl,
            description = metadata.description ?: existing?.description,
            author = metadata.author ?: existing?.author,
            artist = metadata.artist ?: existing?.artist,
            status = metadata.status ?: existing?.status ?: DbStatus.Unknown,
            itemType = entry.itemType,
            genre = metadata.genres ?: existing?.genre,
            cast = metadata.cast ?: existing?.cast.orEmpty(),
            isLocalArchive = true,
            customCoverImage = if (observedExisting != null && !existing?.customCoverImage.contentEquals(observedExisting.customCoverImage))
                existing?.customCoverImage else coverImage ?: existing?.customCoverImage,
            customCoverFromTracker = metadata.customCoverFromTracker ?: existing?.customCoverFromTracker,
            source = "local",
            lang = metadata.language ?: existing?.lang ?: "en",
            dateAdded = existing?.dateAdded ?: now,
            lastUpdate = now,
            // Favorite season folders that used to be separate titles keep the show in the library.
            favorite = (existing?.favorite ?: false) || inherited != null,
            categories = inherited?.let { (existing?.categories.orEmpty() + it).distinct() } ?: existing?.categories,
            parentId = if (seasonTree == null) existing?.parentId else parentId,
            fetchType = when {
                seasonTree == null -> existing?.fetchType ?: DbFetchType.Episodes
                seasonNode?.seasons == true -> DbFetchType.Seasons
                else -> DbFetchType.Episodes
            },
            seasonNumber = if (seasonTree == null) existing?.seasonNumber
                else seasonNode?.takeIf { it.parent != null }?.let { ChapterRecognition.parseSeasonNumber(it.name)?.toDouble() },
        )
        val savedManga = if (existing != null && nextManga.copy(
                dateAdded = existing.dateAdded,
                lastUpdate = existing.lastUpdate,
                updatedAt = existing.updatedAt,
            ) == existing
        ) existing else database.upsertManga(nextManga)
        if (existing == null) scan.added += 1 else scan.updated += 1
        if (existing == null) scan.addedTitleIds += savedManga.id
        scan.observedTitleIds += savedManga.id
        scan.observedTitleIdentities += localLibraryIdentity(LocalLibraryEntityKind.Title, entry.itemType, virtualPath)
        return savedManga
    }

    /**
     * Upserts one scanned chapter of [savedManga] inside the scan batch and records it in [scan].
     * A chapter still owned by one of [ancestorIds] moves to [savedManga] and is added to [movedChapterIds].
     */
    private fun upsertScannedChapter(
        chapter: LocalChapterScan,
        itemType: DbItemType,
        savedManga: DbManga,
        ancestorIds: Set<Long>,
        existingChapters: MutableMap<Pair<Long?, String>, DbChapter>,
        movedChapterIds: MutableSet<Long>,
        folders: List<DbLocalFolder>,
        now: Long,
        scan: ScanAccumulator,
    ) {
        val virtualChapterPath = chapter.path
        val chapterKey = savedManga.id to virtualChapterPath
        // A show that becomes a Seasons title hands its flattened episodes to the season records.
        val observedChapter = existingChapters[chapterKey]
            ?: ancestorIds.firstNotNullOfOrNull { existingChapters[it to virtualChapterPath] }
        val existingChapter = observedChapter?.let { database.chapter(it.id) }
        if (observedChapter != null && existingChapter == null) return
        if (existingChapter != null && ((existingChapter.mangaId != savedManga.id && existingChapter.mangaId !in ancestorIds) ||
                localVirtualPathFromStoredPath(existingChapter.archivePath, folders) != virtualChapterPath)) return
        if (existingChapter != null && existingChapter.mangaId != savedManga.id) {
            existingChapters.remove(existingChapter.mangaId to virtualChapterPath)
            movedChapterIds += existingChapter.id
        }
        val nextChapter = (existingChapter ?: DbChapter()).copy(
            mangaId = savedManga.id,
            name = chapter.label,
            url = virtualChapterPath,
            archivePath = virtualChapterPath,
            dateUpload = chapter.metadata?.dateUpload ?: existingChapter?.dateUpload ?: now.toString(),
            scanlator = chapter.metadata?.scanlator ?: existingChapter?.scanlator.orEmpty(),
            isFiller = chapter.metadata?.filler ?: existingChapter?.isFiller ?: false,
            description = chapter.metadata?.summary ?: existingChapter?.description,
            thumbnailUrl = chapter.previewUrl ?: existingChapter?.thumbnailUrl,
            number = chapter.number ?: existingChapter?.number,
            season = chapter.season ?: existingChapter?.season,
            numberingName = chapter.numberingName ?: existingChapter?.numberingName,
            fetchedAt = existingChapter?.fetchedAt ?: now,
            updatedAt = now,
        )
        val savedChapter = if (existingChapter != null && nextChapter.copy(updatedAt = existingChapter.updatedAt) == existingChapter) {
            existingChapter
        } else {
            database.upsertChapter(nextChapter)
        }
        existingChapters[chapterKey] = savedChapter
        if (existingChapter == null) scan.addedChapterIds += savedChapter.id
        scan.observedChapterIds += savedChapter.id
        scan.observedChapterIdentities += localLibraryIdentity(LocalLibraryEntityKind.Chapter, itemType, virtualChapterPath)
    }

    private suspend fun reconcileUnlocked(): LocalLibraryReconciliationResult {
        val scan = scanUnlocked()
        val folders = effectiveLocalLibraryFolders(database.settings(), files)
        val operation = localLibraryReconciliationOperation(scan, database, folders)
        return reconcileLocalLibrary(operation)
    }

    override suspend fun reconcile(): LocalLibraryReconciliationResult = withOperationLock {
        reconcileUnlocked()
    }

    override suspend fun reconcile(scan: LocalLibraryScanResult): LocalLibraryReconciliationResult {
        val folders = effectiveLocalLibraryFolders(database.settings(), files)
        val operation = localLibraryReconciliationOperation(scan, database, folders)
        return reconcileLocalLibrary(operation)
    }

    override suspend fun reconcileForEntryManagement(): LocalLibraryReconciliationResult = reconcileUnlocked()

    private data class LocalChapterScan(
        val path: String, val label: String,
        val number: Double? = null, val season: Int? = null, val numberingName: String? = null,
        val metadata: LocalEpisodeMetadata? = null, val previewUrl: String? = null,
    )

    private suspend fun chaptersFor(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory): List<LocalChapterScan> {
        if (entry.itemType != DbItemType.Anime) return chapterPathsFor(entry, folder, inventory).map { LocalChapterScan(it.first, it.second) }
        val directory = if (entry.isArchive) {
            if (entry.path.startsWith("content://")) folder.path else entry.path.substringBeforeLast('/', "")
        } else entry.path
        val episodes = readEpisodes("${directory.trimEnd('/')}/episodes.json", inventory)
        val season = ChapterRecognition.parseSeasonNumber(if (entry.isArchive) directory.substringAfterLast('/') else entry.name)
        val sources = animeEpisodeSources(entry, folder, inventory, directory)
        return sources.map { source ->
            val inferred = ChapterRecognition.rawSeasonAndNumber(entry.name, source.label)
            val localDetails = if (source.directory == directory) null else
                readEpisodes("${source.directory.trimEnd('/')}/episodes.json", inventory).find(inferred.second)
            val details = localDetails ?: episodes.find(inferred.second)
            val previewDirectory = if (localDetails != null) source.directory else directory
            LocalChapterScan(source.path, details?.name ?: source.label, inferred.second,
                ChapterRecognition.parseSeasonNumber(source.label) ?: ChapterRecognition.parseSeasonNumber(source.folderName) ?: season,
                source.label, details, resolveLocalImage(previewDirectory, details?.previewUrl, inventory))
        }
    }

    private data class LocalEpisodeSource(val path: String, val label: String, val directory: String, val folderName: String = "")

    /** Root files and one subfolder level, using provider names instead of parsing opaque document IDs. */
    private fun animeEpisodeSources(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory, directory: String): List<LocalEpisodeSource> {
        if (entry.isArchive) return listOf(LocalEpisodeSource(getLocalVirtualPath(folder, entry.path), entry.name, directory))
        val children = inventory.directoryEntries(directory)
            ?: return chapterPathsForLegacyAnime(entry, folder, inventory, directory)
        val result = mutableListOf<LocalEpisodeSource>()
        fun addFile(child: LocalDirectoryEntry, parent: String, folderName: String) {
            if (child.isDirectory || child.name.startsWith('.') || child.name.substringAfterLast('.', "").lowercase() !in animeChapterExtensions) return
            result += LocalEpisodeSource(getLocalVirtualPath(folder, child.path), child.name.substringBeforeLast('.'), parent, folderName)
        }
        children.filterNot { it.name.startsWith('.') }.forEach { child ->
            if (child.isDirectory) {
                inventory.directoryEntries(child.path).orEmpty().forEach { addFile(it, child.path, child.name) }
            } else addFile(child, directory, entry.name)
        }
        return result.distinctBy { it.path }
    }

    /** Compatibility for custom file backends predating immediate-child listings. */
    private fun chapterPathsForLegacyAnime(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory, directory: String): List<LocalEpisodeSource> =
        inventory.entries(entry.path).orEmpty().filterNot { it.isTitleRootCover(entry.path) }
            .filter { !it.isArchive || it.path.substringAfterLast('.').lowercase() in animeChapterExtensions }
            .map { LocalEpisodeSource(getLocalVirtualPath(folder, it.path), it.name, directory) }
            .ifEmpty { listOf(LocalEpisodeSource(getLocalVirtualPath(folder, entry.path), entry.name, directory)) }

    private suspend fun readEpisodes(path: String, inventory: ScanInventory): LocalEpisodeMetadataIndex {
        inventory.episodes[path]?.let { return it }
        val fingerprint = inventory.fingerprint(path)
        val parsed = fingerprint?.let { episodeCache[it] } ?: if (!files.exists(path)) null else catchingNonCancellation {
            parseLocalEpisodes(files.readBytesAsync(path, 1024L * 1024).decodeToString())
        }.getOrNull()?.also { if (fingerprint != null) episodeCache[fingerprint] = it }
        return (parsed ?: LocalEpisodeMetadataIndex(emptyList())).also { inventory.episodes[path] = it }
    }

    private suspend fun resolveLocalImage(directory: String, reference: String?, inventory: ScanInventory): String? {
        val path = reference ?: return null
        if (path.startsWith("https://", true) || path.startsWith("http://", true)) return path
        if (path.startsWith('/') || path.contains('\\') || path.contains(':') || path.contains('\u0000')) return null
        if (path.split('/').any { it.isBlank() || it == "." || it == ".." }) return null
        return catchingNonCancellation {
            val root = files.canonicalPath(directory)?.replace('\\', '/')?.trimEnd('/')
            if (root == null) {
                // Follow provider children by display name; document IDs need not encode a hierarchy.
                if (!directory.startsWith("content://")) return@catchingNonCancellation null
                val parts = path.split('/')
                if (parts.size > 64) return@catchingNonCancellation null
                var current = directory
                for ((index, name) in parts.withIndex()) {
                    val entries = inventory.directoryEntries(current)
                    if (entries == null) {
                        val sibling = if (index == parts.lastIndex) inventory.children(current).firstOrNull { it.name == name } else null
                        return@catchingNonCancellation sibling?.let { files.readableUrl(it.path) }
                    }
                    val child = entries.singleOrNull { it.name == name } ?: return@catchingNonCancellation null
                    if (child.isDirectory != (index != parts.lastIndex)) return@catchingNonCancellation null
                    current = child.path
                }
                return@catchingNonCancellation files.readableUrl(current)
            }
            val candidate = files.canonicalPath("${directory.trimEnd('/')}/$path")?.replace('\\', '/') ?: return@catchingNonCancellation null
            if (!candidate.startsWith("$root/") || !files.exists(candidate)) null else files.readableUrl(candidate)
        }.getOrNull()
    }

    private suspend fun chapterPathsFor(entry: LocalScanEntry, folder: DbLocalFolder, inventory: ScanInventory): List<Pair<String, String>> {
        if (entry.path.endsWith(".epub", ignoreCase = true)) return epubChapters(folder, entry.path, entry.name)
        if (entry.isArchive) return listOf(getLocalVirtualPath(folder, entry.path) to entry.name)
        return inventory.entries(entry.path).orEmpty()
            .filterNot { it.isTitleRootCover(entry.path) }
            .filter { entry.itemType != DbItemType.Anime || !it.isArchive ||
                it.path.substringAfterLast('.').lowercase() in animeChapterExtensions }
            .flatMap { child ->
                if (child.path.endsWith(".epub", ignoreCase = true)) {
                    epubChapters(folder, child.path, child.name)
                } else {
                    listOf(getLocalVirtualPath(folder, child.path) to child.name)
                }
            }
            .ifEmpty { listOf(getLocalVirtualPath(folder, entry.path) to entry.name) }
    }

    private suspend fun epubChapters(folder: DbLocalFolder, path: String, fallbackName: String): List<Pair<String, String>> {
        val epubChapters = archives.listEpubChaptersAsync(path)
        val virtualPath = getLocalVirtualPath(folder, path)
        return if (epubChapters.isNotEmpty()) {
            epubChapters.mapIndexed { index, chapter -> "$virtualPath#$index" to chapter.title }
        } else {
            listOf(virtualPath to fallbackName)
        }
    }

    /** One anime folder below a library root; [parent] is the virtual path of its Seasons-type owner. */
    private data class SeasonNode(val path: String, val name: String, val virtual: String, val parent: String?, val seasons: Boolean)

    /**
     * Animetail `LocalAnimeFetchTypeManager`: a folder with a video/archive file lists episodes (Yokan also
     * flattens its immediate subfolders); otherwise non-hidden subfolders make it a Seasons title whose
     * subfolders are season titles, recursively. Breadth-first, so parents precede their seasons.
     * Null when the backend has no immediate-child listings; download-layout type folders are skipped.
     */
    private fun animeSeasonTree(folder: DbLocalFolder, inventory: ScanInventory): Map<String, SeasonNode>? {
        fun visible(entries: List<LocalDirectoryEntry>) = entries.filterNot { it.name.startsWith('.') }
        val roots = visible(inventory.directoryEntries(folder.path) ?: return null)
            .filter { it.isDirectory && downloadItemTypeFromFolder(it.name) == null }
        val result = LinkedHashMap<String, SeasonNode>()
        val queue = ArrayDeque(roots.map { it to null as String? })
        // ponytail: 10,000-folder cap per library root; page the walk if libraries outgrow it.
        while (queue.isNotEmpty() && result.size < 10_000) {
            val (directory, parent) = queue.removeFirst()
            val virtual = getLocalVirtualPath(folder, directory.path)
            if (virtual in result) continue
            val children = visible(inventory.directoryEntries(directory.path) ?: continue)
            val hasEpisodes = children.any { !it.isDirectory && it.name.substringAfterLast('.', "").lowercase() in animeChapterExtensions }
            val subfolders = children.filter { it.isDirectory }
            val seasons = !hasEpisodes && subfolders.isNotEmpty()
            result[virtual] = SeasonNode(directory.path, directory.name, virtual, parent, seasons)
            if (seasons) subfolders.forEach { queue.addLast(it to virtual) }
        }
        return result
    }

    /** Seasons titles and their seasons first (parents before children), then every other listed entry. */
    private fun seasonOrderedEntries(
        folder: DbLocalFolder,
        tree: Map<String, SeasonNode>,
        listed: List<LocalScanEntry>,
        skipped: (SeasonNode) -> Boolean,
    ): List<LocalScanEntry> {
        val listedByVirtual = listed.associateBy { getLocalVirtualPath(folder, it.path) }
        val linked = tree.values.filter { (it.seasons || it.parent != null) && !skipped(it) }
        val linkedPaths = linked.mapTo(HashSet()) { it.virtual }
        return linked.map { node -> listedByVirtual[node.virtual] ?: LocalScanEntry(node.path, node.name, false, DbItemType.Anime) } +
            listed.filterNot { getLocalVirtualPath(folder, it.path) in linkedPaths }
    }

    /**
     * Season folders scanned before season records existed were separate top-level titles. Their library
     * membership moves to the show once, when they are first linked; later scans leave the user's choice alone.
     */
    private fun inheritedLibraryState(tree: Map<String, SeasonNode>, existing: Map<Pair<DbItemType, String>, DbManga>): Map<String, Set<Long>> {
        val result = mutableMapOf<String, MutableSet<Long>>()
        tree.values.forEach { node ->
            if (node.parent == null) return@forEach
            val season = existing[DbItemType.Anime to node.virtual]?.takeIf { it.favorite && it.parentId == null } ?: return@forEach
            var show = node
            while (true) show = show.parent?.let(tree::get) ?: break
            result.getOrPut(show.virtual) { linkedSetOf() } += season.categories.orEmpty()
        }
        return result
    }

    private data class LocalScanEntry(
        val path: String,
        val name: String,
        val isArchive: Boolean,
        val itemType: DbItemType,
    )

    private fun LocalEntry.toScanEntry(folder: DbLocalFolder, defaultItemType: DbItemType): LocalScanEntry {
        downloadedTitleEntry(folder, defaultItemType)?.let { return it }
        return LocalScanEntry(path = path, name = name, isArchive = isArchive, itemType = defaultItemType)
    }

    private fun LocalEntry.downloadedTitleEntry(folder: DbLocalFolder, defaultItemType: DbItemType): LocalScanEntry? {
        val relativeParts = relativePathUnder(folder.path, path)
            .split('/')
            .filter { it.isNotBlank() }
        val typeIndex = relativeParts.indexOfFirst { downloadItemTypeFromFolder(it) != null }
        if (typeIndex < 0 || relativeParts.size <= typeIndex + 3) return null
        val itemType = downloadItemTypeFromFolder(relativeParts[typeIndex]) ?: defaultItemType
        val titleRelativeParts = relativeParts.take(typeIndex + 3)
        val titlePath = "${folder.path.trimEnd('/', '\\')}/${titleRelativeParts.joinToString("/")}"
        return LocalScanEntry(
            path = titlePath,
            name = relativeParts[typeIndex + 2],
            isArchive = false,
            itemType = itemType,
        )
    }

    private fun relativePathUnder(base: String, target: String): String {
        val normalizedBase = base.replace('\\', '/').trimEnd('/')
        val normalizedTarget = target.replace('\\', '/').trimEnd('/')
        return if (normalizedTarget.startsWith("$normalizedBase/")) {
            normalizedTarget.substring(normalizedBase.length + 1)
        } else {
            normalizedTarget
        }
    }

    /** Managed import areas are scanned only through their published roots, never an ancestor. */
    private fun scanCanonicalPath(path: String): String? =
        runCatching { files.canonicalPath(path) }.getOrNull()?.replace('\\', '/')?.trimEnd('/')

    private fun LocalEntry.isInColorizerStagingFolder(folderRoot: String): Boolean {
        val normalizedRoot = folderRoot.replace('\\', '/').trimEnd('/')
        val normalizedPath = path.replace('\\', '/').trimEnd('/')
        if (!normalizedPath.startsWith("$normalizedRoot/")) return false
        return normalizedPath.substring(normalizedRoot.length + 1)
            .split('/')
            .any { it.startsWith(".colorizer-") && it.endsWith(".partial") }
    }

    private suspend fun readMetadata(titlePath: String, inventory: ScanInventory, itemType: DbItemType): LocalMetadata {
        val legacy = readLegacyMetadata(titlePath, inventory)
        val detailsPath = "${titlePath.trimEnd('/', '\\')}/details.json"
        val details = if (itemType == DbItemType.Anime && files.exists(detailsPath)) readMetadataFile(detailsPath, inventory, animetail = true) else null
        val metadata = if (details == null) legacy else LocalMetadata(
            name = details.name ?: legacy.name,
            description = details.description ?: legacy.description,
            author = details.author ?: legacy.author,
            artist = details.artist ?: legacy.artist,
            genres = details.genres ?: legacy.genres,
            status = details.status ?: legacy.status,
            imageUrl = legacy.imageUrl,
            customCoverFromTracker = legacy.customCoverFromTracker,
            language = legacy.language,
            cast = details.cast ?: legacy.cast,
        )
        return if (metadata.cast == null) metadata else metadata.copy(cast = metadata.cast.map { credit ->
            credit.copy(imageUrl = resolveLocalImage(titlePath, credit.imageUrl, inventory))
        })
    }

    private suspend fun readMetadataFile(path: String, inventory: ScanInventory, animetail: Boolean = false): LocalMetadata? {
        val fingerprint = inventory.fingerprint(path)
        fingerprint?.let { metadataCache[it] }?.let { return it }
        val parsed = catchingNonCancellation {
            parseLocalMetadata(files.readBytesAsync(path, 64L * 1024).decodeToString(), animetail)
        }.getOrNull()
        if (parsed != null && fingerprint != null) metadataCache[fingerprint] = parsed
        return parsed
    }

    private suspend fun readLegacyMetadata(titlePath: String, inventory: ScanInventory): LocalMetadata {
        metadataCandidates(titlePath, inventory).forEach { path ->
            readMetadataFile(path, inventory)?.let { return it }
        }
        return LocalMetadata()
    }

    private fun metadataCandidates(titlePath: String, inventory: ScanInventory): List<String> =
        buildList {
            add("${titlePath.trimEnd('/', '\\')}/metadata.json")
            inventory.entries(titlePath).orEmpty()
                .map { "${it.path.trimEnd('/', '\\')}/metadata.json" }
                .forEach(::add)
        }.filter { files.exists(it) }

    private suspend fun readCoverImage(titlePath: String, inventory: ScanInventory, excludedImages: Set<String> = emptySet()): ByteArray? {
        val candidates = inventory.children(titlePath)
            .filter { it.path.isCoverImagePath() }
        val imageFiles = if (excludedImages.isEmpty()) candidates else candidates.filterNot { entry ->
            catchingNonCancellation { files.readableUrl(entry.path) }.getOrNull() in excludedImages
        }
        val selected = imageFiles.firstOrNull { it.name.substringBeforeLast('.').equals("cover", ignoreCase = true) }
            ?: imageFiles.singleOrNull()
        return selected?.let { entry ->
            if (entry.lastModified > 0L) coverCache[entry]?.let { return it }
            catchingNonCancellation { files.readBytesAsync(entry.path, 4L * 1024 * 1024) }.getOrNull()?.also { bytes ->
                if (entry.lastModified > 0L) coverCache[entry] = bytes
            }
        }
    }

    private fun LocalEntry.isTitleRootCover(titlePath: String): Boolean {
        val normalizedTitle = titlePath.replace('\\', '/').trimEnd('/')
        val normalizedPath = path.replace('\\', '/')
        val parent = normalizedPath.substringBeforeLast('/', "")
        return parent == normalizedTitle && normalizedPath.isCoverImagePath()
    }

    private fun String.isCoverImagePath(): Boolean {
        val lower = substringAfterLast('/').lowercase()
        return lower.endsWith(".jpg") || lower.endsWith(".jpeg") ||
            lower.endsWith(".png") || lower.endsWith(".webp") ||
            lower.endsWith(".gif") || lower.endsWith(".bmp") ||
            lower.endsWith(".avif")
    }


    private fun inferItemType(root: String): DbItemType {
        val name = root.substringAfterLast('/').lowercase()
        return when {
            "anime" in name -> DbItemType.Anime
            "novel" in name -> DbItemType.Novel
            else -> DbItemType.Manga
        }
    }

    override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? {
        if (pathOrMagnet.isBlank()) return null
        val isMagnet = pathOrMagnet.startsWith("magnet:", ignoreCase = true)
        val extractedName = if (isMagnet) TorrentUtils.extractMagnetDisplayName(pathOrMagnet) else null
        val extractedHash = if (isMagnet) TorrentUtils.extractInfoHashFromMagnet(pathOrMagnet) else null
        val baseName = displayName?.takeIf { it.isNotBlank() }
            ?: extractedName?.takeIf { it.isNotBlank() }
            ?: if (isMagnet) {
                if (!extractedHash.isNullOrBlank()) "Torrent (${extractedHash.take(8)})" else "Torrent"
            } else {
                pathOrMagnet.substringAfterLast('/')
                    .substringBefore('?')
                    .removeSuffix(".torrent")
                    .ifBlank { "Torrent" }
            }
        val now = nowMillis()
        val existing = database.mangas(DbItemType.Anime)
            .firstOrNull {
                it.isLocalArchive == true && it.source == "torrent" &&
                    (it.link == pathOrMagnet || (extractedHash != null && TorrentUtils.extractInfoHashFromMagnet(it.link.orEmpty()) == extractedHash))
            }
        val savedManga = database.upsertManga(
            (existing ?: DbManga()).copy(
                name = baseName,
                source = "torrent",
                itemType = DbItemType.Anime,
                isLocalArchive = true,
                link = pathOrMagnet,
                lang = existing?.lang ?: "en",
                dateAdded = existing?.dateAdded ?: now,
                lastUpdate = now,
                favorite = existing?.favorite ?: true,
            ),
        )
        val existingChapter = database.chapters(savedManga.id).firstOrNull { it.url == pathOrMagnet }
        database.upsertChapter(
            (existingChapter ?: DbChapter()).copy(
                mangaId = savedManga.id,
                name = baseName,
                url = pathOrMagnet,
                archivePath = if (isMagnet) "" else pathOrMagnet,
                dateUpload = (existingChapter?.dateUpload ?: now.toString()),
                fetchedAt = existingChapter?.fetchedAt ?: now,
                updatedAt = now,
            ),
        )
        return savedManga.id
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryController.kt

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

The implementation below defines LocalLibraryScanState, LocalLibraryController, importMedia, pendingImports, recoverImport, discardIncompleteImport, runImportWork, observeLibrary, folders, overview and 12 further declarations.

The source describes its contract as:

App-wide local-library scan state, shared by every screen that shows or triggers a scan.

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.observeSnapshot
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.blockingDispatcher
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.effectiveLocalLibraryFolders
import eu.friedcutlet.yokan.services.metadata.LocalMetadataField
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.services.metadata.MetadataService
import eu.friedcutlet.yokan.services.metadata.selectedLocalMetadataFields
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.services.tracking.EnhancedTracker
import eu.friedcutlet.yokan.services.tracking.TrackerService
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/** App-wide local-library scan state, shared by every screen that shows or triggers a scan. */
data class LocalLibraryScanState(
    val lastScan: LocalLibraryScanResult? = null,
    val running: Boolean = false,
    val error: String? = null,
    val reconciliation: LocalLibraryReconciliationResult? = null,
)

/** App-scoped front of the local library: scans, entry management, and metadata matching. */
class LocalLibraryController(
    private val localLibrary: LocalLibraryService,
    private val entryManagement: LocalEntryManagementService,
    private val repository: YokanRepository,
    private val metadata: MetadataService,
    private val trackers: List<TrackerService>,
    private val files: LocalFileService,
    private val settings: SettingsStore,
    persistSettings: suspend () -> Unit = {},
    private val importScope: CoroutineScope,
    private val isOwnerOpen: () -> Boolean = { true },
    private val artwork: LocalVideoArtwork? = null,
) {
    private val _scan = MutableStateFlow(LocalLibraryScanState())
    val scan: StateFlow<LocalLibraryScanState> = _scan.asStateFlow()
    private val projectionCache = LocalLibraryProjectionCache()
    private val importer = LocalMediaImporter(files, settings, persistSettings)

    suspend fun importMedia(
        selection: eu.friedcutlet.yokan.services.files.LocalMediaSelection,
        type: DbItemType,
        progress: (LocalImportProgress) -> Unit = {},
    ): DbLocalFolder = runImportWork { importer.import(selection, type, progress) }

    suspend fun pendingImports(): List<PendingLocalImport> = runImportWork { importer.pending() }
    suspend fun recoverImport(id: String) = runImportWork { importer.recover(id) }
    suspend fun discardIncompleteImport(id: String) = runImportWork { importer.discardIncomplete(id) }

    private suspend fun <T> runImportWork(action: suspend () -> T): T =
        importScope.runJoined(blockingDispatcher, admit = { check(isOwnerOpen()) { "Profile is no longer active" } }) { action() }

    internal fun observeLibrary(context: CoroutineContext = Dispatchers.Default) =
        repository.observeSnapshot({ it.mangas to it.settings.titleMetadata }, context, projectionCache::get)

    internal fun folders(db: DbSettings) = effectiveLocalLibraryFolders(db, files)

    fun overview(): LocalLibraryOverview {
        val snapshot = repository.snapshots.value
        return projectionCache.get(snapshot).overview(folders(snapshot.settings), _scan.value)
    }

    fun localTitles(type: ItemType): List<Manga> = projectionCache.get(repository.snapshots.value).titlesByType.getValue(type)

    fun metadataReviewQueue(): List<Manga> = projectionCache.get(repository.snapshots.value).reviewQueue

    suspend fun rescan(forceRefresh: Boolean = false): LocalLibraryScanResult {
        _scan.update { it.copy(running = true, error = null) }
        return try {
            val result = withContext(blockingDispatcher) { if (forceRefresh) localLibrary.scanFresh() else localLibrary.scan() }
            _scan.update { it.copy(lastScan = result) }
            // Frame artwork decodes in the background on the profile scope; retirement cancels it.
            if (artwork != null && isOwnerOpen()) importScope.launch {
                catchingNonCancellation { artwork.generate() }
                    .onFailure { eu.friedcutlet.yokan.services.logging.AppLogger.warn("[local] video artwork run failed: ${it.message.orEmpty()}") }
            }
            result
        } catch (error: Throwable) {
            if (error !is CancellationException) _scan.update { it.copy(error = error.message ?: "Scan failed") }
            throw error
        } finally {
            _scan.update { it.copy(running = false) }
        }
    }

    suspend fun rescanAndReconcile(forceRefresh: Boolean = false): LocalLibraryScanResult {
        val result = rescan(forceRefresh)
        val reconciliation = localLibrary.reconcile(result)
        _scan.update { it.copy(reconciliation = reconciliation) }
        return result
    }

    fun preview(op: LocalEntryManagementOperation): LocalEntryManagementPreview = entryManagement.preview(op)

    suspend fun apply(command: LocalEntryManagementCommand): LocalEntryManagementApplyResult {
        val result = entryManagement.apply(command)
        if (result.status == LocalEntryManagementApplyStatus.Applied) {
            _scan.value.lastScan?.let { lastScan ->
                val reconciliation = localLibrary.reconcile(lastScan)
                _scan.update { it.copy(reconciliation = reconciliation) }
            }
        }
        return result
    }

    suspend fun importTorrent(pathOrMagnet: String, displayName: String? = null): Long? =
        localLibrary.importTorrent(pathOrMagnet, displayName)

    suspend fun searchMetadataCandidates(manga: Manga): List<LocalMetadataSourceResult> {
        val results = mutableListOf<LocalMetadataSourceResult>()
        val baseUrl = settings.db.value.metadataServerUrl.trim()
        results += if (baseUrl.startsWith("http://") || baseUrl.startsWith("https://")) {
            metadataServerCandidates(baseUrl, manga)
        } else {
            LocalMetadataSourceResult("Metadata server", LocalMetadataSourceState.Offline, message = "No valid server URL")
        }
        if (!localTrackerSearchSupported(manga.itemType)) {
            results += LocalMetadataSourceResult("Trackers", LocalMetadataSourceState.Unsupported, message = "Tracker search does not support novels")
            return results
        }
        val isManga = manga.itemType == ItemType.Manga
        // Server trackers only match their own source; account trackers join once signed in.
        trackers.filter { it.supports(isManga) && it !is EnhancedTracker && (it.loginFields.isEmpty() || it.checkRefresh()) }.forEach { tracker ->
            val candidates = catchingNonCancellation { tracker.search(manga.name, isManga) }.getOrElse { error ->
                results += LocalMetadataSourceResult(tracker.name, LocalMetadataSourceState.Error, message = error.message)
                return@forEach
            }.map { candidate ->
                MetadataMedia(
                    id = candidate.mediaId?.toString() ?: "${tracker.syncId}:${candidate.title}",
                    source = tracker.name,
                    mediaType = manga.itemType.toDb(),
                    title = candidate.title.orEmpty(),
                    description = candidate.summary,
                    status = candidate.publishingStatus,
                    score = candidate.score,
                    coverUrl = candidate.coverUrl,
                    url = candidate.trackingUrl,
                )
            }
            results += LocalMetadataSourceResult(tracker.name, candidates.resultState(), candidates)
        }
        return results.map { it.copy(candidates = it.candidates.distinctBy { candidate -> "${candidate.source}:${candidate.id}" }) }
    }

    private suspend fun metadataServerCandidates(baseUrl: String, manga: Manga): LocalMetadataSourceResult {
        val source = "Metadata server"
        val online = catchingNonCancellation { metadata.health(baseUrl) }.getOrElse { error ->
            return LocalMetadataSourceResult(source, LocalMetadataSourceState.Error, message = error.message)
        }
        if (!online) return LocalMetadataSourceResult(source, LocalMetadataSourceState.Offline)
        return catchingNonCancellation { metadata.search(baseUrl, manga.name, manga.itemType.toDb()) }.fold(
            onSuccess = { candidates -> LocalMetadataSourceResult(source, candidates.resultState(), candidates) },
            onFailure = { LocalMetadataSourceResult(source, LocalMetadataSourceState.Error, message = it.message) },
        )
    }

    fun applyMetadataCandidate(manga: Manga, candidate: MetadataMedia, fields: Set<LocalMetadataField>): Manga? {
        val safeFields = selectedLocalMetadataFields(fields, candidate)
        if (safeFields.isEmpty()) return manga
        return repository.applyLocalMetadataFields(manga.id, candidate, safeFields)
    }

    fun clear(): Int = repository.clearLocalLibrary()
}

private fun List<MetadataMedia>.resultState(): LocalMetadataSourceState =
    if (isEmpty()) LocalMetadataSourceState.NoResults else LocalMetadataSourceState.Results

Check your understanding

Scan a folder twice, then change one sidecar and rescan. Confirm stable title/chapter IDs and a bounded, visible result for an unreadable metadata file. [chapter-content-end]: #

Step 4: implement reconciliation and entry management

Rebuild local projection/reconciliation, title/episode metadata, sidecar compatibility and review workflows. Separate source facts from user overrides, including manual filler. Implement preview/apply for local entry changes using the database's atomic snapshot capability and expected snapshot. Preserve original external media files when changing database metadata.

Implement local anime season records, sidecar episode numbering, local-video stream resolution and frame-derived artwork. Resolve virtual chapter archive paths to playable URLs under the owner; source local is not a network extension. Frame extraction should have bounded work and retain user-selected artwork.

Follow the code

The reconciliation step rereads current records inside the mutation boundary and merges source facts into them. User progress, notes, bookmarks and overrides may have changed since scanning began. A deleted or rebound record must not be recreated from an old candidate. Entry management builds preview/apply changes against an expected snapshot. Source sidecars and extracted video artwork are inputs; preserve user-selected artwork and original external media.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryProjection.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryReconciliation.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalTitleMetadata.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalEpisodeMetadata.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalEntryManagementService.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalVideoArtwork.kt

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryProjection.kt

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

The implementation below defines LocalLibraryProjection, titleNames, overview, LocalLibraryProjectionCache, get.

The source describes its contract as:

Both local screens share these immutable lists; scan status and folder edits don't rebuild them.

Cross-chapter imports used by this file: DbLocalFolder, DbManga, DbTitleMetadata, YokanDatabaseSnapshot, ItemType, Manga. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.data.toDomainMangas
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbTitleMetadata
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.util.PlatformLock

/** Both local screens share these immutable lists; scan status and folder edits don't rebuild them. */
internal class LocalLibraryProjection(snapshot: YokanDatabaseSnapshot) {
    // Season records are reached from their parent title's detail screen, never listed separately.
    private val local = snapshot.mangas.filter { it.isLocalArchive && it.parentId == null }.toDomainMangas(snapshot.settings)
    private val managed = local.filterNot { it.source.equals("torrent", ignoreCase = true) }
    val titlesByType = ItemType.entries.associateWith { type -> managed.filter { it.itemType == type } }
    val browseTitlesByType = ItemType.entries.associateWith { type ->
        local.filter { it.itemType == type }.sortedBy { it.name.lowercase() }
    }
    val reviewQueue = ItemType.entries.flatMap { titlesByType.getValue(it) }
        .filter { it.metadataServerId == null || it.description.isBlank() }.distinctBy { it.id }
    private val names = snapshot.mangas.associate { it.id to it.name.orEmpty() }

    fun titleNames(reconciliation: LocalLibraryReconciliationResult?): Map<Long, String> {
        reconciliation ?: return emptyMap()
        val ids = reconciliation.staleTitleCandidates.map { it.id } + reconciliation.duplicateTitleGroups.flatMap { it.ids }
        return ids.distinct().mapNotNull { id -> names[id]?.let { id to it } }.toMap()
    }

    fun overview(folders: List<DbLocalFolder>, scan: LocalLibraryScanState) = LocalLibraryOverview(
        folders = folders,
        manga = titlesByType.getValue(ItemType.Manga).size,
        anime = titlesByType.getValue(ItemType.Anime).size,
        novels = titlesByType.getValue(ItemType.Novel).size,
        lastScan = scan.lastScan,
        scanRunning = scan.running,
        scanError = scan.error,
        reconciliation = scan.reconciliation,
    )
}

/** Controller-owned and bounded to one revision; collectors can run on different dispatchers. */
internal class LocalLibraryProjectionCache {
    private val lock = PlatformLock()
    private var mangas: List<DbManga>? = null
    private var metadata: List<DbTitleMetadata>? = null
    private var cached: LocalLibraryProjection? = null

    fun get(snapshot: YokanDatabaseSnapshot): LocalLibraryProjection = lock.withLock {
        if (cached == null || mangas !== snapshot.mangas || metadata != snapshot.settings.titleMetadata) {
            cached = LocalLibraryProjection(snapshot)
            mangas = snapshot.mangas
            metadata = snapshot.settings.titleMetadata
        }
        requireNotNull(cached)
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryReconciliation.kt

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

This code is where an earlier filesystem observation meets current database state. Preserve its guards and merge rules rather than writing the scan's old complete record back to storage.

The implementation below defines LocalLibraryEntityKind, LocalLibraryIdentity, localLibraryIdentity, LocalLibraryDuplicateGroup, LocalLibraryStaleCandidate, LocalLibraryScanResult, LocalLibraryReconciliationEntry, LocalLibraryReconciliationOperation, LocalLibraryReconciliationResult, reconcileLocalLibrary and 4 further declarations.

The source describes its contract as:

Stable, exact local-library identity. [relativePath] deliberately keeps EPUB fragments.

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.localVirtualPathFromStoredPath
import kotlinx.serialization.Serializable

@Serializable
enum class LocalLibraryEntityKind {
    Title,
    Chapter,
}

/** Stable, exact local-library identity.  [relativePath] deliberately keeps EPUB fragments. */
@Serializable
data class LocalLibraryIdentity(
    val kind: LocalLibraryEntityKind,
    val itemType: DbItemType,
    val virtualFolder: String,
    val relativePath: String,
)

fun localLibraryIdentity(kind: LocalLibraryEntityKind, itemType: DbItemType, virtualPath: String): LocalLibraryIdentity {
    val normalized = virtualPath.replace('\\', '/').trim('/')
    val separator = normalized.indexOf('/')
    return if (separator < 0) {
        LocalLibraryIdentity(kind, itemType, normalized, "")
    } else {
        LocalLibraryIdentity(
            kind = kind,
            itemType = itemType,
            virtualFolder = normalized.substring(0, separator),
            relativePath = normalized.substring(separator + 1),
        )
    }
}

@Serializable
data class LocalLibraryDuplicateGroup(
    val identity: LocalLibraryIdentity,
    val ids: List<Long>,
)

@Serializable
data class LocalLibraryStaleCandidate(
    val id: Long,
    val identity: LocalLibraryIdentity,
)

@Serializable
data class LocalLibraryScanResult(
    val added: Int,
    val updated: Int,
    val total: Int,
    val addedTitleIds: List<Long> = emptyList(),
    val observedTitleIds: List<Long> = emptyList(),
    val addedChapterIds: List<Long> = emptyList(),
    val observedChapterIds: List<Long> = emptyList(),
    val healthyFolders: List<DbLocalFolder> = emptyList(),
    val unavailableFolders: List<DbLocalFolder> = emptyList(),
    val observedTitleIdentities: List<LocalLibraryIdentity> = emptyList(),
    val observedChapterIdentities: List<LocalLibraryIdentity> = emptyList(),
)

@Serializable
data class LocalLibraryReconciliationEntry(
    val id: Long,
    val identity: LocalLibraryIdentity,
)

/** Serializable input to reconciliation; it contains no imperative delete operation. */
@Serializable
data class LocalLibraryReconciliationOperation(
    val scan: LocalLibraryScanResult,
    val existingTitles: List<LocalLibraryReconciliationEntry> = emptyList(),
    val existingChapters: List<LocalLibraryReconciliationEntry> = emptyList(),
)

@Serializable
data class LocalLibraryReconciliationResult(
    val addedTitleIds: List<Long> = emptyList(),
    val observedTitleIds: List<Long> = emptyList(),
    val addedChapterIds: List<Long> = emptyList(),
    val observedChapterIds: List<Long> = emptyList(),
    val staleTitleCandidates: List<LocalLibraryStaleCandidate> = emptyList(),
    val staleChapterCandidates: List<LocalLibraryStaleCandidate> = emptyList(),
    val duplicateTitleGroups: List<LocalLibraryDuplicateGroup> = emptyList(),
    val duplicateChapterGroups: List<LocalLibraryDuplicateGroup> = emptyList(),
    val unavailableFolders: List<DbLocalFolder> = emptyList(),
)

/**
 * Reconcile evidence without changing the database or touching the filesystem.
 * Unknown roots are intentionally not considered stale: absence of evidence is not
 * evidence of absence when a mount was renamed or is unavailable.
 */
fun reconcileLocalLibrary(operation: LocalLibraryReconciliationOperation): LocalLibraryReconciliationResult {
    val scan = operation.scan
    val observedTitles = scan.observedTitleIdentities.toSet()
    val observedChapters = scan.observedChapterIdentities.toSet()
    val healthyFolders = scan.healthyFolders.map { it.name }.toSet()
    val unavailableFolders = scan.unavailableFolders.map { it.name }.toSet()

    fun stale(entries: List<LocalLibraryReconciliationEntry>, observed: Set<LocalLibraryIdentity>): List<LocalLibraryStaleCandidate> {
        val duplicateIdentities = entries.groupingBy { it.identity }
            .eachCount()
            .filterValues { it > 1 }
            .keys
        return entries.asSequence()
            .filter { it.identity !in observed }
            .filter { it.identity.virtualFolder in healthyFolders }
            .filterNot { it.identity.virtualFolder in unavailableFolders }
            .filterNot { it.identity in duplicateIdentities }
            .map { LocalLibraryStaleCandidate(it.id, it.identity) }
            .toList()
    }

    fun duplicates(entries: List<LocalLibraryReconciliationEntry>): List<LocalLibraryDuplicateGroup> =
        entries.groupBy { it.identity }
            .filterValues { it.size > 1 }
            .map { (identity, matches) -> LocalLibraryDuplicateGroup(identity, matches.map { it.id }) }
            .sortedWith(compareBy({ it.identity.kind }, { it.identity.itemType }, { it.identity.virtualFolder }, { it.identity.relativePath }))

    return LocalLibraryReconciliationResult(
        addedTitleIds = scan.addedTitleIds,
        observedTitleIds = scan.observedTitleIds,
        addedChapterIds = scan.addedChapterIds,
        observedChapterIds = scan.observedChapterIds,
        staleTitleCandidates = stale(operation.existingTitles, observedTitles),
        staleChapterCandidates = stale(operation.existingChapters, observedChapters),
        duplicateTitleGroups = duplicates(operation.existingTitles),
        duplicateChapterGroups = duplicates(operation.existingChapters),
        unavailableFolders = scan.unavailableFolders,
    )
}

internal fun DbManga.isLocalLibraryEntry(): Boolean =
    isLocalArchive && source?.equals("torrent", ignoreCase = true) != true

fun localLibraryReconciliationOperation(
    scan: LocalLibraryScanResult,
    database: YokanDatabase,
    folders: List<DbLocalFolder>,
): LocalLibraryReconciliationOperation = LocalLibraryReconciliationOperation(
    scan = scan,
    existingTitles = database.mangas()
        .filter { it.isLocalLibraryEntry() }
        .mapNotNull { manga ->
            manga.link?.let { localVirtualPathFromStoredPath(it, folders) }
                ?.takeIf(String::isNotBlank)
                ?.let { LocalLibraryReconciliationEntry(manga.id, localLibraryIdentity(LocalLibraryEntityKind.Title, manga.itemType, it)) }
        },
    existingChapters = database.chapters()
        .mapNotNull { chapter ->
            val manga = chapter.mangaId?.let(database::manga)?.takeIf { it.isLocalLibraryEntry() }
                ?: return@mapNotNull null
            val path = chapter.archivePath.ifBlank { chapter.url }
            localVirtualPathFromStoredPath(path, folders)
                .takeIf(String::isNotBlank)
                ?.let { LocalLibraryReconciliationEntry(chapter.id, localLibraryIdentity(LocalLibraryEntityKind.Chapter, manga.itemType, it)) }
        },
)

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalTitleMetadata.kt

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

The implementation below defines LocalMetadata, parseLocalMetadata, JsonObject.toAnimetailMetadata, JsonObject.animetailStatus, JsonObject.toLocalMetadata, JsonObject.string, JsonObject.genres, JsonObject.status.

The source describes its contract as:

Title metadata read from a local metadata.json or Animetail details.json.

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbStatus
import eu.friedcutlet.yokan.domain.TitleCredit
import eu.friedcutlet.yokan.services.metadata.parseTitleCast
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull

/** Title metadata read from a local `metadata.json` or Animetail `details.json`. */
internal data class LocalMetadata(
    val name: String? = null,
    val description: String? = null,
    val author: String? = null,
    val artist: String? = null,
    val genres: List<String>? = null,
    val status: DbStatus? = null,
    val imageUrl: String? = null,
    val customCoverFromTracker: String? = null,
    val language: String? = null,
    val cast: List<TitleCredit>? = null,
) {
    val weight: Int get() = maxOf(1,
        listOfNotNull(name, description, author, artist, imageUrl, customCoverFromTracker, language).sumOf { it.length * 2 } +
            genres.orEmpty().sumOf { it.length * 2 } + cast.orEmpty().sumOf { credit ->
                128 + listOfNotNull(credit.name, credit.role, credit.character, credit.imageUrl).sumOf { it.length * 2 }
            },
    )
}

/** Parses [json] as Animetail `details.json` when [animetail], else as Yokan `metadata.json`; null if not an object. */
internal fun parseLocalMetadata(json: String, animetail: Boolean): LocalMetadata? =
    (Json.parseToJsonElement(json) as? JsonObject)?.let { value ->
        if (animetail) value.toAnimetailMetadata() else value.toLocalMetadata()
    }

/** Animetail SAnime numbers are not Yokan metadata.json enum ordinals. */
private fun JsonObject.toAnimetailMetadata(): LocalMetadata = LocalMetadata(
    name = string("title"), description = string("description"), author = string("author"), artist = string("artist"),
    genres = (this["genre"] as? JsonArray)?.takeIf { values -> values.all { (it as? JsonPrimitive)?.isString == true } }
        ?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf(String::isNotEmpty) }?.distinct(),
    status = animetailStatus(),
    cast = parseTitleCast(this["cast"]),
)

private fun JsonObject.animetailStatus(): DbStatus? = when ((this["status"] as? JsonPrimitive)?.intOrNull) {
    null -> null
    0 -> DbStatus.Unknown
    1 -> DbStatus.Ongoing
    2 -> DbStatus.Completed
    3 -> DbStatus.Licensed
    4 -> DbStatus.PublishingFinished
    5 -> DbStatus.Canceled
    6 -> DbStatus.OnHiatus
    7 -> DbStatus.Upcoming
    else -> null
}

private fun JsonObject.toLocalMetadata(): LocalMetadata =
    LocalMetadata(
        name = string("name", "title"),
        description = string("description", "summary"),
        author = string("author"),
        artist = string("artist"),
        genres = genres("genre", "genres", "tags"),
        status = status("status"),
        imageUrl = string("imageUrl", "thumbnailUrl", "thumbnail_url", "cover", "coverUrl"),
        customCoverFromTracker = string("customCoverFromTracker"),
        language = string("language", "lang"),
        cast = parseTitleCast(this["cast"]),
    )

private fun JsonObject.string(vararg keys: String): String? {
    for (key in keys) {
        val value = (this[key] as? JsonPrimitive)?.contentOrNull?.trim()
        if (!value.isNullOrEmpty()) return value
    }
    return null
}

private fun JsonObject.genres(vararg keys: String): List<String>? {
    for (key in keys) {
        when (val value = this[key]) {
            is JsonArray -> {
                val genres = value.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim() }
                    .filter { it.isNotEmpty() }
                if (genres.isNotEmpty()) return genres
            }
            is JsonPrimitive -> {
                val genres = value.contentOrNull
                    ?.split(',', ';')
                    ?.map { it.trim() }
                    ?.filter { it.isNotEmpty() }
                    .orEmpty()
                if (genres.isNotEmpty()) return genres
            }
            else -> Unit
        }
    }
    return null
}

private fun JsonObject.status(key: String): DbStatus? {
    val value = this[key] ?: return null
    (value as? JsonPrimitive)?.intOrNull?.let { index -> return DbStatus.entries.getOrNull(index) }
    val label = (value as? JsonPrimitive)?.contentOrNull?.trim().orEmpty()
    if (label.isEmpty()) return null
    return DbStatus.entries.firstOrNull { it.name.equals(label, ignoreCase = true) }
        ?: when (label.lowercase()) {
            "ongoing" -> DbStatus.Ongoing
            "completed", "complete" -> DbStatus.Completed
            "cancelled", "canceled" -> DbStatus.Canceled
            "hiatus", "on hiatus" -> DbStatus.OnHiatus
            "publishing finished" -> DbStatus.PublishingFinished
            else -> DbStatus.Unknown
        }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalEpisodeMetadata.kt

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

The implementation below defines LocalEpisodeMetadata, LocalEpisodeMetadataIndex, find, parseLocalEpisodes, string.

The source describes its contract as:

Indexed once per sidecar; duplicate exact declarations keep their first entry.

package eu.friedcutlet.yokan.services.library

import kotlinx.datetime.LocalDate
import kotlinx.serialization.json.*
import kotlin.math.abs

internal data class LocalEpisodeMetadata(
    val number: Double,
    val name: String?,
    val dateUpload: String?,
    val filler: Boolean?,
    val scanlator: String?,
    val summary: String?,
    val previewUrl: String?,
)

/** Indexed once per sidecar; duplicate exact declarations keep their first entry. */
internal class LocalEpisodeMetadataIndex(entries: List<LocalEpisodeMetadata>) {
    private val byNumber = entries.distinctBy { it.number }.sortedBy { it.number }
    val weight: Int = maxOf(1, byNumber.sumOf { entry ->
        128 + listOf(entry.name, entry.dateUpload, entry.scanlator, entry.summary, entry.previewUrl).sumOf { (it?.length ?: 0) * 2 }
    })

    fun find(number: Double?): LocalEpisodeMetadata? {
        if (number == null || !number.isFinite() || number < 0) return null
        var low = 0
        var high = byNumber.size
        while (low < high) {
            val middle = (low + high) ushr 1
            if (byNumber[middle].number < number) low = middle + 1 else high = middle
        }
        val next = byNumber.getOrNull(low)
        if (next?.number == number) return next
        val before = byNumber.getOrNull(low - 1)?.takeIf { abs(it.number - number) < 0.0001 }
        val after = next?.takeIf { abs(it.number - number) < 0.0001 }
        // Ambiguous close declarations must not apply metadata to the wrong episode.
        if (before != null && (after != null || byNumber.getOrNull(low - 2)?.let { abs(it.number - number) < 0.0001 } == true)) return null
        if (after != null && byNumber.getOrNull(low + 1)?.let { abs(it.number - number) < 0.0001 } == true) return null
        return before ?: after
    }
}

/** Called only after a bounded asynchronous read; malformed individual rows are optional. */
internal fun parseLocalEpisodes(text: String): LocalEpisodeMetadataIndex {
    val values = Json.parseToJsonElement(text) as? JsonArray ?: error("Episode metadata must be an array")
    require(values.size <= 10_000) { "Too many episode metadata entries" }
    return LocalEpisodeMetadataIndex(values.mapNotNull { value ->
        val row = value as? JsonObject ?: return@mapNotNull null
        val number = (row["episode_number"] as? JsonPrimitive)?.takeUnless { it.isString }?.doubleOrNull
            ?.takeIf { it.isFinite() && it >= 0 } ?: return@mapNotNull null
        fun string(key: String) = (row[key] as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull
        LocalEpisodeMetadata(
            number = if (number == 0.0) 0.0 else number,
            name = string("name")?.trim()?.takeIf(String::isNotEmpty),
            dateUpload = string("date_upload")?.let { runCatching { LocalDate.parse(it).toString() }.getOrNull() },
            filler = (row["fillermark"] as? JsonPrimitive)?.takeUnless { it.isString }?.booleanOrNull,
            scanlator = string("scanlator")?.trim(),
            summary = string("summary"),
            previewUrl = string("preview_url")?.trim()?.takeIf(String::isNotEmpty),
        )
    })
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalEntryManagementService.kt

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

Preview and apply are separate operations. The expected snapshot protects edits made while a user reviews the preview, and external originals remain outside managed database cleanup.

The implementation below defines LocalEntryManagementBlockers, LocalEntryManagementOperation, ForgetStale, MergeDuplicateTitles, LocalEntryManagementCommand, LocalEntrySourceTitleEffect, LocalEntryManagementPreview, LocalEntryManagementApplyStatus, LocalEntryManagementApplyResult, LocalEntryManagementService and 48 further declarations.

The source describes its contract as:

Reasons an entry-management command is not safe to apply.

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.SnapshotReplacementConflictException
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.mergeProgress
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.CancellationException
import kotlinx.serialization.Serializable

/** Reasons an entry-management command is not safe to apply. */
object LocalEntryManagementBlockers {
    const val StateChanged = "STATE_CHANGED"
    const val AtomicSnapshotPersistenceUnavailable = "ATOMIC_SNAPSHOT_PERSISTENCE_UNAVAILABLE"
    const val AtomicSnapshotPersistenceFailed = "ATOMIC_SNAPSHOT_PERSISTENCE_FAILED"
    const val StaleEvidenceRequired = "STALE_EVIDENCE_REQUIRED"
    const val CandidateChanged = "CANDIDATE_CHANGED"
    const val FreshReconciliationChanged = "FRESH_RECONCILIATION_CHANGED"
    const val ActiveDownload = "ACTIVE_DOWNLOAD"
    const val InvalidDuplicateGroup = "INVALID_DUPLICATE_GROUP"
    const val TorrentEntry = "TORRENT_ENTRY"
    const val ItemTypeMismatch = "ITEM_TYPE_MISMATCH"
    const val RemoteMetadataConflict = "REMOTE_METADATA_CONFLICT"
    const val TrackerBindingConflict = "TRACKER_BINDING_CONFLICT"
    const val TrackerStateConflict = "TRACKER_STATE_CONFLICT"
    const val ChapterProgressConflict = "CHAPTER_PROGRESS_CONFLICT"
    const val CompletedDownloadConflict = "COMPLETED_DOWNLOAD_CONFLICT"
    const val DownloadIdentityConflict = "DOWNLOAD_IDENTITY_CONFLICT"
}

@Serializable
sealed class LocalEntryManagementOperation {
    /** Only IDs present in [evidence] may be forgotten. */
    @Serializable
    data class ForgetStale(
        val evidence: LocalLibraryReconciliationResult,
        val titleIds: List<Long> = emptyList(),
        val chapterIds: List<Long> = emptyList(),
    ) : LocalEntryManagementOperation()

    /** The group is exact-local-identity evidence; no fuzzy title matching is used. */
    @Serializable
    data class MergeDuplicateTitles(
        val evidence: LocalLibraryReconciliationResult,
        val titleIds: List<Long>,
        val canonicalTitleId: Long? = null,
    ) : LocalEntryManagementOperation()
}

@Serializable
data class LocalEntryManagementCommand(
    val operation: LocalEntryManagementOperation,
    val stateFingerprint: String,
)

@Serializable
data class LocalEntrySourceTitleEffect(
    val canonicalTitleId: Long,
    val favoriteBefore: Boolean,
    val favoriteAfter: Boolean,
    val lastReadBefore: Long,
    val lastReadAfter: Long,
    val dateAddedBefore: Long? = null,
    val dateAddedAfter: Long? = null,
    val smartUpdateDaysFallback: Int? = null,
    val customCoverFallback: Boolean = false,
    val metadataFallbackFields: List<String> = emptyList(),
)

@Serializable
data class LocalEntryManagementPreview(
    val command: LocalEntryManagementCommand,
    val titleIds: List<Long> = emptyList(),
    val chapterIds: List<Long> = emptyList(),
    val titleRowsRemoved: Int = 0,
    val chapterRowsRemoved: Int = 0,
    val databaseRowsRemoved: Int = 0,
    val databaseRowsAdded: Int = 0,
    val databaseRowsUpdated: Int = 0,
    val settingsRecordsAffected: Int = 0,
    val sourceFilesAffected: Int = 0,
    val blockers: List<String> = emptyList(),
    val sourceTitleEffect: LocalEntrySourceTitleEffect? = null,
)

@Serializable
enum class LocalEntryManagementApplyStatus { Applied, Rejected }

@Serializable
data class LocalEntryManagementApplyResult(
    val status: LocalEntryManagementApplyStatus,
    val blocker: String? = null,
    val preview: LocalEntryManagementPreview,
)

interface LocalEntryManagementService {
    /** Pure: reads the database and returns a command/preview; it never mutates either backend. */
    fun preview(operation: LocalEntryManagementOperation): LocalEntryManagementPreview

    /** Rechecks the fingerprint and evidence before an atomic snapshot replacement. */
    suspend fun apply(command: LocalEntryManagementCommand): LocalEntryManagementApplyResult
}

class DefaultLocalEntryManagementService(
    private val database: YokanDatabase,
    private val localLibrary: LocalLibraryService,
) : LocalEntryManagementService {
    override fun preview(operation: LocalEntryManagementOperation): LocalEntryManagementPreview {
        val snapshot = database.snapshot()
        val plan = plan(snapshot, operation)
        val command = LocalEntryManagementCommand(operation, fingerprint(snapshot, operation))
        return previewOf(command, plan, snapshot)
    }

    override suspend fun apply(command: LocalEntryManagementCommand): LocalEntryManagementApplyResult =
        localLibrary.withOperationLock {
            val freshEvidence = localLibrary.reconcileForEntryManagement()
            if (!evidenceStillCurrent(command.operation, freshEvidence)) {
                return@withOperationLock rejected(command, LocalEntryManagementBlockers.FreshReconciliationChanged)
            }
            applyAfterFreshScan(command)
        }

    private suspend fun applyAfterFreshScan(command: LocalEntryManagementCommand): LocalEntryManagementApplyResult {
        val current = database.snapshot()
        if (fingerprint(current, command.operation) != command.stateFingerprint) {
            return LocalEntryManagementApplyResult(
                LocalEntryManagementApplyStatus.Rejected,
                LocalEntryManagementBlockers.StateChanged,
                previewOf(command, Plan(blockers = listOf(LocalEntryManagementBlockers.StateChanged)), current),
            )
        }

        val currentPlan = plan(current, command.operation)
        val currentPreview = previewOf(command, currentPlan, current)
        currentPlan.blockers.firstOrNull()?.let { blocker ->
            return LocalEntryManagementApplyResult(LocalEntryManagementApplyStatus.Rejected, blocker, currentPreview)
        }
        if (!database.supportsAtomicSnapshotPersistence()) {
            return LocalEntryManagementApplyResult(
                LocalEntryManagementApplyStatus.Rejected,
                LocalEntryManagementBlockers.AtomicSnapshotPersistenceUnavailable,
                currentPreview.copy(blockers = listOf(LocalEntryManagementBlockers.AtomicSnapshotPersistenceUnavailable)),
            )
        }

        return try {
            database.replaceAllAtomically(checkNotNull(currentPlan.snapshot), expectedSnapshot = current)
            LocalEntryManagementApplyResult(LocalEntryManagementApplyStatus.Applied, preview = currentPreview)
        } catch (_: SnapshotReplacementConflictException) {
            LocalEntryManagementApplyResult(
                LocalEntryManagementApplyStatus.Rejected,
                LocalEntryManagementBlockers.StateChanged,
                previewOf(
                    command,
                    Plan(blockers = listOf(LocalEntryManagementBlockers.StateChanged)),
                    database.snapshot(),
                ),
            )
        } catch (error: CancellationException) {
            throw error
        } catch (_: Throwable) {
            LocalEntryManagementApplyResult(
                LocalEntryManagementApplyStatus.Rejected,
                LocalEntryManagementBlockers.AtomicSnapshotPersistenceFailed,
                currentPreview.copy(blockers = listOf(LocalEntryManagementBlockers.AtomicSnapshotPersistenceFailed)),
            )
        }
    }

    private fun rejected(command: LocalEntryManagementCommand, blocker: String) =
        LocalEntryManagementApplyResult(
            LocalEntryManagementApplyStatus.Rejected,
            blocker,
            previewOf(command, Plan(blockers = listOf(blocker)), database.snapshot()),
        )

    private fun evidenceStillCurrent(
        operation: LocalEntryManagementOperation,
        fresh: LocalLibraryReconciliationResult,
    ): Boolean = when (operation) {
        is LocalEntryManagementOperation.ForgetStale ->
            operation.titleIds.all { id -> fresh.staleTitleCandidates.any { it.id == id && it in operation.evidence.staleTitleCandidates } } &&
                operation.chapterIds.all { id -> fresh.staleChapterCandidates.any { it.id == id && it in operation.evidence.staleChapterCandidates } }
        is LocalEntryManagementOperation.MergeDuplicateTitles ->
            fresh.duplicateTitleGroups.any { group ->
                group.ids.toSet() == operation.titleIds.toSet() &&
                    group.identity == operation.evidence.duplicateTitleGroups.firstOrNull { it.ids.toSet() == operation.titleIds.toSet() }?.identity
            }
    }

    private fun previewOf(command: LocalEntryManagementCommand, plan: Plan, before: YokanDatabaseSnapshot): LocalEntryManagementPreview {
        val after = plan.snapshot
        val removedTitles = if (after == null) emptySet() else before.mangas.map { it.id }.toSet() - after.mangas.map { it.id }.toSet()
        val removedChapters = if (after == null) emptySet() else before.chapters.map { it.id }.toSet() - after.chapters.map { it.id }.toSet()
        val insertedRows = if (after == null) 0 else addedRowCount(before, after)
        val updatedRows = if (after == null) 0 else changedRowCount(before, after) + insertedRows
        val settingsAffected = if (after?.settings != before.settings) 1 else 0
        return LocalEntryManagementPreview(
            command = command,
            titleIds = removedTitles.toList().sorted(),
            chapterIds = removedChapters.toList().sorted(),
            titleRowsRemoved = removedTitles.size,
            chapterRowsRemoved = removedChapters.size,
            databaseRowsRemoved = if (after == null) 0 else removedRowCount(before, after),
            databaseRowsAdded = insertedRows,
            databaseRowsUpdated = updatedRows.coerceAtLeast(0),
            settingsRecordsAffected = settingsAffected,
            // Management is logical only. It never deletes, moves, or copies files.
            sourceFilesAffected = 0,
            blockers = plan.blockers,
            sourceTitleEffect = plan.sourceTitleEffect,
        )
    }

    private data class Plan(
        val snapshot: YokanDatabaseSnapshot? = null,
        val blockers: List<String> = emptyList(),
        val sourceTitleEffect: LocalEntrySourceTitleEffect? = null,
    )

    private fun plan(snapshot: YokanDatabaseSnapshot, operation: LocalEntryManagementOperation): Plan = when (operation) {
        is LocalEntryManagementOperation.ForgetStale -> forgetPlan(snapshot, operation)
        is LocalEntryManagementOperation.MergeDuplicateTitles -> mergePlan(snapshot, operation)
    }

    private fun forgetPlan(snapshot: YokanDatabaseSnapshot, operation: LocalEntryManagementOperation.ForgetStale): Plan {
        if (operation.titleIds.isEmpty() && operation.chapterIds.isEmpty()) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.StaleEvidenceRequired))
        }
        val titleCandidates = operation.evidence.staleTitleCandidates.associateBy { it.id }
        val chapterCandidates = operation.evidence.staleChapterCandidates.associateBy { it.id }
        if (operation.titleIds.any { it !in titleCandidates } || operation.chapterIds.any { it !in chapterCandidates }) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.StaleEvidenceRequired))
        }

        val titles = operation.titleIds.mapNotNull { id -> snapshot.mangas.firstOrNull { it.id == id } }
        val chapters = operation.chapterIds.mapNotNull { id -> snapshot.chapters.firstOrNull { it.id == id } }
        if (titles.size != operation.titleIds.size || chapters.size != operation.chapterIds.size) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.CandidateChanged))
        }
        if (titles.any { !it.isLocalLibraryEntry() } || chapters.any { chapter ->
                chapter.mangaId?.let { mangaId -> snapshot.mangas.firstOrNull { it.id == mangaId } }?.isLocalLibraryEntry() != true
            }) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.CandidateChanged))
        }
        if (titles.any { titleCandidates[it.id]?.identity != it.titleIdentity() } || chapters.any { chapter ->
                val owner = chapter.mangaId?.let { mangaId -> snapshot.mangas.firstOrNull { it.id == mangaId } }
                chapterCandidates[chapter.id]?.identity != chapterIdentity(chapter, owner?.itemType)
            }) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.CandidateChanged))
        }

        val titleIds = operation.titleIds.toMutableSet()
        val chapterIds = operation.chapterIds.toMutableSet()
        snapshot.chapters.filter { it.mangaId in titleIds }.forEach { chapterIds += it.id }
        val active = snapshot.downloads.any { it.chapterId in chapterIds && it.isActive() }
        if (active) return Plan(blockers = listOf(LocalEntryManagementBlockers.ActiveDownload))
        return Plan(snapshot = removeEntries(snapshot, titleIds, chapterIds))
    }

    private fun mergePlan(snapshot: YokanDatabaseSnapshot, operation: LocalEntryManagementOperation.MergeDuplicateTitles): Plan {
        val group = operation.evidence.duplicateTitleGroups.firstOrNull { it.ids == operation.titleIds }
            ?: operation.evidence.duplicateTitleGroups.firstOrNull { it.ids.toSet() == operation.titleIds.toSet() }
            ?: return Plan(blockers = listOf(LocalEntryManagementBlockers.InvalidDuplicateGroup))
        val titles = operation.titleIds.mapNotNull { id -> snapshot.mangas.firstOrNull { it.id == id } }
        if (titles.size != operation.titleIds.size || titles.size < 2) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.InvalidDuplicateGroup))
        }
        if (titles.any { !it.isLocalLibraryEntry() || it.source?.equals("torrent", ignoreCase = true) == true }) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.TorrentEntry))
        }
        if (titles.map { it.itemType }.distinct().size != 1 || titles.any { it.titleIdentity() != group.identity }) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.ItemTypeMismatch))
        }
        val canonicalId = operation.canonicalTitleId ?: operation.titleIds.min()
        if (canonicalId !in operation.titleIds) return Plan(blockers = listOf(LocalEntryManagementBlockers.InvalidDuplicateGroup))

        val metadata = snapshot.settings.titleMetadata.orEmpty().filter { it.mangaId in operation.titleIds }
        val metadataBindings = metadata.mapNotNull { it.metadataServerId to it.metadataSource }.distinct()
        if (metadataBindings.size > 1) return Plan(blockers = listOf(LocalEntryManagementBlockers.RemoteMetadataConflict))
        val sourceBindings = titles.mapNotNull { it.sourceId }.distinct()
        if (sourceBindings.size > 1) return Plan(blockers = listOf(LocalEntryManagementBlockers.RemoteMetadataConflict))

        val tracks = snapshot.tracks.filter { it.mangaId in operation.titleIds }
        val trackerBindings = tracks.filter { it.syncId != null }.groupBy { it.syncId }
            .values.any { rows -> rows.map { it.mediaId }.distinct().size > 1 }
        if (trackerBindings) return Plan(blockers = listOf(LocalEntryManagementBlockers.TrackerBindingConflict))
        val trackerStateConflict = tracks.filter { it.syncId != null }
            .groupBy { it.syncId to it.mediaId }
            .values.any { rows ->
                rows.map { it.lastChapterRead ?: 0 }.distinct().size == 1 &&
                    (rows.map { it.status }.distinct().size > 1 || rows.mapNotNull { it.score }.distinct().size > 1)
            }
        if (trackerStateConflict) return Plan(blockers = listOf(LocalEntryManagementBlockers.TrackerStateConflict))

        val titleIds = operation.titleIds.toSet()
        val chapterMap = chapterMapFor(snapshot, titleIds, canonicalId)
        val affectedChapterIds = snapshot.chapters.filter { it.mangaId in titleIds }.mapTo(mutableSetOf()) { it.id }
        if (snapshot.downloads.any { it.chapterId in affectedChapterIds && it.isActive() }) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.ActiveDownload))
        }
        val downloadTargets = snapshot.downloads
            .filter { it.chapterId in affectedChapterIds }
            .groupBy { chapterMap[it.chapterId] ?: it.chapterId }
        val ambiguousRemaps = downloadTargets.values.filter { rows ->
            rows.size > 1 && rows.any { it.chapterId in chapterMap.keys }
        }
        if (ambiguousRemaps.any { rows -> rows.any { it.isDownload == true } }) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.CompletedDownloadConflict))
        }
        if (ambiguousRemaps.isNotEmpty()) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.DownloadIdentityConflict))
        }
        // A remapped download's task ID (and the storage lookup derived from it)
        // uses the old chapter ID. It cannot safely follow the chapter merge.
        if (snapshot.downloads.any { it.chapterId in chapterMap.keys }) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.DownloadIdentityConflict))
        }
        if (hasChapterProgressConflict(snapshot, titleIds, canonicalId)) {
            return Plan(blockers = listOf(LocalEntryManagementBlockers.ChapterProgressConflict))
        }

        return Plan(
            snapshot = mergeEntries(snapshot, titleIds, canonicalId),
            sourceTitleEffect = sourceTitleEffect(snapshot, titleIds, canonicalId),
        )
    }

    private fun sourceTitleEffect(snapshot: YokanDatabaseSnapshot, titleIds: Set<Long>, canonicalId: Long): LocalEntrySourceTitleEffect {
        val canonical = snapshot.mangas.first { it.id == canonicalId }
        val duplicates = snapshot.mangas.filter { it.id in titleIds && it.id != canonicalId }
        val merged = mergeTitleState(canonical, duplicates)
        val fallbackFields = listOf(
            "name" to (canonical.name.isNullOrBlank() && !merged.name.isNullOrBlank()),
            "imageUrl" to (canonical.imageUrl.isNullOrBlank() && !merged.imageUrl.isNullOrBlank()),
            "description" to (canonical.description.isNullOrBlank() && !merged.description.isNullOrBlank()),
            "author" to (canonical.author.isNullOrBlank() && !merged.author.isNullOrBlank()),
            "artist" to (canonical.artist.isNullOrBlank() && !merged.artist.isNullOrBlank()),
            "genre" to (canonical.genre.isNullOrEmpty() && !merged.genre.isNullOrEmpty()),
            "status" to (canonical.status == eu.friedcutlet.yokan.database.DbStatus.Unknown && merged.status != canonical.status),
            "lang" to (canonical.lang.isNullOrBlank() && !merged.lang.isNullOrBlank()),
        ).filter { it.second }.map { it.first }
        return LocalEntrySourceTitleEffect(
            canonicalTitleId = canonicalId,
            favoriteBefore = canonical.favorite,
            favoriteAfter = merged.favorite,
            lastReadBefore = canonical.lastRead,
            lastReadAfter = merged.lastRead,
            dateAddedBefore = canonical.dateAdded,
            dateAddedAfter = merged.dateAdded,
            smartUpdateDaysFallback = merged.smartUpdateDays.takeIf { canonical.smartUpdateDays == null },
            customCoverFallback = canonical.customCoverImage == null && merged.customCoverImage != null,
            metadataFallbackFields = fallbackFields,
        )
    }

    private fun chapterMapFor(snapshot: YokanDatabaseSnapshot, titleIds: Set<Long>, canonicalId: Long): Map<Long, Long> {
        val itemType = snapshot.mangas.first { it.id == canonicalId }.itemType
        val chapters = snapshot.chapters.filter { it.mangaId in titleIds }
        val targets = chapters.filter { it.mangaId == canonicalId }
            .associateBy { chapterIdentity(it, itemType) }
            .mapValues { it.value.id }
            .toMutableMap()
        val map = mutableMapOf<Long, Long>()
        chapters.filter { it.mangaId != canonicalId }.forEach { chapter ->
            val identity = chapterIdentity(chapter, itemType)
            val target = targets[identity]
            if (target != null) {
                map[chapter.id] = target
            } else {
                targets[identity] = chapter.id
            }
        }
        return map
    }

    private fun hasChapterProgressConflict(snapshot: YokanDatabaseSnapshot, titleIds: Set<Long>, canonicalId: Long): Boolean {
        val itemType = snapshot.mangas.first { it.id == canonicalId }.itemType
        val chapters = snapshot.chapters.filter { it.mangaId in titleIds }
        val canonicalByIdentity = chapters.filter { it.mangaId == canonicalId }
            .associateBy { chapterIdentity(it, itemType) }
        return chapters.filter { it.mangaId != canonicalId }.any { duplicate ->
            val canonical = canonicalByIdentity[chapterIdentity(duplicate, itemType)] ?: return@any false
            conflictingPagePositions(canonical.lastPageRead, duplicate.lastPageRead)
        }
    }

    private fun conflictingPagePositions(first: String, second: String): Boolean {
        if (first.isBlank() || second.isBlank() || first == second) return false
        val firstNumber = first.toLongOrNull()
        val secondNumber = second.toLongOrNull()
        return firstNumber == null || secondNumber == null
    }

    private fun removeEntries(snapshot: YokanDatabaseSnapshot, titleIds: Set<Long>, chapterIds: Set<Long>): YokanDatabaseSnapshot {
        val allChapterIds = snapshot.chapters.filter { it.id in chapterIds || it.mangaId in titleIds }.mapTo(mutableSetOf()) { it.id }
        val removedTitles = titleIds
        val removedChapters = allChapterIds
        val removedHistories = snapshot.histories.filter { it.mangaId in removedTitles || it.chapterId in removedChapters }.mapTo(mutableSetOf()) { it.id }
        val removedUpdates = snapshot.updates.filter { it.mangaId in removedTitles || it.chapterId in removedChapters }.mapTo(mutableSetOf()) { it.id }
        val removedTracks = snapshot.tracks.filter { it.mangaId in removedTitles }.mapTo(mutableSetOf()) { it.id }
        val settings = cleanSettings(snapshot.settings, removedTitles, removedChapters)
        return snapshot.copy(
            settings = settings,
            mangas = snapshot.mangas.filterNot { it.id in removedTitles },
            chapters = snapshot.chapters.filterNot { it.id in removedChapters },
            histories = snapshot.histories.filterNot { it.mangaId in removedTitles || it.chapterId in removedChapters },
            updates = snapshot.updates.filterNot { it.mangaId in removedTitles || it.chapterId in removedChapters },
            downloads = snapshot.downloads.filterNot { it.chapterId in removedChapters },
            tracks = snapshot.tracks.filterNot { it.mangaId in removedTitles },
            trackSearches = snapshot.trackSearches.filterNot { it.libraryId in removedTitles },
            pageCache = snapshot.pageCache.filterNot { it.chapterId in removedChapters },
            changedParts = mergeTombstones(
                snapshot.changedParts,
                removedTitles = removedTitles,
                removedChapters = removedChapters,
                removedHistories = removedHistories,
                removedUpdates = removedUpdates,
                removedTracks = removedTracks,
            ),
        )
    }

    private fun mergeEntries(snapshot: YokanDatabaseSnapshot, titleIds: Set<Long>, canonicalId: Long): YokanDatabaseSnapshot {
        val duplicateIds = titleIds - canonicalId
        val canonical = snapshot.mangas.first { it.id == canonicalId }
        val itemType = canonical.itemType
        val chapterMap = chapterMapFor(snapshot, titleIds, canonicalId)
        val chapterIdentities = snapshot.chapters.filter { it.mangaId in titleIds }
            .associateWith { chapterIdentity(it, itemType) }
        val canonicalChapterById = snapshot.chapters.associateBy { it.id }.toMutableMap()
        chapterMap.forEach { (duplicateId, targetId) ->
            canonicalChapterById[targetId] = canonicalChapterById.getValue(targetId)
                .mergeProgress(canonicalChapterById.getValue(duplicateId))
        }
        val mergedChapters = snapshot.chapters
            .filterNot { it.id in chapterMap }
            .map { chapter ->
                when {
                    chapter.id in canonicalChapterById && chapter.id in chapterMap.values -> canonicalChapterById.getValue(chapter.id)
                    chapter.mangaId in duplicateIds -> chapter.copy(mangaId = canonicalId)
                    else -> chapter
                }
            }

        val mergedTitles = snapshot.mangas
            .filterNot { it.id in duplicateIds }
            .map { title ->
                if (title.id != canonicalId) title else mergeTitleState(
                    title,
                    snapshot.mangas.filter { it.id in duplicateIds },
                )
            }
        val settings = mergeSettings(snapshot.settings, titleIds, duplicateIds, chapterMap, canonicalId)
        val historyMerge = mergeHistories(snapshot, titleIds, duplicateIds, chapterMap, canonicalId, mergedChapters)
        val trackMerge = mergeTracks(snapshot.tracks, duplicateIds, canonicalId)
        return snapshot.copy(
            settings = settings,
            mangas = mergedTitles,
            chapters = mergedChapters,
            histories = historyMerge.rows,
            updates = snapshot.updates.map { it.remap(duplicateIds, chapterMap, canonicalId) },
            downloads = snapshot.downloads.map { download -> download.copy(chapterId = chapterMap[download.chapterId] ?: download.chapterId) },
            tracks = trackMerge.rows,
            trackSearches = snapshot.trackSearches.map { it.copy(libraryId = it.libraryId?.let { id -> if (id in duplicateIds) canonicalId else id }) },
            pageCache = mergePageCache(snapshot, chapterMap),
            changedParts = mergeTombstones(
                snapshot.changedParts,
                removedTitles = duplicateIds,
                removedChapters = chapterMap.keys,
                removedHistories = historyMerge.removedIds,
                removedTracks = trackMerge.removedIds,
                cancelledTitles = setOf(canonicalId),
                cancelledChapters = snapshot.chapters.filter { it.mangaId in titleIds && it.id !in chapterMap }.mapTo(mutableSetOf()) { it.id },
                cancelledHistories = historyMerge.rows.filter { it.mangaId == canonicalId }.mapTo(mutableSetOf()) { it.id },
                cancelledTracks = trackMerge.rows.filter { it.mangaId == canonicalId }.mapTo(mutableSetOf()) { it.id },
            ),
        )
    }

    private fun mergeTitleState(canonical: DbManga, duplicates: List<DbManga>): DbManga {
        fun String?.fallbackField(selector: (DbManga) -> String?): String? = this?.takeIf { it.isNotBlank() }
            ?: duplicates.asSequence().mapNotNull { selector(it)?.takeIf(String::isNotBlank) }.firstOrNull()

        val dateCandidates = listOfNotNull(canonical.dateAdded) + duplicates.mapNotNull { it.dateAdded }
        val smartUpdate = canonical.smartUpdateDays ?: duplicates.mapNotNull { it.smartUpdateDays }.firstOrNull()
        val cover = canonical.customCoverImage ?: duplicates.firstNotNullOfOrNull { it.customCoverImage }
        val trackerCover = canonical.customCoverFromTracker.fallbackField(DbManga::customCoverFromTracker)
        val genres = canonical.genre?.takeIf { it.isNotEmpty() }
            ?: duplicates.firstNotNullOfOrNull { it.genre?.takeIf(List<String>::isNotEmpty) }
        val status = if (canonical.status == eu.friedcutlet.yokan.database.DbStatus.Unknown) {
            duplicates.firstOrNull { it.status != eu.friedcutlet.yokan.database.DbStatus.Unknown }?.status ?: canonical.status
        } else canonical.status
        return canonical.copy(
            name = canonical.name.fallbackField(DbManga::name),
            imageUrl = canonical.imageUrl.fallbackField(DbManga::imageUrl),
            description = canonical.description.fallbackField(DbManga::description),
            author = canonical.author.fallbackField(DbManga::author),
            artist = canonical.artist.fallbackField(DbManga::artist),
            status = status,
            genre = genres,
            favorite = canonical.favorite || duplicates.any { it.favorite },
            lang = canonical.lang.fallbackField(DbManga::lang),
            dateAdded = dateCandidates.minOrNull(),
            lastRead = maxOf(canonical.lastRead, duplicates.maxOfOrNull { it.lastRead } ?: 0L),
            categories = (canonical.categories.orEmpty() + duplicates.flatMap { it.categories.orEmpty() })
                .distinct().takeIf { it.isNotEmpty() },
            customCoverImage = cover,
            customCoverFromTracker = trackerCover,
            smartUpdateDays = smartUpdate,
            sourceId = canonical.sourceId ?: duplicates.mapNotNull(DbManga::sourceId).firstOrNull(),
            updatedAt = maxOf(canonical.updatedAt, duplicates.maxOfOrNull { it.updatedAt } ?: 0L),
        )
    }

    private data class MappedHistory(val originalMangaId: Long?, val row: DbHistory)

    private data class HistoryMergeResult(
        val rows: List<DbHistory>,
        val removedIds: Set<Long>,
    )

    private fun mergeHistories(
        snapshot: YokanDatabaseSnapshot,
        titleIds: Set<Long>,
        duplicateIds: Set<Long>,
        chapterMap: Map<Long, Long>,
        canonicalId: Long,
        mergedChapters: List<DbChapter>,
    ): HistoryMergeResult {
        val mapped = snapshot.histories.map { history ->
            MappedHistory(history.mangaId, history.remap(duplicateIds, chapterMap, canonicalId))
        }
        val affected = mapped.filter { it.originalMangaId in titleIds }
        val grouped = affected.groupBy { it.row.mangaId }
        val rowsForTitle = grouped[canonicalId].orEmpty()
        if (rowsForTitle.isEmpty()) return HistoryMergeResult(mapped.map { it.row }, emptySet())

        val validChapterIds = mergedChapters.mapTo(mutableSetOf()) { it.id }
        val valid = rowsForTitle.filter { it.row.chapterId == null || it.row.chapterId in validChapterIds }
        val validWithChapter = valid.filter { it.row.chapterId != null }
        val representative = (validWithChapter.ifEmpty { valid }).maxWithOrNull(historyComparator())
            ?: rowsForTitle.maxWith(historyComparator())
        // Keep the canonical title's history row identity where one exists;
        // only its state is consolidated from the newest valid history.
        val canonicalHistoryId = rowsForTitle.firstOrNull { it.originalMangaId == canonicalId }?.row?.id
            ?: representative.row.id
        val readingTime = rowsForTitle.mapNotNull { it.row.readingTimeSeconds?.toLong() }.sum()
        val consolidated = representative.row.copy(
            id = canonicalHistoryId,
            mangaId = canonicalId,
            chapterId = representative.row.chapterId?.takeIf { it in validChapterIds },
            readingTimeSeconds = readingTime.coerceAtMost(Int.MAX_VALUE.toLong()).toInt().takeIf { rowsForTitle.any { it.row.readingTimeSeconds != null } },
            updatedAt = rowsForTitle.maxOf { it.row.updatedAt },
        )
        val removedIds = rowsForTitle.mapTo(mutableSetOf()) { it.row.id } - canonicalHistoryId
        val result = mapped.filterNot { it.originalMangaId in titleIds }
            .map { it.row }
            .toMutableList()
        result += consolidated
        return HistoryMergeResult(result, removedIds)
    }

    private fun historyComparator(): Comparator<MappedHistory> = compareBy(
        { it.row.updatedAt },
        { it.row.date?.toLongOrNull() ?: Long.MIN_VALUE },
        { it.row.id },
    )

    private data class TrackMergeResult(
        val rows: List<DbTrack>,
        val removedIds: Set<Long>,
    )

    private fun mergeTracks(tracks: List<DbTrack>, duplicateIds: Set<Long>, canonicalId: Long): TrackMergeResult {
        val result = tracks.filter { it.mangaId !in duplicateIds }.toMutableList()
        val removedIds = mutableSetOf<Long>()
        tracks.filter { it.mangaId in duplicateIds }.forEach { duplicate ->
            val migrated = duplicate.copy(
                mangaId = canonicalId,
                libraryId = duplicate.libraryId?.let { if (it in duplicateIds) canonicalId else it },
            )
            val index = result.indexOfFirst { it.mangaId == canonicalId && it.syncId == migrated.syncId && it.mediaId == migrated.mediaId }
            if (index < 0) result += migrated else {
                result[index] = mergeTrackState(result[index], migrated)
                removedIds += duplicate.id
            }
        }
        return TrackMergeResult(result, removedIds)
    }

    private fun mergeTrackState(canonical: DbTrack, duplicate: DbTrack): DbTrack {
        val duplicateHasMoreProgress = (duplicate.lastChapterRead ?: 0) > (canonical.lastChapterRead ?: 0)
        return canonical.copy(
        lastChapterRead = maxOf(canonical.lastChapterRead ?: 0, duplicate.lastChapterRead ?: 0).takeIf { it > 0 },
        totalChapter = maxOf(canonical.totalChapter ?: 0, duplicate.totalChapter ?: 0).takeIf { it > 0 },
        score = when {
            duplicate.updatedAt > canonical.updatedAt || duplicateHasMoreProgress -> duplicate.score ?: canonical.score
            else -> canonical.score ?: duplicate.score
        },
        status = if (duplicate.updatedAt > canonical.updatedAt || duplicateHasMoreProgress) duplicate.status else canonical.status,
        startedReadingDate = listOfNotNull(canonical.startedReadingDate, duplicate.startedReadingDate).minOrNull(),
        finishedReadingDate = listOfNotNull(canonical.finishedReadingDate, duplicate.finishedReadingDate).maxOrNull(),
        updatedAt = maxOf(canonical.updatedAt, duplicate.updatedAt),
        )
    }

    private fun mergePageCache(snapshot: YokanDatabaseSnapshot, chapterMap: Map<Long, Long>) =
        snapshot.pageCache.fold(mutableListOf<eu.friedcutlet.yokan.database.DbChapterPageUrls>()) { result, cache ->
            val targetId = chapterMap[cache.chapterId] ?: cache.chapterId
            val index = result.indexOfFirst { it.chapterId == targetId }
            val migrated = cache.copy(chapterId = targetId)
            if (index < 0) result += migrated else result[index] = mergePageCacheState(result[index], migrated)
            result
        }

    // A merged list mixes two chapters' pages, so it is never served as fresh.
    private fun mergePageCacheState(canonical: eu.friedcutlet.yokan.database.DbChapterPageUrls, duplicate: eu.friedcutlet.yokan.database.DbChapterPageUrls) = canonical.copy(
        chapterUrl = canonical.chapterUrl ?: duplicate.chapterUrl,
        urls = (canonical.urls.orEmpty() + duplicate.urls.orEmpty()).distinct().takeIf { it.isNotEmpty() },
        headers = (canonical.headers.orEmpty() + duplicate.headers.orEmpty()).distinct().takeIf { it.isNotEmpty() },
        fetchedAt = null,
    )

    private fun cleanSettings(settings: eu.friedcutlet.yokan.database.DbSettings, titleIds: Set<Long>, chapterIds: Set<Long>) = settings.copy(
        titleMetadata = settings.titleMetadata?.filterNot { it.mangaId in titleIds },
        personalReaderModeList = settings.personalReaderModeList?.filterNot { it.mangaId in titleIds },
        personalPageModeList = settings.personalPageModeList?.filterNot { it.mangaId in titleIds },
        autoScrollPages = settings.autoScrollPages?.filterNot { it.mangaId in titleIds },
        filterScanlatorList = settings.filterScanlatorList?.filterNot { it.mangaId in titleIds },
        sortChapterList = settings.sortChapterList?.filterNot { it.mangaId in titleIds },
        chapterFilterDownloadedList = settings.chapterFilterDownloadedList?.filterNot { it.mangaId in titleIds },
        chapterFilterUnreadList = settings.chapterFilterUnreadList?.filterNot { it.mangaId in titleIds },
        chapterFilterBookmarkedList = settings.chapterFilterBookmarkedList?.filterNot { it.mangaId in titleIds },
        chapterPageIndexList = settings.chapterPageIndexList?.filterNot { it.chapterId in chapterIds },
        updatedAt = nowMillis(),
    )

    private fun mergeSettings(settings: eu.friedcutlet.yokan.database.DbSettings, titleIds: Set<Long>, duplicateIds: Set<Long>, chapterMap: Map<Long, Long>, canonicalId: Long) = settings.copy(
        titleMetadata = mergeMetadata(settings.titleMetadata, duplicateIds, canonicalId),
        personalReaderModeList = settings.personalReaderModeList?.map { it.copy(mangaId = it.mangaId?.let { id -> if (id in duplicateIds) canonicalId else id }) },
        personalPageModeList = settings.personalPageModeList?.map { it.copy(mangaId = it.mangaId?.let { id -> if (id in duplicateIds) canonicalId else id }) },
        autoScrollPages = settings.autoScrollPages?.map { it.copy(mangaId = it.mangaId?.let { id -> if (id in duplicateIds) canonicalId else id }) },
        filterScanlatorList = settings.filterScanlatorList?.map { it.copy(mangaId = it.mangaId?.let { id -> if (id in duplicateIds) canonicalId else id }) },
        sortChapterList = settings.sortChapterList?.map { it.copy(mangaId = it.mangaId?.let { id -> if (id in duplicateIds) canonicalId else id }) },
        chapterFilterDownloadedList = settings.chapterFilterDownloadedList?.map { it.copy(mangaId = it.mangaId?.let { id -> if (id in duplicateIds) canonicalId else id }) },
        chapterFilterUnreadList = settings.chapterFilterUnreadList?.map { it.copy(mangaId = it.mangaId?.let { id -> if (id in duplicateIds) canonicalId else id }) },
        chapterFilterBookmarkedList = settings.chapterFilterBookmarkedList?.map { it.copy(mangaId = it.mangaId?.let { id -> if (id in duplicateIds) canonicalId else id }) },
        chapterPageIndexList = mergeSettingsPageIndexes(settings.chapterPageIndexList, chapterMap),
        updatedAt = nowMillis(),
    )

    private fun mergeSettingsPageIndexes(
        values: List<eu.friedcutlet.yokan.database.DbChapterPageIndex>?,
        chapterMap: Map<Long, Long>,
    ) = values?.map { it.copy(chapterId = chapterMap[it.chapterId] ?: it.chapterId) }
        ?.groupBy { it.chapterId }
        ?.values
        ?.map { rows -> rows.maxByOrNull { it.index ?: 0 } ?: rows.first() }

    private fun mergeTombstones(
        changedParts: List<eu.friedcutlet.yokan.database.DbChangedPart>,
        removedTitles: Set<Long>,
        removedChapters: Set<Long>,
        removedHistories: Set<Long> = emptySet(),
        removedUpdates: Set<Long> = emptySet(),
        removedTracks: Set<Long> = emptySet(),
        cancelledTitles: Set<Long> = emptySet(),
        cancelledChapters: Set<Long> = emptySet(),
        cancelledHistories: Set<Long> = emptySet(),
        cancelledUpdates: Set<Long> = emptySet(),
        cancelledTracks: Set<Long> = emptySet(),
    ): List<eu.friedcutlet.yokan.database.DbChangedPart> {
        val cancelled = changedParts.filterNot { part ->
            (part.actionType == eu.friedcutlet.yokan.database.DbActionType.RemoveItem && part.isarId in cancelledTitles) ||
                (part.actionType == eu.friedcutlet.yokan.database.DbActionType.RemoveChapter && part.isarId in cancelledChapters) ||
                (part.actionType == eu.friedcutlet.yokan.database.DbActionType.RemoveHistory && part.isarId in cancelledHistories) ||
                (part.actionType == eu.friedcutlet.yokan.database.DbActionType.RemoveUpdate && part.isarId in cancelledUpdates) ||
                (part.actionType == eu.friedcutlet.yokan.database.DbActionType.RemoveTrack && part.isarId in cancelledTracks)
        }
        val existingKeys = cancelled.mapTo(mutableSetOf()) { it.actionType to it.isarId }
        val result = cancelled.toMutableList()
        var nextId = (result.maxOfOrNull { it.id } ?: 0L) + 1L
        fun append(action: eu.friedcutlet.yokan.database.DbActionType, id: Long) {
            if (action to id in existingKeys) return
            while (result.any { it.id == nextId }) nextId++
            result += eu.friedcutlet.yokan.database.DbChangedPart(
                id = nextId++,
                actionType = action,
                isarId = id,
                data = "",
                clientDate = nowMillis(),
            )
            existingKeys += action to id
        }
        removedTitles.sorted().forEach { append(eu.friedcutlet.yokan.database.DbActionType.RemoveItem, it) }
        removedChapters.sorted().forEach { append(eu.friedcutlet.yokan.database.DbActionType.RemoveChapter, it) }
        removedHistories.sorted().forEach { append(eu.friedcutlet.yokan.database.DbActionType.RemoveHistory, it) }
        removedUpdates.sorted().forEach { append(eu.friedcutlet.yokan.database.DbActionType.RemoveUpdate, it) }
        removedTracks.sorted().forEach { append(eu.friedcutlet.yokan.database.DbActionType.RemoveTrack, it) }
        return result
    }

    private fun mergeMetadata(metadata: List<eu.friedcutlet.yokan.database.DbTitleMetadata>?, duplicateIds: Set<Long>, canonicalId: Long) = metadata?.let { all ->
        val unaffected = all.filterNot { it.mangaId == canonicalId || it.mangaId in duplicateIds }
        val affected = all.filter { it.mangaId == canonicalId || it.mangaId in duplicateIds }
            .groupBy { it.metadataServerId to it.metadataSource }
            .flatMap { (_, rows) ->
                val base = rows.firstOrNull { it.mangaId == canonicalId } ?: rows.first()
                val merged = rows.fold(base) { current, row ->
                    current.copy(
                        mangaId = canonicalId,
                        titles = (current.titles + row.titles).distinct(),
                        updatedAt = maxOf(current.updatedAt, row.updatedAt),
                    )
                }
                listOf(merged.copy(mangaId = canonicalId))
            }
        unaffected + affected
    }

    private fun DbHistory.remap(duplicateIds: Set<Long>, chapterMap: Map<Long, Long>, canonicalId: Long) = copy(
        mangaId = mangaId?.let { if (it in duplicateIds) canonicalId else it },
        chapterId = chapterMap[chapterId] ?: chapterId,
    )

    private fun DbUpdate.remap(duplicateIds: Set<Long>, chapterMap: Map<Long, Long>, canonicalId: Long) = copy(
        mangaId = mangaId?.let { if (it in duplicateIds) canonicalId else it },
        chapterId = chapterMap[chapterId] ?: chapterId,
    )

    private fun DbManga.titleIdentity(): LocalLibraryIdentity = localLibraryIdentity(LocalLibraryEntityKind.Title, itemType, link.orEmpty())

    private fun chapterIdentity(chapter: DbChapter, itemType: DbItemType?): LocalLibraryIdentity =
        localLibraryIdentity(LocalLibraryEntityKind.Chapter, itemType ?: DbItemType.Manga, chapter.archivePath.ifBlank { chapter.url })

    private fun eu.friedcutlet.yokan.database.DbDownload.isActive(): Boolean = isStartDownload == true && isDownload != true

    private fun fingerprint(snapshot: YokanDatabaseSnapshot, operation: LocalEntryManagementOperation): String {
        val payload = eu.friedcutlet.yokan.database.DatabaseJson.encodeToString(snapshot) +
            eu.friedcutlet.yokan.database.DatabaseJson.encodeToString(operation)
        var hash = 0xcbf29ce484222325UL
        payload.encodeToByteArray().forEach { byte -> hash = (hash xor byte.toUByte().toULong()) * 0x100000001b3UL }
        return hash.toString(16)
    }

    private fun removedRowCount(before: YokanDatabaseSnapshot, after: YokanDatabaseSnapshot): Int =
        removedByKey(before.mangas, after.mangas, DbManga::id) +
            removedByKey(before.chapters, after.chapters, DbChapter::id) +
            removedByKey(before.categories, after.categories) { it.id } +
            removedByKey(before.sources, after.sources) { it.id } +
            removedByKey(before.histories, after.histories, DbHistory::id) +
            removedByKey(before.updates, after.updates, DbUpdate::id) +
            removedByKey(before.downloads, after.downloads) { it.id } +
            removedByKey(before.tracks, after.tracks, DbTrack::id) +
            removedByContent(before.trackSearches, after.trackSearches) +
            removedByKey(before.trackPreferences, after.trackPreferences) { it.syncId } +
            removedByKey(before.syncPreferences, after.syncPreferences) { it.syncId } +
            removedByKey(before.changedParts, after.changedParts) { it.id } +
            removedByKey(before.customButtons, after.customButtons) { it.id } +
            removedByKey(before.pageCache, after.pageCache) { it.chapterId }

    private fun changedRowCount(before: YokanDatabaseSnapshot, after: YokanDatabaseSnapshot): Int =
        changedByKey(before.mangas, after.mangas, DbManga::id) +
            changedByKey(before.chapters, after.chapters, DbChapter::id) +
            changedByKey(before.categories, after.categories) { it.id } +
            changedByKey(before.sources, after.sources) { it.id } +
            changedByKey(before.histories, after.histories, DbHistory::id) +
            changedByKey(before.updates, after.updates, DbUpdate::id) +
            changedByKey(before.downloads, after.downloads) { it.id } +
            changedByKey(before.tracks, after.tracks, DbTrack::id) +
            changedByKey(before.trackSearches, after.trackSearches) { it.id } +
            changedByKey(before.trackPreferences, after.trackPreferences) { it.syncId } +
            changedByKey(before.syncPreferences, after.syncPreferences) { it.syncId } +
            changedByKey(before.changedParts, after.changedParts) { it.id } +
            changedByKey(before.customButtons, after.customButtons) { it.id } +
            changedByKey(before.pageCache, after.pageCache) { it.chapterId } +
            if (before.settings != after.settings) 1 else 0

    private fun addedRowCount(before: YokanDatabaseSnapshot, after: YokanDatabaseSnapshot): Int =
        addedByKey(before.mangas, after.mangas, DbManga::id) +
            addedByKey(before.chapters, after.chapters, DbChapter::id) +
            addedByKey(before.categories, after.categories) { it.id } +
            addedByKey(before.sources, after.sources) { it.id } +
            addedByKey(before.histories, after.histories, DbHistory::id) +
            addedByKey(before.updates, after.updates, DbUpdate::id) +
            addedByKey(before.downloads, after.downloads) { it.id } +
            addedByKey(before.tracks, after.tracks, DbTrack::id) +
            addedByContent(before.trackSearches, after.trackSearches) +
            addedByKey(before.trackPreferences, after.trackPreferences) { it.syncId } +
            addedByKey(before.syncPreferences, after.syncPreferences) { it.syncId } +
            addedByKey(before.changedParts, after.changedParts) { it.id } +
            addedByKey(before.customButtons, after.customButtons) { it.id } +
            addedByKey(before.pageCache, after.pageCache) { it.chapterId }

    private fun <T, K> removedByKey(before: List<T>, after: List<T>, key: (T) -> K): Int {
        val afterKeys = after.mapTo(HashSet(), key)
        return before.count { key(it) !in afterKeys }
    }

    private fun <T> removedByContent(before: List<T>, after: List<T>): Int {
        val beforeCounts = before.groupingBy { it.toString() }.eachCount()
        val afterCounts = after.groupingBy { it.toString() }.eachCount()
        return beforeCounts.entries.sumOf { (content, count) -> (count - (afterCounts[content] ?: 0)).coerceAtLeast(0) }
    }

    private fun <T, K> changedByKey(before: List<T>, after: List<T>, key: (T) -> K): Int {
        // Reversed so a repeated key resolves to its first row.
        val afterByKey = after.asReversed().associateBy(key)
        return before.count { old -> afterByKey[key(old)]?.let { it != old } == true }
    }

    private fun <T, K> addedByKey(before: List<T>, after: List<T>, key: (T) -> K): Int {
        val beforeKeys = before.mapTo(HashSet(), key)
        return after.count { key(it) !in beforeKeys }
    }

    private fun <T> addedByContent(before: List<T>, after: List<T>): Int {
        val beforeCounts = before.groupingBy { it.toString() }.eachCount()
        val afterCounts = after.groupingBy { it.toString() }.eachCount()
        return afterCounts.entries.sumOf { (content, count) -> (count - (beforeCounts[content] ?: 0)).coerceAtLeast(0) }
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/library/LocalVideoArtwork.kt

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

The implementation below defines LocalVideoArtwork, generate, decorate, episodes, setCover, write, frame, DbManga.isLocalAnime, DbManga.needsCover.

The source describes its contract as:

Frame-derived artwork for local anime that ships none: a cover for titles without any cover, and a thumbnail for episodes without a preview. One decode at a time, at most [maxDecodesPerRun] per run. Frames are cached under \<downloadRoot\>/.yokan-artwork, keyed by the episode's virtual path, size and modification time, so later runs reuse them instead of decoding again. Existing artwork always wins.

Cross-chapter imports used by this file: DbChapter, DbItemType, DbManga, DbSettings, YokanDatabase, sha256. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.util.sha256
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.media.VideoFrameExtractor
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.services.files.resolveLocalEpisodeVideo

/**
 * Frame-derived artwork for local anime that ships none: a cover for titles without any cover, and a
 * thumbnail for episodes without a preview. One decode at a time, at most [maxDecodesPerRun] per run.
 * Frames are cached under `<downloadRoot>/.yokan-artwork`, keyed by the episode's virtual path, size and
 * modification time, so later runs reuse them instead of decoding again. Existing artwork always wins.
 */
class LocalVideoArtwork(
    private val database: YokanDatabase,
    private val files: LocalFileService,
    private val library: LocalLibraryService,
    private val extractor: VideoFrameExtractor,
    private val maxDecodesPerRun: Int = 12,
) {
    private val running = Mutex()
    // ponytail: failures are remembered for this session only; persist markers if restarts re-decoding broken files matters.
    private val failed = mutableSetOf<String>()
    private var budget = 0

    /** False when a run is already in progress; that run (or the next scan) picks up new episodes. */
    suspend fun generate(): Boolean {
        if (!running.tryLock()) return false
        try {
            budget = maxDecodesPerRun
            files.prepare()
            val settings = database.settings()
            val titles = database.mangas(DbItemType.Anime).filter(DbManga::isLocalAnime)
            for (title in titles) {
                catchingNonCancellation { decorate(title, titles, settings) }
                    .onFailure { AppLogger.warn("[local] video artwork failed for title ${title.id}: ${it.message.orEmpty()}") }
            }
        } finally { running.unlock() }
        return true
    }

    private suspend fun decorate(title: DbManga, titles: List<DbManga>, settings: DbSettings) {
        val episodes = episodes(title.id)
        var needsCover = title.needsCover()
        for (episode in episodes) {
            val needsThumbnail = episode.thumbnailUrl == null
            if (!needsThumbnail && !needsCover) continue
            val frame = frame(episode, settings) ?: continue
            if (needsThumbnail) {
                val url = files.readableUrl(frame)
                write {
                    val current = database.chapter(episode.id) ?: return@write
                    if (current.mangaId == title.id && current.archivePath == episode.archivePath && current.thumbnailUrl == null) {
                        database.upsertChapter(current.copy(thumbnailUrl = url))
                    }
                }
            }
            if (needsCover) {
                setCover(title.id, frame)
                needsCover = false
            }
        }
        // Seasons parents own no episodes: their first season's first frame stands in.
        if (needsCover && episodes.isEmpty()) {
            val season = titles.filter { it.parentId == title.id }.minByOrNull { it.id } ?: return
            episodes(season.id).firstNotNullOfOrNull { frame(it, settings) }?.let { setCover(title.id, it) }
        }
    }

    private fun episodes(titleId: Long): List<DbChapter> =
        database.chapters(titleId).sortedWith(compareBy<DbChapter>({ it.season ?: 0 }, { it.number ?: Double.MAX_VALUE }, { it.archivePath }))

    private suspend fun setCover(titleId: Long, frame: String) {
        val bytes = files.readBytesAsync(frame, MaxFrameBytes.toLong())
        write {
            val current = database.manga(titleId) ?: return@write
            // A cover the user picked, a scanned cover file or metadata artwork that arrived meanwhile wins.
            if (current.isLocalAnime() && current.needsCover()) database.upsertManga(current.copy(customCoverImage = bytes))
        }
    }

    /** The scanner and entry management hold this lock, so writes never interleave with a scan's read-modify-write. */
    private suspend fun write(block: () -> Unit) = library.withOperationLock { database.batch(block) }

    /** Path of the cached frame, decoding it when absent; null when unavailable, failed or over budget. */
    private suspend fun frame(episode: DbChapter, settings: DbSettings): String? {
        val video = resolveLocalEpisodeVideo(episode.archivePath, files, settings) ?: return null
        val name = video.substringAfterLast('/')
        val fingerprint = files.listFiles(video.substringBeforeLast('/', "")).firstOrNull { it.name == name }
        val key = sha256("${episode.archivePath}|${fingerprint?.sizeBytes}|${fingerprint?.lastModified}".encodeToByteArray()).toHexString().take(32)
        val target = "${files.downloadRoot.trimEnd('/')}/$ArtworkDirectory/$key.jpg"
        if (files.exists(target)) return target
        if (key in failed || budget <= 0) return null
        budget--
        val bytes = catchingNonCancellation { extractor.extractJpeg(files.readableUrl(video), MaxFrameDimension) }
            .onFailure { AppLogger.warn("[local] frame extraction failed: ${it.message.orEmpty()}") }
            .getOrNull()?.takeIf { it.size in 1..MaxFrameBytes }
        if (bytes == null) {
            failed += key
            return null
        }
        val partial = "$target.part"
        try {
            files.writeBytesAsync(partial, bytes)
            check(files.promoteAsync(partial, target)) { "Artwork cache could not be written" }
        } finally {
            withContext(NonCancellable) { if (files.exists(partial)) files.deleteRecursivelyAsync(partial) }
        }
        return target
    }

    internal companion object {
        const val ArtworkDirectory = ".yokan-artwork"
        const val MaxFrameDimension = 512
        const val MaxFrameBytes = 1024 * 1024
    }
}

private fun DbManga.isLocalAnime(): Boolean = isLocalArchive && source == "local" && itemType == DbItemType.Anime

private fun DbManga.needsCover(): Boolean =
    customCoverImage == null && imageUrl.isNullOrBlank() && customCoverFromTracker.isNullOrBlank()

Check your understanding

Pause a scan after reading files, edit progress, then finish it. Repeat after deletion. Only source-owned metadata should update, and the deleted entry must stay deleted. [chapter-content-end]: #

Step 5: build local-library screens

Create overview and browse ViewModels/screens, folder selection, scan status, import results, metadata search/review and entry management. Persist selections by stable identity. Display unsupported inputs and lost grants as recoverable errors, not empty libraries.

Follow the code

The ViewModels expose scan status/results, current locations and recoverable access errors. Screen state should distinguish no content, unsupported input and a lost grant. Metadata review presents candidate changes before applying them. Stable entry identity carries through browsing and editing so a rescan cannot redirect an action to a different item.

Write these files in this order:

  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryViewModel.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryBrowseViewModel.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalMetadataReview.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalEntryManagement.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryBrowseScreen.kt
  • composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryOverviewScreen.kt

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryViewModel.kt

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

The implementation below defines LocalMetadataReviewState, LocalLibraryUiState, LocalLibraryEvent, Rescan, FullRescan, ImportMedia, CancelImport, RecoverImport, DiscardIncompleteImport, PreviewOperation and 25 further declarations.

The source describes its contract as:

Candidate search and field selection for one local title; nothing is written until applied.

Cross-chapter imports used by this file: LibraryIndexStore, SettingsStore, Chapter, ItemType, Manga, ColorizationJob. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.local

import kotlinx.coroutines.CoroutineDispatcher
import eu.friedcutlet.yokan.services.library.LocalMetadataSourceResult
import eu.friedcutlet.yokan.services.library.LocalLibraryOverview
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.colorization.ColorizationJob
import eu.friedcutlet.yokan.services.colorization.LocalColorizationQueue
import eu.friedcutlet.yokan.services.library.LocalEntryManagementApplyStatus
import eu.friedcutlet.yokan.services.library.LocalEntryManagementOperation
import eu.friedcutlet.yokan.services.library.LocalEntryManagementPreview
import eu.friedcutlet.yokan.services.library.LocalLibraryController
import eu.friedcutlet.yokan.services.library.LocalLibraryDuplicateGroup
import eu.friedcutlet.yokan.services.library.LocalImportProgress
import eu.friedcutlet.yokan.services.library.PendingLocalImport
import eu.friedcutlet.yokan.services.files.LocalMediaSelection
import eu.friedcutlet.yokan.services.files.pickLocalMedia
import eu.friedcutlet.yokan.services.metadata.LocalMetadataField
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.services.library.visibleChapters
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/** Candidate search and field selection for one local title; nothing is written until applied. */
data class LocalMetadataReviewState(
    val manga: Manga,
    val sourceResults: List<LocalMetadataSourceResult> = emptyList(),
    val selectedCandidate: MetadataMedia? = null,
    val selectedFields: Set<LocalMetadataField> = emptySet(),
    val error: String? = null,
    val loading: Boolean = false,
) {
    val candidates: List<MetadataMedia> = sourceResults.flatMap { it.candidates }
}

data class LocalLibraryUiState(
    val overview: LocalLibraryOverview = LocalLibraryOverview(folders = emptyList(), manga = 0, anime = 0, novels = 0),
    val titlesByType: Map<ItemType, List<Manga>> = emptyMap(),
    val reviewQueue: List<Manga> = emptyList(),
    /** Names of the titles the reconciliation refers to, for the stale and duplicate rows. */
    val titleNames: Map<Long, String> = emptyMap(),
    val message: String? = null,
    val managementPreview: LocalEntryManagementPreview? = null,
    val selectedEntry: Manga? = null,
    val selectedEntryChapters: List<Chapter> = emptyList(),
    val metadataReview: LocalMetadataReviewState? = null,
    val colorizationJobs: List<ColorizationJob> = emptyList(),
    val colorizationSupported: Boolean = false,
    val colorizationError: String? = null,
    val importBusy: Boolean = false,
    val importProgress: LocalImportProgress? = null,
    val importFailed: Boolean = false,
    val importError: String? = null,
    val importCompleted: Boolean = false,
    val pendingImports: List<PendingLocalImport> = emptyList(),
)

sealed interface LocalLibraryEvent {
    data object Rescan : LocalLibraryEvent
    data object FullRescan : LocalLibraryEvent
    data class ImportMedia(val type: ItemType, val directory: Boolean) : LocalLibraryEvent
    data object CancelImport : LocalLibraryEvent
    data class RecoverImport(val id: String) : LocalLibraryEvent
    data class DiscardIncompleteImport(val id: String) : LocalLibraryEvent
    data class PreviewOperation(val operation: LocalEntryManagementOperation) : LocalLibraryEvent
    data class PreviewMerge(val group: LocalLibraryDuplicateGroup, val canonicalTitleId: Long) : LocalLibraryEvent
    data object ConfirmOperation : LocalLibraryEvent
    data object DismissOperation : LocalLibraryEvent
    data class SelectEntry(val manga: Manga?) : LocalLibraryEvent
    data class OpenMetadataReview(val manga: Manga) : LocalLibraryEvent
    data object DismissMetadataReview : LocalLibraryEvent
    data object SearchMetadataCandidates : LocalLibraryEvent
    data class SelectCandidate(val candidate: MetadataMedia) : LocalLibraryEvent
    data class SetFieldSelected(val field: LocalMetadataField, val selected: Boolean) : LocalLibraryEvent
    data object ApplyMetadata : LocalLibraryEvent
    data class EnqueueColorization(val manga: Manga) : LocalLibraryEvent
    data class ColorizationAction(val jobId: String, val action: ColorizationJobAction) : LocalLibraryEvent
}

enum class ColorizationJobAction { Pause, Resume, Retry, Cancel }

/** Local media overview: folders, scan state, metadata review queue, and forget/merge management. */
class LocalLibraryViewModel(
    private val controller: LocalLibraryController,
    settings: SettingsStore,
    libraryIndex: LibraryIndexStore,
    private val colorizationQueue: LocalColorizationQueue? = null,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
    private val mediaPicker: suspend (Boolean) -> LocalMediaSelection? = ::pickLocalMedia,
) : ViewModel() {
    private val _state = MutableStateFlow(LocalLibraryUiState())
    val state: StateFlow<LocalLibraryUiState> = _state.asStateFlow()
    private var searchJob: Job? = null
    private var importJob: Job? = null

    init {
        refreshPendingImports()
        viewModelScope.launch {
            combine(controller.observeLibrary(workDispatcher),
                settings.db.map(controller::folders).distinctUntilChanged(), controller.scan) { library, folders, scan ->
                Derived(
                    overview = library.overview(folders, scan),
                    titlesByType = library.titlesByType,
                    reviewQueue = library.reviewQueue,
                    titleNames = library.titleNames(scan.reconciliation),
                )
            }.flowOn(workDispatcher).collect { derived ->
                _state.update {
                    it.copy(
                        overview = derived.overview,
                        titlesByType = derived.titlesByType,
                        reviewQueue = derived.reviewQueue,
                        titleNames = derived.titleNames,
                    )
                }
            }
        }
        colorizationQueue?.let { queue ->
            viewModelScope.launch {
                queue.jobs.collect { jobs -> _state.update { it.copy(colorizationJobs = jobs) } }
            }
            _state.update { it.copy(colorizationSupported = queue.supported) }
        }
        viewModelScope.launch {
            combine(_state.map { it.selectedEntry }.distinctUntilChanged(), libraryIndex.index, settings.db) { manga, index, db ->
                manga to manga?.let { visibleChapters(it, index.chapters(it.id), db, index.downloadedChapterIds) }.orEmpty()
            }.flowOn(workDispatcher).collect { (manga, chapters) ->
                _state.update { if (it.selectedEntry?.id == manga?.id) it.copy(selectedEntryChapters = chapters) else it }
            }
        }
    }

    fun onEvent(event: LocalLibraryEvent) {
        when (event) {
            LocalLibraryEvent.Rescan -> rescan()
            LocalLibraryEvent.FullRescan -> rescan(forceRefresh = true)
            is LocalLibraryEvent.ImportMedia -> importMedia(event)
            LocalLibraryEvent.CancelImport -> importJob?.cancel()
            is LocalLibraryEvent.RecoverImport -> importAction { controller.recoverImport(event.id); controller.rescanAndReconcile() }
            is LocalLibraryEvent.DiscardIncompleteImport -> importAction { controller.discardIncompleteImport(event.id) }
            is LocalLibraryEvent.PreviewOperation -> preview(event.operation)
            is LocalLibraryEvent.PreviewMerge -> _state.value.overview.reconciliation?.let { evidence ->
                preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, event.group.ids, event.canonicalTitleId))
            }
            LocalLibraryEvent.ConfirmOperation -> confirmOperation()
            LocalLibraryEvent.DismissOperation -> _state.update { it.copy(managementPreview = null) }
            is LocalLibraryEvent.SelectEntry -> _state.update {
                it.copy(selectedEntry = event.manga, selectedEntryChapters = emptyList())
            }
            is LocalLibraryEvent.OpenMetadataReview -> {
                searchJob?.cancel()
                _state.update { it.copy(selectedEntry = null, metadataReview = LocalMetadataReviewState(event.manga)) }
            }
            LocalLibraryEvent.DismissMetadataReview -> {
                searchJob?.cancel()
                _state.update { it.copy(metadataReview = null) }
            }
            LocalLibraryEvent.SearchMetadataCandidates -> searchCandidates()
            is LocalLibraryEvent.SelectCandidate -> updateReview { it.copy(selectedCandidate = event.candidate) }
            is LocalLibraryEvent.SetFieldSelected -> updateReview {
                it.copy(selectedFields = if (event.selected) it.selectedFields + event.field else it.selectedFields - event.field)
            }
            LocalLibraryEvent.ApplyMetadata -> applyMetadata()
            is LocalLibraryEvent.EnqueueColorization -> colorizationQueue?.let { queue ->
                if (event.manga.itemType == ItemType.Manga && event.manga.isLocalArchive && !event.manga.source.equals("torrent", true)) {
                    viewModelScope.launch {
                        try {
                            withContext(workDispatcher) { queue.enqueue(event.manga.id) }
                            _state.update { it.copy(colorizationError = null) }
                        } catch (error: CancellationException) {
                            throw error
                        } catch (error: Throwable) {
                            _state.update { it.copy(colorizationError = error.message ?: "Could not start colorization.") }
                        }
                    }
                }
            }
            is LocalLibraryEvent.ColorizationAction -> colorizationQueue?.let { queue ->
                viewModelScope.launch {
                    try {
                        withContext(workDispatcher) {
                            when (event.action) {
                                ColorizationJobAction.Pause -> queue.pause(event.jobId)
                                ColorizationJobAction.Resume -> queue.resume(event.jobId)
                                ColorizationJobAction.Retry -> queue.retry(event.jobId)
                                ColorizationJobAction.Cancel -> queue.cancel(event.jobId)
                            }
                        }
                        _state.update { it.copy(colorizationError = null) }
                    } catch (error: CancellationException) {
                        throw error
                    } catch (error: Throwable) {
                        _state.update { it.copy(colorizationError = error.message ?: "Could not update colorization.") }
                    }
                }
            }
        }
    }

    private fun refreshPendingImports() {
        viewModelScope.launch {
            catchingNonCancellation { controller.pendingImports() }
                .onSuccess { pending -> _state.update { it.copy(pendingImports = pending) } }
        }
    }

    private fun importMedia(event: LocalLibraryEvent.ImportMedia) = importAction {
        // Keep the picker on Main and before any dispatcher hop so browsers retain user activation.
        val selection = mediaPicker(event.directory) ?: return@importAction
        try {
            controller.importMedia(selection, event.type.toDb()) { progress ->
                _state.update { it.copy(importProgress = progress) }
            }
        } finally { selection.close() }
        controller.rescanAndReconcile()
        _state.update { it.copy(importCompleted = true) }
    }

    private fun importAction(action: suspend () -> Unit) {
        if (importJob?.isActive == true) return
        _state.update { it.copy(importBusy = true, importProgress = null, importFailed = false, importError = null, importCompleted = false) }
        importJob = viewModelScope.launch {
            try { action() }
            catch (cancelled: CancellationException) { throw cancelled }
            catch (error: Throwable) { _state.update { it.copy(importFailed = true, importError = error.message) } }
            finally {
                _state.update { it.copy(importBusy = false, importProgress = null) }
                refreshPendingImports()
            }
        }
    }

    private fun rescan(forceRefresh: Boolean = false) {
        _state.update { it.copy(message = null) }
        viewModelScope.launch {
            catchingNonCancellation { controller.rescanAndReconcile(forceRefresh) }
                .onFailure { error -> _state.update { it.copy(message = error.message ?: "Scan or reconciliation failed") } }
        }
    }

    private fun preview(operation: LocalEntryManagementOperation) {
        viewModelScope.launch {
            val preview = withContext(workDispatcher) { controller.preview(operation) }
            _state.update { it.copy(managementPreview = preview) }
        }
    }

    private fun confirmOperation() {
        val preview = _state.value.managementPreview ?: return
        viewModelScope.launch {
            val result = controller.apply(preview.command)
            _state.update {
                if (result.status == LocalEntryManagementApplyStatus.Applied) {
                    it.copy(managementPreview = null)
                } else {
                    it.copy(message = "Operation blocked: ${result.blocker ?: "unknown reason"}")
                }
            }
        }
    }

    private fun searchCandidates() {
        val review = _state.value.metadataReview ?: return
        if (review.loading) return
        updateReview { it.copy(sourceResults = emptyList(), error = null, loading = true) }
        searchJob = viewModelScope.launch {
            val result = catchingNonCancellation { controller.searchMetadataCandidates(review.manga) }
            updateReview { current ->
                result.fold(
                    onSuccess = { current.copy(sourceResults = it, loading = false) },
                    onFailure = { current.copy(error = it.message ?: "Search failed", loading = false) },
                )
            }
        }
    }

    private fun applyMetadata() {
        val review = _state.value.metadataReview ?: return
        val candidate = review.selectedCandidate ?: return
        controller.applyMetadataCandidate(review.manga, candidate, review.selectedFields)
        onEvent(LocalLibraryEvent.DismissMetadataReview)
    }

    private fun updateReview(transform: (LocalMetadataReviewState) -> LocalMetadataReviewState) {
        _state.update { state -> state.metadataReview?.let { state.copy(metadataReview = transform(it)) } ?: state }
    }

    private class Derived(
        val overview: LocalLibraryOverview,
        val titlesByType: Map<ItemType, List<Manga>>,
        val reviewQueue: List<Manga>,
        val titleNames: Map<Long, String>,
    )
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryBrowseViewModel.kt

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

The implementation below defines LocalLibraryBrowseUiState, LocalLibraryBrowseViewModel, rescan.

The source describes its contract as:

Every local-archive title per type, sorted by name.

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

package eu.friedcutlet.yokan.ui.screens.local

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.library.LocalLibraryController
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

data class LocalLibraryBrowseUiState(
    /** Every local-archive title per type, sorted by name. */
    val titlesByType: Map<ItemType, List<Manga>> = emptyMap(),
    val scanMessage: String? = null,
    val scanning: Boolean = false,
)

class LocalLibraryBrowseViewModel(
    private val controller: LocalLibraryController,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    private val _state = MutableStateFlow(LocalLibraryBrowseUiState())
    val state: StateFlow<LocalLibraryBrowseUiState> = _state.asStateFlow()

    init {
        viewModelScope.launch {
            controller.observeLibrary(workDispatcher).collect { library ->
                _state.update { it.copy(titlesByType = library.browseTitlesByType) }
            }
        }
    }

    fun rescan() {
        if (_state.value.scanning) return
        _state.update { it.copy(scanning = true) }
        viewModelScope.launch {
            val result = catchingNonCancellation { controller.rescan() }
            val message = result.fold(
                onSuccess = { "Last scan: ${it.total} items, ${it.added} added, ${it.updated} updated" },
                onFailure = { error -> "Scan failed: ${error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }}" },
            )
            _state.update { it.copy(scanMessage = message, scanning = false) }
        }
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalMetadataReview.kt

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

The implementation below defines LocalMetadataReviewDialog, sourceStateLabel, localFieldValue, candidateFieldValue, metadataSearchActionLabel.

The source describes its contract as:

Candidate search and field-by-field confirmation for one local title's metadata. Nothing is written until the user applies the selected fields; every opening starts from an empty [LocalMetadataReviewState].

Cross-chapter imports used by this file: Manga, LocalMetadataField, MetadataMedia, YokanListRow. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.local

import eu.friedcutlet.yokan.services.library.LocalMetadataSourceResult
import eu.friedcutlet.yokan.services.library.LocalMetadataSourceState
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.metadata.LocalMetadataField
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.ui.components.YokanListRow

/**
 * Candidate search and field-by-field confirmation for one local title's metadata.
 * Nothing is written until the user applies the selected fields; every opening starts
 * from an empty [LocalMetadataReviewState].
 */
@Composable
internal fun LocalMetadataReviewDialog(
    review: LocalMetadataReviewState,
    onEvent: (LocalLibraryEvent) -> Unit,
) {
    val manga = review.manga
    val sourceResults = review.sourceResults
    val candidates = review.candidates
    val onDismiss = { onEvent(LocalLibraryEvent.DismissMetadataReview) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Review metadata: ${manga.name}") },
        text = {
            Column(Modifier.verticalScroll(rememberScrollState())) {
                if (candidates.isEmpty() && !review.loading && review.error == null && sourceResults.isEmpty()) {
                    Text("Search existing metadata and tracker sources. Nothing is saved automatically.")
                }
                review.error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
                if (review.loading) Text("Searching…")
                sourceResults.filter { it.candidates.isEmpty() }.forEach { source ->
                    Text("${source.source}: ${sourceStateLabel(source)}", color = MaterialTheme.colorScheme.onSurfaceVariant)
                }
                candidates.forEach { candidate ->
                    val select = { onEvent(LocalLibraryEvent.SelectCandidate(candidate)) }
                    YokanListRow(
                        title = candidate.title,
                        subtitle = "${candidate.source}${candidate.year?.let { " · $it" } ?: ""}",
                        onClick = select,
                        trailingContent = { RadioButton(selected = review.selectedCandidate == candidate, onClick = select) },
                    )
                }
                review.selectedCandidate?.let { candidate ->
                    Text("Confirm fields to write", style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(top = 12.dp))
                    LocalMetadataField.entries.forEach { field ->
                        val available = 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()
                        }
                        if (available) Row(verticalAlignment = Alignment.CenterVertically) {
                            Checkbox(
                                checked = field in review.selectedFields,
                                onCheckedChange = { checked -> onEvent(LocalLibraryEvent.SetFieldSelected(field, checked)) },
                            )
                            Text("${field.name}: ${localFieldValue(manga, field)} → ${candidateFieldValue(candidate, field)}")
                        }
                    }
                }
            }
        },
        confirmButton = {
            TextButton(
                enabled = review.selectedCandidate != null && review.selectedFields.isNotEmpty(),
                onClick = { onEvent(LocalLibraryEvent.ApplyMetadata) },
            ) { Text("Apply selected fields") }
        },
        dismissButton = {
            TextButton(onClick = {
                when {
                    review.loading -> Unit
                    candidates.isEmpty() -> onEvent(LocalLibraryEvent.SearchMetadataCandidates)
                    else -> onDismiss()
                }
            }) {
                Text(metadataSearchActionLabel(sourceResults.isNotEmpty(), review.loading, candidates.isNotEmpty()))
            }
        },
    )
}

private fun sourceStateLabel(source: LocalMetadataSourceResult): String = when (source.state) {
    LocalMetadataSourceState.Results -> "results"
    LocalMetadataSourceState.NoResults -> "no results"
    LocalMetadataSourceState.Offline -> "offline${source.message?.let { ": $it" } ?: ""}"
    LocalMetadataSourceState.Error -> "error${source.message?.let { ": $it" } ?: ""}"
    LocalMetadataSourceState.Unsupported -> "not supported for this media type"
}

private fun localFieldValue(manga: Manga, field: LocalMetadataField): String = when (field) {
    LocalMetadataField.Title -> manga.name
    LocalMetadataField.Cover -> manga.imageUrl ?: "empty"
    LocalMetadataField.Description -> manga.description.ifBlank { "empty" }
    LocalMetadataField.Genres -> manga.genres.joinToString().ifBlank { "empty" }
    LocalMetadataField.Status -> manga.status.name
    LocalMetadataField.MetadataLink -> manga.metadataServerId ?: "unlinked"
}

private fun candidateFieldValue(candidate: MetadataMedia, field: LocalMetadataField): String = when (field) {
    LocalMetadataField.Title -> candidate.title
    LocalMetadataField.Cover -> candidate.coverUrl ?: "empty"
    LocalMetadataField.Description -> candidate.description ?: "empty"
    LocalMetadataField.Genres -> candidate.genres.joinToString().ifBlank { "empty" }
    LocalMetadataField.Status -> candidate.status ?: "empty"
    LocalMetadataField.MetadataLink -> "${candidate.source}:${candidate.id}"
}

internal fun metadataSearchActionLabel(hasSearched: Boolean, loading: Boolean, hasCandidates: Boolean): String = when {
    loading -> "Searching…"
    !hasSearched -> "Find candidates"
    !hasCandidates -> "Retry search"
    else -> "Cancel"
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalEntryManagement.kt

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

The implementation below defines LocalEntryDetailContent, LocalDuplicateGroupDialog, LocalEntryOperationDialog, localBlockerLabel.

The source describes its contract as:

Read-only detail of one indexed local entry: source path, metadata link, reconciliation state and chapters.

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

package eu.friedcutlet.yokan.ui.screens.local

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.library.LocalEntryManagementOperation
import eu.friedcutlet.yokan.services.library.LocalEntryManagementPreview
import eu.friedcutlet.yokan.services.library.LocalLibraryDuplicateGroup
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_cancel

/** Read-only detail of one indexed local entry: source path, metadata link, reconciliation state and chapters. */
@Composable
internal fun LocalEntryDetailContent(
    manga: Manga,
    stale: Boolean,
    chapters: List<Chapter>,
    modifier: Modifier,
    onReviewMetadata: () -> Unit,
    canColorize: Boolean = false,
    onColorize: () -> Unit = {},
) {
    Column(modifier) {
        Text(manga.name, style = MaterialTheme.typography.titleLarge)
        Text("Source path", style = MaterialTheme.typography.titleSmall)
        Text(manga.link.ifBlank { "Unavailable" })
        Text("Media type: ${manga.itemType}")
        Text("Metadata: ${if (manga.metadataServerId == null) "unmatched" else "linked (${manga.metadataSource})"}")
        TextButton(onClick = onReviewMetadata) { Text("Review metadata") }
        if (canColorize) TextButton(onClick = onColorize) { Text("Create colorized copy") }
        Text("Reconciliation: ${if (stale) "stale" else "no title issue reported"}")
        Text("Chapters", style = MaterialTheme.typography.titleSmall, modifier = Modifier.padding(top = 12.dp))
        chapters.forEach { chapter -> Text("${chapter.name} · ${chapter.url}", modifier = Modifier.padding(vertical = 4.dp)) }
    }
}

/** Picks the canonical database entry of an exact-identity duplicate group; [onChoose] receives its id. */
@Composable
internal fun LocalDuplicateGroupDialog(
    group: LocalLibraryDuplicateGroup,
    titleName: (Long) -> String?,
    onChoose: (Long) -> Unit,
    onDismiss: () -> Unit,
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Choose canonical entry") },
        text = {
            Column {
                Text("Only exact local identities can be merged. Source files affected: 0.")
                group.ids.forEach { id ->
                    TextButton(onClick = { onChoose(id) }) { Text(titleName(id) ?: "Entry $id") }
                }
            }
        },
        confirmButton = {},
    )
}

/** Confirms a previewed forget/merge operation, showing its database impact and any blockers. */
@Composable
internal fun LocalEntryOperationDialog(
    preview: LocalEntryManagementPreview,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit,
) {
    val isMerge = preview.command.operation is LocalEntryManagementOperation.MergeDuplicateTitles
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(if (isMerge) "Review merge" else "Review forgetting entry") },
        text = {
            Column {
                Text("Database rows removed: ${preview.databaseRowsRemoved}")
                Text("Database rows updated: ${preview.databaseRowsUpdated}")
                Text("Source files affected: ${preview.sourceFilesAffected}")
                if (preview.blockers.isNotEmpty()) {
                    Text("Blocked: ${preview.blockers.joinToString { localBlockerLabel(it) }}", color = MaterialTheme.colorScheme.error)
                } else if (!isMerge) {
                    Text("Forget from database only. Source files remain unchanged.")
                }
            }
        },
        confirmButton = {
            TextButton(
                enabled = preview.blockers.isEmpty(),
                onClick = onConfirm,
            ) { Text(if (isMerge) "Merge entries" else "Forget from database") }
        },
        dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } },
    )
}

private fun localBlockerLabel(blocker: String): String = when (blocker) {
    "STATE_CHANGED" -> "the entry changed; review again"
    "FRESH_RECONCILIATION_CHANGED" -> "fresh reconciliation is required"
    "STALE_EVIDENCE_REQUIRED" -> "stale evidence is required"
    "CANDIDATE_CHANGED" -> "the stale candidate changed"
    "ACTIVE_DOWNLOAD" -> "an active download is using this entry"
    "INVALID_DUPLICATE_GROUP" -> "this is not an exact duplicate group"
    "TORRENT_ENTRY" -> "torrent entries cannot be merged"
    "ITEM_TYPE_MISMATCH" -> "media types do not match"
    "REMOTE_METADATA_CONFLICT" -> "metadata sources conflict"
    "TRACKER_BINDING_CONFLICT" -> "tracker links conflict"
    "ATOMIC_SNAPSHOT_PERSISTENCE_UNAVAILABLE" -> "atomic database updates are unavailable"
    "ATOMIC_SNAPSHOT_PERSISTENCE_FAILED" -> "the database update failed safely"
    else -> blocker
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryBrowseScreen.kt

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

The implementation below defines LocalLibraryBrowseRoute, LocalLibraryBrowseScreen, LocalLibraryCoverCell.

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

package eu.friedcutlet.yokan.ui.screens.local

import androidx.compose.foundation.clickable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
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.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
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.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
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.TypeDot
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route

@Composable
internal fun LocalLibraryBrowseRoute(route: Route.LocalLibraryBrowse, nav: Navigator) {
    val vm = viewModel { LocalLibraryBrowseViewModel(YokanRuntime.localLibrary) }
    val state by vm.state.collectAsStateWithLifecycle()
    LocalLibraryBrowseScreen(
        state = state,
        title = "Local Library",
        initialItemType = route.itemType,
        onRescan = vm::rescan,
        onOpenTitle = { manga -> nav.navigate(Route.Detail(manga.id)) },
        onBack = nav::back,
    )
}

@Composable
internal fun LocalLibraryBrowseScreen(
    state: LocalLibraryBrowseUiState,
    title: String,
    initialItemType: ItemType,
    onRescan: () -> Unit,
    onOpenTitle: (Manga) -> Unit,
    onBack: () -> Unit,
) {
    var selectedType by remember(initialItemType) { mutableStateOf(initialItemType) }
    var query by remember { mutableStateOf("") }
    val focusManager = LocalFocusManager.current
    val localEntries = state.titlesByType[selectedType].orEmpty()
    val entries = remember(localEntries, query) {
        val normalizedQuery = query.trim().lowercase()
        localEntries.filter { manga ->
            normalizedQuery.isEmpty() ||
                manga.name.lowercase().contains(normalizedQuery) ||
                manga.author.orEmpty().lowercase().contains(normalizedQuery) ||
                manga.artist.orEmpty().lowercase().contains(normalizedQuery) ||
                manga.genres.any { it.lowercase().contains(normalizedQuery) }
        }
    }

    RouteScaffold(title, onBack = onBack) {
        item {
            FlowRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                ItemType.entries.forEach { type ->
                    FilterChip(
                        selected = selectedType == type,
                        onClick = { selectedType = type },
                        label = { Text(type.label) },
                        leadingIcon = { TypeDot(type) },
                    )
                }
            }
        }
        item {
            OutlinedTextField(
                value = query,
                onValueChange = { query = it },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true,
                label = { Text("Search local library") },
                leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
                trailingIcon = {
                    if (query.isNotBlank()) {
                        IconButton(onClick = { query = "" }) {
                            Icon(Icons.Filled.Clear, contentDescription = "Clear search")
                        }
                    }
                },
                keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                    imeAction = androidx.compose.ui.text.input.ImeAction.Search,
                ),
                keyboardActions = androidx.compose.foundation.text.KeyboardActions(
                    onSearch = { focusManager.clearFocus() },
                ),
            )
        }
        item {
            ElevatedCard(modifier = Modifier.fillMaxWidth()) {
                Row(
                    modifier = Modifier.fillMaxWidth().padding(14.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                ) {
                    Icon(Icons.Filled.Folder, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
                    Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
                        Text("Indexed local folders", fontWeight = FontWeight.SemiBold)
                        Text(
                            state.scanMessage ?: "${localEntries.size} ${selectedType.label.lowercase()} title${if (localEntries.size == 1) "" else "s"}",
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            style = MaterialTheme.typography.bodySmall,
                        )
                    }
                    TextButton(enabled = !state.scanning, onClick = onRescan) {
                        Text(if (state.scanning) "Scanning..." else "Rescan")
                    }
                }
            }
        }
        if (entries.isEmpty()) {
            item {
                EmptyState(
                    icon = Icons.Filled.Folder,
                    title = if (query.isBlank()) {
                        "No local ${selectedType.label.lowercase()} titles"
                    } else {
                        "No local matches"
                    },
                    modifier = Modifier.fillMaxWidth().padding(vertical = 48.dp),
                    subtitle = if (query.isBlank()) {
                        "Add or rescan local folders from Download settings, then local entries appear here."
                    } else {
                        "Try another search term or switch item type."
                    },
                )
            }
        } else {
            item {
                FlowRow(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp),
                ) {
                    entries.forEach { manga ->
                        LocalLibraryCoverCell(manga = manga, onClick = { onOpenTitle(manga) })
                    }
                }
            }
        }
    }
}

@Composable
private fun LocalLibraryCoverCell(
    manga: Manga,
    onClick: () -> Unit,
) {
    val interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
    val hovered by interactionSource.collectIsHoveredAsState()
    val elevation by androidx.compose.animation.core.animateDpAsState(if (hovered) 8.dp else 0.dp)
    Column(
        modifier = Modifier
            .width(132.dp)
            .clip(MaterialTheme.shapes.medium)
            .hoverable(interactionSource = interactionSource)
            .clickable(interactionSource = interactionSource, indication = null, onClick = onClick),
        verticalArrangement = Arrangement.spacedBy(6.dp),
    ) {
        Surface(
            shape = MaterialTheme.shapes.medium,
            shadowElevation = elevation,
            tonalElevation = 0.dp,
            color = Color.Transparent,
        ) {
            CoverImage(
                model = manga.customCoverImage ?: manga.customCoverFromTracker ?: manga.imageUrl,
                contentDescription = "${manga.name} cover",
                contentScale = androidx.compose.ui.layout.ContentScale.Crop,
                fallbackInitials = manga.name.split(" ")
                    .take(2)
                    .joinToString("") { it.firstOrNull()?.uppercase() ?: "" },
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(0.7f),
            )
        }
        Text(
            text = manga.name,
            style = MaterialTheme.typography.bodySmall,
            fontWeight = FontWeight.Medium,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis,
            modifier = Modifier.padding(horizontal = 2.dp),
        )
    }
}

Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryOverviewScreen.kt

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

The implementation below defines LocalLibraryOverviewRoute, LocalLibraryUnsupportedScreen, LocalLibraryOverviewScreen.

Cross-chapter imports used by this file: YokanRuntime, ItemType, ColorizationJobState, isLocalLibraryManagerSupported, YokanListRow, YokanTopBar. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.local

import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Error
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.LocalLibrary
import androidx.compose.material.icons.automirrored.outlined.MenuBook
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Storage
import androidx.compose.material.icons.outlined.Sync
import androidx.compose.material.icons.outlined.VideoLibrary
import androidx.compose.material.icons.outlined.Palette
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.local_library_full_rescan
import yokan.composeapp.generated.resources.local_import_files
import yokan.composeapp.generated.resources.local_import_folder
import yokan.composeapp.generated.resources.local_import_explanation
import yokan.composeapp.generated.resources.local_import_type
import yokan.composeapp.generated.resources.local_import_manga
import yokan.composeapp.generated.resources.local_import_anime
import yokan.composeapp.generated.resources.local_import_novel
import yokan.composeapp.generated.resources.action_cancel
import yokan.composeapp.generated.resources.retry
import yokan.composeapp.generated.resources.ui_close
import yokan.composeapp.generated.resources.local_import_progress
import yokan.composeapp.generated.resources.local_import_preparing
import yokan.composeapp.generated.resources.local_import_failed
import yokan.composeapp.generated.resources.local_import_complete
import yokan.composeapp.generated.resources.local_import_recovery
import yokan.composeapp.generated.resources.local_import_finish
import yokan.composeapp.generated.resources.local_import_discard
import eu.friedcutlet.yokan.services.library.LocalImportPhase
import androidx.compose.material3.TextButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
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.domain.ItemType
import eu.friedcutlet.yokan.services.library.LocalEntryManagementOperation
import eu.friedcutlet.yokan.services.library.LocalLibraryDuplicateGroup
import eu.friedcutlet.yokan.services.colorization.ColorizationJobState
import eu.friedcutlet.yokan.services.system.isLocalLibraryManagerSupported
import eu.friedcutlet.yokan.ui.components.YokanListRow
import eu.friedcutlet.yokan.ui.components.YokanTopBar
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.navigation.SettingsPage
import eu.friedcutlet.yokan.ui.theme.YokanHorizontalDivider as HorizontalDivider
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold

@Composable
internal fun LocalLibraryOverviewRoute(nav: Navigator) {
    if (!isLocalLibraryManagerSupported()) {
        LocalLibraryUnsupportedScreen(onBack = nav::back)
        return
    }
    val vm = viewModel {
        LocalLibraryViewModel(YokanRuntime.localLibrary, YokanRuntime.settings, YokanRuntime.libraryIndex, YokanRuntime.colorizationQueue)
    }
    val state by vm.state.collectAsStateWithLifecycle()
    LocalLibraryOverviewScreen(
        state = state,
        onEvent = vm::onEvent,
        onOpenDownloadSettings = { nav.navigate(Route.Settings(SettingsPage.Downloads)) },
        onBack = nav::back,
    )
}

@Composable
private fun LocalLibraryUnsupportedScreen(onBack: () -> Unit) {
    Scaffold(topBar = { YokanTopBar("Local media", onBack = onBack) }) { padding ->
        Text(
            "Local media management is unavailable on this platform. Configure local media on Android, iOS, or Desktop.",
            modifier = Modifier.padding(padding).padding(24.dp),
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
    }
}

@Composable
internal fun LocalLibraryOverviewScreen(
    state: LocalLibraryUiState,
    onEvent: (LocalLibraryEvent) -> Unit,
    onOpenDownloadSettings: () -> Unit,
    onBack: () -> Unit,
) {
    val overview = state.overview
    var duplicateGroup by remember { mutableStateOf<LocalLibraryDuplicateGroup?>(null) }
    var selectedType by remember { mutableStateOf<ItemType?>(null) }
    var importDirectory by remember { mutableStateOf<Boolean?>(null) }
    var colorizationConfirmation by remember { mutableStateOf<eu.friedcutlet.yokan.domain.Manga?>(null) }

    Scaffold(topBar = { YokanTopBar("Local media", onBack = onBack) }) { innerPadding ->
        Column(
            modifier = Modifier.fillMaxSize().padding(innerPadding).verticalScroll(rememberScrollState()),
        ) {
            if (state.colorizationJobs.isNotEmpty()) {
                Text("Colorization queue", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(16.dp))
                state.colorizationJobs.forEach { job ->
                    YokanListRow(
                        title = job.cloneTitle,
                        subtitle = "${job.state.name} · ${job.donePages}/${job.totalPages} pages${job.currentChapter?.let { " · $it" }.orEmpty()}${job.error?.let { " · $it" }.orEmpty()}",
                        icon = Icons.Outlined.Palette,
                        onClick = {},
                    )
                    if (job.state == ColorizationJobState.Running || job.state == ColorizationJobState.Publishing) {
                        LinearProgressIndicator(
                            progress = { if (job.totalPages > 0) job.donePages.toFloat() / job.totalPages else 0f },
                            modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),
                        )
                    }
                    androidx.compose.foundation.layout.Row(Modifier.padding(horizontal = 12.dp)) {
                        when (job.state) {
                            ColorizationJobState.Queued, ColorizationJobState.Running -> TextButton(onClick = { onEvent(LocalLibraryEvent.ColorizationAction(job.id, ColorizationJobAction.Pause)) }) { Text("Pause") }
                            ColorizationJobState.Paused -> TextButton(onClick = { onEvent(LocalLibraryEvent.ColorizationAction(job.id, ColorizationJobAction.Resume)) }) { Text("Resume") }
                            ColorizationJobState.Blocked -> TextButton(onClick = { onEvent(LocalLibraryEvent.ColorizationAction(job.id, ColorizationJobAction.Retry)) }) { Text(stringResource(Res.string.retry)) }
                            else -> Unit
                        }
                        if (job.state !in setOf(ColorizationJobState.Completed, ColorizationJobState.Cancelled)) {
                            TextButton(onClick = { onEvent(LocalLibraryEvent.ColorizationAction(job.id, ColorizationJobAction.Cancel)) }) { Text(stringResource(Res.string.action_cancel)) }
                        }
                    }
                }
            }
            state.colorizationError?.let { Text(it, modifier = Modifier.padding(horizontal = 16.dp), color = MaterialTheme.colorScheme.error) }
            Spacer(Modifier.height(24.dp))
            YokanListRow(
                title = "Local media",
                subtitle = "Manage folders and indexed local titles",
                icon = Icons.Outlined.Storage,
                onClick = {},
            )
            HorizontalDivider()
            Text(stringResource(Res.string.local_import_explanation), modifier = Modifier.padding(16.dp), color = MaterialTheme.colorScheme.onSurfaceVariant)
            androidx.compose.foundation.layout.Row(Modifier.padding(horizontal = 16.dp)) {
                TextButton(onClick = { importDirectory = false }, enabled = !state.importBusy) { Text(stringResource(Res.string.local_import_files)) }
                TextButton(onClick = { importDirectory = true }, enabled = !state.importBusy) { Text(stringResource(Res.string.local_import_folder)) }
            }
            if (state.importBusy) {
                val progress = state.importProgress
                Text(if (progress == null) stringResource(Res.string.local_import_preparing)
                    else stringResource(Res.string.local_import_progress, progress.filesDone, progress.filesTotal, progress.bytesDone / (1024 * 1024)), modifier = Modifier.padding(horizontal = 16.dp))
                LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp))
                TextButton(onClick = { onEvent(LocalLibraryEvent.CancelImport) }, modifier = Modifier.padding(horizontal = 16.dp)) { Text(stringResource(Res.string.action_cancel)) }
            }
            if (state.importFailed) Text(stringResource(Res.string.local_import_failed) + state.importError?.let { ": $it" }.orEmpty(), modifier = Modifier.padding(16.dp), color = MaterialTheme.colorScheme.error)
            if (state.importCompleted) Text(stringResource(Res.string.local_import_complete), modifier = Modifier.padding(16.dp))
            if (state.pendingImports.isNotEmpty()) {
                Text(stringResource(Res.string.local_import_recovery), modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.titleMedium)
                state.pendingImports.forEach { pending ->
                    Text(pending.name, modifier = Modifier.padding(horizontal = 16.dp))
                    TextButton(onClick = {
                        onEvent(if (pending.phase == LocalImportPhase.Ready) LocalLibraryEvent.RecoverImport(pending.id) else LocalLibraryEvent.DiscardIncompleteImport(pending.id))
                    }, enabled = !state.importBusy, modifier = Modifier.padding(horizontal = 16.dp)) {
                        Text(stringResource(if (pending.phase == LocalImportPhase.Ready) Res.string.local_import_finish else Res.string.local_import_discard))
                    }
                }
            }
            YokanListRow(
                title = "${overview.folders.size} configured folder${if (overview.folders.size == 1) "" else "s"}",
                subtitle = overview.folders.joinToString { it.name }.ifBlank { "No folders configured" },
                icon = Icons.Outlined.Storage,
                onClick = onOpenDownloadSettings,
            )
            if (overview.folders.isEmpty()) {
                YokanListRow(
                    title = "Set up a local folder",
                    subtitle = "Choose folders to scan for manga, anime, and novels",
                    icon = Icons.Outlined.Settings,
                    onClick = onOpenDownloadSettings,
                )
            } else {
                YokanListRow("Manga", onClick = { selectedType = ItemType.Manga }, subtitle = "${overview.manga} local title${if (overview.manga == 1) "" else "s"}", icon = Icons.AutoMirrored.Outlined.MenuBook)
                YokanListRow("Anime", onClick = { selectedType = ItemType.Anime }, subtitle = "${overview.anime} local title${if (overview.anime == 1) "" else "s"}", icon = Icons.Outlined.VideoLibrary)
                YokanListRow("Novels", onClick = { selectedType = ItemType.Novel }, subtitle = "${overview.novels} local title${if (overview.novels == 1) "" else "s"}", icon = Icons.Outlined.LocalLibrary)
                selectedType?.let { type ->
                    Text("${type.name} local titles", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(16.dp))
                    state.titlesByType[type].orEmpty().forEach { manga ->
                        YokanListRow(title = manga.name, subtitle = manga.link, icon = Icons.Outlined.Storage, onClick = { onEvent(LocalLibraryEvent.SelectEntry(manga)) })
                    }
                }
            }
            overview.lastScan?.let { scan ->
                val needsReview = scan.unavailableFolders.size
                YokanListRow(
                    title = "Last scan: ${scan.total} item${if (scan.total == 1) "" else "s"}",
                    subtitle = if (needsReview > 0) "$needsReview folder${if (needsReview == 1) "" else "s"} unavailable" else "No folder issues reported",
                    icon = Icons.Outlined.History,
                    onClick = {},
                )
            }
            overview.scanError?.let { error ->
                YokanListRow(
                    title = "Scan failed",
                    subtitle = "$error · Retry with Scan folders",
                    icon = Icons.Outlined.Error,
                    onClick = {},
                )
            }
            overview.reconciliation?.let { reconciliation ->
                val reviewCount = reconciliation.staleTitleCandidates.size +
                    reconciliation.staleChapterCandidates.size +
                    reconciliation.duplicateTitleGroups.size + reconciliation.duplicateChapterGroups.size
                YokanListRow(
                    title = "Reconciliation: $reviewCount item${if (reviewCount == 1) "" else "s"} need attention",
                    subtitle = "No physical files are changed",
                    icon = Icons.Outlined.Sync,
                    onClick = {},
                )
            }
            state.message?.let { Text(it, modifier = Modifier.padding(16.dp), color = MaterialTheme.colorScheme.error) }
            Button(
                onClick = { onEvent(LocalLibraryEvent.Rescan) },
                enabled = !overview.scanRunning && !state.importBusy,
                modifier = Modifier.padding(16.dp).fillMaxWidth(),
            ) { Text(if (overview.scanRunning) "Scanning…" else "Scan folders") }
            TextButton(
                onClick = { onEvent(LocalLibraryEvent.FullRescan) },
                enabled = !overview.scanRunning && !state.importBusy,
                modifier = Modifier.padding(horizontal = 16.dp),
            ) { Text(stringResource(Res.string.local_library_full_rescan)) }
            Text("Needs metadata review", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(16.dp))
            if (state.reviewQueue.isEmpty()) {
                Text("No incomplete local titles found.", modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
            } else {
                state.reviewQueue.forEach { manga ->
                    YokanListRow(
                        title = manga.name,
                        subtitle = "Select a candidate before changing metadata",
                        icon = Icons.Outlined.Search,
                        onClick = { onEvent(LocalLibraryEvent.OpenMetadataReview(manga)) },
                    )
                }
            }
            overview.reconciliation?.let { reconciliation ->
                if (reconciliation.staleTitleCandidates.isNotEmpty()) {
                    Text("Stale entries", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(16.dp))
                    reconciliation.staleTitleCandidates.forEach { stale ->
                        YokanListRow(
                            title = "Forget ${state.titleNames[stale.id] ?: "local entry"}",
                            subtitle = "Source files remain unchanged",
                            icon = Icons.Outlined.Delete,
                            onClick = {
                                onEvent(
                                    LocalLibraryEvent.PreviewOperation(
                                        LocalEntryManagementOperation.ForgetStale(reconciliation, titleIds = listOf(stale.id)),
                                    ),
                                )
                            },
                        )
                    }
                }
                if (reconciliation.staleChapterCandidates.isNotEmpty()) {
                    Text("Stale chapters", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(16.dp))
                    reconciliation.staleChapterCandidates.forEach { stale ->
                        YokanListRow(
                            title = "Forget stale chapter ${stale.id}",
                            subtitle = "Forget from database only · source files unchanged",
                            icon = Icons.Outlined.Delete,
                            onClick = {
                                onEvent(
                                    LocalLibraryEvent.PreviewOperation(
                                        LocalEntryManagementOperation.ForgetStale(reconciliation, chapterIds = listOf(stale.id)),
                                    ),
                                )
                            },
                        )
                    }
                }
                if (reconciliation.duplicateTitleGroups.isNotEmpty()) {
                    Text("Exact-identity duplicates", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(16.dp))
                    reconciliation.duplicateTitleGroups.forEach { group ->
                        YokanListRow(
                            title = "${group.ids.size} duplicate entries",
                            subtitle = "Choose a canonical database entry",
                            icon = Icons.Outlined.ContentCopy,
                            onClick = { duplicateGroup = group },
                        )
                    }
                }
                if (reconciliation.duplicateChapterGroups.isNotEmpty()) {
                    Text("Duplicate chapters", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(16.dp))
                    reconciliation.duplicateChapterGroups.forEach { group ->
                        YokanListRow(
                            title = "${group.ids.size} exact-identity duplicate chapters",
                            subtitle = "Chapter merge is unavailable; source files affected: 0",
                            icon = Icons.Outlined.ContentCopy,
                            onClick = {},
                        )
                    }
                }
            }
        }
    }
    importDirectory?.let { directory ->
        AlertDialog(
            onDismissRequest = { importDirectory = null },
            title = { Text(stringResource(Res.string.local_import_type)) },
            text = {
                Column {
                    listOf(ItemType.Manga to Res.string.local_import_manga, ItemType.Anime to Res.string.local_import_anime, ItemType.Novel to Res.string.local_import_novel).forEach { (type, label) ->
                        TextButton(onClick = { importDirectory = null; onEvent(LocalLibraryEvent.ImportMedia(type, directory)) }) { Text(stringResource(label)) }
                    }
                }
            },
            confirmButton = {},
            dismissButton = { TextButton(onClick = { importDirectory = null }) { Text(stringResource(Res.string.action_cancel)) } },
        )
    }
    state.metadataReview?.let { review ->
        LocalMetadataReviewDialog(review = review, onEvent = onEvent)
    }
    duplicateGroup?.let { group ->
        LocalDuplicateGroupDialog(
            group = group,
            titleName = { id -> state.titleNames[id] },
            onChoose = { canonicalTitleId ->
                onEvent(LocalLibraryEvent.PreviewMerge(group, canonicalTitleId))
                duplicateGroup = null
            },
            onDismiss = { duplicateGroup = null },
        )
    }
    state.managementPreview?.let { preview ->
        LocalEntryOperationDialog(
            preview = preview,
            onConfirm = { onEvent(LocalLibraryEvent.ConfirmOperation) },
            onDismiss = { onEvent(LocalLibraryEvent.DismissOperation) },
        )
    }
    BoxWithConstraints(Modifier.fillMaxSize()) {
        state.selectedEntry?.let { manga ->
            val stale = overview.reconciliation?.staleTitleCandidates?.any { it.id == manga.id } == true
            val openReview = { onEvent(LocalLibraryEvent.OpenMetadataReview(manga)) }
            if (maxWidth >= 900.dp) {
                Surface(
                    modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight().width(360.dp).padding(16.dp),
                    shape = MaterialTheme.shapes.large,
                    tonalElevation = 2.dp,
                ) {
                    LocalEntryDetailContent(manga, stale, state.selectedEntryChapters, Modifier.verticalScroll(rememberScrollState()).padding(16.dp), openReview,
                        canColorize = state.colorizationSupported && manga.itemType == ItemType.Manga && manga.isLocalArchive && !manga.source.equals("torrent", true),
                        onColorize = { colorizationConfirmation = manga })
                }
            } else {
                AlertDialog(
                    onDismissRequest = { onEvent(LocalLibraryEvent.SelectEntry(null)) },
                    title = { Text(manga.name) },
                    text = { LocalEntryDetailContent(manga, stale, state.selectedEntryChapters, Modifier.verticalScroll(rememberScrollState()), openReview,
                        canColorize = state.colorizationSupported && manga.itemType == ItemType.Manga && manga.isLocalArchive && !manga.source.equals("torrent", true),
                        onColorize = { colorizationConfirmation = manga }) },
                    confirmButton = { TextButton(onClick = { onEvent(LocalLibraryEvent.SelectEntry(null)) }) { Text(stringResource(Res.string.ui_close)) } },
                )
            }
        }
    }
    colorizationConfirmation?.let { manga ->
        AlertDialog(
            onDismissRequest = { colorizationConfirmation = null },
            title = { Text("Colorize ${manga.name}?") },
            text = { Text("A separate local copy named “${manga.name} (Colorized)” will be created from all chapters. The original stays unchanged. The queue resumes after you reopen the app.") },
            confirmButton = { TextButton(onClick = { onEvent(LocalLibraryEvent.EnqueueColorization(manga)); colorizationConfirmation = null }) { Text("Create colorized copy") } },
            dismissButton = { TextButton(onClick = { colorizationConfirmation = null }) { Text(stringResource(Res.string.action_cancel)) } },
        )
    }
}

Check your understanding

Import manga, EPUB and a video season, restart, and open them offline. Then remove access to one external folder and verify the UI offers a recoverable error. [chapter-content-end]: #

Recreate the tests and verify the chapter

Run natural-order/archive/path, local import/reconciliation, metadata/season and entry-management fixtures, including concurrent database edits and deletions during scans. Browser inventory/OPFS, iOS scoped inputs and Android SAF require their own platform tests and manual restart checks.

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/androidHostTest/kotlin/eu/friedcutlet/yokan/services/files/AndroidSafLocalArchiveServiceTest.kt

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

The implementation below defines AndroidSafLocalArchiveServiceTest, fullRescanRefreshesStagedBooksWithoutProviderTimestamps, stagesEachDocumentOnceAndReusesTheCopy, keepsOnlyTheMostRecentlyUsedStagedCopies, uri, providerFailureReturnsNullAndDoesNotLeaveAStagedFile, treeChildUrisStageTheChildArchiveInsteadOfTheTreeRoot, epub, cbz, zipOf and 2 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • fullRescanRefreshesStagedBooksWithoutProviderTimestamps
  • stagesEachDocumentOnceAndReusesTheCopy
  • keepsOnlyTheMostRecentlyUsedStagedCopies
  • providerFailureReturnsNullAndDoesNotLeaveAStagedFile
  • treeChildUrisStageTheChildArchiveInsteadOfTheTreeRoot
package eu.friedcutlet.yokan.services.files

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.net.URI
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class AndroidSafLocalArchiveServiceTest {
    @Test
    fun fullRescanRefreshesStagedBooksWithoutProviderTimestamps() {
        val root = testDirectory()
        var title = "before"
        var opens = 0
        val book = "content://test/document/book.epub"
        try {
            val service = AndroidSafLocalArchiveService(root.absolutePath, contentStreamOpener = {
                opens++
                ByteArrayInputStream(epub(title))
            })
            assertEquals("before", service.listEpubChapters(book).single().title)
            title = "after"
            assertEquals("before", service.listEpubChapters(book).single().title)
            assertEquals(1, opens)
            service.invalidateIndexCache()
            assertEquals("after", service.listEpubChapters(book).single().title)
            assertEquals(2, opens)
        } finally {
            root.deleteRecursively()
        }
    }

    @Test
    fun stagesEachDocumentOnceAndReusesTheCopy() {
        val root = testDirectory()
        val book = "content://test/document/book.epub"
        var opens = 0
        try {
            val service = AndroidSafLocalArchiveService(
                cacheRoot = root.absolutePath,
                contentStreamOpener = { uri ->
                    opens++
                    ByteArrayInputStream(epub(uri.substringAfterLast('/')))
                },
            )

            assertEquals("book.epub", service.listEpubChapters(book).single().title)
            assertTrue(service.readEpubChapter(book, 0).contains("book.epub"))
            assertTrue(service.readEpubResource(book, "chapter.xhtml") != null)

            assertEquals(1, opens)
            assertEquals(1, stagedCopies(root).size)
        } finally {
            root.deleteRecursively()
        }
    }

    @Test
    fun keepsOnlyTheMostRecentlyUsedStagedCopies() {
        val root = testDirectory()
        val books = listOf("a", "b", "c", "d").associateWith { epub(it) }
        val opens = mutableListOf<String>()
        fun uri(book: String) = "content://test/document/$book"
        try {
            val service = AndroidSafLocalArchiveService(
                cacheRoot = root.absolutePath,
                contentStreamOpener = { uri ->
                    val book = uri.substringAfterLast('/')
                    opens += book
                    books[book]?.let(::ByteArrayInputStream)
                },
            )
            listOf("a", "b", "c").forEach { assertTrue(service.readEpubResource(uri(it), "chapter.xhtml") != null) }
            // Pin the LRU order explicitly: filesystem mtimes can tie within one test.
            stagedCopies(root).forEach { copy ->
                val book = books.entries.first { it.value.contentEquals(copy.readBytes()) }.key
                copy.setLastModified(1_000L * (1 + "abc".indexOf(book)))
            }

            assertTrue(service.readEpubResource(uri("a"), "chapter.xhtml") != null) // reuse marks a as used
            assertTrue(service.readEpubResource(uri("d"), "chapter.xhtml") != null) // evicts b, the oldest
            val remaining = stagedCopies(root).map { copy -> books.entries.first { it.value.contentEquals(copy.readBytes()) }.key }
            assertEquals(setOf("a", "c", "d"), remaining.toSet())

            assertTrue(service.readEpubResource(uri("b"), "chapter.xhtml") != null)
            assertEquals(listOf("a", "b", "c", "d", "b"), opens)
        } finally {
            root.deleteRecursively()
        }
    }

    @Test
    fun providerFailureReturnsNullAndDoesNotLeaveAStagedFile() {
        val root = testDirectory()
        try {
            val service = AndroidSafLocalArchiveService(
                cacheRoot = root.absolutePath,
                contentStreamOpener = { error("provider unavailable") },
            )

            assertEquals(null, service.readEpubResource("content://test/document/book.epub", "chapter.xhtml"))
            assertTrue(stagedCopies(root).isEmpty())
        } finally {
            root.deleteRecursively()
        }
    }

    @Test
    fun treeChildUrisStageTheChildArchiveInsteadOfTheTreeRoot() {
        val root = testDirectory()
        val requestedUris = mutableListOf<String>()
        // The Android SDK's DocumentsContract builders are not implemented in JVM tests.
        // Keep the SAF-shaped fixture literal; the service still receives document URIs.
        val rootEpub = "content://test/tree/root/document/root.epub"
        val childEpub = "content://test/tree/root/document/child.epub"
        val rootCbz = "content://test/tree/root/document/root.cbz"
        val childCbz = "content://test/tree/root/document/child.cbz"
        val streams = mapOf(
            rootEpub to epub("root"),
            childEpub to epub("child"),
            rootCbz to cbz("root"),
            childCbz to cbz("child"),
        )
        try {
            val service = AndroidSafLocalArchiveService(
                cacheRoot = root.absolutePath,
                contentStreamOpener = { uri ->
                    requestedUris += uri
                    streams[uri]?.let(::ByteArrayInputStream)
                },
            )

            assertEquals("child", service.listEpubChapters(childEpub).single().title)
            val pages = service.listPages(childCbz)
            assertEquals(1, pages.size)
            assertEquals("child", File(URI(pages.single().url)).readText())
            assertTrue(childEpub in requestedUris)
            assertTrue(childCbz in requestedUris)
            assertTrue(rootEpub !in requestedUris)
            assertTrue(rootCbz !in requestedUris)
        } finally {
            root.deleteRecursively()
        }
    }

    private fun epub(title: String): ByteArray = zipOf(
        "META-INF/container.xml" to """
            <?xml version="1.0"?>
            <container><rootfiles><rootfile full-path="content.opf"/></rootfiles></container>
        """.trimIndent(),
        "content.opf" to """
            <package><manifest><item id="chapter" href="chapter.xhtml"/></manifest>
            <spine><itemref idref="chapter"/></spine></package>
        """.trimIndent(),
        "chapter.xhtml" to "<html><head><title>$title</title></head><body>$title</body></html>",
    )

    private fun cbz(page: String): ByteArray = zipOf("$page.jpg" to page)

    private fun zipOf(vararg entries: Pair<String, String>): ByteArray =
        ByteArrayOutputStream().also { bytes ->
            ZipOutputStream(bytes).use { zip ->
                entries.forEach { (name, content) ->
                    zip.putNextEntry(ZipEntry(name))
                    zip.write(content.encodeToByteArray())
                    zip.closeEntry()
                }
            }
        }.toByteArray()

    private fun stagedCopies(root: File): List<File> = File(root, "archive-staging").listFiles().orEmpty().toList()

    private fun testDirectory(): File =
        File(System.getProperty("java.io.tmpdir"), "yokan-archive-test-${System.nanoTime()}").also { it.mkdirs() }
}

Write composeApp/src/androidHostTest/kotlin/eu/friedcutlet/yokan/services/files/SafDocumentPathTest.kt

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

The implementation below defines SafDocumentPathTest, opaqueRootAndDocumentIdsRemainWhole, appendedSidecarsResolveFromRootOrExplicitDocument, invalidOrExcessiveDescendantsAreRejected.

Read the setup, action and assertions in these cases before implementing their production paths:

  • opaqueRootAndDocumentIdsRemainWhole
  • appendedSidecarsResolveFromRootOrExplicitDocument
  • invalidOrExcessiveDescendantsAreRejected
package eu.friedcutlet.yokan.services.files

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class SafDocumentPathTest {
    @Test
    fun opaqueRootAndDocumentIdsRemainWhole() {
        assertEquals(SafDocumentPath("primary:Shows/Season 2", emptyList()), safDocumentPath(listOf("tree", "primary:Shows/Season 2")))
        assertEquals(SafDocumentPath("opaque:folder/id", emptyList()), safDocumentPath(listOf("tree", "root", "document", "opaque:folder/id")))
    }

    @Test
    fun appendedSidecarsResolveFromRootOrExplicitDocument() {
        assertEquals(SafDocumentPath("root", listOf("episodes.json")), safDocumentPath(listOf("tree", "root", "episodes.json")))
        assertEquals(SafDocumentPath("opaque:id", listOf("Season 2", "episodes.json")), safDocumentPath(listOf("tree", "root", "document", "opaque:id", "Season 2", "episodes.json")))
    }

    @Test
    fun invalidOrExcessiveDescendantsAreRejected() {
        for (child in listOf("", ".", "..", "a/b", "a\\b", "a\u0000b")) {
            assertNull(safDocumentPath(listOf("tree", "root", child)))
        }
        assertNull(safDocumentPath(listOf("tree", "root") + List(65) { "folder" }))
        assertNull(safDocumentPath(listOf("tree", "root", "document")))
        assertNull(safDocumentPath(listOf("document", "opaque:id")))
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/files/BoundedCacheTest.kt

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

The implementation below defines BoundedCacheTest, evictsLeastRecentlyUsedMetadataWithinBothBudgets, oversizedReplacementDoesNotRemainCached.

Read the setup, action and assertions in these cases before implementing their production paths:

  • evictsLeastRecentlyUsedMetadataWithinBothBudgets
  • oversizedReplacementDoesNotRemainCached
package eu.friedcutlet.yokan.services.files

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class BoundedCacheTest {
    @Test
    fun evictsLeastRecentlyUsedMetadataWithinBothBudgets() {
        val cache = BoundedCache<String, String>(maxEntries = 2, maxWeight = 6) { it.length }
        cache["a"] = "aa"
        cache["b"] = "bb"
        assertEquals("aa", cache["a"])
        cache["c"] = "ccc"
        assertNull(cache["b"])
        assertEquals("aa", cache["a"])
        cache["c"] = "ccccc"
        assertNull(cache["a"])
        assertEquals("ccccc", cache["c"])
    }

    @Test
    fun oversizedReplacementDoesNotRemainCached() {
        val cache = BoundedCache<String, String>(maxEntries = 2, maxWeight = 4) { it.length }
        cache["book"] = "old"
        cache["book"] = "too large"
        assertNull(cache["book"])
        cache["other"] = "fits"
        assertEquals("fits", cache["other"])
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/files/EpubManifestTest.kt

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

The implementation below defines EpubManifestTest, readsSelfClosingAndExplicitlyClosedItemsWithNormalisedRelativePaths.

Read the setup, action and assertions in these cases before implementing their production paths:

  • asynchronousManifestPreservesSpinePositionsAndRelativePaths
  • readsSelfClosingAndExplicitlyClosedItemsWithNormalisedRelativePaths
package eu.friedcutlet.yokan.services.files

import kotlin.test.Test
import kotlin.test.assertEquals

class EpubManifestTest {
    @Test fun asynchronousManifestPreservesSpinePositionsAndRelativePaths() = kotlinx.coroutines.test.runTest {
        val entries = mapOf(
            "META-INF/container.xml" to """<rootfile full-path="OPS/book.opf"/>""",
            "OPS/book.opf" to """<manifest><item id="one" href="Text/a%20b.xhtml"/></manifest><spine><itemref idref="missing"/><itemref idref="one"/></spine>""",
            "OPS/Text/a b.xhtml" to "<html><p>Untitled</p></html>",
        )
        val reads = mutableListOf<String>()
        val actual = readEpubManifestAsync { path -> reads += path; kotlinx.coroutines.yield(); entries[path]?.encodeToByteArray() }
        assertEquals(listOf(LocalEpubChapter("Chapter 2", "OPS/Text/a b.xhtml")), actual)
        assertEquals(readEpubManifest { entries[it]?.encodeToByteArray() }, actual)
        assertEquals(listOf("META-INF/container.xml", "OPS/book.opf", "OPS/Text/a b.xhtml"), reads)
    }
    @Test
    fun readsSelfClosingAndExplicitlyClosedItemsWithNormalisedRelativePaths() {
        val entries = mapOf(
            "META-INF/container.xml" to """<container><rootfiles><rootfile full-path="OEBPS/content.opf"/></rootfiles></container>""",
            "OEBPS/content.opf" to """
                <package>
                  <manifest>
                    <item id="one" href="Text/ch1.xhtml" media-type="application/xhtml+xml"/>
                    <item id="two"
                          href="./Text/../Text/chapter%20two.xhtml"
                          media-type="application/xhtml+xml"></item>
                    <item id="missing" href="Text/missing.xhtml"/>
                  </manifest>
                  <spine><itemref idref="one"/><itemref idref="missing"/><itemref idref="two"/></spine>
                </package>
            """.trimIndent(),
            "OEBPS/Text/ch1.xhtml" to "<html><head><title>Opening <b>Night</b></title></head></html>",
            "OEBPS/Text/chapter two.xhtml" to "<html><body>untitled</body></html>",
        )

        val chapters = readEpubManifest { path -> entries[path]?.encodeToByteArray() }

        assertEquals(
            listOf(
                LocalEpubChapter(title = "Opening Night", href = "OEBPS/Text/ch1.xhtml"),
                LocalEpubChapter(title = "Chapter 3", href = "OEBPS/Text/chapter two.xhtml"),
            ),
            chapters,
        )
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/files/NaturalPageOrderTest.kt

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

The implementation below defines NaturalPageOrderTest, sortsDigitRunsNaturallyAndUsesDeterministicCaseTieBreak.

Read the setup, action and assertions in these cases before implementing their production paths:

  • sortsDigitRunsNaturallyAndUsesDeterministicCaseTieBreak
package eu.friedcutlet.yokan.services.files

import kotlin.test.Test
import kotlin.test.assertEquals

class NaturalPageOrderTest {
    @Test
    fun sortsDigitRunsNaturallyAndUsesDeterministicCaseTieBreak() {
        assertEquals(
            listOf("1.jpg", "02.jpg", "2.jpg", "10.jpg", "Page2.jpg", "page10.jpg"),
            listOf("page10.jpg", "2.jpg", "02.jpg", "10.jpg", "Page2.jpg", "1.jpg")
                .sortedWith(naturalPageNameComparator),
        )
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/files/TestFiles.kt

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

The implementation below defines NoFiles, writeBytes, readBytes, canonicalPath, exists, deleteRecursively, directorySize, openLocation, listLocalEntries, listFiles and 7 further declarations.

The source describes its contract as:

A filesystem that stores nothing: writes vanish and every path is absent.

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.database.DbPageUrl

/** A filesystem that stores nothing: writes vanish and every path is absent. */
internal object NoFiles : LocalFileService {
    override val downloadRoot = "/downloads"
    override val backupRoot = "/backups"
    override val cacheRoot = "/cache"
    override fun writeBytes(path: String, bytes: ByteArray) = Unit
    override fun readBytes(path: String) = ByteArray(0)
    override fun canonicalPath(path: String) = path
    override fun exists(path: String) = false
    override fun deleteRecursively(path: String) = true
    override fun directorySize(path: String) = 0L
    override fun openLocation(path: String) = false
    override fun listLocalEntries(root: String) = emptyList<LocalEntry>()
    override fun listFiles(root: String) = emptyList<LocalFileEntry>()
}

/**
 * Map-backed filesystem with directory semantics derived from `/`-separated paths.
 * Methods are `open` so tests can inject failures by subclassing.
 */
internal open class MemoryFiles : LocalFileService {
    override val downloadRoot = "/downloads"
    override val backupRoot = "/backups"
    override val cacheRoot = "/cache"
    val files = linkedMapOf<String, ByteArray>()
    val paths: Set<String> get() = files.keys

    override fun writeBytes(path: String, bytes: ByteArray) {
        files[path] = bytes.copyOf()
    }

    override fun readBytes(path: String): ByteArray = files[path]?.copyOf() ?: ByteArray(0)
    override fun canonicalPath(path: String): String? = path
    override fun exists(path: String): Boolean = path in files || files.keys.any { it.startsWith("$path/") }

    override fun deleteRecursively(path: String): Boolean {
        files.keys.removeAll { it == path || it.startsWith("$path/") }
        return true
    }

    override fun directorySize(path: String): Long =
        files.filterKeys { it == path || it.startsWith("$path/") }.values.sumOf { it.size.toLong() }

    override fun openLocation(path: String) = false
    override fun listLocalEntries(root: String): List<LocalEntry>? = emptyList()
    override fun listFiles(root: String): List<LocalFileEntry> =
        files.filterKeys { it.substringBeforeLast('/') == root }
            .map { (path, bytes) -> LocalFileEntry(path, path.substringAfterLast('/'), bytes.size.toLong(), 0L) }
}

/** Archives that contain nothing and cannot be packaged. */
internal object NoArchives : LocalArchiveService {
    override fun listPages(archivePath: String) = emptyList<DbPageUrl>()
    override fun listEpubChapters(archivePath: String) = emptyList<LocalEpubChapter>()
    override fun readEpubChapter(archivePath: String, index: Int) = ""
    override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null
    override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? = null
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalAnimeDetailsTest.kt

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

The implementation below defines LocalAnimeDetailsTest, AnimeDetailsFiles, database, writeBytes, readBytes, readBytesAsync, canonicalPath, exists, deleteRecursively, directorySize and 3 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • castImagesStayWithinTheTitleAndMissingOrInvalidCastPreservesExistingCredits
  • detailsOverrideDeclaredFieldsAndKeepLegacyArtworkLanguageAndProgress
  • animetailNumericStatusesDoNotUseLegacyEnumOrdinals
  • malformedDetailsFallBackAndSuspendingReadsPreserveConcurrentUserEdits
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.files.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class LocalAnimeDetailsTest {
    @Test fun castImagesStayWithinTheTitleAndMissingOrInvalidCastPreservesExistingCredits() = runTest {
        val files = AnimeDetailsFiles().apply {
            details = """{"cast":[{"name":"Actor","role":"Voice actor","character":"Hero","image_url":"actor.png"},{"name":"Other","image_url":"../private.png"}]}"""
            extraFiles["/anime/Show/actor.png"] = byteArrayOf(1, 2)
        }
        val db = files.database()
        val scanner = DefaultLocalLibraryService(db, files, NoArchives)
        scanner.scan()
        val title = db.mangas().single()
        assertEquals("file:///anime/Show/actor.png", title.cast[0].imageUrl)
        assertNull(title.cast[1].imageUrl)
        assertNull(title.customCoverImage, "A referenced portrait must not become the title cover")
        assertFalse(files.reads.any { it.endsWith("actor.png") || "private.png" in it })
        val original = db.chapters(title.id).single()
        for (text in listOf("{}", """{"cast":{}}""", """{"cast":[{"name":3}]}""")) {
            files.details = text; files.version++; scanner.scan()
            assertEquals(title.cast, db.manga(title.id)?.cast)
        }
        files.details = """{"cast":[{"name":"Changed actor"}]}"""; files.version++
        val entered = CompletableDeferred<Unit>()
        val release = CompletableDeferred<Unit>()
        files.beforeDetails = { entered.complete(Unit); release.await() }
        val work = async { scanner.scan() }
        entered.await()
        db.upsertManga(title.copy(privateNote = "Concurrent note", favorite = true))
        db.upsertChapter(original.copy(isRead = true, isBookmarked = true, lastPageRead = "1234"))
        release.complete(Unit); work.await()
        assertEquals("Changed actor", db.manga(title.id)?.cast?.single()?.name)
        assertEquals("Concurrent note", db.manga(title.id)?.privateNote)
        assertEquals("1234", db.chapter(original.id)?.lastPageRead)
        files.beforeDetails = {}; files.details = """{"cast":[]}"""; files.version++
        scanner.scan()
        assertEquals(emptyList(), db.manga(title.id)?.cast)
    }

    @Test fun detailsOverrideDeclaredFieldsAndKeepLegacyArtworkLanguageAndProgress() = runTest {
        val files = AnimeDetailsFiles()
        val db = files.database()
        val scanner = DefaultLocalLibraryService(db, files, NoArchives)
        scanner.scan()
        val initial = db.mangas().single()
        val chapter = db.chapters(initial.id).single()
        assertEquals("File title", initial.name)
        assertEquals("File description", initial.description)
        assertEquals("Author", initial.author)
        assertEquals("Artist", initial.artist)
        assertEquals(listOf("Action"), initial.genre)
        assertEquals(DbStatus.Completed, initial.status)
        assertEquals("https://cover.test/image", initial.imageUrl)
        assertEquals("ja", initial.lang)
        db.upsertManga(initial.copy(favorite = true, categories = listOf(8), privateNote = "Private"))
        db.upsertChapter(chapter.copy(isRead = true, isBookmarked = true, lastPageRead = "1200"))
        val count = files.reads.size
        scanner.scan()
        assertEquals(count, files.reads.size)
        files.details = """{"title":"Renamed","genre":[],"status":4}"""
        files.version++
        scanner.scan()
        val updated = assertNotNull(db.manga(initial.id))
        assertEquals("Renamed", updated.name)
        assertEquals(emptyList(), updated.genre)
        assertEquals(DbStatus.PublishingFinished, updated.status)
        assertTrue(updated.favorite)
        assertEquals(listOf(8L), updated.categories)
        assertEquals("Private", updated.privateNote)
        val current = assertNotNull(db.chapter(chapter.id))
        assertTrue(current.isRead && current.isBookmarked)
        assertEquals("1200", current.lastPageRead)
        assertTrue(files.bounds.all { it == 65536L })
    }

    @Test fun animetailNumericStatusesDoNotUseLegacyEnumOrdinals() = runTest {
        val files = AnimeDetailsFiles()
        val db = files.database()
        val scanner = DefaultLocalLibraryService(db, files, NoArchives)
        val expected = listOf(DbStatus.Unknown, DbStatus.Ongoing, DbStatus.Completed, DbStatus.Licensed,
            DbStatus.PublishingFinished, DbStatus.Canceled, DbStatus.OnHiatus, DbStatus.Upcoming)
        expected.forEachIndexed { value, status ->
            files.details = "{\"status\":$value}"; files.version++
            scanner.scan()
            assertEquals(status, db.mangas().single().status, "Animetail status $value")
        }
    }

    @Test fun malformedDetailsFallBackAndSuspendingReadsPreserveConcurrentUserEdits() = runTest {
        val files = AnimeDetailsFiles().apply { details = "not JSON" }
        val db = files.database()
        val scanner = DefaultLocalLibraryService(db, files, NoArchives)
        scanner.scan()
        val title = db.mangas().single()
        assertEquals("Legacy", title.name)
        assertEquals(DbStatus.Ongoing, title.status)
        files.details = """{"title":"Updated"}"""; files.version++
        val entered = CompletableDeferred<Unit>()
        val release = CompletableDeferred<Unit>()
        files.beforeDetails = { entered.complete(Unit); release.await() }
        val scan = async { scanner.scan() }
        entered.await()
        db.upsertManga(title.copy(privateNote = "Edited during read", favorite = true))
        release.complete(Unit); scan.await()
        assertEquals("Edited during read", db.manga(title.id)?.privateNote)
        assertEquals(true, db.manga(title.id)?.favorite)
        files.version++
        files.beforeDetails = { throw CancellationException("Retired") }
        assertFailsWith<CancellationException> { scanner.scan() }
        assertEquals(1, db.mangas().size)
    }
}

internal class AnimeDetailsFiles : LocalFileService {
    override val downloadRoot = "/downloads"
    override val backupRoot = "/backups"
    override val cacheRoot = "/cache"
    var version = 1L
    var details = """{"title":"File title","description":"File description","author":"Author","artist":"Artist","genre":["Action"],"status":2}"""
    var beforeDetails: suspend () -> Unit = {}
    var episodes: String? = null
    var beforeEpisodes: suspend () -> Unit = {}
    val extraFiles = mutableMapOf<String, ByteArray>()
    val reads = mutableListOf<String>()
    val bounds = mutableListOf<Long>()
    fun database() = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", "/anime")))))
    override fun writeBytes(path: String, bytes: ByteArray) = error("Read-only")
    override fun readBytes(path: String): ByteArray = error("Use async reads")
    override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray {
        reads += path; bounds += maxBytes
        if (path.endsWith("details.json")) beforeDetails()
        if (path.endsWith("episodes.json")) beforeEpisodes()
        extraFiles[path]?.let { return it.also { require(it.size <= maxBytes) } }
        val text = if (path.endsWith("details.json")) details else if (path.endsWith("episodes.json")) requireNotNull(episodes)
            else """{"name":"Legacy","status":0,"imageUrl":"https://cover.test/image","language":"ja"}"""
        return text.encodeToByteArray().also { require(it.size <= maxBytes) }
    }
    override fun canonicalPath(path: String) = path
    override fun exists(path: String) = path in extraFiles || (path == "/anime/Show/episodes.json" && episodes != null) ||
        path in setOf("/anime", "/anime/Show", "/anime/Show/metadata.json", "/anime/Show/details.json")
    override fun deleteRecursively(path: String) = false
    override fun directorySize(path: String) = 0L
    override fun openLocation(path: String) = false
    override fun listFiles(root: String) = if (root == "/anime/Show") listOf(
        LocalFileEntry("$root/metadata.json", "metadata.json", 100, version),
        LocalFileEntry("$root/details.json", "details.json", details.length.toLong(), version),
    ) + listOfNotNull(episodes?.let { LocalFileEntry("$root/episodes.json", "episodes.json", it.length.toLong(), version) }) +
        extraFiles.map { (path, bytes) -> LocalFileEntry(path, path.substringAfterLast('/'), bytes.size.toLong(), version) }
        else emptyList()
    override fun listLocalEntries(root: String): List<LocalEntry>? = when (root) {
        "/anime" -> listOf(LocalEntry("/anime/Show", "Show", false))
        "/anime/Show" -> listOf(LocalEntry("/anime/Show/Episode 1.mp4", "Episode 1", true)) +
            extraFiles.keys.map { LocalEntry(it, it.substringAfterLast('/').substringBeforeLast('.'), true) }
        else -> emptyList()
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalAnimeEpisodesTest.kt

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

The implementation below defines LocalAnimeEpisodesTest, canonicalPath, exists, listFiles, listLocalEntries, listDirectoryEntries, readBytesAsync.

Read the setup, action and assertions in these cases before implementing their production paths:

  • opaqueProviderIdsUseDisplayNamesForEpisodesSeasonsAndNestedPreviews
  • episodeSidecarsApplyMetadataWithoutChangingFileIdentityOrProgress
  • malformedOversizedAndCancelledEpisodeReadsDoNotDestroyUserState
  • titleDeletedDuringAnEpisodeReadIsNotResurrected
  • manualFillerMarksWinOverSidecarRescansUntilCleared
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.files.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class LocalAnimeEpisodesTest {
    @Test fun opaqueProviderIdsUseDisplayNamesForEpisodesSeasonsAndNestedPreviews() = runTest {
        val root = "content://provider/tree/anime"
        val title = "$root/document/opaque-title"
        val season = "$root/document/opaque-season"
        val video = "$root/document/opaque-video"
        val art = "$root/document/opaque-art"
        val preview = "$root/document/opaque-preview"
        val delegate = AnimeDetailsFiles()
        val files = object : LocalFileService by delegate {
            override fun canonicalPath(path: String): String? = null
            override fun exists(path: String) = path == root || path == "$season/episodes.json"
            override fun listFiles(root: String) = emptyList<LocalFileEntry>()
            override fun listLocalEntries(root: String) = if (root == "content://provider/tree/anime")
                listOf(LocalEntry(title, "Show", false)) else emptyList()
            override fun listDirectoryEntries(root: String) = when (root) {
                title -> listOf(LocalDirectoryEntry(season, "Season 2", true))
                season -> listOf(LocalDirectoryEntry(video, "Episode 7.mp4", false), LocalDirectoryEntry(art, "art", true))
                art -> listOf(LocalDirectoryEntry(preview, "preview.png", false))
                else -> emptyList()
            }
            override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray {
                assertEquals("$season/episodes.json", path)
                return """[{"episode_number":7,"name":"A custom title","preview_url":"art/preview.png"}]""".encodeToByteArray()
            }
        }
        val folder = DbLocalFolder("Anime", root)
        val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(folder))))
        val scanner = DefaultLocalLibraryService(db, files, NoArchives)
        scanner.scan()
        val chapter = db.chapters().single()
        assertEquals("A custom title", chapter.name)
        assertEquals(7.0, chapter.number)
        assertEquals(2, chapter.season)
        assertEquals("Episode 7", chapter.numberingName)
        assertEquals(preview, chapter.thumbnailUrl)
        assertEquals(video, resolveLocalArchivePath(chapter.archivePath, listOf(folder)))
        scanner.scanFresh()
        assertEquals(listOf(chapter.id), db.chapters().map { it.id })
    }

    @Test fun episodeSidecarsApplyMetadataWithoutChangingFileIdentityOrProgress() = runTest {
        val files = AnimeDetailsFiles().apply {
            episodes = """[{"episode_number":1,"name":"Opening Night","date_upload":"2026-04-12","fillermark":true,"scanlator":"Group","summary":"Synopsis","preview_url":"preview.png"}]"""
            extraFiles["/anime/Show/preview.png"] = byteArrayOf(1, 2, 3)
        }
        val db = files.database()
        val scanner = DefaultLocalLibraryService(db, files, NoArchives)
        scanner.scan()
        val title = db.mangas().single()
        val original = db.chapters(title.id).single()
        assertEquals("Opening Night", original.name)
        assertEquals(1.0, original.number)
        assertEquals("Episode 1", original.numberingName)
        assertEquals("2026-04-12", original.dateUpload)
        assertTrue(original.isFiller)
        assertEquals("Group", original.scanlator)
        assertEquals("Synopsis", original.description)
        assertEquals("file:///anime/Show/preview.png", original.thumbnailUrl)
        assertTrue(original.archivePath.endsWith("/Episode 1.mp4"))
        val reads = files.reads.count { it.endsWith("episodes.json") }
        scanner.scan()
        assertEquals(reads, files.reads.count { it.endsWith("episodes.json") })
        files.version++
        files.episodes = """[{"episode_number":1,"name":"Changed title","fillermark":false,"scanlator":"","summary":"","preview_url":"../private.png"}]"""
        val entered = CompletableDeferred<Unit>()
        val release = CompletableDeferred<Unit>()
        files.beforeEpisodes = { entered.complete(Unit); release.await() }
        val scan = async { scanner.scan() }
        entered.await()
        db.upsertChapter(original.copy(isRead = true, isBookmarked = true, lastPageRead = "45000"))
        release.complete(Unit); scan.await()
        val updated = assertNotNull(db.chapter(original.id))
        assertEquals(original.archivePath, updated.archivePath)
        assertEquals(original.url, updated.url)
        assertEquals("Changed title", updated.name)
        assertFalse(updated.isFiller)
        assertEquals("", updated.description)
        assertEquals("", updated.scanlator)
        assertEquals(original.thumbnailUrl, updated.thumbnailUrl)
        assertEquals("45000", updated.lastPageRead)
        assertTrue(updated.isRead && updated.isBookmarked)
        assertTrue(files.bounds.contains(1024L * 1024))
        assertFalse(files.reads.any { "private.png" in it })
    }

    @Test fun malformedOversizedAndCancelledEpisodeReadsDoNotDestroyUserState() = runTest {
        val files = AnimeDetailsFiles().apply { episodes = "not JSON" }
        val db = files.database()
        val scanner = DefaultLocalLibraryService(db, files, NoArchives)
        scanner.scan()
        val original = db.chapters().single()
        assertEquals("Episode 1", original.name)
        db.upsertChapter(original.copy(isRead = true, isFiller = true, lastPageRead = "9000"))
        files.version++
        files.episodes = " ".repeat(1024 * 1024 + 1)
        scanner.scan()
        assertTrue(assertNotNull(db.chapter(original.id)).isFiller)
        assertEquals("9000", db.chapter(original.id)?.lastPageRead)
        files.version++
        files.beforeEpisodes = { throw CancellationException("Retired") }
        assertFailsWith<CancellationException> { scanner.scan() }
        assertEquals("9000", db.chapter(original.id)?.lastPageRead)
    }

    @Test fun titleDeletedDuringAnEpisodeReadIsNotResurrected() = runTest {
        val files = AnimeDetailsFiles().apply { episodes = "[]" }
        val db = files.database()
        val scanner = DefaultLocalLibraryService(db, files, NoArchives)
        scanner.scan()
        val title = db.mangas().single()
        files.version++
        val entered = CompletableDeferred<Unit>()
        val release = CompletableDeferred<Unit>()
        files.beforeEpisodes = { entered.complete(Unit); release.await() }
        val scan = async { scanner.scan() }
        entered.await(); db.removeManga(title.id); release.complete(Unit); scan.await()
        assertNull(db.manga(title.id))
    }

    @Test fun manualFillerMarksWinOverSidecarRescansUntilCleared() = runTest {
        val files = AnimeDetailsFiles().apply { episodes = """[{"episode_number":1,"fillermark":true}]""" }
        val db = files.database()
        val scanner = DefaultLocalLibraryService(db, files, NoArchives)
        scanner.scan()
        val original = db.chapters().single()
        val repository = eu.friedcutlet.yokan.data.DefaultYokanRepository(db)
        repository.setChaptersFillerOverride(setOf(original.id), false)
        files.version++
        files.episodes = """[{"episode_number":1,"name":"Renamed","fillermark":true}]"""
        scanner.scan()
        val rescanned = assertNotNull(db.chapter(original.id))
        assertEquals("Renamed", rescanned.name)
        assertTrue(rescanned.isFiller, "The sidecar value stays the source value")
        assertFalse(rescanned.effectiveFiller)
        assertFalse(repository.chapters(original.mangaId!!).single().isFiller)
        repository.setChaptersFillerOverride(setOf(original.id), null)
        assertTrue(repository.chapters(original.mangaId).single().isFiller)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalCastMetadataTest.kt

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

The implementation below defines LocalCastMetadataTest.

Read the setup, action and assertions in these cases before implementing their production paths:

  • validCreditsKeepOrderAndSkipMalformedOrDuplicateRows
  • invalidOrOversizedCastIsDistinctFromExplicitClear

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.domain.TitleCredit
import eu.friedcutlet.yokan.services.metadata.parseTitleCast
import kotlinx.serialization.json.Json
import kotlin.test.*

class LocalCastMetadataTest {
    @Test fun validCreditsKeepOrderAndSkipMalformedOrDuplicateRows() {
        val cast = parseTitleCast(Json.parseToJsonElement("""[
            {"name":" Actor ","role":"Voice actor","character":"Hero","image_url":"portrait.png"},
            {"name":"Actor","role":"Voice actor","character":"Hero","image_url":"other.png"},
            {"name":"Writer","role":12,"character":""}, {"name":""}, {"name":7}, null
        ]"""))
        assertEquals(listOf(TitleCredit("Actor", "Voice actor", "Hero", "portrait.png"), TitleCredit("Writer")), cast)
    }

    @Test fun invalidOrOversizedCastIsDistinctFromExplicitClear() {
        assertNull(parseTitleCast(null))
        assertNull(parseTitleCast(Json.parseToJsonElement("{}")))
        assertNull(parseTitleCast(Json.parseToJsonElement("""[{"name":4}]""")))
        assertNull(parseTitleCast(Json.parseToJsonElement(List(501) { "{\"name\":\"Actor $it\"}" }.joinToString(",", "[", "]"))))
        assertEquals(emptyList(), parseTitleCast(Json.parseToJsonElement("[]")))
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalEntryManagementServiceTest.kt

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

The implementation below defines LocalEntryManagementServiceTest, forgetPreviewIsLogicalAndApplyCleansDependents, activeDownloadAndChangedStateRejectApply, atomicReplacementConflictForwardsAsStateChanged, mergeKeepsCanonicalAndMigratesChapterAndTrackerReferences, mergeRejectsActiveAffectedChapterDownload, forgetRecordsHistoryUpdateAndTrackTombstones, mergeBlocksAmbiguousCompletedDownloadWithoutChangingDownloadIdentity, mergeBlocksCompletedDownloadOnDuplicateChapterWithoutRemappingIdentity, tombstonesUseTableAwareIdsAndDoNotRedirectRemoveEntries and 7 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • forgetPreviewIsLogicalAndApplyCleansDependents
  • activeDownloadAndChangedStateRejectApply
  • atomicReplacementConflictForwardsAsStateChanged
  • mergeKeepsCanonicalAndMigratesChapterAndTrackerReferences
  • mergeRejectsActiveAffectedChapterDownload
  • forgetRecordsHistoryUpdateAndTrackTombstones
  • mergeBlocksAmbiguousCompletedDownloadWithoutChangingDownloadIdentity
  • mergeBlocksCompletedDownloadOnDuplicateChapterWithoutRemappingIdentity
  • tombstonesUseTableAwareIdsAndDoNotRedirectRemoveEntries
  • applyRequiresFreshReconciliationEvidence

Cross-chapter imports used by this file: DbActionType, DbChangedPart, DbChapter, DbChapterPageUrls, DbDownload, DbHistory. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbActionType
import eu.friedcutlet.yokan.database.DbChangedPart
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbChapterPageUrls
import eu.friedcutlet.yokan.database.DbDownload
import eu.friedcutlet.yokan.database.DbHistory
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbTrack
import eu.friedcutlet.yokan.database.DbTrackStatus
import eu.friedcutlet.yokan.database.DbUpdate
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class LocalEntryManagementServiceTest {
    @Test
    fun forgetPreviewIsLogicalAndApplyCleansDependents() = runTest {
        val title = DbManga(id = 10, name = "Old", link = "USB/Old", source = "local", isLocalArchive = true)
        val chapter = DbChapter(id = 11, mangaId = title.id, archivePath = "USB/Old/chapter.cbz")
        val identity = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)
        val chapterIdentity = localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, chapter.archivePath)
        val evidence = LocalLibraryReconciliationResult(
            staleTitleCandidates = listOf(LocalLibraryStaleCandidate(title.id, identity)),
            staleChapterCandidates = listOf(LocalLibraryStaleCandidate(chapter.id, chapterIdentity)),
        )
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(title),
            chapters = listOf(chapter),
            downloads = listOf(DbDownload(id = 1, chapterId = chapter.id, isDownload = true)),
        ))
        val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))
        val preview = service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id)))

        assertEquals(0, preview.sourceFilesAffected)
        assertEquals(1, preview.titleRowsRemoved)
        assertEquals(1, preview.chapterRowsRemoved)
        assertEquals(1, database.mangas().size)

        val applied = service.apply(preview.command)
        assertEquals(LocalEntryManagementApplyStatus.Applied, applied.status)
        assertTrue(database.mangas().isEmpty())
        assertTrue(database.chapters().isEmpty())
        assertTrue(database.downloads().isEmpty())
    }

    @Test
    fun activeDownloadAndChangedStateRejectApply() = runTest {
        val title = DbManga(id = 20, link = "USB/Old", source = "local", isLocalArchive = true)
        val identity = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)
        val evidence = LocalLibraryReconciliationResult(
            staleTitleCandidates = listOf(LocalLibraryStaleCandidate(title.id, identity)),
        )
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title)))
        val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))
        val preview = service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id)))
        database.upsertManga(title.copy(name = "changed"))
        val changed = service.apply(preview.command)
        assertEquals(LocalEntryManagementBlockers.StateChanged, changed.blocker)

        val activeDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(title),
            chapters = listOf(DbChapter(id = 21, mangaId = title.id, archivePath = "USB/Old/chapter.cbz")),
            downloads = listOf(DbDownload(id = 2, chapterId = 21, isStartDownload = true)),
        ))
        val activeEvidence = evidence.copy(staleChapterCandidates = listOf(
            LocalLibraryStaleCandidate(21, localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Old/chapter.cbz")),
        ))
        val activeService = DefaultLocalEntryManagementService(activeDatabase, EvidenceLibrary(activeEvidence))
        val activePreview = activeService.preview(LocalEntryManagementOperation.ForgetStale(activeEvidence, titleIds = listOf(title.id)))
        assertEquals(LocalEntryManagementBlockers.ActiveDownload, activeService.apply(activePreview.command).blocker)
    }

    @Test
    fun atomicReplacementConflictForwardsAsStateChanged() = runTest {
        val title = DbManga(id = 22, link = "USB/Old", source = "local", isLocalArchive = true)
        val evidence = LocalLibraryReconciliationResult(
            staleTitleCandidates = listOf(
                LocalLibraryStaleCandidate(
                    title.id,
                    localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!),
                ),
            ),
        )
        val backing = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title)))
        val database = InjectingDatabase(backing) {
            backing.upsertManga(title.copy(name = "Concurrent edit"))
        }
        val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))
        val preview = service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id)))

        val result = service.apply(preview.command)

        assertEquals(LocalEntryManagementApplyStatus.Rejected, result.status)
        assertEquals(LocalEntryManagementBlockers.StateChanged, result.blocker)
        assertEquals("Concurrent edit", backing.mangas().single().name)
    }

    @Test
    fun mergeKeepsCanonicalAndMigratesChapterAndTrackerReferences() = runTest {
        val first = DbManga(id = 30, name = "Canonical", link = "USB/Same", source = "local", isLocalArchive = true, lastRead = 2, dateAdded = 200)
        val second = DbManga(id = 31, name = "Duplicate", link = "USB/Same", source = "local", isLocalArchive = true, favorite = true, lastRead = 8, dateAdded = 100, smartUpdateDays = 4, customCoverImage = byteArrayOf(1, 2), description = "fallback description")
        val groupIdentity = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same")
        val evidence = LocalLibraryReconciliationResult(
            duplicateTitleGroups = listOf(LocalLibraryDuplicateGroup(groupIdentity, listOf(first.id, second.id))),
        )
        val canonicalChapter = DbChapter(id = 32, mangaId = first.id, archivePath = "USB/Same/chapter.cbz", lastPageRead = "2")
        val duplicateChapter = DbChapter(id = 34, mangaId = second.id, archivePath = "USB/Same/chapter.cbz", isRead = true, isBookmarked = true, lastPageRead = "7")
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(first, second),
            chapters = listOf(canonicalChapter, duplicateChapter),
            histories = listOf(
                DbHistory(id = 36, mangaId = first.id, chapterId = canonicalChapter.id, itemType = DbItemType.Manga, date = "100", readingTimeSeconds = 10),
                DbHistory(id = 37, mangaId = second.id, chapterId = duplicateChapter.id, itemType = DbItemType.Manga, date = "200", readingTimeSeconds = 25),
            ),
            tracks = listOf(
                DbTrack(id = 33, mangaId = first.id, syncId = 1, mediaId = 99, lastChapterRead = 2, status = DbTrackStatus.Reading),
                DbTrack(id = 35, mangaId = second.id, syncId = 1, mediaId = 99, lastChapterRead = 8, status = DbTrackStatus.Completed),
            ),
            pageCache = listOf(
                DbChapterPageUrls(chapterId = canonicalChapter.id, urls = listOf("page-1")),
                DbChapterPageUrls(chapterId = duplicateChapter.id, urls = listOf("page-2")),
            ),
            changedParts = listOf(
                DbChangedPart(id = 40, actionType = DbActionType.RemoveItem, isarId = first.id, data = "canonical", clientDate = 1),
                DbChangedPart(id = 41, actionType = DbActionType.RemoveItem, isarId = second.id, data = "duplicate", clientDate = 1),
                DbChangedPart(id = 42, actionType = DbActionType.RemoveChapter, isarId = duplicateChapter.id, data = "duplicate chapter", clientDate = 1),
            ),
        ))
        val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))
        val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id)))
        val applied = service.apply(preview.command)

        assertEquals(LocalEntryManagementApplyStatus.Applied, applied.status)
        assertEquals(listOf(first.id), database.mangas().map { it.id })
        val mergedTitle = database.mangas().single()
        assertTrue(mergedTitle.favorite)
        assertEquals(8, mergedTitle.lastRead)
        assertEquals(100, mergedTitle.dateAdded)
        assertEquals(4, mergedTitle.smartUpdateDays)
        assertTrue(mergedTitle.customCoverImage!!.contentEquals(byteArrayOf(1, 2)))
        assertEquals("fallback description", mergedTitle.description)
        assertEquals(first.id, applied.preview.sourceTitleEffect?.canonicalTitleId)
        assertTrue(applied.preview.sourceTitleEffect?.favoriteAfter == true)
        assertTrue(applied.preview.sourceTitleEffect.metadataFallbackFields.contains("description"))
        assertEquals(listOf(canonicalChapter.id), database.chapters().map { it.id })
        assertEquals(first.id, database.chapters().single().mangaId)
        assertTrue(database.chapters().single().isRead)
        assertTrue(database.chapters().single().isBookmarked)
        assertEquals("7", database.chapters().single().lastPageRead)
        assertEquals(8, database.tracks().single().lastChapterRead)
        assertEquals(DbTrackStatus.Completed, database.tracks().single().status)
        assertEquals(1, database.histories().size)
        assertEquals(35, database.histories().single().readingTimeSeconds)
        assertEquals(canonicalChapter.id, database.histories().single().chapterId)
        assertEquals(listOf("page-1", "page-2"), database.pageCache().single().urls)
        assertTrue(database.changedParts().none { it.actionType == DbActionType.RemoveItem && it.isarId == first.id })
        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveItem && it.isarId == second.id })
        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveChapter && it.isarId == duplicateChapter.id })
        assertTrue(database.changedParts().none { it.actionType == DbActionType.RemoveChapter && it.isarId == canonicalChapter.id })
        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveHistory && it.isarId == 37L })
        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveTrack && it.isarId == 35L })
        // Removed: title 31, chapter 34, history 37, track 35, tombstone 40, page cache 34.
        // Added: RemoveHistory/RemoveTrack tombstones. Updated: canonical title, chapter, history,
        // track, page cache and settings rows, plus the two added rows.
        assertEquals(6, applied.preview.databaseRowsRemoved)
        assertEquals(2, applied.preview.databaseRowsAdded)
        assertEquals(8, applied.preview.databaseRowsUpdated)
        assertEquals(1, applied.preview.settingsRecordsAffected)
        assertEquals(0, applied.preview.sourceFilesAffected)
    }

    @Test
    fun mergeRejectsActiveAffectedChapterDownload() = runTest {
        val first = DbManga(id = 40, link = "USB/Same", source = "local", isLocalArchive = true)
        val second = first.copy(id = 41)
        val chapter = DbChapter(id = 42, mangaId = second.id, archivePath = "USB/Same/chapter.cbz")
        val evidence = LocalLibraryReconciliationResult(
            duplicateTitleGroups = listOf(LocalLibraryDuplicateGroup(
                localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"),
                listOf(first.id, second.id),
            )),
        )
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(first, second),
            chapters = listOf(chapter),
            downloads = listOf(DbDownload(id = 43, chapterId = chapter.id, isStartDownload = true)),
        ))
        val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))
        val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id)))
        assertEquals(LocalEntryManagementBlockers.ActiveDownload, service.apply(preview.command).blocker)
    }

    @Test
    fun forgetRecordsHistoryUpdateAndTrackTombstones() = runTest {
        val title = DbManga(id = 44, link = "USB/Removed", source = "local", isLocalArchive = true)
        val chapter = DbChapter(id = 45, mangaId = title.id, archivePath = "USB/Removed/chapter.cbz")
        val evidence = LocalLibraryReconciliationResult(staleTitleCandidates = listOf(
            LocalLibraryStaleCandidate(
                title.id,
                localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!),
            ),
        ))
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(title),
            chapters = listOf(chapter),
            histories = listOf(DbHistory(id = 46, mangaId = title.id, chapterId = chapter.id, itemType = DbItemType.Manga)),
            updates = listOf(DbUpdate(id = 47, mangaId = title.id, chapterId = chapter.id)),
            tracks = listOf(DbTrack(id = 48, mangaId = title.id, status = DbTrackStatus.Reading)),
        ))
        val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))

        service.apply(service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id))).command)

        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveHistory && it.isarId == 46L })
        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveUpdate && it.isarId == 47L })
        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveTrack && it.isarId == 48L })
    }

    @Test
    fun mergeBlocksAmbiguousCompletedDownloadWithoutChangingDownloadIdentity() = runTest {
        val first = DbManga(id = 70, link = "USB/Same", source = "local", isLocalArchive = true)
        val second = first.copy(id = 71)
        val firstChapter = DbChapter(id = 72, mangaId = first.id, archivePath = "USB/Same/chapter.cbz")
        val secondChapter = firstChapter.copy(id = 73, mangaId = second.id)
        val evidence = LocalLibraryReconciliationResult(duplicateTitleGroups = listOf(
            LocalLibraryDuplicateGroup(
                localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"),
                listOf(first.id, second.id),
            ),
        ))
        val completed = DbDownload(id = 74, chapterId = firstChapter.id, isDownload = true)
        val duplicate = DbDownload(id = 75, chapterId = secondChapter.id, isDownload = true)
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(first, second),
            chapters = listOf(firstChapter, secondChapter),
            downloads = listOf(completed, duplicate),
        ))
        val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))
        val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id)))

        assertEquals(LocalEntryManagementBlockers.CompletedDownloadConflict, preview.blockers.single())
        assertEquals(LocalEntryManagementBlockers.CompletedDownloadConflict, service.apply(preview.command).blocker)
        assertEquals(setOf(74L, 75L), database.downloads().map { it.id }.toSet())
        assertEquals(setOf(firstChapter.id, secondChapter.id), database.downloads().mapNotNull { it.chapterId }.toSet())
    }

    @Test
    fun mergeBlocksCompletedDownloadOnDuplicateChapterWithoutRemappingIdentity() = runTest {
        val first = DbManga(id = 76, link = "USB/Same", source = "local", isLocalArchive = true)
        val second = first.copy(id = 77)
        val canonicalChapter = DbChapter(id = 78, mangaId = first.id, archivePath = "USB/Same/chapter.cbz")
        val duplicateChapter = canonicalChapter.copy(id = 79, mangaId = second.id)
        val evidence = LocalLibraryReconciliationResult(duplicateTitleGroups = listOf(
            LocalLibraryDuplicateGroup(
                localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"),
                listOf(first.id, second.id),
            ),
        ))
        val completed = DbDownload(id = 80, chapterId = duplicateChapter.id, isDownload = true)
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(first, second),
            chapters = listOf(canonicalChapter, duplicateChapter),
            downloads = listOf(completed),
        ))
        val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))
        val preview = service.preview(LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, second.id)))

        assertEquals(LocalEntryManagementBlockers.DownloadIdentityConflict, preview.blockers.single())
        assertEquals(LocalEntryManagementBlockers.DownloadIdentityConflict, service.apply(preview.command).blocker)
        assertEquals(listOf(completed), database.downloads())
    }

    @Test
    fun tombstonesUseTableAwareIdsAndDoNotRedirectRemoveEntries() = runTest {
        val title = DbManga(id = 50, link = "USB/Old", source = "local", isLocalArchive = true)
        val chapter = DbChapter(id = 50, mangaId = title.id, archivePath = "USB/Old/chapter.cbz")
        val evidence = LocalLibraryReconciliationResult(staleTitleCandidates = listOf(
            LocalLibraryStaleCandidate(title.id, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)),
        ))
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            mangas = listOf(title),
            chapters = listOf(chapter),
            changedParts = listOf(
                DbChangedPart(id = 1, actionType = DbActionType.RemoveExtension, isarId = title.id, data = "source", clientDate = 1),
                DbChangedPart(id = 2, actionType = DbActionType.RemoveItem, isarId = title.id, data = "old", clientDate = 1),
            ),
        ))
        val service = DefaultLocalEntryManagementService(database, EvidenceLibrary(evidence))
        val result = service.apply(service.preview(LocalEntryManagementOperation.ForgetStale(evidence, titleIds = listOf(title.id))).command)
        assertEquals(LocalEntryManagementApplyStatus.Applied, result.status)
        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveExtension && it.isarId == title.id })
        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveItem && it.isarId == title.id })
        assertTrue(database.changedParts().any { it.actionType == DbActionType.RemoveChapter && it.isarId == chapter.id })
        assertEquals(database.changedParts().map { it.id }.size, database.changedParts().map { it.id }.toSet().size)
    }

    @Test
    fun applyRequiresFreshReconciliationEvidence() = runTest {
        val title = DbManga(id = 60, link = "USB/Old", source = "local", isLocalArchive = true)
        val oldEvidence = LocalLibraryReconciliationResult(staleTitleCandidates = listOf(
            LocalLibraryStaleCandidate(title.id, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, title.link!!)),
        ))
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(mangas = listOf(title)))
        val freshLibrary = EvidenceLibrary(LocalLibraryReconciliationResult())
        val service = DefaultLocalEntryManagementService(database, freshLibrary)
        val command = service.preview(LocalEntryManagementOperation.ForgetStale(oldEvidence, titleIds = listOf(title.id))).command
        assertEquals(LocalEntryManagementBlockers.FreshReconciliationChanged, service.apply(command).blocker)
        assertEquals(1, freshLibrary.reconcileCalls)
    }

    private class EvidenceLibrary(
        private val result: LocalLibraryReconciliationResult,
    ) : LocalLibraryService {
        var reconcileCalls = 0
        override suspend fun scan() = LocalLibraryScanResult(0, 0, 0)
        override suspend fun reconcile(): LocalLibraryReconciliationResult {
            reconcileCalls++
            return result
        }
        override suspend fun importTorrent(pathOrMagnet: String, displayName: String?) = null
    }

    private class InjectingDatabase(
        private val delegate: InMemoryYokanDatabase,
        private val beforeReplacement: () -> Unit,
    ) : YokanDatabase by delegate {
        override suspend fun replaceAllAtomically(
            snapshot: YokanDatabaseSnapshot,
            expectedSnapshot: YokanDatabaseSnapshot?,
            removedSourceIds: Set<Long>,
        ) {
            beforeReplacement()
            delegate.replaceAllAtomically(snapshot, expectedSnapshot, removedSourceIds)
        }
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalEpisodeMetadataTest.kt

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

The implementation below defines LocalEpisodeMetadataTest.

Read the setup, action and assertions in these cases before implementing their production paths:

  • numberedEntriesValidateOptionalFieldsAndKeepTheFirstExactDuplicate
  • floatingPointToleranceAndAmbiguousDeclarationsAreHandledDeterministically
  • metadataMustBeABoundedArray
package eu.friedcutlet.yokan.services.library

import kotlin.test.*

class LocalEpisodeMetadataTest {
    @Test fun numberedEntriesValidateOptionalFieldsAndKeepTheFirstExactDuplicate() {
        val index = parseLocalEpisodes("""[
            {"episode_number":1,"name":" Opening ","date_upload":"2026-02-28","fillermark":true,"scanlator":" Group ","summary":"Summary","preview_url":"preview.png"},
            {"episode_number":1,"name":"Duplicate"},
            {"episode_number":2,"date_upload":"2026-02-30","fillermark":"false","scanlator":"","summary":""},
            {"episode_number":-1,"name":"Invalid"},
            {"episode_number":"3","name":"Invalid"}, null
        ]""")
        val first = assertNotNull(index.find(1.0))
        assertEquals("Opening", first.name)
        assertEquals("2026-02-28", first.dateUpload)
        assertEquals(true, first.filler)
        assertEquals("Group", first.scanlator)
        assertEquals("Summary", first.summary)
        assertEquals("preview.png", first.previewUrl)
        val second = assertNotNull(index.find(2.0))
        assertNull(second.dateUpload)
        assertNull(second.filler)
        assertEquals("", second.scanlator)
        assertEquals("", second.summary)
        assertNull(index.find(3.0))
        assertNull(index.find(Double.NaN))
    }

    @Test fun floatingPointToleranceAndAmbiguousDeclarationsAreHandledDeterministically() {
        val index = parseLocalEpisodes("""[{"episode_number":12.5,"name":"Half"},{"episode_number":1.00001,"name":"Left"},{"episode_number":1.00005,"name":"Right"}]""")
        assertEquals("Half", index.find(12.5000001)?.name)
        assertNull(index.find(12.501))
        assertNull(index.find(1.00003))
        assertNull(index.find(1.00007))
        assertNull(index.find(0.99998))
        assertEquals("Left", index.find(1.00001)?.name)
        assertNull(index.find(null))
    }

    @Test fun metadataMustBeABoundedArray() {
        assertFails { parseLocalEpisodes("{}") }
        assertFails { parseLocalEpisodes("not JSON") }
        assertFails { parseLocalEpisodes(List(10_001) { "{}" }.joinToString(",", "[", "]")) }
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalEpisodePlaybackTest.kt

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

The implementation below defines LocalEpisodePlaybackTest.

Read the setup, action and assertions in these cases before implementing their production paths:

  • scannedSourcelessEpisodePlaysTheFileFromItsConfiguredFolder

Cross-chapter imports used by this file: ProfileId, DefaultYokanRepository, Chapter, ChapterPageResolver, ProfileReaderContent, ProfileReaderContentTest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest
import eu.friedcutlet.yokan.services.files.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class LocalEpisodePlaybackTest {
    @Test fun scannedSourcelessEpisodePlaysTheFileFromItsConfiguredFolder() = runTest {
        val files = MemoryVideoFiles()
        files.put("/anime/Show/Episode 1.mkv")
        val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", "/anime")))))
        DefaultLocalLibraryService(db, files, NoArchives).scan()
        val title = db.mangas().single()
        assertTrue(title.isLocalArchive)
        assertEquals("local", title.source)
        assertEquals(DbItemType.Anime, title.itemType)
        val stored = db.chapters(title.id).single()
        assertEquals("Anime/Show/Episode 1.mkv", stored.archivePath)
        val episode = Chapter(id = stored.id, mangaId = title.id, name = stored.name.orEmpty(), url = stored.url, archivePath = stored.archivePath)

        val factory = ProfileReaderContentTest.RuntimeFactory(db, "local")
        val owner = SupervisorJob()
        val content = ProfileReaderContent(
            ProfileId.Default, db, factory, ChapterPageResolver(DefaultYokanRepository(db), db, factory),
            files, NoArchives, CoroutineScope(owner + StandardTestDispatcher(testScheduler)), StandardTestDispatcher(testScheduler),
        )
        try {
            val video = content.videos(null, episode).single()
            assertEquals("file:///anime/Show/Episode 1.mkv", video.url)
            assertEquals("Downloaded", video.quality)

            // The virtual path follows the folder when the user re-points it.
            files.data["/moved/Show/Episode 1.mkv"] = files.data.remove("/anime/Show/Episode 1.mkv")!!
            db.updateSettings(db.settings().copy(namedLocalFolders = listOf(DbLocalFolder("Anime", "/moved"))))
            assertEquals("file:///moved/Show/Episode 1.mkv", content.videos(null, episode).single().url)

            // A missing file never becomes a fabricated stream.
            files.data.remove("/moved/Show/Episode 1.mkv")
            assertEquals(emptyList(), content.videos(null, episode))
            assertEquals(0, factory.created)
        } finally { content.closeAndJoin(); owner.cancelAndJoin() }
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryAsyncReadTest.kt

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

The implementation below defines LocalLibraryAsyncReadTest, AsyncFiles, prepare, writeBytes, readBytes, readBytesAsync, canonicalPath, exists, deleteRecursively, directorySize and 3 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • scannerPreparesStorageAndUsesBoundedAsyncMetadataAndCoverReads
  • editsMadeDuringAsyncReadsSurviveAndDeletedTitlesAreNotRecreated
  • oversizedMetadataAndCoverAreIgnoredAndCancellationPropagates
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.files.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class LocalLibraryAsyncReadTest {
    @Test fun scannerPreparesStorageAndUsesBoundedAsyncMetadataAndCoverReads() = runTest {
        val files = AsyncFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        DefaultLocalLibraryService(db, files, NoArchives).scan()
        assertTrue(files.prepared)
        assertEquals(listOf(65536L, 4194304L), files.bounds)
        val title = db.mangas().single()
        assertEquals("File title", title.name)
        assertContentEquals(byteArrayOf(1, 2), title.customCoverImage)
        assertEquals(1, db.chapters(title.id).size)
    }

    @Test fun editsMadeDuringAsyncReadsSurviveAndDeletedTitlesAreNotRecreated() = runTest {
        val files = AsyncFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val service = DefaultLocalLibraryService(db, files, NoArchives)
        service.scan()
        val title = db.mangas().single()
        val chapter = db.chapters(title.id).single()
        files.version++
        val started = CompletableDeferred<Unit>()
        val release = CompletableDeferred<Unit>()
        files.beforeMetadata = { started.complete(Unit); release.await() }
        val scan = async { service.scan() }
        started.await()
        db.upsertManga(checkNotNull(db.manga(title.id)).copy(favorite = true, privateNote = "User note", categories = listOf(123),
            customCoverImage = byteArrayOf(9)))
        db.upsertChapter(checkNotNull(db.chapter(chapter.id)).copy(isRead = true, isBookmarked = true, lastPageRead = "7"))
        release.complete(Unit)
        scan.await()
        val saved = checkNotNull(db.manga(title.id))
        assertTrue(saved.favorite)
        assertEquals("User note", saved.privateNote)
        assertEquals(listOf(123L), saved.categories)
        assertContentEquals(byteArrayOf(9), saved.customCoverImage)
        assertTrue(checkNotNull(db.chapter(chapter.id)).isRead)
        assertTrue(checkNotNull(db.chapter(chapter.id)).isBookmarked)
        assertEquals("7", db.chapter(chapter.id)?.lastPageRead)
        files.version++
        val secondStarted = CompletableDeferred<Unit>()
        val secondRelease = CompletableDeferred<Unit>()
        files.beforeMetadata = { secondStarted.complete(Unit); secondRelease.await() }
        val deletedScan = async { service.scan() }
        secondStarted.await()
        db.removeManga(title.id)
        secondRelease.complete(Unit)
        deletedScan.await()
        assertNull(db.manga(title.id))
        assertTrue(db.mangas().isEmpty())
    }

    @Test fun oversizedMetadataAndCoverAreIgnoredAndCancellationPropagates() = runTest {
        val files = AsyncFiles().apply { oversized = true }
        val db = InMemoryYokanDatabase(emptySnapshot())
        val service = DefaultLocalLibraryService(db, files, NoArchives)
        service.scan()
        assertEquals("Title", db.mangas().single().name)
        assertNull(db.mangas().single().customCoverImage)
        files.version++
        files.beforeMetadata = { throw CancellationException("Retired") }
        assertFailsWith<CancellationException> { service.scan() }
        assertEquals(1, db.mangas().size)
    }
}

private class AsyncFiles : LocalFileService {
    override val downloadRoot = "/downloads"
    override val backupRoot = "/backups"
    override val cacheRoot = "/cache"
    var prepared = false
    var version = 1L
    var oversized = false
    var beforeMetadata: suspend () -> Unit = {}
    val bounds = mutableListOf<Long>()
    override suspend fun prepare() { prepared = true }
    override fun writeBytes(path: String, bytes: ByteArray) = error("Read-only fixture")
    override fun readBytes(path: String): ByteArray = error("Synchronous reads must not be used")
    override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray {
        check(prepared)
        bounds += maxBytes
        if (path.endsWith("metadata.json")) beforeMetadata()
        if (oversized) error("File exceeds bound")
        return if (path.endsWith("metadata.json")) "{\"name\":\"File title\"}".encodeToByteArray() else byteArrayOf(1, 2)
    }
    override fun canonicalPath(path: String) = path
    override fun exists(path: String): Boolean { check(prepared); return path in setOf("/downloads/local", "/downloads/local/Title", "/downloads/local/Title/metadata.json", "/downloads/local/Title/cover.png") }
    override fun deleteRecursively(path: String) = false
    override fun directorySize(path: String) = 0L
    override fun openLocation(path: String) = false
    override fun listLocalEntries(root: String): List<LocalEntry>? {
        check(prepared)
        return when (root) {
            "/downloads/local" -> listOf(LocalEntry("$root/Title", "Title", false))
            "/downloads/local/Title" -> listOf(LocalEntry("$root/Chapter 1.cbz", "Chapter 1", true), LocalEntry("$root/cover.png", "cover", true))
            else -> emptyList()
        }
    }
    override fun listFiles(root: String) = if (root == "/downloads/local/Title") listOf(
        LocalFileEntry("$root/metadata.json", "metadata.json", 100, version), LocalFileEntry("$root/cover.png", "cover.png", 2, version)) else emptyList()
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryProjectionTest.kt

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

The implementation below defines LocalLibraryProjectionTest, bothScreensShareMappingAndOnlyTitleDependenciesInvalidateIt.

Read the setup, action and assertions in these cases before implementing their production paths:

  • bothScreensShareMappingAndOnlyTitleDependenciesInvalidateIt

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbTitleMetadata
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.ItemType
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
import kotlin.test.assertNotSame

class LocalLibraryProjectionTest {
    @Test
    fun bothScreensShareMappingAndOnlyTitleDependenciesInvalidateIt() {
        val snapshot = seedDatabaseSnapshot().copy(mangas = listOf(
            DbManga(id = 1, name = "Local", description = "Description", isLocalArchive = true, itemType = DbItemType.Manga),
            DbManga(id = 2, name = "Torrent", source = "TORRENT", isLocalArchive = true, itemType = DbItemType.Manga),
            DbManga(id = 3, name = "Remote", itemType = DbItemType.Manga),
        ))
        val cache = LocalLibraryProjectionCache()
        val initial = cache.get(snapshot)
        assertEquals(listOf(1L), initial.titlesByType.getValue(ItemType.Manga).map { it.id })
        assertEquals(listOf(1L, 2L), initial.browseTitlesByType.getValue(ItemType.Manga).map { it.id })
        assertSame(initial.titlesByType.getValue(ItemType.Manga).single(), initial.browseTitlesByType.getValue(ItemType.Manga).first())
        assertEquals(listOf(1L), initial.reviewQueue.map { it.id })
        assertSame(initial, cache.get(snapshot.copy(settings = snapshot.settings.copy(themeIsDark = !snapshot.settings.themeIsDark))))
        val updated = cache.get(snapshot.copy(settings = snapshot.settings.copy(titleMetadata = listOf(DbTitleMetadata(1, metadataServerId = "linked")))))
        assertNotSame(initial, updated)
        assertEquals(emptyList(), updated.reviewQueue)
        assertEquals("linked", updated.browseTitlesByType.getValue(ItemType.Manga).first().metadataServerId)
        assertEquals(null, initial.browseTitlesByType.getValue(ItemType.Manga).first().metadataServerId)
        val deleted = cache.get(snapshot.copy(mangas = emptyList()))
        assertEquals(0, deleted.overview(emptyList(), LocalLibraryScanState()).manga)
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryReconciliationTest.kt

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

The implementation below defines LocalLibraryReconciliationTest, unreadableFolderIsUnavailableInsteadOfHealthyEmpty, scansShareOneOperationLock, reconciliationIsConservativeAndNeverDeletes, remountKeepsVirtualIdentityAndSecondScanIsIdempotent, oneScanRefreshesExistingLocalRowsWithoutReplacingTheirIds, colorizerStagingIsIgnoredUntilPublishedAndPublishedCbzIsIdempotent, unchangedScanReusesReadsAndFreshScanBypassesFingerprints, FixtureFiles, writeBytes and 14 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • unreadableFolderIsUnavailableInsteadOfHealthyEmpty
  • scansShareOneOperationLock
  • reconciliationIsConservativeAndNeverDeletes
  • remountKeepsVirtualIdentityAndSecondScanIsIdempotent
  • oneScanRefreshesExistingLocalRowsWithoutReplacingTheirIds
  • colorizerStagingIsIgnoredUntilPublishedAndPublishedCbzIsIdempotent
  • unchangedScanReusesReadsAndFreshScanBypassesFingerprints

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbLocalFolder
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.files.LocalEpubChapter
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.files.LocalFileService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

class LocalLibraryReconciliationTest {
    @Test
    fun unreadableFolderIsUnavailableInsteadOfHealthyEmpty() = runTest {
        val files = FixtureFiles(roots = setOf("/downloads/local"), entries = emptyMap())
        val service = DefaultLocalLibraryService(InMemoryYokanDatabase(), files, EmptyArchives)

        val result = service.scan()

        assertEquals(emptyList(), result.healthyFolders)
        assertEquals(listOf(DbLocalFolder("local", "/downloads/local")), result.unavailableFolders)
    }

    @Test
    fun scansShareOneOperationLock() = runTest {
        val files = FixtureFiles(roots = emptySet(), entries = emptyMap())
        val service = DefaultLocalLibraryService(InMemoryYokanDatabase(), files, EmptyArchives)
        var active = 0
        var maximum = 0
        val first = async {
            service.withOperationLock {
                active++
                maximum = maxOf(maximum, active)
                delay(10)
                active--
            }
        }
        val second = async {
            service.withOperationLock {
                active++
                maximum = maxOf(maximum, active)
                delay(10)
                active--
            }
        }
        first.await()
        second.await()
        assertEquals(1, maximum)
    }

    @Test
    fun reconciliationIsConservativeAndNeverDeletes() {
        val healthy = DbLocalFolder("USB", "/mounted")
        val unavailable = DbLocalFolder("Offline", "/offline")
        val oldTitle = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Old")
        val oldChapter = localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Old/book.epub#0")
        val currentTitle = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Current")
        val duplicateTitle = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Duplicate")
        val duplicateChapter = localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Duplicate/book.epub#0")
        val renamedFolder = localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "Renamed/Old")
        val scan = LocalLibraryScanResult(
            added = 1,
            updated = 1,
            total = 1,
            addedTitleIds = listOf(20),
            observedTitleIds = listOf(20),
            addedChapterIds = listOf(21),
            observedChapterIds = listOf(21),
            healthyFolders = listOf(healthy),
            unavailableFolders = listOf(unavailable),
            observedTitleIdentities = listOf(currentTitle),
            observedChapterIdentities = listOf(
                localLibraryIdentity(LocalLibraryEntityKind.Chapter, DbItemType.Manga, "USB/Current/book.epub#0"),
            ),
        )
        val operation = LocalLibraryReconciliationOperation(
            scan = scan,
            existingTitles = listOf(
                LocalLibraryReconciliationEntry(1, oldTitle),
                LocalLibraryReconciliationEntry(2, duplicateTitle),
                LocalLibraryReconciliationEntry(3, duplicateTitle),
                LocalLibraryReconciliationEntry(4, renamedFolder),
                LocalLibraryReconciliationEntry(5, localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "Offline/Kept")),
            ),
            existingChapters = listOf(
                LocalLibraryReconciliationEntry(10, oldChapter),
                LocalLibraryReconciliationEntry(11, duplicateChapter),
                LocalLibraryReconciliationEntry(12, duplicateChapter),
            ),
        )

        val result = reconcileLocalLibrary(operation)

        assertEquals(listOf(20L), result.addedTitleIds)
        assertEquals(listOf(20L), result.observedTitleIds)
        assertEquals("Old/book.epub#0", oldChapter.relativePath)
        assertEquals(listOf(1L), result.staleTitleCandidates.map { it.id })
        assertEquals(listOf(10L), result.staleChapterCandidates.map { it.id })
        assertEquals(listOf(2L, 3L), result.duplicateTitleGroups.single().ids)
        assertEquals(listOf(11L, 12L), result.duplicateChapterGroups.single().ids)
        assertEquals(listOf(unavailable), result.unavailableFolders)
        assertTrue(result.staleTitleCandidates.none { it.id == 4L || it.id == 5L })

        // The operation/result are transportable and contain no delete command.
        val roundTrip = Json.decodeFromString<LocalLibraryReconciliationOperation>(Json.encodeToString(operation))
        assertEquals(result, reconcileLocalLibrary(roundTrip))
    }

    @Test
    fun remountKeepsVirtualIdentityAndSecondScanIsIdempotent() = runTest {
        val files = FixtureFiles(
            roots = setOf("/downloads/local", "/old"),
            entries = mapOf(
                "/old" to listOf(LocalEntry("/old/Title", "Title", false)),
                "/old/Title" to listOf(LocalEntry("/old/Title/book.epub", "book", true)),
            ),
        )
        val database = InMemoryYokanDatabase(
            seedDatabaseSnapshot().copy(
                settings = seedDatabaseSnapshot().settings.copy(
                    namedLocalFolders = listOf(DbLocalFolder("USB", "/old")),
                ),
            ),
        )
        val service = DefaultLocalLibraryService(database, files, EmptyArchives)

        val first = service.scan()
        files.roots = setOf("/downloads/local", "/new")
        files.entries = mapOf(
            "/new" to listOf(LocalEntry("/new/Title", "Title", false)),
            "/new/Title" to listOf(LocalEntry("/new/Title/book.epub", "book", true)),
        )
        database.updateSettings(database.settings().copy(namedLocalFolders = listOf(DbLocalFolder("USB", "/new"))))
        val second = service.scan()

        assertEquals(first.observedTitleIds, second.observedTitleIds)
        assertEquals(1, first.observedChapterIds.size)
        assertEquals(first.observedChapterIds, second.observedChapterIds)
        assertEquals("Title/book.epub#0", first.observedChapterIdentities.single().relativePath)
        assertEquals(first.observedChapterIdentities, second.observedChapterIdentities)
        assertEquals(emptyList(), second.addedTitleIds)
        assertEquals("USB/Title", database.mangas().single { it.isLocalArchive }.link)
        assertTrue(files.deleteCalls == 0)
    }

    @Test
    fun oneScanRefreshesExistingLocalRowsWithoutReplacingTheirIds() = runTest {
        val folder = DbLocalFolder("USB", "/mounted")
        val title = eu.friedcutlet.yokan.database.DbManga(
            id = 90,
            name = "Old title",
            link = "USB/Title",
            source = "local",
            isLocalArchive = true,
            favorite = true,
            lastRead = 4,
        )
        val chapter = eu.friedcutlet.yokan.database.DbChapter(
            id = 91,
            mangaId = title.id,
            name = "Old chapter",
            url = "USB/Title/book.cbz",
            archivePath = "USB/Title/book.cbz",
        )
        val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
            settings = seedDatabaseSnapshot().settings.copy(namedLocalFolders = listOf(folder)),
            mangas = listOf(title),
            chapters = listOf(chapter),
        ))
        val files = FixtureFiles(
            roots = setOf("/downloads/local", "/mounted"),
            entries = mapOf(
                "/mounted" to listOf(LocalEntry("/mounted/Title", "Fresh title", false)),
                "/mounted/Title" to listOf(LocalEntry("/mounted/Title/book.cbz", "Fresh chapter", true)),
            ),
        )

        val result = DefaultLocalLibraryService(database, files, EmptyArchives).scan()

        assertEquals(0, result.added)
        assertEquals(1, result.updated)
        assertEquals(listOf(title.id), result.observedTitleIds)
        assertEquals(listOf(chapter.id), result.observedChapterIds)
        assertEquals(title.id, database.mangas().single().id)
        assertEquals("Fresh title", database.mangas().single().name)
        assertTrue(database.mangas().single().favorite)
        assertEquals(4, database.mangas().single().lastRead)
        assertEquals(chapter.id, database.chapters().single().id)
        assertEquals("Fresh chapter", database.chapters().single().name)
    }

    @Test
    fun colorizerStagingIsIgnoredUntilPublishedAndPublishedCbzIsIdempotent() = runTest {
        val stagingPath = "/downloads/local/.colorizer-abc123.partial"
        val files = FixtureFiles(
            roots = setOf("/downloads/local"),
            entries = mapOf(
                "/downloads/local" to listOf(
                    LocalEntry("$stagingPath/cover.jpg", "cover", true),
                    LocalEntry("$stagingPath/chapter.cbz", "chapter", true),
                ),
            ),
        )
        val database = InMemoryYokanDatabase()
        val service = DefaultLocalLibraryService(database, files, EmptyArchives)

        val stagingScan = service.scan()

        assertEquals(0, stagingScan.total)
        assertTrue(database.mangas().isEmpty())
        assertTrue(database.chapters().isEmpty())

        files.entries = mapOf(
            "/downloads/local" to listOf(LocalEntry("/downloads/local/Final", "Final", false)),
            "/downloads/local/Final" to listOf(
                LocalEntry("/downloads/local/Final/cover.jpg", "cover", true),
                LocalEntry("/downloads/local/Final/chapter.cbz", "chapter", true),
            ),
        )
        val publishedScan = service.scan()
        val repeatedScan = service.scan()

        assertEquals(1, publishedScan.added)
        assertEquals(1, publishedScan.total)
        assertEquals(1, database.mangas().size)
        assertEquals(1, database.chapters().size)
        assertEquals("chapter.cbz", database.chapters().single().url.substringAfterLast('/'))
        assertEquals(emptyList(), repeatedScan.addedTitleIds)
        assertEquals(publishedScan.observedTitleIds, repeatedScan.observedTitleIds)
        assertEquals(publishedScan.observedChapterIds, repeatedScan.observedChapterIds)
    }

    @Test
    fun unchangedScanReusesReadsAndFreshScanBypassesFingerprints() = runTest {
        val root = "/downloads/local"
        val title = "$root/Title"
        val metadata = "$title/metadata.json"
        val cover = "$title/cover.jpg"
        val files = FixtureFiles(setOf(root), mapOf(root to listOf(LocalEntry(title, "Title", false)),
            title to listOf(LocalEntry("$title/01.cbz", "01", true))))
        files.contents[metadata] = """{"name":"Original"}""".encodeToByteArray()
        files.contents[cover] = byteArrayOf(1, 2, 3)
        val database = InMemoryYokanDatabase()
        val service = DefaultLocalLibraryService(database, files, EmptyArchives)
        service.scan()
        val before = database.snapshot()
        val reads = files.readCalls
        files.listCalls.clear()
        service.scan()
        assertEquals(reads, files.readCalls)
        assertEquals(1, files.listCalls[title])
        kotlin.test.assertSame(before.mangas, database.snapshot().mangas)
        kotlin.test.assertSame(before.chapters, database.snapshot().chapters)

        files.contents[metadata] = """{"name":"Modified"}""".encodeToByteArray()
        files.modified++
        service.scan()
        assertEquals("Modified", database.mangas().single().name)
        val afterRead = files.readCalls
        service.scanFresh()
        assertTrue(files.readCalls > afterRead)
    }

    private class FixtureFiles(
        var roots: Set<String>,
        var entries: Map<String, List<LocalEntry>>,
    ) : LocalFileService {
        var deleteCalls = 0
        var readCalls = 0
        var modified = 1L
        val contents = mutableMapOf<String, ByteArray>()
        val listCalls = mutableMapOf<String, Int>()
        override val downloadRoot = "/downloads"
        override val backupRoot = "/backups"
        override val cacheRoot = "/cache"
        override fun writeBytes(path: String, bytes: ByteArray) = Unit
        override fun readBytes(path: String): ByteArray { readCalls++; return contents[path] ?: ByteArray(0) }
        override fun canonicalPath(path: String): String? = path
        override fun exists(path: String): Boolean = path in roots || entries.keys.any { path.startsWith("$it/") }
        override fun deleteRecursively(path: String): Boolean {
            deleteCalls++
            return true
        }
        override fun directorySize(path: String): Long = 0
        override fun openLocation(path: String): Boolean = false
        override fun listLocalEntries(root: String): List<LocalEntry>? { listCalls[root] = (listCalls[root] ?: 0) + 1; return entries[root] }
        override fun listFiles(root: String): List<LocalFileEntry> = contents.filterKeys { it.substringBeforeLast('/') == root }
            .map { (path, bytes) -> LocalFileEntry(path, path.substringAfterLast('/'), bytes.size.toLong(), modified) }
    }

    private object EmptyArchives : LocalArchiveService {
        override fun listPages(archivePath: String) = emptyList<eu.friedcutlet.yokan.database.DbPageUrl>()
        override fun listEpubChapters(archivePath: String) = listOf(LocalEpubChapter("Chapter", "chapter.xhtml"))
        override fun readEpubChapter(archivePath: String, index: Int) = ""
        override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? = null
        override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean) = null
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalMediaImporterTest.kt

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

The implementation below defines LocalMediaImporterTest, readChunks, Input, ImportFiles, writeBytes, appendBytes, readBytes, canonicalPath, exists, deleteRecursively and 5 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • copiesAreHiddenUntilCompleteAndPublicationPreservesConcurrentSettings
  • cancellationAndChangedSourcesRemoveOnlyUnpublishedCopies
  • readyJournalSurvivesSaveFailureAndRecoveryIsIdempotent
  • recoveryRejectsMissingFilesAndNeverDeletesCompletedContent
  • incompleteRecoveryCannotDeleteConfiguredRootsOrEscapeItsProfile
  • unsafeOrConflictingNamesAreRejectedBeforeAnySourceRead
  • repeatedNamesGetUniqueFoldersAndNoExistingMediaIsOverwritten
  • progressCoalescesBurstsButAlwaysReportsTheCompletedByteAndFileCount
  • redirectedImportRootsCannotWriteOrDeleteOriginalFiles
  • recoveringAnAlreadyPublishedReadyCopyKeepsItsOriginalFolderName
  • redirectionDuringCopyStopsNewWritesAndNeverAuthorizesCleanup

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.files.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.runTest
import kotlin.test.*
import eu.friedcutlet.yokan.services.files.effectiveLocalLibraryFolders

class LocalMediaImporterTest {
    @Test fun copiesAreHiddenUntilCompleteAndPublicationPreservesConcurrentSettings() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val started = CompletableDeferred<Unit>()
        val resume = CompletableDeferred<Unit>()
        val source = Input("Show/Episode 1.mp4", byteArrayOf(1, 2)) {
            started.complete(Unit); resume.await()
        }
        val importer = LocalMediaImporter(files, settings, newId = { "one" })
        val work = async { importer.import(LocalMediaSelection(listOf(source, Input("Show/metadata.json", "{}".encodeToByteArray()))), DbItemType.Anime) }
        started.await()
        assertTrue(settings.db.value.configuredLocalFolders().isEmpty())
        assertTrue(effectiveLocalLibraryFolders(settings.db.value, files).none { "local-imports" in it.path })
        settings.updateDb { it.copy(themeIsDark = true) }
        resume.complete(Unit)
        val folder = work.await()
        assertEquals("Show", folder.name)
        assertEquals("/downloads/local-imports/one/anime", folder.path)
        assertContentEquals(byteArrayOf(1, 2), files.bytes["${folder.path}/Show/Episode 1.mp4"])
        assertTrue(settings.db.value.themeIsDark)
        assertEquals(listOf(folder), settings.db.value.configuredLocalFolders())
        assertTrue(importer.pending().isEmpty())
        assertTrue(files.maxChunk <= LOCAL_IMPORT_CHUNK_BYTES)
    }

    @Test fun cancellationAndChangedSourcesRemoveOnlyUnpublishedCopies() = runTest {
        val files = ImportFiles().apply { bytes["/source/original.mp4"] = byteArrayOf(7) }
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val importer = LocalMediaImporter(files, settings, newId = { "cancel" })
        val source = Input("clip.mp4", byteArrayOf(1)) { throw CancellationException("Cancelled") }
        assertFailsWith<CancellationException> { importer.import(LocalMediaSelection(listOf(source)), DbItemType.Anime) }
        assertEquals(setOf("/source/original.mp4"), files.bytes.keys)
        val changed = Input("clip.mp4", byteArrayOf(1), announcedSize = 2)
        assertFailsWith<IllegalStateException> { importer.import(LocalMediaSelection(listOf(changed)), DbItemType.Anime) }
        assertEquals(setOf("/source/original.mp4"), files.bytes.keys)
        assertTrue(settings.db.value.configuredLocalFolders().isEmpty())
    }

    @Test fun readyJournalSurvivesSaveFailureAndRecoveryIsIdempotent() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val importer = LocalMediaImporter(files, settings, persistSettings = { error("Disk save failed") }, newId = { "ready" })
        assertFailsWith<IllegalStateException> { importer.import(LocalMediaSelection(listOf(Input("book.epub", byteArrayOf(8)))), DbItemType.Novel) }
        val journal = importer.pending().single()
        assertEquals(LocalImportPhase.Ready, journal.phase)
        assertFailsWith<IllegalArgumentException> { importer.discardIncomplete(journal.id) }
        val content = settings.db.value.configuredLocalFolders().single().path
        assertContentEquals(byteArrayOf(8), files.bytes["$content/book.epub"])
        // Simulate restart before the settings write reached disk.
        settings.updateDb { it.copy(namedLocalFolders = emptyList()) }
        val reopened = LocalMediaImporter(files, settings)
        val recovered = reopened.recover(journal.id)
        assertEquals(content, recovered.path)
        assertEquals(1, settings.db.value.configuredLocalFolders().size)
        assertTrue(reopened.pending().isEmpty())
    }

    @Test fun recoveryRejectsMissingFilesAndNeverDeletesCompletedContent() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val importer = LocalMediaImporter(files, settings, persistSettings = { error("Save failed") }, newId = { "changed" })
        assertFails { importer.import(LocalMediaSelection(listOf(Input("chapter.cbz", byteArrayOf(1)))), DbItemType.Manga) }
        files.bytes.remove("/downloads/local-imports/changed/manga/chapter.cbz")
        assertFailsWith<IllegalStateException> { LocalMediaImporter(files, settings).recover("changed") }
        assertEquals(LocalImportPhase.Ready, importer.pending().single().phase)
    }

    @Test fun incompleteRecoveryCannotDeleteConfiguredRootsOrEscapeItsProfile() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val journal = PendingLocalImport("partial", "Title", DbItemType.Manga)
        files.writeBytes("/downloads/local-imports/partial.json", DatabaseJson.encodeToString(journal).encodeToByteArray())
        files.writeBytes("/downloads/local-imports/partial/manga/title.cbz", byteArrayOf(1))
        // Malformed or mismatched journals never authorize deletion.
        files.writeBytes("/downloads/local-imports/evil.json", DatabaseJson.encodeToString(journal.copy(id = "../outside")).encodeToByteArray())
        val importer = LocalMediaImporter(files, settings)
        assertEquals(listOf(journal), importer.pending())
        settings.updateDb { it.copy(namedLocalFolders = listOf(DbLocalFolder("Owned", "/downloads/local-imports/partial/manga"))) }
        assertFailsWith<IllegalArgumentException> { importer.discardIncomplete("partial") }
        assertTrue(files.exists("/downloads/local-imports/partial/manga/title.cbz"))
        settings.updateDb { it.copy(namedLocalFolders = emptyList()) }
        importer.discardIncomplete("partial")
        assertFalse(files.exists("/downloads/local-imports/partial"))
        assertTrue(files.exists("/downloads/local-imports/evil.json"))
    }

    @Test fun unsafeOrConflictingNamesAreRejectedBeforeAnySourceRead() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        for (names in listOf(listOf("../title.mp4"), listOf("/title.mp4"), listOf("folder\\title.mp4"),
            listOf("Title.mp4", "title.mp4"), listOf("title.mp4", "title.mp4/child.mp4"))) {
            val inputs = names.map { Input(it, byteArrayOf(1)) { error("Must not read") } }
            assertFailsWith<IllegalArgumentException> { LocalMediaImporter(files, settings).import(LocalMediaSelection(inputs), DbItemType.Anime) }
            assertTrue(files.bytes.isEmpty())
        }
    }

    @Test fun repeatedNamesGetUniqueFoldersAndNoExistingMediaIsOverwritten() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        for (id in listOf("first", "second")) LocalMediaImporter(files, settings, newId = { id }).import(
            LocalMediaSelection(listOf(Input("book.epub", byteArrayOf(id.length.toByte())))), DbItemType.Novel)
        val folders = settings.db.value.configuredLocalFolders()
        assertEquals(2, folders.map { it.name }.toSet().size)
        assertEquals(2, folders.map { it.path }.toSet().size)
        assertContentEquals(byteArrayOf(5), files.bytes["${folders[0].path}/book.epub"])
        assertContentEquals(byteArrayOf(6), files.bytes["${folders[1].path}/book.epub"])
    }

    @Test fun progressCoalescesBurstsButAlwaysReportsTheCompletedByteAndFileCount() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val updates = mutableListOf<LocalImportProgress>()
        val source = object : LocalMediaInput {
            override val relativePath = "clip.mp4"
            override val sizeBytes = 1000L
            override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { repeat(1000) { consume(byteArrayOf(1)) } }
        }
        LocalMediaImporter(files, settings, progressClockMillis = { 0 }).import(LocalMediaSelection(listOf(source)), DbItemType.Anime, updates::add)
        assertEquals(listOf(LocalImportProgress(0, 1, 0), LocalImportProgress(1, 1, 1000)), updates)
    }

    @Test fun redirectedImportRootsCannotWriteOrDeleteOriginalFiles() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val importer = LocalMediaImporter(files, settings, newId = { "redirected" })
        files.resolveCanonical = { path -> if (path.startsWith("/downloads/local-imports")) path.replace("/downloads/local-imports", "/originals") else path }
        assertFailsWith<IllegalArgumentException> { importer.import(LocalMediaSelection(listOf(Input("chapter.cbz", byteArrayOf(1)))), DbItemType.Manga) }
        assertTrue(files.bytes.isEmpty())
        files.resolveCanonical = { it }
        val journal = PendingLocalImport("redirected", "Title", DbItemType.Manga)
        files.writeBytes("/downloads/local-imports/redirected.json", DatabaseJson.encodeToString(journal).encodeToByteArray())
        files.writeBytes("/downloads/local-imports/redirected/manga/chapter.cbz", byteArrayOf(1))
        files.resolveCanonical = { path -> if (path.startsWith("/downloads/local-imports/redirected/")) path.replace("/downloads/local-imports/redirected", "/originals")
            else if (path == "/downloads/local-imports/redirected") "/originals" else path }
        assertFailsWith<IllegalArgumentException> { importer.discardIncomplete("redirected") }
        assertContentEquals(byteArrayOf(1), files.bytes["/downloads/local-imports/redirected/manga/chapter.cbz"])
    }

    @Test fun recoveringAnAlreadyPublishedReadyCopyKeepsItsOriginalFolderName() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val importer = LocalMediaImporter(files, settings, persistSettings = { error("Save failed") })
        assertFails { importer.import(LocalMediaSelection(listOf(Input("book.epub", byteArrayOf(1)))), DbItemType.Novel) }
        val before = settings.db.value.configuredLocalFolders().single()
        val pending = importer.pending().single()
        assertEquals(before, LocalMediaImporter(files, settings).recover(pending.id))
        assertEquals(listOf(before), settings.db.value.configuredLocalFolders())
    }

    @Test fun redirectionDuringCopyStopsNewWritesAndNeverAuthorizesCleanup() = runTest {
        val files = ImportFiles()
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val first = Input("first.mp4", byteArrayOf(1)) {
            files.resolveCanonical = { path -> if (path.startsWith("/downloads/local-imports")) path.replace("/downloads/local-imports", "/originals") else path }
        }
        val second = Input("second.mp4", byteArrayOf(2)) { error("Must not read after redirection") }
        assertFailsWith<IllegalArgumentException> {
            LocalMediaImporter(files, settings, newId = { "moving" }).import(LocalMediaSelection(listOf(first, second)), DbItemType.Anime)
        }
        assertTrue(files.exists("/downloads/local-imports/moving.json"))
        assertTrue(files.exists("/downloads/local-imports/moving/anime/first.mp4"))
        assertFalse(files.exists("/downloads/local-imports/moving/anime/second.mp4"))
        assertTrue(settings.db.value.configuredLocalFolders().isEmpty())
    }
}

private class Input(
    override val relativePath: String,
    private val bytes: ByteArray,
    override val sizeBytes: Long? = bytes.size.toLong(),
    private val beforeRead: suspend () -> Unit = {},
) : LocalMediaInput {
    constructor(path: String, bytes: ByteArray, announcedSize: Long) : this(path, bytes, announcedSize, {})
    override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { beforeRead(); consume(bytes) }
}

private class ImportFiles : LocalFileService {
    override val downloadRoot = "/downloads"
    override val backupRoot = "/backups"
    override val cacheRoot = "/cache"
    val bytes = mutableMapOf<String, ByteArray>()
    var resolveCanonical: (String) -> String? = { it }
    var maxChunk = 0
    override fun writeBytes(path: String, bytes: ByteArray) { this.bytes[path] = bytes.copyOf() }
    override fun appendBytes(path: String, bytes: ByteArray) { maxChunk = maxOf(maxChunk, bytes.size); this.bytes[path] = this.bytes[path].orEmptyBytes() + bytes }
    override fun readBytes(path: String): ByteArray = bytes[path] ?: error("Missing file")
    override fun canonicalPath(path: String) = resolveCanonical(path)
    override fun exists(path: String) = bytes.keys.any { it == path || it.startsWith("$path/") }
    override fun deleteRecursively(path: String): Boolean { bytes.keys.filter { it == path || it.startsWith("$path/") }.forEach(bytes::remove); return true }
    override fun directorySize(path: String) = bytes.filterKeys { it == path || it.startsWith("$path/") }.values.sumOf { it.size.toLong() }
    override fun openLocation(path: String) = false
    override fun listLocalEntries(root: String): List<LocalEntry>? = emptyList()
    override fun listFiles(root: String) = bytes.filterKeys { it.substringBeforeLast('/') == root }.map { (path, data) -> LocalFileEntry(path, path.substringAfterLast('/'), data.size.toLong(), 1) }
    private fun ByteArray?.orEmptyBytes() = this ?: ByteArray(0)
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalMetadataReviewStateTest.kt

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

The implementation below defines LocalMetadataReviewStateTest, novelCandidatesDoNotUseBinaryTrackerSearch.

Read the setup, action and assertions in these cases before implementing their production paths:

  • novelCandidatesDoNotUseBinaryTrackerSearch

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.domain.ItemType
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class LocalMetadataReviewStateTest {
    @Test
    fun novelCandidatesDoNotUseBinaryTrackerSearch() {
        assertFalse(localTrackerSearchSupported(ItemType.Novel))
        assertTrue(localTrackerSearchSupported(ItemType.Manga))
        assertTrue(localTrackerSearchSupported(ItemType.Anime))
    }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/library/LocalVideoArtworkTest.kt

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

The implementation below defines LocalVideoArtworkTest, Fixture, frameFor, artwork, cacheFiles, title, episode, LockingLibrary, withOperationLock, scan and 18 further declarations.

The source describes its contract as:

A small in-memory filesystem with the immediate-child listing semantics of the native services.

Read the setup, action and assertions in these cases before implementing their production paths:

  • framesAreDecodedOnceAndCachedByPathSizeAndModificationTime
  • runsAreBoundedAndTheNextRunContinues
  • failedEmptyAndOversizedFramesStoreNothingAndAreNotRetriedThisSession
  • existingCoversPreviewsAndNonLocalTitlesAreNeverTouched
  • editsAndScansDuringDecodingWin
  • cancellationLeavesNoPartialCacheFileAndARetrySucceeds
  • seasonsParentUsesItsFirstSeasonFrame

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.files.*
import eu.friedcutlet.yokan.services.media.VideoFrameExtractor
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlin.test.*

@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class LocalVideoArtworkTest {
    @Test fun framesAreDecodedOnceAndCachedByPathSizeAndModificationTime() = runTest {
        val f = Fixture()
        val title = f.title()
        val first = f.episode(title, "Episode 1.mkv", 1.0)
        val second = f.episode(title, "Episode 2.mp4", 2.0)
        assertTrue(f.artwork().generate())
        assertEquals(listOf("file:///anime/Show/Episode 1.mkv", "file:///anime/Show/Episode 2.mp4"), f.decoded)
        assertEquals(setOf(LocalVideoArtwork.MaxFrameDimension), f.dimensions.toSet())
        assertContentEquals(f.frameFor("file:///anime/Show/Episode 1.mkv"), f.db.manga(title.id)?.customCoverImage)
        val thumbnails = listOf(first, second).map { assertNotNull(f.db.chapter(it.id)?.thumbnailUrl) }
        assertTrue(thumbnails.all { it.startsWith("file:///downloads/.yokan-artwork/") && it.endsWith(".jpg") })
        assertContentEquals(f.frameFor("file:///anime/Show/Episode 2.mp4"), f.files.data.getValue(thumbnails[1].removePrefix("file://")))

        // A cleared and rescanned library reuses the cache instead of decoding again, even in a new session.
        f.db.upsertManga(f.db.manga(title.id)!!.copy(customCoverImage = null))
        listOf(first, second).forEach { f.db.upsertChapter(f.db.chapter(it.id)!!.copy(thumbnailUrl = null)) }
        f.artwork().generate()
        assertEquals(2, f.decoded.size)
        assertEquals(thumbnails, listOf(first, second).map { f.db.chapter(it.id)?.thumbnailUrl })
        assertNotNull(f.db.manga(title.id)?.customCoverImage)

        // A replaced file is a different cache entry.
        f.files.modified["/anime/Show/Episode 2.mp4"] = 99L
        f.db.upsertChapter(f.db.chapter(second.id)!!.copy(thumbnailUrl = null))
        f.artwork().generate()
        assertEquals(3, f.decoded.size)
        assertNotEquals(thumbnails[1], f.db.chapter(second.id)?.thumbnailUrl)
    }

    @Test fun runsAreBoundedAndTheNextRunContinues() = runTest {
        val f = Fixture()
        val title = f.title(imageUrl = "https://cover")
        val episodes = (1..5).map { f.episode(title, "Episode $it.mp4", it.toDouble()) }
        val artwork = f.artwork(maxDecodes = 2)
        artwork.generate()
        assertEquals(2, f.decoded.size)
        artwork.generate()
        artwork.generate()
        assertEquals(5, f.decoded.size)
        assertTrue(episodes.all { f.db.chapter(it.id)?.thumbnailUrl != null })
        assertEquals("https://cover", f.db.manga(title.id)?.imageUrl)
        assertNull(f.db.manga(title.id)?.customCoverImage)
    }

    @Test fun failedEmptyAndOversizedFramesStoreNothingAndAreNotRetriedThisSession() = runTest {
        val f = Fixture()
        val title = f.title()
        val episodes = listOf("Broken.mp4", "Empty.mp4", "Huge.mp4").mapIndexed { index, name -> f.episode(title, name, index + 1.0) }
        f.extract = { url ->
            when {
                "Broken" in url -> error("decoder failed")
                "Empty" in url -> null
                else -> ByteArray(LocalVideoArtwork.MaxFrameBytes + 1)
            }
        }
        val artwork = f.artwork()
        artwork.generate()
        artwork.generate()
        assertEquals(3, f.decoded.size)
        assertTrue(f.cacheFiles().isEmpty())
        assertTrue(episodes.all { f.db.chapter(it.id)?.thumbnailUrl == null })
        assertNull(f.db.manga(title.id)?.customCoverImage)
    }

    @Test fun existingCoversPreviewsAndNonLocalTitlesAreNeverTouched() = runTest {
        val f = Fixture()
        val picked = f.title(name = "Picked", cover = byteArrayOf(7))
        val metadata = f.title(name = "Metadata", imageUrl = "file:///anime/Metadata/poster.png")
        val tracker = f.title(name = "Tracker", trackerCover = "https://tracker")
        listOf(picked, metadata, tracker).forEach { f.episode(it, "Episode 1.mp4", 1.0, thumbnail = "file:///sidecar.png") }
        val remote = f.db.upsertManga(DbManga(name = "Remote", itemType = DbItemType.Anime, source = "Some source"))
        f.episode(remote, "Episode 1.mp4", 1.0)
        val manga = f.db.upsertManga(DbManga(name = "Comic", itemType = DbItemType.Manga, isLocalArchive = true, source = "local"))
        f.episode(manga, "Episode 1.mp4", 1.0)
        val missingPreview = f.episode(picked, "Episode 2.mp4", 2.0)
        f.artwork().generate()
        assertEquals(listOf("file:///anime/Picked/Episode 2.mp4"), f.decoded)
        assertNotNull(f.db.chapter(missingPreview.id)?.thumbnailUrl)
        assertContentEquals(byteArrayOf(7), f.db.manga(picked.id)?.customCoverImage)
        assertNull(f.db.manga(metadata.id)?.customCoverImage)
        assertNull(f.db.manga(tracker.id)?.customCoverImage)
        assertNull(f.db.manga(remote.id)?.customCoverImage)
        assertTrue(f.db.chapters().filter { it.id != missingPreview.id && it.mangaId in setOf(picked.id, metadata.id, tracker.id) }
            .all { it.thumbnailUrl == "file:///sidecar.png" })
        assertTrue(f.db.chapters().filter { it.mangaId in setOf(remote.id, manga.id) }.all { it.thumbnailUrl == null })
    }

    @Test fun editsAndScansDuringDecodingWin() = runTest {
        val f = Fixture()
        val title = f.title()
        val episode = f.episode(title, "Episode 1.mp4", 1.0)
        val entered = CompletableDeferred<Unit>()
        val release = CompletableDeferred<Unit>()
        f.extract = { url -> entered.complete(Unit); release.await(); f.frameFor(url) }
        val artwork = f.artwork()
        val run = async { artwork.generate() }
        entered.await()
        assertFalse(artwork.generate(), "a second run must not start while one is decoding")
        // The user picks a cover; a scan holding the library lock adds a sidecar preview.
        f.db.upsertManga(f.db.manga(title.id)!!.copy(customCoverImage = byteArrayOf(1)))
        f.library.lock.lock()
        release.complete(Unit)
        runCurrent()
        assertNull(f.db.chapter(episode.id)?.thumbnailUrl, "artwork must wait for the running scan")
        f.db.upsertChapter(f.db.chapter(episode.id)!!.copy(thumbnailUrl = "file:///anime/Show/preview.png"))
        f.library.lock.unlock()
        assertTrue(run.await())
        assertContentEquals(byteArrayOf(1), f.db.manga(title.id)?.customCoverImage)
        assertEquals("file:///anime/Show/preview.png", f.db.chapter(episode.id)?.thumbnailUrl)
    }

    @Test fun cancellationLeavesNoPartialCacheFileAndARetrySucceeds() = runTest {
        val f = Fixture()
        val title = f.title()
        val episode = f.episode(title, "Episode 1.mp4", 1.0)
        val decoding = CompletableDeferred<Unit>()
        f.extract = { decoding.complete(Unit); CompletableDeferred<Unit>().await(); null }
        val duringDecode = async { f.artwork().generate() }
        decoding.await()
        duringDecode.cancelAndJoin()
        assertTrue(f.cacheFiles().isEmpty())

        val written = CompletableDeferred<Unit>()
        f.extract = { url -> f.frameFor(url) }
        f.files.afterWrite = { path -> if (path.endsWith(".part")) { written.complete(Unit); CompletableDeferred<Unit>().await() } }
        val duringWrite = async { f.artwork().generate() }
        written.await()
        duringWrite.cancelAndJoin()
        assertTrue(f.cacheFiles().isEmpty(), "a partially written frame must be removed: ${f.cacheFiles()}")
        assertNull(f.db.chapter(episode.id)?.thumbnailUrl)
        assertNull(f.db.manga(title.id)?.customCoverImage)

        f.files.afterWrite = {}
        f.artwork().generate()
        assertEquals(1, f.cacheFiles().size)
        assertNotNull(f.db.chapter(episode.id)?.thumbnailUrl)
        assertNotNull(f.db.manga(title.id)?.customCoverImage)
    }

    @Test fun seasonsParentUsesItsFirstSeasonFrame() = runTest {
        val f = Fixture()
        val parent = f.title(name = "Show")
        val season = f.db.upsertManga(f.db.manga(f.title(name = "Show/Season 1").id)!!.copy(parentId = parent.id))
        f.episode(season, "Episode 1.mp4", 1.0)
        f.artwork().generate()
        assertEquals(1, f.decoded.size)
        val frame = f.frameFor("file:///anime/Show/Season 1/Episode 1.mp4")
        assertContentEquals(frame, f.db.manga(parent.id)?.customCoverImage)
        assertContentEquals(frame, f.db.manga(season.id)?.customCoverImage)
    }

    private class Fixture {
        val files = MemoryVideoFiles()
        val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", "/anime")))))
        val library = LockingLibrary()
        val decoded = mutableListOf<String>()
        val dimensions = mutableListOf<Int>()
        var extract: suspend (String) -> ByteArray? = { frameFor(it) }
        fun frameFor(url: String) = "frame:$url".encodeToByteArray()
        fun artwork(maxDecodes: Int = 12) = LocalVideoArtwork(db, files, library, VideoFrameExtractor { url, maxDimension ->
            decoded += url
            dimensions += maxDimension
            extract(url)
        }, maxDecodes)
        fun cacheFiles() = files.data.keys.filter { it.startsWith("/downloads/.yokan-artwork/") }
        fun title(name: String = "Show", cover: ByteArray? = null, imageUrl: String? = null, trackerCover: String? = null) = db.upsertManga(DbManga(
            name = name, link = "Anime/$name", itemType = DbItemType.Anime, isLocalArchive = true, source = "local",
            customCoverImage = cover, imageUrl = imageUrl, customCoverFromTracker = trackerCover,
        ))
        fun episode(title: DbManga, file: String, number: Double, thumbnail: String? = null): DbChapter {
            files.put("/anime/${title.name}/$file")
            return db.upsertChapter(DbChapter(
                mangaId = title.id, name = file, url = "Anime/${title.name}/$file", archivePath = "Anime/${title.name}/$file",
                number = number, thumbnailUrl = thumbnail,
            ))
        }
    }

    private class LockingLibrary : LocalLibraryService {
        val lock = Mutex()
        override suspend fun <T> withOperationLock(block: suspend () -> T): T = lock.withLock { block() }
        override suspend fun scan(): LocalLibraryScanResult = error("Not scanned here")
        override suspend fun reconcile(): LocalLibraryReconciliationResult = error("Not reconciled here")
        override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? = null
    }
}

/** A small in-memory filesystem with the immediate-child listing semantics of the native services. */
internal class MemoryVideoFiles : LocalFileService {
    override val downloadRoot = "/downloads"
    override val backupRoot = "/backups"
    override val cacheRoot = "/cache"
    val data = linkedMapOf<String, ByteArray>()
    val modified = mutableMapOf<String, Long>()
    var afterWrite: suspend (String) -> Unit = {}

    fun put(path: String, bytes: ByteArray = byteArrayOf(1)) { data[path] = bytes }
    private fun children(root: String): List<String> = data.keys.mapNotNull { path ->
        path.removePrefix("$root/").takeIf { path.startsWith("$root/") }?.substringBefore('/')?.let { "$root/$it" }
    }.distinct().sorted()
    private fun isFile(path: String) = path in data
    private fun isReadable(path: String) = path.substringAfterLast('.').lowercase() in readableLocalFileExtensions

    override fun writeBytes(path: String, bytes: ByteArray) { data[path] = bytes }
    override suspend fun writeBytesAsync(path: String, bytes: ByteArray) { writeBytes(path, bytes); afterWrite(path) }
    override fun readBytes(path: String): ByteArray = data[path] ?: error("Missing $path")
    override fun canonicalPath(path: String) = path
    override fun exists(path: String) = path in data || data.keys.any { it.startsWith("$path/") }
    override fun deleteRecursively(path: String): Boolean { data.keys.removeAll { it == path || it.startsWith("$path/") }; return true }
    override fun directorySize(path: String) = 0L
    override fun openLocation(path: String) = false
    override fun listLocalEntries(root: String): List<LocalEntry>? {
        if (!exists(root)) return null
        return children(root).flatMap { child ->
            when {
                isFile(child) -> if (isReadable(child)) listOf(LocalEntry(child, child.substringAfterLast('/').substringBeforeLast('.'), true)) else emptyList()
                children(child).any { isFile(it) && isReadable(it) } -> listOf(LocalEntry(child, child.substringAfterLast('/'), false))
                else -> listLocalEntries(child).orEmpty()
            }
        }
    }
    override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? =
        if (!exists(root) || isFile(root)) null else children(root).map { LocalDirectoryEntry(it, it.substringAfterLast('/'), !isFile(it)) }
    override fun listFiles(root: String) = children(root).filter(::isFile)
        .map { LocalFileEntry(it, it.substringAfterLast('/'), data.getValue(it).size.toLong(), modified[it] ?: 1L) }
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalLibraryViewModelTest.kt

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

The implementation below defines LocalLibraryViewModelTest, tearDown, viewModel, cancellingImportReleasesItsSelectionAndClearsBusyStateWithoutReportingFailure, readChunks, profileRetirementCancelsImportAndReleasesThePickerSelection, bridgeFailuresAreShownAndDoNotLeaveImportBusy, metadataOnlyEditsRefreshBothScreensAndScanStatusReusesTitles, overviewListsLocalTitlesWithoutTorrentsAndFollowsDatabaseChanges, reopeningReviewStartsWithNoPreviousSearchOrSelection and 10 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • cancellingImportReleasesItsSelectionAndClearsBusyStateWithoutReportingFailure
  • profileRetirementCancelsImportAndReleasesThePickerSelection
  • bridgeFailuresAreShownAndDoNotLeaveImportBusy
  • metadataOnlyEditsRefreshBothScreensAndScanStatusReusesTitles
  • overviewListsLocalTitlesWithoutTorrentsAndFollowsDatabaseChanges
  • reopeningReviewStartsWithNoPreviousSearchOrSelection
  • applyingMetadataWritesOnlySelectedFieldsAndClosesTheReview

Cross-chapter imports used by this file: ViewModelTestHost, DefaultYokanRepository, LibraryIndexStore, SettingsStore, DbItemType, DbManga. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.ui.screens.local

import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbTitleMetadata
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.files.NoFiles
import eu.friedcutlet.yokan.services.files.LocalMediaInput
import eu.friedcutlet.yokan.services.files.LocalMediaSelection
import eu.friedcutlet.yokan.services.files.pickLocalMedia
import eu.friedcutlet.yokan.services.library.DefaultLocalEntryManagementService
import eu.friedcutlet.yokan.services.library.LocalLibraryController
import eu.friedcutlet.yokan.services.library.LocalLibraryReconciliationResult
import eu.friedcutlet.yokan.services.library.LocalLibraryScanResult
import eu.friedcutlet.yokan.services.library.LocalLibraryService
import eu.friedcutlet.yokan.services.metadata.LocalMetadataField
import eu.friedcutlet.yokan.services.metadata.MetadataLibraryEntry
import eu.friedcutlet.yokan.services.metadata.MetadataMedia
import eu.friedcutlet.yokan.services.metadata.MetadataService
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest

@OptIn(ExperimentalCoroutinesApi::class)
class LocalLibraryViewModelTest {
    private val database = InMemoryYokanDatabase(
        seedDatabaseSnapshot().copy(
            mangas = listOf(
                DbManga(id = 1, name = "Local", link = "/local/a", source = "local", itemType = DbItemType.Manga, isLocalArchive = true),
                DbManga(id = 2, name = "Torrent", link = "magnet:x", source = "torrent", itemType = DbItemType.Manga, isLocalArchive = true),
                DbManga(id = 3, name = "Remote", link = "/remote", source = "Remote", itemType = DbItemType.Manga),
            ),
        ),
    )
    private val repository = DefaultYokanRepository(database)
    private val candidate = MetadataMedia(
        id = "m1",
        source = "Metadata server",
        mediaType = DbItemType.Manga,
        title = "Better title",
        description = "Found description",
    )
    private val host = ViewModelTestHost()
    private val dispatcher = host.dispatcher
    private var browseModel: LocalLibraryBrowseViewModel? = null

    @AfterTest
    fun tearDown() = host.close()

    private fun viewModel(
        scope: CoroutineScope,
        includeBrowse: Boolean = false,
        mediaPicker: suspend (Boolean) -> LocalMediaSelection? = ::pickLocalMedia,
        importScope: CoroutineScope = scope,
    ): LocalLibraryViewModel {
        val settings = SettingsStore(repository, scope, onSchedulingChanged = {})
        val controller = LocalLibraryController(
            localLibrary = NoScanLibrary,
            entryManagement = DefaultLocalEntryManagementService(database, NoScanLibrary),
            repository = repository,
            metadata = SingleCandidateMetadata(candidate),
            trackers = emptyList(),
            files = NoFiles,
            settings = settings,
            importScope = importScope,
        )
        val index = LibraryIndexStore(repository, scope)
        if (includeBrowse) browseModel = host.create { LocalLibraryBrowseViewModel(controller, dispatcher) }
        return host.create { LocalLibraryViewModel(controller, settings, index, workDispatcher = dispatcher, mediaPicker = mediaPicker) }
    }

    @Test
    fun cancellingImportReleasesItsSelectionAndClearsBusyStateWithoutReportingFailure() = runTest {
        val started = CompletableDeferred<Unit>()
        val closed = CompletableDeferred<Unit>()
        val source = object : LocalMediaInput {
            override val relativePath = "clip.mp4"
            override val sizeBytes = 1L
            override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { started.complete(Unit); awaitCancellation() }
        }
        val vm = viewModel(backgroundScope, mediaPicker = { LocalMediaSelection(listOf(source)) { closed.complete(Unit) } })
        vm.onEvent(LocalLibraryEvent.ImportMedia(ItemType.Anime, directory = false))
        started.await()
        vm.onEvent(LocalLibraryEvent.CancelImport)
        closed.await()
        val state = vm.state.first { !it.importBusy }
        kotlin.test.assertFalse(state.importFailed)
        kotlin.test.assertFalse(state.importCompleted)
        assertNull(state.importProgress)
    }

    @Test
    fun profileRetirementCancelsImportAndReleasesThePickerSelection() = runTest {
        val owner = CoroutineScope(SupervisorJob() + dispatcher)
        val started = CompletableDeferred<Unit>()
        val closed = CompletableDeferred<Unit>()
        val source = object : LocalMediaInput {
            override val relativePath = "clip.mp4"
            override val sizeBytes = 1L
            override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) { started.complete(Unit); awaitCancellation() }
        }
        val vm = viewModel(backgroundScope, mediaPicker = { LocalMediaSelection(listOf(source)) { closed.complete(Unit) } }, importScope = owner)
        try {
            vm.onEvent(LocalLibraryEvent.ImportMedia(ItemType.Anime, directory = false))
            started.await()
            owner.cancel()
            closed.await()
            kotlin.test.assertFalse(vm.state.first { !it.importBusy }.importFailed)
        } finally { owner.cancel() }
    }

    @Test
    fun bridgeFailuresAreShownAndDoNotLeaveImportBusy() = runTest {
        // JavaScript bridge failures need not derive from kotlin.Exception.
        val vm = viewModel(backgroundScope, mediaPicker = { throw Throwable("Storage provider failed") })
        vm.onEvent(LocalLibraryEvent.ImportMedia(ItemType.Anime, directory = false))
        val state = vm.state.first { it.importFailed && !it.importBusy }
        assertEquals("Storage provider failed", state.importError)
        assertNull(state.importProgress)
    }

    @Test
    fun metadataOnlyEditsRefreshBothScreensAndScanStatusReusesTitles() = runTest {
        database.upsertManga(checkNotNull(database.manga(1)).copy(description = "Description"))
        val vm = viewModel(backgroundScope, includeBrowse = true)
        val browse = checkNotNull(browseModel)
        val initial = vm.state.first { it.titlesByType.isNotEmpty() }
        browse.state.first { it.titlesByType.isNotEmpty() }
        val mangas = database.snapshots().value.mangas

        database.updateSettings(database.settings().copy(titleMetadata = listOf(DbTitleMetadata(1, metadataServerId = "linked"))))
        val updated = vm.state.first { it.reviewQueue.isEmpty() }
        val browsed = browse.state.first { it.titlesByType[ItemType.Manga]?.first()?.metadataServerId == "linked" }
        assertSame(mangas, database.snapshots().value.mangas)
        assertEquals(listOf(1L), initial.reviewQueue.map { it.id })
        assertEquals("linked", updated.titlesByType.getValue(ItemType.Manga).single().metadataServerId)
        assertSame(updated.titlesByType.getValue(ItemType.Manga).single(), browsed.titlesByType.getValue(ItemType.Manga).first())

        database.updateSettings(database.settings().copy(themeIsDark = !database.settings().themeIsDark))
        vm.onEvent(LocalLibraryEvent.Rescan)
        val scanned = vm.state.first { it.overview.lastScan != null && !it.overview.scanRunning }
        assertSame(updated.titlesByType, scanned.titlesByType)
        assertSame(browsed.titlesByType, browse.state.value.titlesByType)
    }

    @Test
    fun overviewListsLocalTitlesWithoutTorrentsAndFollowsDatabaseChanges() = runTest {
        val vm = viewModel(backgroundScope)

        val initial = vm.state.first { it.titlesByType.isNotEmpty() }
        assertEquals(listOf(1L), initial.titlesByType.getValue(ItemType.Manga).map { it.id })
        assertEquals(1, initial.overview.manga)
        assertEquals(listOf(1L), initial.reviewQueue.map { it.id })

        database.upsertManga(DbManga(id = 4, name = "Clip", link = "/local/b", source = "local", itemType = DbItemType.Anime, isLocalArchive = true))

        val updated = vm.state.first { it.overview.anime == 1 }
        assertEquals(listOf(4L), updated.titlesByType.getValue(ItemType.Anime).map { it.id })
        assertEquals(setOf(1L, 4L), updated.reviewQueue.map { it.id }.toSet())
    }

    @Test
    fun reopeningReviewStartsWithNoPreviousSearchOrSelection() = runTest {
        val vm = viewModel(backgroundScope)
        val manga = checkNotNull(repository.manga(1))

        vm.onEvent(LocalLibraryEvent.OpenMetadataReview(manga))
        vm.onEvent(LocalLibraryEvent.SearchMetadataCandidates)
        vm.state.first { it.metadataReview?.candidates == listOf(candidate) }
        vm.onEvent(LocalLibraryEvent.SelectCandidate(candidate))
        vm.onEvent(LocalLibraryEvent.SetFieldSelected(LocalMetadataField.Description, true))
        vm.onEvent(LocalLibraryEvent.DismissMetadataReview)
        vm.onEvent(LocalLibraryEvent.OpenMetadataReview(manga))

        assertEquals(LocalMetadataReviewState(manga), vm.state.value.metadataReview)
    }

    @Test
    fun applyingMetadataWritesOnlySelectedFieldsAndClosesTheReview() = runTest {
        val vm = viewModel(backgroundScope)

        vm.onEvent(LocalLibraryEvent.OpenMetadataReview(checkNotNull(repository.manga(1))))
        vm.onEvent(LocalLibraryEvent.SearchMetadataCandidates)
        vm.state.first { it.metadataReview?.candidates?.isNotEmpty() == true }
        vm.onEvent(LocalLibraryEvent.SelectCandidate(candidate))
        vm.onEvent(LocalLibraryEvent.SetFieldSelected(LocalMetadataField.Title, true))
        vm.onEvent(LocalLibraryEvent.SetFieldSelected(LocalMetadataField.Description, true))
        vm.onEvent(LocalLibraryEvent.SetFieldSelected(LocalMetadataField.Title, false))
        vm.onEvent(LocalLibraryEvent.ApplyMetadata)

        val saved = checkNotNull(repository.manga(1))
        assertEquals("Local", saved.name)
        assertEquals("Found description", saved.description)
        assertNull(vm.state.value.metadataReview)
    }
}

private object NoScanLibrary : LocalLibraryService {
    override suspend fun scan() = LocalLibraryScanResult(0, 0, 0)
    override suspend fun reconcile() = LocalLibraryReconciliationResult()
    override suspend fun importTorrent(pathOrMagnet: String, displayName: String?): Long? = null
}

private class SingleCandidateMetadata(private val candidate: MetadataMedia) : MetadataService {
    override suspend fun health(baseUrl: String) = true
    override suspend fun search(baseUrl: String, query: String, itemType: DbItemType, limit: Int) = listOf(candidate)
    override suspend fun library(baseUrl: String, token: String, itemType: DbItemType): List<Pair<MetadataLibraryEntry, MetadataMedia>> = emptyList()
    override suspend fun upsertLibraryEntry(
        baseUrl: String,
        token: String,
        mediaId: String,
        status: String,
        progress: Int,
        score: Int?,
        isFavorite: Boolean,
    ) = false
}

Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/local/LocalMetadataSearchStateTest.kt

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

The implementation below defines LocalMetadataSearchStateTest, emptyResultsAfterSearchOfferRetryInsteadOfClosing.

Read the setup, action and assertions in these cases before implementing their production paths:

  • emptyResultsAfterSearchOfferRetryInsteadOfClosing
package eu.friedcutlet.yokan.ui.screens.local

import kotlin.test.Test
import kotlin.test.assertEquals

class LocalMetadataSearchStateTest {
    @Test
    fun emptyResultsAfterSearchOfferRetryInsteadOfClosing() {
        assertEquals("Find candidates", metadataSearchActionLabel(false, false, false))
        assertEquals("Retry search", metadataSearchActionLabel(true, false, false))
        assertEquals("Cancel", metadataSearchActionLabel(true, false, true))
        assertEquals("Searching…", metadataSearchActionLabel(true, true, false))
    }
}

Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/library/LocalEntryManagementRoomTest.kt

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

The implementation below defines LocalEntryManagementRoomTest, appliedMergeSurvivesRoomCloseAndReopen, openRoom, FixedEvidenceLibrary, scan, reconcile, importTorrent.

Read the setup, action and assertions in these cases before implementing their production paths:

  • appliedMergeSurvivesRoomCloseAndReopen

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

package eu.friedcutlet.yokan.services.library

import androidx.room.Room
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.room.RoomYokanDatabase
import eu.friedcutlet.yokan.database.room.YokanRoomDatabase
import eu.friedcutlet.yokan.database.room.roomPersistenceDispatcher
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import java.nio.file.Files
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest

class LocalEntryManagementRoomTest {
    @Test
    fun appliedMergeSurvivesRoomCloseAndReopen() = runTest {
        val directory = Files.createTempDirectory("yokan-room-test")
        val databasePath = directory.resolve("yokan.db").toString()
        try {
            val firstRoom = openRoom(databasePath)
            val first = DbManga(
                id = 100,
                name = "Canonical",
                link = "USB/Same",
                source = "local",
                isLocalArchive = true,
                lastRead = 1,
            )
            val duplicate = first.copy(id = 101, name = "Duplicate", favorite = true, lastRead = 8)
            val evidence = LocalLibraryReconciliationResult(
                duplicateTitleGroups = listOf(
                    LocalLibraryDuplicateGroup(
                        localLibraryIdentity(LocalLibraryEntityKind.Title, DbItemType.Manga, "USB/Same"),
                        listOf(first.id, duplicate.id),
                    ),
                ),
            )
            val initial = seedDatabaseSnapshot().copy(mangas = listOf(first, duplicate))
            val database = RoomYokanDatabase(firstRoom, legacySnapshotProvider = { initial })
            val service = DefaultLocalEntryManagementService(database, FixedEvidenceLibrary(evidence))

            val result = service.apply(
                service.preview(
                    LocalEntryManagementOperation.MergeDuplicateTitles(evidence, listOf(first.id, duplicate.id)),
                ).command,
            )

            assertEquals(LocalEntryManagementApplyStatus.Applied, result.status)
            firstRoom.close()

            val reopenedRoom = openRoom(databasePath)
            try {
                val reopened = RoomYokanDatabase(reopenedRoom)
                assertEquals(listOf(first.id), reopened.mangas().map { it.id })
                assertTrue(reopened.mangas().single().favorite)
                assertEquals(8, reopened.mangas().single().lastRead)
            } finally {
                reopenedRoom.close()
            }
        } finally {
            directory.toFile().deleteRecursively()
        }
    }

    private fun openRoom(path: String): YokanRoomDatabase =
        Room.databaseBuilder<YokanRoomDatabase>(name = path)
            .setDriver(BundledSQLiteDriver())
            .setQueryCoroutineContext(roomPersistenceDispatcher)
            .build()

    private class FixedEvidenceLibrary(
        private val result: LocalLibraryReconciliationResult,
    ) : LocalLibraryService {
        override suspend fun scan() = LocalLibraryScanResult(0, 0, 0)
        override suspend fun reconcile() = result
        override suspend fun importTorrent(pathOrMagnet: String, displayName: String?) = null
    }
}

Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryImportVisibilityTest.kt

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

The implementation below defines LocalLibraryImportVisibilityTest, readChunks.

Read the setup, action and assertions in these cases before implementing their production paths:

  • aConfiguredParentCannotExposePartialImportsOrDuplicatePublishedTitles

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.files.*
import java.io.File
import java.nio.file.Files
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class LocalLibraryImportVisibilityTest {
    @Test fun aConfiguredParentCannotExposePartialImportsOrDuplicatePublishedTitles() = runTest {
        val root = Files.createTempDirectory("yokan-import-visibility").toFile()
        try {
            val downloads = File(root, "downloads").apply { mkdirs() }
            val files = JvmLocalFileService(downloads.path, File(root, "backups").path, File(root, "cache").path)
            val db = InMemoryYokanDatabase(emptySnapshot())
            val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
            settings.updateDb { it.copy(namedLocalFolders = listOf(DbLocalFolder("Everything", downloads.path))) }
            val scanner = DefaultLocalLibraryService(db, files, JvmLocalArchiveService(files.cacheRoot))
            val started = CompletableDeferred<Unit>()
            val resume = CompletableDeferred<Unit>()
            val input = object : LocalMediaInput {
                override val relativePath = "Show/Episode 1.mp4"
                override val sizeBytes = 1L
                override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) {
                    started.complete(Unit); resume.await(); consume(byteArrayOf(1))
                }
            }
            val work = async { LocalMediaImporter(files, settings).import(LocalMediaSelection(listOf(input)), DbItemType.Anime) }
            started.await()
            assertEquals(0, scanner.scan().total)
            assertTrue(db.mangas().isEmpty())
            resume.complete(Unit)
            work.await()
            assertEquals(1, scanner.scan().total)
            val title = db.mangas().single()
            assertEquals(DbItemType.Anime, title.itemType)
            assertEquals(1, db.chapters(title.id).size)
            assertEquals(0, scanner.scan().added)
            assertEquals(listOf(title.id), db.mangas().map { it.id })
        } finally { root.deleteRecursively() }
    }
}

Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/library/LocalLibraryNestedAnimeTest.kt

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

The implementation below defines LocalLibraryNestedAnimeTest, put.

Read the setup, action and assertions in these cases before implementing their production paths:

  • rootAndSeasonVideosKeepFileIdentitiesAndUseTheirOwnSidecars
  • immediateListingDoesNotFollowSymlinksOrFlattenEmptyDirectories
package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.files.*
import java.io.File
import java.nio.file.Files
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class LocalLibraryNestedAnimeTest {
    @Test fun rootAndSeasonVideosKeepFileIdentitiesAndUseTheirOwnSidecars() = runTest {
        val temp = Files.createTempDirectory("yokan-nested-anime").toFile()
        try {
            val root = File(temp, "anime").apply { mkdirs() }
            fun put(path: String, text: String = "video") = File(root, "Show/$path").apply { parentFile.mkdirs(); writeText(text) }
            put("Episode 3.mp4")
            put("Season 0/Episode 1.mkv")
            put("Season 1/Episode 1.mp4")
            put("Season 1/Episode 2.mp4")
            put("Season 1/deeper/Episode 99.mp4")
            put(".hidden/Episode 50.mp4")
            put("Season 1/.Episode 51.mp4")
            put("Season 1/preview.png")
            put("episodes.json", """[{"episode_number":3,"name":"Finale"}]""")
            put("Season 0/episodes.json", """[{"episode_number":1,"name":"Special"}]""")
            put("Season 1/episodes.json", """[{"episode_number":1,"name":"Premiere","preview_url":"art/preview.png"}]""")
            put("Season 1/art/preview.png")
            val files = JvmLocalFileService(temp.path, File(temp, "backup").path, File(temp, "cache").path)
            val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root.path)))))
            val scanner = DefaultLocalLibraryService(db, files, JvmLocalArchiveService(files.cacheRoot))
            scanner.scan()
            val title = db.mangas().single()
            val episodes = db.chapters(title.id)
            assertEquals(4, episodes.size)
            assertEquals(setOf("Finale", "Special", "Premiere", "Episode 2"), episodes.map { it.name }.toSet())
            assertEquals(0, episodes.single { it.name == "Special" }.season)
            val premiere = episodes.single { it.name == "Premiere" }
            assertEquals(1, premiere.season)
            assertEquals(1.0, premiere.number)
            assertEquals("Episode 1", premiere.numberingName)
            assertTrue(assertNotNull(premiere.thumbnailUrl).endsWith("/Season 1/art/preview.png"))
            assertTrue(episodes.all { it.archivePath.endsWith(".mp4") || it.archivePath.endsWith(".mkv") })
            db.upsertChapter(premiere.copy(isRead = true, isBookmarked = true, lastPageRead = "2345"))
            scanner.scanFresh()
            assertEquals(episodes.map { it.id }.toSet(), db.chapters(title.id).map { it.id }.toSet())
            assertEquals("2345", db.chapter(premiere.id)?.lastPageRead)
            assertTrue(db.chapter(premiere.id)?.isRead == true)
        } finally { temp.deleteRecursively() }
    }

    @Test fun immediateListingDoesNotFollowSymlinksOrFlattenEmptyDirectories() {
        val temp = Files.createTempDirectory("yokan-immediate-list").toFile()
        try {
            File(temp, "empty").mkdirs()
            File(temp, "one.mp4").writeText("video")
            Files.createSymbolicLink(File(temp, "linked").toPath(), File(temp, "empty").toPath())
            val files = JvmLocalFileService(temp.path, temp.path, temp.path)
            assertEquals(setOf("empty", "one.mp4"), assertNotNull(files.listDirectoryEntries(temp.path)).map { it.name }.toSet())
            assertEquals(emptyList(), files.listDirectoryEntries(File(temp, "empty").path))
            assertNull(files.listDirectoryEntries(File(temp, "missing").path))
        } finally { temp.deleteRecursively() }
    }
}

Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/library/LocalSeasonRecordsTest.kt

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

The implementation below defines LocalSeasonRecordsTest, put.

Read the setup, action and assertions in these cases before implementing their production paths:

  • foldersWithoutEpisodeFilesBecomeSeasonTitlesAndKeepEarlierProgressAndLibraryMembership

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

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.services.files.*
import java.io.File
import java.nio.file.Files
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class LocalSeasonRecordsTest {
    @Test fun foldersWithoutEpisodeFilesBecomeSeasonTitlesAndKeepEarlierProgressAndLibraryMembership() = runTest {
        val temp = Files.createTempDirectory("yokan-local-seasons").toFile()
        try {
            val root = File(temp, "anime").apply { mkdirs() }
            fun put(path: String) = File(root, path).apply { parentFile.mkdirs(); writeText("video") }
            put("Show/cover.jpg")
            put("Show/Season 1/Episode 1.mp4")
            put("Show/Season 2/Episode 1.mp4")
            put("Show/Season 2/Extras/Bonus.mp4")
            put("Show/.hidden/Episode 9.mp4")
            put("Group/S1/Episode 1.mp4")
            put("Flat/Episode 1.mp4")
            put("Flat/Season 2/Episode 2.mp4")
            // State left by the previous scanner: a cover made `Show` one flattened title, and `Group`'s
            // only season was a separate library title.
            val db = InMemoryYokanDatabase(emptySnapshot().copy(
                settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root.path))),
                mangas = listOf(
                    DbManga(id = 1, name = "Show", link = "Anime/Show", itemType = DbItemType.Anime, source = "local", isLocalArchive = true, favorite = true),
                    DbManga(id = 2, name = "S1", link = "Anime/Group/S1", itemType = DbItemType.Anime, source = "local", isLocalArchive = true,
                        favorite = true, categories = listOf(5)),
                ),
                chapters = listOf(DbChapter(id = 10, mangaId = 1, name = "Episode 1", url = "Anime/Show/Season 1/Episode 1.mp4",
                    archivePath = "Anime/Show/Season 1/Episode 1.mp4", isRead = true, lastPageRead = "77", isBookmarked = true)),
                histories = listOf(DbHistory(id = 20, mangaId = 1, chapterId = 10, itemType = DbItemType.Anime, date = "1")),
            ))
            val files = JvmLocalFileService(temp.path, File(temp, "backup").path, File(temp, "cache").path)
            val scanner = DefaultLocalLibraryService(db, files, JvmLocalArchiveService(files.cacheRoot))
            scanner.scan()

            val show = assertNotNull(db.manga(1))
            assertEquals(DbFetchType.Seasons, show.fetchType)
            assertNull(show.parentId)
            assertTrue(db.chapters(1).isEmpty())
            val seasons = db.mangas().filter { it.parentId == 1L }.sortedBy { it.seasonNumber }
            assertEquals(listOf("Season 1", "Season 2"), seasons.map { it.name })
            assertEquals(listOf(1.0, 2.0), seasons.map { it.seasonNumber })
            assertTrue(seasons.all { it.fetchType == DbFetchType.Episodes && !it.favorite })
            val moved = assertNotNull(db.chapter(10))
            assertEquals(seasons[0].id, moved.mangaId)
            assertEquals("77", moved.lastPageRead)
            assertTrue(moved.isRead && moved.isBookmarked)
            assertEquals(seasons[0].id, db.histories().single().mangaId)
            assertEquals(setOf("Episode 1", "Bonus"), db.chapters(seasons[1].id).map { it.name }.toSet())

            val group = db.mangas().single { it.link == "Anime/Group" }
            assertEquals(DbFetchType.Seasons, group.fetchType)
            assertTrue(group.favorite)
            assertEquals(listOf(5L), group.categories)
            assertEquals(group.id, db.manga(2)?.parentId)

            val flat = db.mangas().single { it.link == "Anime/Flat" }
            assertEquals(DbFetchType.Episodes, flat.fetchType)
            assertEquals(2, db.chapters(flat.id).size)

            assertEquals(setOf(1L, group.id), DefaultYokanRepository(db).library(ItemType.Anime).map { it.id }.toSet())
            assertTrue(db.mangas().none { it.name == ".hidden" })

            // Removing the show from the library later is not undone by the next scan.
            db.upsertManga(db.manga(group.id)!!.copy(favorite = false))
            val before = db.mangas().map { it.id }.toSet()
            scanner.scanFresh()
            assertEquals(before, db.mangas().map { it.id }.toSet())
            assertFalse(db.manga(group.id)!!.favorite)
            assertEquals(10L, db.chapters(seasons[0].id).single().id)
            assertEquals(2, DefaultYokanRepository(db).cleanDatabase().let { db.mangas().count { m -> m.parentId == 1L } })
        } finally { temp.deleteRecursively() }
    }
}

Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/library/LocalVideoDesktopTest.kt

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

The implementation below defines LocalVideoDesktopTest, Library, playableUrls, withLibrary, assumeLibmpv, assertRedJpeg.

The source describes its contract as:

Real files, the real scanner, the player's resolution path and (when installed or bundled) real libmpv.

Read the setup, action and assertions in these cases before implementing their production paths:

  • scannedLocalVideosResolveToTheirFilesAndPlayInTheMpvController
  • libmpvExtractsBoundedRedJpegFramesFromMkvAndMp4
  • artworkRunGivesTheTitleACoverAndEpisodesThumbnailsFromRealFrames

Cross-chapter imports used by this file: ProfileId, DefaultYokanRepository, Chapter, ChapterPageResolver, ProfileReaderContent, ProfileReaderContentTest. Keep those contracts available as you connect this step.

package eu.friedcutlet.yokan.services.library

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest
import eu.friedcutlet.yokan.services.files.JvmLocalArchiveService
import eu.friedcutlet.yokan.services.files.JvmLocalFileService
import eu.friedcutlet.yokan.services.media.MpvVideoFrameExtractor
import eu.friedcutlet.yokan.services.media.player.MediaPlayerConfiguration
import eu.friedcutlet.yokan.services.media.player.MpvMediaPlayerController
import eu.friedcutlet.yokan.services.media.player.NoopMediaStreamProxy
import eu.friedcutlet.yokan.services.media.player.createMpvMediaPlayerController
import io.github.kmpmpv.MpvPlayer
import java.io.ByteArrayInputStream
import java.io.File
import java.nio.file.Files
import javax.imageio.ImageIO
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.Assume.assumeTrue
import kotlin.test.*

/** Real files, the real scanner, the player's resolution path and (when installed or bundled) real libmpv. */
class LocalVideoDesktopTest {
    @Test fun scannedLocalVideosResolveToTheirFilesAndPlayInTheMpvController() = runBlocking {
        withLibrary { library ->
            val urls = library.playableUrls()
            assertEquals(library.expectedUrls.toSet(), urls.toSet())
            assumeLibmpv()
            urls.forEach { url ->
                val controller = createMpvMediaPlayerController(
                    MediaPlayerConfiguration(useMpvConfig = false, hwdecMode = "no"),
                    NoopMediaStreamProxy,
                    mapOf("vo" to "libmpv", "ao" to "null"),
                ) as MpvMediaPlayerController
                try {
                    controller.withSoftwareRendering { renderer ->
                        // Like the desktop surface: the render context exists before the file loads.
                        renderer.renderFrame(1, 1)
                        controller.load(url)
                        withTimeout(20_000) { while (controller.durationMs() <= 0L) delay(20) }
                        assertTrue(controller.durationMs() in 800L..1200L, "duration of $url: ${controller.durationMs()}")
                        val deadline = System.currentTimeMillis() + 10_000
                        var red = false
                        while (!red && System.currentTimeMillis() < deadline) {
                            val frame = renderer.renderFrame(16, 12)
                            val center = 6 * frame.strideBytes + 8 * 4
                            val (b, g, r) = Triple(frame.pixels[center].toInt() and 0xff, frame.pixels[center + 1].toInt() and 0xff, frame.pixels[center + 2].toInt() and 0xff)
                            red = r > 200 && g < 60 && b < 60
                            if (!red) delay(50)
                        }
                        assertTrue(red, "the decoded red frame of $url was never rendered")
                    }
                } finally { controller.releaseAndJoin() }
            }
        }
    }

    @Test fun libmpvExtractsBoundedRedJpegFramesFromMkvAndMp4() = runBlocking {
        withLibrary { library ->
            assumeLibmpv()
            val extractor = MpvVideoFrameExtractor()
            library.expectedUrls.forEach { url ->
                assertRedJpeg(assertNotNull(extractor.extractJpeg(url, 512), url), 64, 48)
                assertRedJpeg(assertNotNull(extractor.extractJpeg(url, 32), url), 32, 24)
            }
            assertNull(extractor.extractJpeg("file://${library.root.path}/missing.mkv", 512))
        }
    }

    @Test fun artworkRunGivesTheTitleACoverAndEpisodesThumbnailsFromRealFrames() = runBlocking {
        withLibrary { library ->
            assumeLibmpv()
            val artwork = LocalVideoArtwork(library.db, library.files, library.scanner, MpvVideoFrameExtractor())
            assertTrue(artwork.generate())
            val title = library.db.mangas().single()
            assertRedJpeg(assertNotNull(title.customCoverImage), 64, 48)
            library.db.chapters(title.id).forEach { episode ->
                val thumbnail = assertNotNull(episode.thumbnailUrl).removePrefix("file://")
                assertTrue(thumbnail.startsWith(File(library.files.downloadRoot, ".yokan-artwork").path), thumbnail)
                assertRedJpeg(File(thumbnail).readBytes(), 64, 48)
            }
            // A rescan keeps the frame artwork and a new run reuses the cache.
            library.scanner.scan()
            val cached = File(library.files.downloadRoot, ".yokan-artwork").listFiles().orEmpty().map { it.name to it.lastModified() }
            assertTrue(LocalVideoArtwork(library.db, library.files, library.scanner, { _, _ -> error("must not decode") }).generate())
            assertEquals(cached, File(library.files.downloadRoot, ".yokan-artwork").listFiles().orEmpty().map { it.name to it.lastModified() })
            assertNotNull(library.db.mangas().single().customCoverImage)
        }
    }

    private class Library(val root: File, val files: JvmLocalFileService, val db: InMemoryYokanDatabase, val scanner: DefaultLocalLibraryService) {
        // '%20' in a name: mpv percent-decodes file:// URLs, so the player must hand it the raw path.
        val expectedUrls = listOf("Episode 1.mkv", "Episode 2 100%20.mp4").map { "file://${File(root, "Show/$it").path}" }

        suspend fun playableUrls(): List<String> {
            val factory = ProfileReaderContentTest.RuntimeFactory(db, "local")
            val owner = SupervisorJob()
            val content = ProfileReaderContent(
                ProfileId.Default, db, factory, ChapterPageResolver(DefaultYokanRepository(db), db, factory),
                files, JvmLocalArchiveService(files.cacheRoot), CoroutineScope(owner),
            )
            return try {
                val title = db.mangas().single()
                db.chapters(title.id).sortedBy { it.number }.map { stored ->
                    val episode = Chapter(id = stored.id, mangaId = title.id, name = stored.name.orEmpty(), url = stored.url, archivePath = stored.archivePath)
                    content.videos(null, episode).single().url
                }.also { assertEquals(0, factory.created) }
            } finally { content.closeAndJoin(); owner.cancelAndJoin() }
        }
    }

    private suspend fun withLibrary(block: suspend (Library) -> Unit) {
        val temp = Files.createTempDirectory("yokan-local-video").toFile()
        try {
            val root = File(temp, "anime")
            File(root, "Show").mkdirs()
            File(root, "Show/Episode 1.mkv").writeBytes(RedVideoFixtures.mkv)
            File(root, "Show/Episode 2 100%20.mp4").writeBytes(RedVideoFixtures.mp4)
            val files = JvmLocalFileService(File(temp, "downloads").path, File(temp, "backups").path, File(temp, "cache").path)
            val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root.path)))))
            val scanner = DefaultLocalLibraryService(db, files, JvmLocalArchiveService(files.cacheRoot))
            scanner.scan()
            assertEquals(2, db.chapters(db.mangas().single().id).size)
            block(Library(root, files, db, scanner))
        } finally { temp.deleteRecursively() }
    }

    private suspend fun assumeLibmpv() {
        val probe = runCatching { MpvPlayer.create() }
        assumeTrue("libmpv is neither bundled nor installed on this machine: ${probe.exceptionOrNull()}", probe.isSuccess)
        probe.getOrNull()?.release()
    }

    private fun assertRedJpeg(bytes: ByteArray, width: Int, height: Int) {
        val image = assertNotNull(ImageIO.read(ByteArrayInputStream(bytes)), "not a decodable image")
        assertEquals(width to height, image.width to image.height)
        val pixel = java.awt.Color(image.getRGB(width / 2, height / 2))
        assertTrue(pixel.red > 200 && pixel.green < 60 && pixel.blue < 60, "center pixel $pixel")
    }
}

Write composeApp/src/iosTest/kotlin/eu/friedcutlet/yokan/services/files/IosArchivePagesTest.kt

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

The implementation below defines IosArchivePagesTest, zipsDirectoryAndExtractsCbzPages, extractsTarPages, strictInventoryReextractsReplacedCbzAtSamePath, strictInventoryRejectsMalformedSecondZipDirectoryRecord, strictInventoryRejectsUnderreportedEocdEntryCountAndDirectoryExtent, strictInventoryRejectsTruncatedTarImage, evictsLeastRecentlyUsedExtractedPagesBeyondTheBudget, setModified, extractionOf and 4 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • zipsDirectoryAndExtractsCbzPages
  • extractsTarPages
  • strictInventoryReextractsReplacedCbzAtSamePath
  • strictInventoryRejectsMalformedSecondZipDirectoryRecord
  • strictInventoryRejectsUnderreportedEocdEntryCountAndDirectoryExtent
  • strictInventoryRejectsTruncatedTarImage
  • evictsLeastRecentlyUsedExtractedPagesBeyondTheBudget
package eu.friedcutlet.yokan.services.files

import kotlinx.cinterop.ExperimentalForeignApi
import platform.Foundation.NSDate
import platform.Foundation.NSFileManager
import platform.Foundation.NSFileModificationDate
import platform.Foundation.dateWithTimeIntervalSince1970
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue

class IosArchivePagesTest {
    @Test
    fun zipsDirectoryAndExtractsCbzPages() {
        val files = createPlatformLocalFileService()
        val dir = "${files.cacheRoot}/cbz-src-${Random.nextLong()}"
        val pageA = byteArrayOf(1, 2, 3, 4)
        val pageB = byteArrayOf(9, 8, 7)
        files.writeBytes("$dir/002.png", pageB)
        files.writeBytes("$dir/001.jpg", pageA)
        files.writeBytes("$dir/notes.txt", byteArrayOf(0))
        files.writeBytes("$dir/001.jpg.complete", ByteArray(0))
        files.writeBytes("$dir/$CHAPTER_METADATA_FILE", "{}".encodeToByteArray())
        var cbz: String? = null

        try {
            val archives = createPlatformLocalArchiveService()
            cbz = archives.zipDirectoryToCbz(dir, deleteSource = false)
            assertNotNull(cbz)
            assertTrue(files.exists(cbz))
            assertEquals(setOf("001.jpg", "002.png", CHAPTER_METADATA_FILE), IosZipArchive.openFile(cbz)?.entryNames?.toSet())

            val pages = archives.listPages(cbz)
            assertEquals(listOf("0000_001.jpg", "0001_002.png"), pages.map { it.fileName })
            assertContentEquals(pageA, files.readBytes(pages[0].url))
            assertContentEquals(pageB, files.readBytes(pages[1].url))
        } finally {
            files.deleteRecursively(dir)
            cbz?.let(files::deleteRecursively)
        }
    }

    @Test
    fun extractsTarPages() {
        val files = createPlatformLocalFileService()
        val tarPath = "${files.cacheRoot}/pages-${Random.nextLong()}.cbt"
        val image = byteArrayOf(5, 6, 7, 8, 9)
        files.writeBytes(tarPath, tarWith("p1.png" to image, "skip.txt" to byteArrayOf(1)))

        try {
            val archives = createPlatformLocalArchiveService()
            val pages = archives.listPages(tarPath)
            assertEquals(listOf("0000_p1.png"), pages.map { it.fileName })
            assertContentEquals(image, files.readBytes(pages.single().url))
        } finally {
            files.deleteRecursively(tarPath)
        }
    }

    @Test
    fun strictInventoryReextractsReplacedCbzAtSamePath() {
        val files = createPlatformLocalFileService()
        val archive = "${files.cacheRoot}/strict ${Random.nextLong()} %20 #.cbz"
        try {
            val archives = createPlatformLocalArchiveService()
            files.writeBytes(archive, buildStoredZip(listOf("nested/page%20#one.jpg" to byteArrayOf(1))))
            val first = archives.listPagesStrict(archive).single()
            assertTrue(first.url.contains("%2520%23"), first.url)
            assertContentEquals(byteArrayOf(1), files.readBytes(first.url))
            files.writeBytes(archive, buildStoredZip(listOf("nested/page%20#one.jpg" to byteArrayOf(2))))
            val second = archives.listPagesStrict(archive).single()
            assertContentEquals(byteArrayOf(2), files.readBytes(second.url))
            assertFalse(first.url == second.url)
        } finally {
            files.deleteRecursively(archive)
        }
    }

    @Test
    fun strictInventoryRejectsMalformedSecondZipDirectoryRecord() {
        val files = createPlatformLocalFileService()
        val archive = "${files.cacheRoot}/malformed-${Random.nextLong()}.cbz"
        try {
            val bytes = buildStoredZip(listOf("one.jpg" to byteArrayOf(1), "two.jpg" to byteArrayOf(2)))
            val signature = byteArrayOf(0x50, 0x4b, 0x01, 0x02)
            val first = bytes.indexOfBytes(signature)
            val second = bytes.indexOfBytes(signature, first + signature.size)
            check(first >= 0 && second >= 0)
            bytes[second] = 0
            files.writeBytes(archive, bytes)
            kotlin.test.assertFails { createPlatformLocalArchiveService().listPagesStrict(archive) }
        } finally {
            files.deleteRecursively(archive)
        }
    }

    @Test
    fun strictInventoryRejectsUnderreportedEocdEntryCountAndDirectoryExtent() {
        val files = createPlatformLocalFileService()
        val root = "${files.cacheRoot}/eocd-${Random.nextLong()}"
        val archives = createPlatformLocalArchiveService()
        val entries = listOf("one.jpg" to byteArrayOf(1), "two.jpg" to byteArrayOf(2))
        val original = buildStoredZip(entries)
        val eocd = original.size - 22
        val firstRecordSize = 46 + "one.jpg".encodeToByteArray().size

        try {
            // Tamper total count and central size, leaving the per-disk count unchanged.
            val countMismatch = original.copyOf().apply {
                putLe16(eocd + 10, 1)
                putLe32(eocd + 12, firstRecordSize)
            }
            val countMismatchPath = "$root-count.cbz"
            files.writeBytes(countMismatchPath, countMismatch)
            kotlin.test.assertFails { archives.listPagesStrict(countMismatchPath) }

            // Matching the per-disk count must still fail because the claimed directory no longer reaches EOCD.
            val extentMismatch = original.copyOf().apply {
                putLe16(eocd + 8, 1)
                putLe16(eocd + 10, 1)
                putLe32(eocd + 12, firstRecordSize)
            }
            val extentMismatchPath = "$root-extent.cbz"
            files.writeBytes(extentMismatchPath, extentMismatch)
            kotlin.test.assertFails { archives.listPagesStrict(extentMismatchPath) }

            // A well-formed ZIP comment remains accepted by strict inventory.
            val withComment = original.copyOf(original.size + 4).apply {
                putLe16(eocd + 20, 4)
                "note".encodeToByteArray().copyInto(this, original.size)
            }
            val commentedPath = "$root-comment.cbz"
            files.writeBytes(commentedPath, withComment)
            assertEquals(2, archives.listPagesStrict(commentedPath).size)
        } finally {
            files.deleteRecursively(root)
            files.deleteRecursively("$root-count.cbz")
            files.deleteRecursively("$root-extent.cbz")
            files.deleteRecursively("$root-comment.cbz")
        }
    }

    @Test
    fun strictInventoryRejectsTruncatedTarImage() {
        val files = createPlatformLocalFileService()
        val archive = "${files.cacheRoot}/truncated-${Random.nextLong()}.cbt"
        try {
            val complete = tarWith("page.png" to byteArrayOf(1, 2, 3, 4, 5))
            files.writeBytes(archive, complete.copyOf(512 + 2))
            kotlin.test.assertFails { createPlatformLocalArchiveService().listPagesStrict(archive) }
        } finally {
            files.deleteRecursively(archive)
        }
    }

    @OptIn(ExperimentalForeignApi::class)
    @Test
    fun evictsLeastRecentlyUsedExtractedPagesBeyondTheBudget() {
        val files = createPlatformLocalFileService()
        val root = "${files.cacheRoot}/lru-${Random.nextLong()}"
        val page = ByteArray(1_000) { it.toByte() }
        val comics = listOf("a", "b", "c").associateWith { name ->
            "$root/$name.cbz".also { files.writeBytes(it, buildStoredZip(listOf("001.jpg" to page))) }
        }
        fun setModified(path: String, seconds: Double) {
            NSFileManager.defaultManager.setAttributes(
                mapOf<Any?, Any?>(NSFileModificationDate to NSDate.dateWithTimeIntervalSince1970(seconds)),
                ofItemAtPath = path,
                error = null,
            )
        }

        try {
            // Two chapters' pages fit; the third extraction must evict one.
            val archives = IosLocalArchiveService(extractedPagesBudgetBytes = 2_500)
            fun extractionOf(comic: String) =
                archives.listPages(comics.getValue(comic)).single().url.removePrefix("file://").substringBeforeLast('/')

            val a = extractionOf("a")
            val b = extractionOf("b")
            // Pin the LRU order explicitly: filesystem mtimes can tie within one test.
            setModified(a, 1_000.0)
            setModified(b, 2_000.0)
            assertEquals(a, extractionOf("a")) // cached page list; marks a as used
            val c = extractionOf("c")

            assertTrue(files.exists(a))
            assertFalse(files.exists(b))
            assertTrue(files.exists(c))
            // b's cached page list pointed into the evicted directory, so it extracts again.
            assertContentEquals(page, files.readBytes(archives.listPages(comics.getValue("b")).single().url))
        } finally {
            files.deleteRecursively(root)
        }
    }

    private fun tarWith(vararg entries: Pair<String, ByteArray>): ByteArray {
        val output = mutableListOf<Byte>()
        entries.forEach { (name, data) ->
            val header = ByteArray(512)
            name.encodeToByteArray().copyInto(header)
            val sizeOctal = data.size.toString(8).padStart(11, '0')
            sizeOctal.encodeToByteArray().copyInto(header, 124)
            header[156] = '0'.code.toByte()
            for (index in 148..155) header[index] = ' '.code.toByte()
            val checksum = header.sumOf { it.toInt() and 0xff }.toString(8).padStart(6, '0').encodeToByteArray()
            checksum.copyInto(header, 148)
            header[154] = 0
            header[155] = ' '.code.toByte()
            output += header.toList()
            output += data.toList()
            val padding = (512 - (data.size % 512)) % 512
            repeat(padding) { output += 0 }
        }
        repeat(1024) { output += 0 }
        return output.toByteArray()
    }

    private fun ByteArray.indexOfBytes(needle: ByteArray, start: Int = 0): Int =
        (start until size).firstOrNull { index ->
            index + needle.size <= size && needle.indices.all { this[index + it] == needle[it] }
        } ?: -1

    private fun ByteArray.putLe16(offset: Int, value: Int) {
        this[offset] = value.toByte()
        this[offset + 1] = (value ushr 8).toByte()
    }

    private fun ByteArray.putLe32(offset: Int, value: Int) {
        for (index in 0..3) this[offset + index] = (value ushr (index * 8)).toByte()
    }
}

Write composeApp/src/iosTest/kotlin/eu/friedcutlet/yokan/services/files/IosDocumentTypesTest.kt

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

The implementation below defines IosDocumentTypesTest, restorePickerAllowsEveryRequestedExtension, knownUtisUnionInsteadOfFirstMatch, emptyExtensionsFallBackToData.

Read the setup, action and assertions in these cases before implementing their production paths:

  • restorePickerAllowsEveryRequestedExtension
  • knownUtisUnionInsteadOfFirstMatch
  • emptyExtensionsFallBackToData
package eu.friedcutlet.yokan.services.files

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class IosDocumentTypesTest {
    @Test
    fun restorePickerAllowsEveryRequestedExtension() {
        // The restore flow asks for these; a first-match-wins mapping once
        // collapsed the list to public.json, making .backup unselectable.
        val types = documentTypesFor(setOf("tachibk", "proto", "json", "backup"))
        assertTrue("public.json" in types, types.toString())
        // Every non-json extension must be covered by something beyond json:
        // either a dynamic per-extension UTI or the public.data fallback.
        assertTrue(types.any { it != "public.json" }, types.toString())
    }

    @Test
    fun knownUtisUnionInsteadOfFirstMatch() {
        val types = documentTypesFor(setOf("json", "zip"))
        assertTrue("public.json" in types, types.toString())
        assertTrue("public.zip-archive" in types, types.toString())
    }

    @Test
    fun emptyExtensionsFallBackToData() {
        assertEquals(listOf("public.data"), documentTypesFor(emptySet()))
    }
}

Write composeApp/src/iosTest/kotlin/eu/friedcutlet/yokan/services/files/IosEpubArchiveServiceTest.kt

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

The implementation below defines IosEpubArchiveServiceTest, readsDeflatedChaptersAndEmbeddedResources, rereadsAnArchiveRewrittenAtTheSamePath.

Read the setup, action and assertions in these cases before implementing their production paths:

  • readsDeflatedChaptersAndEmbeddedResources
  • rereadsAnArchiveRewrittenAtTheSamePath
package eu.friedcutlet.yokan.services.files

import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertTrue

@OptIn(ExperimentalEncodingApi::class)
class IosEpubArchiveServiceTest {
    @Test
    fun readsDeflatedChaptersAndEmbeddedResources() {
        val files = createPlatformLocalFileService()
        val path = "${files.cacheRoot}/epub-${Random.nextLong()}.epub"
        files.writeBytes(path, Base64.decode(EPUB_FIXTURE))

        try {
            val archives = createPlatformLocalArchiveService()
            val chapters = archives.listEpubChapters(path)

            assertEquals(1, chapters.size)
            assertEquals("Opening", chapters.single().title)
            assertEquals("OEBPS/Text/ch1.xhtml", chapters.single().href)
            assertTrue(archives.readEpubChapter(path, 0).contains("<p>Hello</p>"))
            assertContentEquals(
                byteArrayOf(137.toByte(), 80, 78, 71, 1, 2, 3, 4),
                archives.readEpubResource(path, "OEBPS/Images/pic.png"),
            )
        } finally {
            files.deleteRecursively(path)
        }
    }

    @Test
    fun rereadsAnArchiveRewrittenAtTheSamePath() {
        val files = createPlatformLocalFileService()
        val path = "${files.cacheRoot}/rewrite-${Random.nextLong()}.epub"

        try {
            val archives = createPlatformLocalArchiveService()
            files.writeBytes(path, buildStoredZip(listOf("text.txt" to "first".encodeToByteArray())))
            assertEquals("first", archives.readEpubResource(path, "text.txt")?.decodeToString())

            files.writeBytes(path, buildStoredZip(listOf("text.txt" to "second edition".encodeToByteArray())))
            assertEquals("second edition", archives.readEpubResource(path, "text.txt")?.decodeToString())
        } finally {
            files.deleteRecursively(path)
        }
    }

    private companion object {
        const val EPUB_FIXTURE =
            "UEsDBBQAAAAIAIx++lziFcbyUwAAAGwAAAAWAAAATUVUQS1JTkYvY29udGFpbmVyLnhtbLOxr8jNUShLLSrOzM+zVTLUM1Cyt7NJzs8rSczMSy2ysynKzy9Jy8xJLUYwFdJKc3J0CxJLMmyV/F2dAoL1QepT80r08gvSlPTtbPSRNOkjzAIAUEsDBBQAAAAIAIx++lzUwMA0ZQAAAJcAAAARAAAAT0VCUFMvY29udGVudC5vcGZNjkEOgCAMBL9ieAANd/Tu3Q8QLNIohAgHnm9RiV67M7vVydjdbDjpYCI5zGXSVDAMtI7CKjH4E90oFqwFrFey+hIOAT8oke3UHLgpA19kiluj4GvNiSI+HsOs3gpPNOwNoX9zAVBLAwQUAAAACACMfvpcnH1m7VUAAABnAAAAFAAAAE9FQlBTL1RleHQvY2gxLnhodG1sJY3JDYAwDMBWQR2gWSDkDS9mKCVKI/WIaD9sD6JPy7KMaZRMmDhchENHZjqMq1ZBmIgw5dmuh9Bo45wbghFqkaXfcXXew16CcAfT6K2Kgy+bAfyDF1BLAwQUAAAACACMfvpcu2N6QgoAAAAIAAAAFAAAAE9FQlBTL0ltYWdlcy9waWMucG5n6wzwc2dkYmYBAFBLAQIUAxQAAAAIAIx++lziFcbyUwAAAGwAAAAWAAAAAAAAAAAAAACAAQAAAABNRVRBLUlORi9jb250YWluZXIueG1sUEsBAhQDFAAAAAgAjH76XNTAwDRlAAAAlwAAABEAAAAAAAAAAAAAAIABhwAAAE9FQlBTL2NvbnRlbnQub3BmUEsBAhQDFAAAAAgAjH76XJx9Zu1VAAAAZwAAABQAAAAAAAAAAAAAAIABGwEAAE9FQlBTL1RleHQvY2gxLnhodG1sUEsBAhQDFAAAAAgAjH76XLtjekIKAAAACAAAABQAAAAAAAAAAAAAAIABogEAAE9FQlBTL0ltYWdlcy9waWMucG5nUEsFBgAAAAAEAAQABwEAAN4BAAAAAA=="
    }
}

Write composeApp/src/iosTest/kotlin/eu/friedcutlet/yokan/services/files/IosLocalFileServiceTest.kt

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

The implementation below defines IosLocalFileServiceTest, writesEmptyFilesWithoutDereferencingMissingStorage, boundedReadOfSmallFileDoesNotAllocateTheLargeAllowance, persistedFolderBookmarkKeepsLogicalPathsForLaterReads, publishesStagedDirectoryAndRefusesExistingDestination.

Read the setup, action and assertions in these cases before implementing their production paths:

  • writesEmptyFilesWithoutDereferencingMissingStorage
  • boundedReadOfSmallFileDoesNotAllocateTheLargeAllowance
  • persistedFolderBookmarkKeepsLogicalPathsForLaterReads
  • publishesStagedDirectoryAndRefusesExistingDestination
package eu.friedcutlet.yokan.services.files

import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import platform.Foundation.NSURL

class IosLocalFileServiceTest {
    @Test
    fun writesEmptyFilesWithoutDereferencingMissingStorage() {
        val files = createPlatformLocalFileService()
        val path = "${files.cacheRoot}/tests/empty-${kotlin.random.Random.nextLong()}.bin"

        try {
            files.writeBytes(path, ByteArray(0))

            assertTrue(files.exists(path))
            assertContentEquals(ByteArray(0), files.readBytes(path))
        } finally {
            files.deleteRecursively(path)
        }
    }

    @Test
    fun boundedReadOfSmallFileDoesNotAllocateTheLargeAllowance() {
        val files = createPlatformLocalFileService()
        val path = "${files.cacheRoot}/tests/bounded-${kotlin.random.Random.nextLong()}.bin"
        val bytes = byteArrayOf(1, 2, 3, 4)
        try {
            files.writeBytes(path, bytes)
            assertContentEquals(bytes, files.readBytesBounded(path, 512L * 1024 * 1024))
        } finally {
            files.deleteRecursively(path)
        }
    }

    @Test
    fun persistedFolderBookmarkKeepsLogicalPathsForLaterReads() {
        val files = createPlatformLocalFileService()
        val root = "${files.cacheRoot}/bookmark-${kotlin.random.Random.nextLong()}"
        val content = byteArrayOf(4, 5, 6)
        files.writeBytes("$root/book.cbz", content)

        try {
            assertEquals(root, IosSecurityScopedBookmarks.persist(NSURL.fileURLWithPath(root)))
            assertTrue(files.exists(root))
            assertEquals("$root/book.cbz", files.listLocalEntries(root)?.single()?.path)
            assertContentEquals(content, files.readBytes("$root/book.cbz"))
        } finally {
            files.deleteRecursively(root)
        }
    }

    @Test
    fun publishesStagedDirectoryAndRefusesExistingDestination() {
        val files = createPlatformLocalFileService()
        val root = "${files.cacheRoot}/publish-${kotlin.random.Random.nextLong()}"
        val staged = "$root/staged"
        val destination = "$root/job"
        val existingStage = "$root/staged-existing"
        val existingDestination = "$root/job-existing"
        files.writeBytes("$staged/page", byteArrayOf(1, 2, 3))
        files.writeBytes("$existingStage/page", byteArrayOf(4, 5, 6))
        files.writeBytes("$existingDestination/keep", byteArrayOf(7))

        try {
            assertTrue(files.publishDirectoryIfAbsent(staged, destination))
            assertFalse(files.exists(staged))
            assertContentEquals(byteArrayOf(1, 2, 3), files.readBytes("$destination/page"))

            assertFalse(files.publishDirectoryIfAbsent(existingStage, existingDestination))
            assertTrue(files.exists("$existingStage/page"))
            assertContentEquals(byteArrayOf(7), files.readBytes("$existingDestination/keep"))
        } finally {
            files.deleteRecursively(root)
        }
    }
}

Write composeApp/src/iosTest/kotlin/eu/friedcutlet/yokan/services/files/IosLocalMediaInputTest.kt

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

The implementation below defines IosLocalMediaInputTest.

Read the setup, action and assertions in these cases before implementing their production paths:

  • minimalBookmarksAndCoordinatedReadsPreserveTheSourceAndBoundChunks
  • cancellationInsideACoordinatedReadStopsBeforeAnotherChunk
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package eu.friedcutlet.yokan.services.files

import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import platform.Foundation.NSFileManager
import platform.Foundation.NSURL
import kotlin.random.Random
import kotlin.test.*

class IosLocalMediaInputTest {
    @Test fun minimalBookmarksAndCoordinatedReadsPreserveTheSourceAndBoundChunks() = runTest {
        val root = "${IosLocalFileService.cacheRoot}/test-import-${Random.nextLong().toULong()}"
        val path = "$root/clip.mp4"
        val bytes = ByteArray(3 * LOCAL_IMPORT_CHUNK_BYTES + 3) { it.toByte() }
        try {
            IosLocalFileService.writeBytes(path, bytes)
            assertContentEquals(bytes, IosLocalFileService.readBytes(path))
            assertEquals(path, IosSecurityScopedBookmarks.persist(NSURL.fileURLWithPath(path)))
            val chunks = mutableListOf<ByteArray>()
            IosLocalMediaInput("clip.mp4", bytes.size.toLong(), path).readChunks { chunks += it }
            assertEquals(listOf(65536, 65536, 65536, 3), chunks.map { it.size })
            assertContentEquals(bytes, chunks.reduce { a, b -> a + b })
            assertContentEquals(bytes, IosLocalFileService.readBytes(path))
        } finally { NSFileManager.defaultManager.removeItemAtPath(root, error = null) }
    }

    @Test fun cancellationInsideACoordinatedReadStopsBeforeAnotherChunk() = runTest {
        val root = "${IosLocalFileService.cacheRoot}/test-import-${Random.nextLong().toULong()}"
        val path = "$root/clip.mp4"
        val bytes = ByteArray(3 * LOCAL_IMPORT_CHUNK_BYTES) { it.toByte() }
        try {
            IosLocalFileService.writeBytes(path, bytes)
            assertContentEquals(bytes, IosLocalFileService.readBytes(path))
            val first = CompletableDeferred<Unit>()
            var chunks = 0
            val work = launch {
                IosLocalMediaInput("clip.mp4", bytes.size.toLong(), path).readChunks {
                    chunks++
                    first.complete(Unit)
                    awaitCancellation()
                }
            }
            first.await()
            work.cancelAndJoin()
            assertEquals(1, chunks)
            assertContentEquals(bytes, IosLocalFileService.readBytes(path))
        } finally { NSFileManager.defaultManager.removeItemAtPath(root, error = null) }
    }
}

Write composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/files/JvmLocalArchiveServiceTest.kt

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

The implementation below defines JvmLocalArchiveServiceTest, standaloneImagesOpenAsOnePageIncludingEncodedFileLocators, detectsArchiveTypesFromNamesAndSafMimeTypes, evictsLeastRecentlyUsedExtractedPagesBeyondTheBudget, extractionOf, chapterCbzKeepsPagesAndMetadataButNotDownloadMarkers, strictInventoryUsesDecodedLocatorsAndNeverReusesReplacedArchivePages, strictInventoryRejectsUndecodableImageWithValidZipCrc, strictInventoryRejectsDecodableImageWithBadZipCrc, cbzOf and 3 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • standaloneImagesOpenAsOnePageIncludingEncodedFileLocators
  • detectsArchiveTypesFromNamesAndSafMimeTypes
  • evictsLeastRecentlyUsedExtractedPagesBeyondTheBudget
  • chapterCbzKeepsPagesAndMetadataButNotDownloadMarkers
  • strictInventoryUsesDecodedLocatorsAndNeverReusesReplacedArchivePages
  • strictInventoryRejectsUndecodableImageWithValidZipCrc
  • strictInventoryRejectsDecodableImageWithBadZipCrc
package eu.friedcutlet.yokan.services.files

import java.io.ByteArrayOutputStream
import java.io.DataOutputStream
import java.io.File
import java.net.URI
import java.nio.file.Files
import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import java.util.zip.ZipOutputStream
import java.util.zip.CRC32
import java.util.zip.DeflaterOutputStream
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class JvmLocalArchiveServiceTest {
    @Test
    fun standaloneImagesOpenAsOnePageIncludingEncodedFileLocators() {
        val root = Files.createTempDirectory("yokan image % pages").toFile()
        try {
            val image = File(root, "page space.png").apply { writeBytes(png(0x22)) }
            val service = JvmLocalArchiveService(File(root, "cache").path)
            val page = service.listPages(image.toURI().toString()).single()
            assertEquals(image.name, page.fileName)
            assertContentEquals(image.readBytes(), File(URI(page.url)).readBytes())
            assertEquals(listOf(page), service.listPagesStrict(image.toURI().toString()))
            image.writeBytes(byteArrayOf(1, 2, 3))
            kotlin.test.assertFails { service.listPagesStrict(image.path) }
        } finally { root.deleteRecursively() }
    }

    @Test
    fun detectsArchiveTypesFromNamesAndSafMimeTypes() {
        assertEquals(LocalArchiveType.Epub, localArchiveType("book.epub", null))
        assertEquals(LocalArchiveType.Zip, localArchiveType("opaque", "application/zip"))
        assertEquals(LocalArchiveType.Tar, localArchiveType("opaque", "application/x-tar"))
        assertEquals(LocalArchiveType.Rar, localArchiveType("comic.cbr", null))
        assertEquals(LocalArchiveType.Rar, localArchiveType("comic.rar", null))
        assertEquals(LocalArchiveType.Rar, localArchiveType("opaque", "application/x-rar-compressed"))
        assertEquals(LocalArchiveType.Unknown, localArchiveType("cover.jpg", "image/jpeg"))
    }

    @Test
    fun evictsLeastRecentlyUsedExtractedPagesBeyondTheBudget() {
        val root = Files.createTempDirectory("yokan-archives").toFile()
        try {
            val page = ByteArray(1_000) { it.toByte() }
            val comics = listOf("a", "b", "c").associateWith { name ->
                File(root, "$name.cbz").apply { writeBytes(cbzOf("001.jpg" to page)) }.path
            }
            // Two chapters' pages fit; the third extraction must evict one.
            val archives = JvmLocalArchiveService(File(root, "cache").path, extractedPagesBudgetBytes = 2_500)
            fun extractionOf(comic: String) = File(URI(archives.listPages(comics.getValue(comic)).single().url)).parentFile!!

            val a = extractionOf("a")
            val b = extractionOf("b")
            // Pin the LRU order explicitly: filesystem mtimes can tie within one test.
            a.setLastModified(1_000)
            b.setLastModified(2_000)
            assertEquals(a, extractionOf("a")) // cached page list; marks a as used
            val c = extractionOf("c")

            assertTrue(a.isDirectory)
            assertFalse(b.isDirectory)
            assertTrue(c.isDirectory)
            // b's cached page list pointed into the evicted directory, so it extracts again.
            val reextracted = archives.listPages(comics.getValue("b")).single()
            assertContentEquals(page, File(URI(reextracted.url)).readBytes())
        } finally {
            root.deleteRecursively()
        }
    }

    @Test
    fun chapterCbzKeepsPagesAndMetadataButNotDownloadMarkers() {
        val root = Files.createTempDirectory("yokan-cbz").toFile()
        try {
            val chapter = File(root, "Chapter 1").apply { mkdirs() }
            File(chapter, "0001.jpg").writeBytes(byteArrayOf(1))
            File(chapter, "0001.jpg.complete").writeBytes(ByteArray(0))
            File(chapter, CHAPTER_METADATA_FILE).writeText("{}")

            val cbz = JvmLocalArchiveService(File(root, "cache").path).zipDirectoryToCbz(chapter.path, deleteSource = true)

            val names = ZipFile(checkNotNull(cbz)).use { zip -> zip.entries().asSequence().map { it.name }.toList() }
            assertEquals(listOf("0001.jpg", CHAPTER_METADATA_FILE), names)
            assertFalse(chapter.exists())
        } finally {
            root.deleteRecursively()
        }
    }

    @Test
    fun strictInventoryUsesDecodedLocatorsAndNeverReusesReplacedArchivePages() {
        val root = Files.createTempDirectory("yokan strict % pages").toFile()
        try {
            val archive = File(root, "comic space.cbz")
            val service = JvmLocalArchiveService(File(root, "cache").path)
            archive.writeBytes(cbzOf("nested/01 % page.png" to png(0x11)))
            val oldPage = service.listPagesStrict(archive.toURI().toString()).single()
            assertContentEquals(png(0x11), File(URI(oldPage.url)).readBytes())
            archive.writeBytes(cbzOf("nested/01 % page.png" to png(0x22)))
            val newPage = service.listPagesStrict(archive.toURI().toString()).single()
            assertContentEquals(png(0x22), File(URI(newPage.url)).readBytes())
            assertFalse(oldPage.url == newPage.url)
        } finally {
            root.deleteRecursively()
        }
    }

    @Test
    fun strictInventoryRejectsUndecodableImageWithValidZipCrc() {
        val root = Files.createTempDirectory("yokan-corrupt-cbz").toFile()
        try {
            val archive = File(root, "broken.cbz")
            val bytes = ByteArrayOutputStream().also { output ->
                ZipOutputStream(output).use { zip ->
                    val data = byteArrayOf(1, 2, 3, 4)
                    val entry = ZipEntry("page.jpg").apply {
                        method = ZipEntry.STORED
                        size = data.size.toLong()
                        compressedSize = data.size.toLong()
                        crc = CRC32().apply { update(data) }.value
                    }
                    zip.putNextEntry(entry)
                    zip.write(data)
                    zip.closeEntry()
                }
            }.toByteArray()
            // The ZIP payload and CRC are valid; the image bytes are not a decodable JPEG.
            archive.writeBytes(bytes)
            kotlin.test.assertFails { JvmLocalArchiveService(File(root, "cache").path).listPagesStrict(archive.path) }
        } finally {
            root.deleteRecursively()
        }
    }

    @Test
    fun strictInventoryRejectsDecodableImageWithBadZipCrc() {
        val root = Files.createTempDirectory("yokan-bad-crc").toFile()
        try {
            val image = png(0x44)
            val bytes = ByteArrayOutputStream().also { output ->
                ZipOutputStream(output).use { zip ->
                    val entry = ZipEntry("page.png").apply {
                        method = ZipEntry.STORED
                        size = image.size.toLong()
                        compressedSize = image.size.toLong()
                        crc = CRC32().apply { update(image) }.value
                    }
                    zip.putNextEntry(entry)
                    zip.write(image)
                    zip.closeEntry()
                }
            }.toByteArray()
            val centralHeader = bytes.indexOfSubsequence(byteArrayOf(0x50, 0x4b, 0x01, 0x02))
            check(centralHeader >= 0)
            bytes[centralHeader + 16] = (bytes[centralHeader + 16].toInt() xor 1).toByte()
            val archive = File(root, "bad-crc.cbz").apply { writeBytes(bytes) }
            kotlin.test.assertFails { JvmLocalArchiveService(File(root, "cache").path).listPagesStrict(archive.path) }
        } finally {
            root.deleteRecursively()
        }
    }

    private fun cbzOf(vararg entries: Pair<String, ByteArray>): ByteArray =
        ByteArrayOutputStream().also { bytes ->
            ZipOutputStream(bytes).use { zip ->
                entries.forEach { (name, content) ->
                    zip.putNextEntry(ZipEntry(name))
                    zip.write(content)
                    zip.closeEntry()
                }
            }
        }.toByteArray()

    private fun png(value: Int): ByteArray {
        val bytes = ByteArrayOutputStream()
        val output = DataOutputStream(bytes)
        output.write(byteArrayOf(137.toByte(), 80, 78, 71, 13, 10, 26, 10))
        fun chunk(type: String, data: ByteArray) {
            val typeBytes = type.encodeToByteArray()
            output.writeInt(data.size)
            output.write(typeBytes)
            output.write(data)
            output.writeInt(CRC32().apply { update(typeBytes); update(data) }.value.toInt())
        }
        val header = ByteArrayOutputStream().also { headerBytes ->
            DataOutputStream(headerBytes).use { headerOut ->
                headerOut.writeInt(1)
                headerOut.writeInt(1)
                headerOut.write(byteArrayOf(8, 6, 0, 0, 0))
            }
        }.toByteArray()
        chunk("IHDR", header)
        val compressed = ByteArrayOutputStream().also { data ->
            DeflaterOutputStream(data).use { it.write(byteArrayOf(0, value.toByte(), value.toByte(), value.toByte(), -1)) }
        }.toByteArray()
        chunk("IDAT", compressed)
        chunk("IEND", ByteArray(0))
        output.flush()
        return bytes.toByteArray()
    }

    private fun ByteArray.indexOfSubsequence(needle: ByteArray): Int =
        indices.firstOrNull { start ->
            start + needle.size <= size && needle.indices.all { this[start + it] == needle[it] }
        } ?: -1

}

Write composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/files/JvmLocalFileServiceTest.kt

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

The implementation below defines JvmLocalFileServiceTest, atomicReplaceReplacesExistingManifest, publishRefusesExistingDestinationAndRetainsStagedDirectory, atomicReplaceFailureRetainsTemporaryFile, concurrentPublishersDoNotReplaceTheWinningDirectory, boundedReadAcceptsLimitAndRejectsOneByteOverForFileUri, withFiles.

Read the setup, action and assertions in these cases before implementing their production paths:

  • atomicReplaceReplacesExistingManifest
  • publishRefusesExistingDestinationAndRetainsStagedDirectory
  • atomicReplaceFailureRetainsTemporaryFile
  • concurrentPublishersDoNotReplaceTheWinningDirectory
  • boundedReadAcceptsLimitAndRejectsOneByteOverForFileUri
package eu.friedcutlet.yokan.services.files

import java.io.File
import java.nio.file.Files
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class JvmLocalFileServiceTest {
    @Test
    fun atomicReplaceReplacesExistingManifest() = withFiles { root, files ->
        val temp = File(root, "manifest.tmp")
        val manifest = File(root, "manifest.json")
        temp.writeText("new")
        manifest.writeText("old")

        assertTrue(files.atomicReplaceFile(temp.path, manifest.path))
        assertEquals("new", manifest.readText())
        assertFalse(temp.exists())
    }

    @Test
    fun publishRefusesExistingDestinationAndRetainsStagedDirectory() = withFiles { root, files ->
        val staged = File(root, "staged").apply { mkdir() }
        File(staged, "page").writeText("complete")
        val destination = File(root, "job").apply { mkdir() }
        File(destination, "existing").writeText("keep")

        assertFalse(files.publishDirectoryIfAbsent(staged.path, destination.path))
        assertTrue(staged.isDirectory)
        assertTrue(File(staged, "page").isFile)
        assertEquals("keep", File(destination, "existing").readText())
    }

    @Test
    fun atomicReplaceFailureRetainsTemporaryFile() = withFiles { root, files ->
        val temp = File(root, "manifest.tmp").apply { writeText("staged") }
        val elsewhere = File(root, "other").apply { mkdir() }
        val destination = File(elsewhere, "manifest.json")

        assertFalse(files.atomicReplaceFile(temp.path, destination.path))
        assertEquals("staged", temp.readText())
        assertFalse(destination.exists())
    }

    @Test
    fun concurrentPublishersDoNotReplaceTheWinningDirectory() = withFiles { root, files ->
        val staged = listOf("first", "second").map { name ->
            File(root, "staged-$name").apply {
                mkdir()
                File(this, "owner").writeText(name)
            }
        }
        val destination = File(root, "job")
        val ready = CountDownLatch(staged.size)
        val start = CountDownLatch(1)
        val executor = Executors.newFixedThreadPool(staged.size)
        try {
            val results = staged.map { source ->
                executor.submit<Boolean> {
                    ready.countDown()
                    start.await()
                    files.publishDirectoryIfAbsent(source.path, destination.path)
                }
            }
            ready.await()
            start.countDown()

            assertEquals(1, results.count { it.get() })
            assertTrue(destination.isDirectory)
            assertEquals(1, staged.count { it.exists() })
        } finally {
            executor.shutdownNow()
        }
    }

    @Test
    fun boundedReadAcceptsLimitAndRejectsOneByteOverForFileUri() = withFiles { root, files ->
        val source = File(root, "encoded space % file.bin").apply { writeBytes(byteArrayOf(1, 2, 3)) }
        assertEquals(listOf<Byte>(1, 2, 3), files.readBytesBounded(source.toURI().toString(), 3).toList())
        kotlin.test.assertFails { files.readBytesBounded(source.toURI().toString(), 2) }
    }

    private fun withFiles(block: (File, JvmLocalFileService) -> Unit) {
        val root = Files.createTempDirectory("yokan-local-files").toFile()
        try {
            block(root, JvmLocalFileService(root.path, root.path, root.path))
        } finally {
            root.deleteRecursively()
        }
    }
}

Write composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/files/JvmLocalMediaInputTest.kt

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

The implementation below defines JvmLocalMediaInputTest, read, close.

Read the setup, action and assertions in these cases before implementing their production paths:

  • readerWaitsForDestinationAndNeverReadsMoreThanOneBoundedChunkAhead
  • cancellationClosesTheSourceWithoutReadingTheRemainingFile
package eu.friedcutlet.yokan.services.files

import java.io.ByteArrayInputStream
import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class JvmLocalMediaInputTest {
    @Test fun readerWaitsForDestinationAndNeverReadsMoreThanOneBoundedChunkAhead() = runTest {
        val bytes = ByteArray(LOCAL_IMPORT_CHUNK_BYTES * 3 + 3) { it.toByte() }
        val reads = AtomicInteger()
        val closes = AtomicInteger()
        val stream = object : ByteArrayInputStream(bytes) {
            override fun read(b: ByteArray, off: Int, len: Int): Int { reads.incrementAndGet(); return super.read(b, off, len) }
            override fun close() { closes.incrementAndGet(); super.close() }
        }
        val first = CompletableDeferred<Unit>()
        val resume = CompletableDeferred<Unit>()
        val chunks = mutableListOf<ByteArray>()
        val reader = JvmLocalMediaInput("clip.mp4", bytes.size.toLong()) { stream }
        val work = async {
            reader.readChunks {
                chunks += it
                if (chunks.size == 1) { first.complete(Unit); resume.await() }
            }
        }
        first.await()
        assertEquals(1, reads.get())
        assertEquals(0, closes.get())
        resume.complete(Unit)
        work.await()
        assertEquals(listOf(65536, 65536, 65536, 3), chunks.map { it.size })
        assertContentEquals(bytes, chunks.reduce { a, b -> a + b })
        assertEquals(1, closes.get())
    }

    @Test fun cancellationClosesTheSourceWithoutReadingTheRemainingFile() = runTest {
        val closes = AtomicInteger()
        val stream = object : ByteArrayInputStream(ByteArray(LOCAL_IMPORT_CHUNK_BYTES * 3)) {
            override fun close() { closes.incrementAndGet(); super.close() }
        }
        val reader = JvmLocalMediaInput("clip.mp4", null) { stream }
        assertFailsWith<CancellationException> { reader.readChunks { throw CancellationException("Cancelled") } }
        assertEquals(1, closes.get())
        assertEquals(LOCAL_IMPORT_CHUNK_BYTES * 2, stream.available())
    }
}

Write composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/files/RarArchiveExtractorTest.kt

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

The implementation below defines RarArchiveExtractorTest, detectsImageExtensions, detectsRar4AndRar5Magic, extractsDisguisedZipCbr, extractsDisguisedZipCbrInNaturalPageOrder.

Read the setup, action and assertions in these cases before implementing their production paths:

  • detectsImageExtensions
  • detectsRar4AndRar5Magic
  • extractsDisguisedZipCbr
  • extractsDisguisedZipCbrInNaturalPageOrder
package eu.friedcutlet.yokan.services.files

import java.io.ByteArrayOutputStream
import java.io.File
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class RarArchiveExtractorTest {
    @Test
    fun detectsImageExtensions() {
        assertTrue(RarArchiveExtractor.isImageFile("page1.jpg"))
        assertTrue(RarArchiveExtractor.isImageFile("page2.jpeg"))
        assertTrue(RarArchiveExtractor.isImageFile("page3.png"))
        assertTrue(RarArchiveExtractor.isImageFile("page4.webp"))
        assertTrue(RarArchiveExtractor.isImageFile("page5.avif"))
        assertTrue(RarArchiveExtractor.isImageFile("page6.gif"))
        assertTrue(RarArchiveExtractor.isImageFile("page7.bmp"))

        assertFalse(RarArchiveExtractor.isImageFile("info.txt"))
        assertFalse(RarArchiveExtractor.isImageFile("comic.xml"))
        assertFalse(RarArchiveExtractor.isImageFile(".DS_Store"))
    }

    @Test
    fun detectsRar4AndRar5Magic() {
        val rar4Magic = byteArrayOf(0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00)
        assertTrue(RarArchiveExtractor.isRar4(rar4Magic))
        assertFalse(RarArchiveExtractor.isRar5(rar4Magic))

        val rar5Magic = byteArrayOf(0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x01, 0x00)
        assertTrue(RarArchiveExtractor.isRar5(rar5Magic))
        assertFalse(RarArchiveExtractor.isRar4(rar5Magic))

        val randomBytes = byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8)
        assertFalse(RarArchiveExtractor.isRar4(randomBytes))
        assertFalse(RarArchiveExtractor.isRar5(randomBytes))
    }

    @Test
    fun extractsDisguisedZipCbr() {
        val tempDir = File(System.getProperty("java.io.tmpdir"), "yokan-cbr-test-${System.nanoTime()}").also { it.mkdirs() }
        val cbrFile = File(tempDir, "comic.cbr")
        val outDir = File(tempDir, "out")

        try {
            val zipBytes = ByteArrayOutputStream().also { bos ->
                ZipOutputStream(bos).use { zos ->
                    zos.putNextEntry(ZipEntry("02.png"))
                    zos.write("page-2".encodeToByteArray())
                    zos.closeEntry()

                    zos.putNextEntry(ZipEntry("01.jpg"))
                    zos.write("page-1".encodeToByteArray())
                    zos.closeEntry()

                    zos.putNextEntry(ZipEntry("metadata.json"))
                    zos.write("{}".encodeToByteArray())
                    zos.closeEntry()
                }
            }.toByteArray()

            cbrFile.writeBytes(zipBytes)
            assertTrue(RarArchiveExtractor.isZipFile(cbrFile))

            val extracted = RarArchiveExtractor.extract(cbrFile, outDir)
            assertEquals(2, extracted.size)
            assertEquals("0000_01.jpg", extracted[0].name)
            assertEquals("page-1", extracted[0].readText())
            assertEquals("0001_02.png", extracted[1].name)
            assertEquals("page-2", extracted[1].readText())
        } finally {
            tempDir.deleteRecursively()
        }
    }

    @Test
    fun extractsDisguisedZipCbrInNaturalPageOrder() {
        val tempDir = File(System.getProperty("java.io.tmpdir"), "yokan-cbr-natural-test-${System.nanoTime()}").also { it.mkdirs() }
        val cbrFile = File(tempDir, "comic.cbr")

        try {
            ZipOutputStream(cbrFile.outputStream()).use { zip ->
                listOf("10.jpg", "2.jpg", "1.jpg").forEach { name ->
                    zip.putNextEntry(ZipEntry(name))
                    zip.write(name.encodeToByteArray())
                    zip.closeEntry()
                }
            }

            val extracted = RarArchiveExtractor.extract(cbrFile, File(tempDir, "out"))
            assertEquals(listOf("0000_1.jpg", "0001_2.jpg", "0002_10.jpg"), extracted.map { it.name })
        } finally {
            tempDir.deleteRecursively()
        }
    }
}

Write composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/files/TarMemoryTest.kt

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

The implementation below defines TarMemoryTest, extractsImageAfterIgnoredEntryLargerThanTheHeap, truncatedImagePayloadIsRejected, header.

Read the setup, action and assertions in these cases before implementing their production paths:

  • extractsImageAfterIgnoredEntryLargerThanTheHeap
  • truncatedImagePayloadIsRejected
package eu.friedcutlet.yokan.services.files

import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.EOFException
import java.io.RandomAccessFile
import java.net.URI
import java.nio.file.Files
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

class TarMemoryTest {
    @Test
    fun extractsImageAfterIgnoredEntryLargerThanTheHeap() {
        val root = Files.createTempDirectory("yokan-tar-memory-").toFile()
        try {
            val archive = root.resolve("chapter.cbt")
            val ignoredSize = 3L * 1024 * 1024 * 1024
            RandomAccessFile(archive, "rw").use { file ->
                file.write(header("ignored.bin", ignoredSize))
                // A sparse entry reproduces the former >Int.MAX_VALUE allocation without
                // allocating or writing gigabytes in the test itself.
                file.seek(512 + ignoredSize)
                file.write(header("page.png", 4))
                file.write(byteArrayOf(1, 2, 3, 4))
                file.write(ByteArray(508 + 1024))
            }
            val pages = JvmLocalArchiveService(root.resolve("cache").path).listPages(archive.path)
            assertEquals(1, pages.size)
            assertContentEquals(byteArrayOf(1, 2, 3, 4), java.io.File(URI(pages.single().url)).readBytes())
        } finally {
            root.deleteRecursively()
        }
    }

    @Test
    fun truncatedImagePayloadIsRejected() {
        assertFailsWith<EOFException> {
            ByteArrayInputStream(byteArrayOf(1, 2)).transferTarEntry(4, ByteArrayOutputStream())
        }
    }

    private fun header(name: String, size: Long): ByteArray = ByteArray(512).also { bytes ->
        name.encodeToByteArray().copyInto(bytes)
        size.toString(8).padStart(11, '0').encodeToByteArray().copyInto(bytes, 124)
        bytes[156] = '0'.code.toByte()
    }
}

Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/files/BrowserEpubReaderTest.kt

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

The implementation below defines BrowserEpubReaderTest, epubSelection, epubOpens, epubCloses, epubReadPadding, holdNextEpubRead, waitForEpubRead, releaseEpubRead.

Read the setup, action and assertions in these cases before implementing their production paths:

  • cancellationJoinsAnInFlightJavascriptReadBeforeClosingTheArchive
  • corruptOptionalResourcesFailCrcValidationWithoutChangingTheStoredBook
  • importedEpubScansAndReadsOfflineWithEmbeddedImagesAndCachedInventory
  • oversizedChaptersAreRejectedAndArchiveSessionsCloseWithoutLosingTheOriginal

Cross-chapter imports used by this file: ProfileId, deletePlatformProfileStorage, DefaultYokanRepository, SettingsStore, ChapterPageResolver, ProfileReaderContent. Keep those contracts available as you connect this step.

@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.extensions.ChapterPageResolver
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest
import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService
import eu.friedcutlet.yokan.services.library.LocalMediaImporter
import eu.friedcutlet.yokan.ui.screens.novel.*
import kotlinx.coroutines.await
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.yield
import kotlinx.coroutines.test.runTest
import kotlin.js.JsAny
import kotlin.js.Promise
import kotlin.test.*

class BrowserEpubReaderTest {
    @Test fun cancellationJoinsAnInFlightJavascriptReadBeforeClosingTheArchive() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val selection = browserMediaSelection(epubSelection(0).await<JsAny>())
        try {
            val db = InMemoryYokanDatabase(emptySnapshot())
            val folder = LocalMediaImporter(files, SettingsStore(DefaultYokanRepository(db), backgroundScope) {}).import(selection, DbItemType.Novel)
            holdNextEpubRead()
            val request = async { createPlatformLocalArchiveService(id).readEpubResourceAsync("${folder.path}/Book.epub", "OEBPS/Images/cover art.png") }
            try {
                waitForEpubRead().await<JsAny?>()
                request.cancel()
                yield()
                assertFalse(request.isCompleted)
                assertEquals(0, epubCloses())
            } finally { releaseEpubRead(); request.cancelAndJoin() }
            assertEquals(1, epubOpens())
            assertEquals(1, epubCloses())
        } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }

    @Test fun corruptOptionalResourcesFailCrcValidationWithoutChangingTheStoredBook() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val selection = browserMediaSelection(epubSelection(2).await<JsAny>())
        try {
            val db = InMemoryYokanDatabase(emptySnapshot())
            val folder = LocalMediaImporter(files, SettingsStore(DefaultYokanRepository(db), backgroundScope) {}).import(selection, DbItemType.Novel)
            val path = "${folder.path}/Book.epub"
            val size = files.directorySize(path)
            val archives = createPlatformLocalArchiveService(id)
            assertEquals(listOf("Second", "First"), archives.listEpubChaptersAsync(path).map { it.title })
            assertNull(archives.readEpubResourceAsync(path, "OEBPS/Images/cover art.png"))
            assertTrue(archives.readEpubChapterAsync(path, 0).contains("Offline second"))
            assertEquals(epubOpens(), epubCloses())
            assertEquals(size, files.directorySize(path))
        } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }
    @Test fun importedEpubScansAndReadsOfflineWithEmbeddedImagesAndCachedInventory() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val archives = createPlatformLocalArchiveService(id)
        val db = InMemoryYokanDatabase(emptySnapshot())
        val repository = DefaultYokanRepository(db)
        val factory = ProfileReaderContentTest.RuntimeFactory(db, "Browser")
        val content = ProfileReaderContent(id, db, factory, ChapterPageResolver(repository, db, factory), files, archives, backgroundScope)
        val selection = browserMediaSelection(epubSelection(0).await<JsAny>())
        try {
            val folder = LocalMediaImporter(files, SettingsStore(repository, backgroundScope) {}).import(selection, DbItemType.Novel)
            val scanner = DefaultLocalLibraryService(db, files, archives)
            assertEquals(1, scanner.scan().added)
            val title = db.mangas().single()
            assertEquals(DbItemType.Novel, title.itemType)
            assertEquals(listOf("Second", "First"), db.chapters(title.id).map { it.name })
            assertEquals(1, epubOpens())
            scanner.scan()
            assertEquals(1, epubOpens())
            val chapter = repository.chapters(title.id).first { it.archivePath.endsWith("#0") }
            val parsed = loadNovelDocument(content, null, title.name.orEmpty(), chapter).parse()
            assertTrue(parsed.plainText.contains("Offline second"))
            val images = parsed.blocks.filterIsInstance<NovelContentBlock.Image>()
            assertEquals(2, images.size)
            assertContentEquals(byteArrayOf(9, 8, 7, 6), assertIs<NovelImageSource.Embedded>(images[0].source).bytes)
            assertSame(assertIs<NovelImageSource.Embedded>(images[0].source).bytes, assertIs<NovelImageSource.Embedded>(images[1].source).bytes)
            assertEquals(0, factory.created)
            assertEquals(3, epubOpens())
            assertEquals(epubOpens(), epubCloses())
            val old = db.chapters(title.id).first { it.archivePath.endsWith("#0") }
            db.upsertChapter(old.copy(isRead = true, lastPageRead = "7", isBookmarked = true))
            scanner.scanFresh()
            val refreshed = assertNotNull(db.chapter(old.id))
            assertTrue(refreshed.isRead && refreshed.isBookmarked)
            assertEquals("7", refreshed.lastPageRead)
            assertEquals(4, epubOpens())
            assertFalse(epubReadPadding())
            assertTrue(files.directorySize("${folder.path}/Book.epub") > 65536)
        } finally {
            selection.close(); content.closeAndJoin(); files.close(); deletePlatformProfileStorage(id, emptyList())
        }
    }

    @Test fun oversizedChaptersAreRejectedAndArchiveSessionsCloseWithoutLosingTheOriginal() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val selection = browserMediaSelection(epubSelection(1).await<JsAny>())
        try {
            val db = InMemoryYokanDatabase(emptySnapshot())
            val folder = LocalMediaImporter(files, SettingsStore(DefaultYokanRepository(db), backgroundScope) {}).import(selection, DbItemType.Novel)
            val path = "${folder.path}/Book.epub"
            val size = files.directorySize(path)
            val archives = createPlatformLocalArchiveService(id)
            assertTrue(archives.listEpubChaptersAsync(path).isEmpty())
            assertFails { archives.readEpubChapterAsync(path, 0) }
            assertEquals(epubOpens(), epubCloses())
            assertEquals(size, files.directorySize(path))
            assertNull(archives.readEpubResourceAsync(path, "../other-profile/secret"))
            assertEquals(epubOpens(), epubCloses())
        } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }
}

private fun epubSelection(mode: Int): Promise<JsAny> = js("""(async () => {
    if (!globalThis.yokanBrowserArchives) await new Promise((resolve, reject) => {
        const script = document.createElement('script'); script.src = '/browser-archives.js';
        script.onload = resolve; script.onerror = reject; document.head.append(script);
    });
    const archives = globalThis.yokanBrowserArchives;
    if (!archives.originalOpenRead) archives.originalOpenRead = archives.openRead;
    globalThis.yokanEpubProbe = { opens: 0, closes: 0, paths: [] };
    archives.openRead = async file => {
        const probe = globalThis.yokanEpubProbe;
        const session = await archives.originalOpenRead(file); probe.opens++;
        return { read: async (name, maximum) => {
                probe.paths.push(name);
                if (probe.gate) { const gate = probe.gate; probe.gate = null; probe.enter(); await gate; }
                return session.read(name, maximum);
            },
            close: async () => { probe.closes++; await session.close(); } };
    };
    const entries = [
        ['mimetype', 'application/epub+zip'],
        ['META-INF/container.xml', '<container><rootfiles><rootfile full-path="OEBPS/book.opf"/></rootfiles></container>'],
        ['OEBPS/book.opf', '<package><manifest><item id="one" href="Text/one.xhtml"/><item id="two" href="Text/two%20words.xhtml"/></manifest><spine><itemref idref="two"/><itemref idref="one"/></spine></package>'],
        ['OEBPS/Text/one.xhtml', '<html><head><title>First</title></head><body>Offline first</body></html>'],
        ['OEBPS/Text/two words.xhtml', mode === 1 ? new Uint8Array(8 * 1024 * 1024 + 1) : '<html><head><title>Second</title></head><body><p>Offline second</p><img src="../Images/cover%20art.png"/><img src="../Images/cover%20art.png"/></body></html>'],
        ['OEBPS/Images/cover art.png', new Uint8Array([9,8,7,6])],
        ['unused-padding.bin', new Uint8Array(65536)],
    ];
    const chunks = [];
    await archives.write(entries.map(([name, bytes]) => ({ name, bytes: new Blob([bytes]) })), new WritableStream({ write: bytes => chunks.push(bytes.slice()) }));
    if (mode === 2) {
        const bytes = new Uint8Array(await new Blob(chunks).arrayBuffer());
        let found = false;
        for (let i = 0; i < bytes.length - 3; i++) if (bytes[i] === 9 && bytes[i+1] === 8 && bytes[i+2] === 7 && bytes[i+3] === 6) {
            bytes[i] ^= 1; found = true; break;
        }
        if (!found) throw new Error('CRC fixture payload was not found.');
        return globalThis.yokanBrowserFiles.selectedMedia([new File([bytes], 'Book.epub')]);
    }
    return globalThis.yokanBrowserFiles.selectedMedia([new File(chunks, 'Book.epub')]);
})()""")
private fun epubOpens(): Int = js("globalThis.yokanEpubProbe.opens")
private fun epubCloses(): Int = js("globalThis.yokanEpubProbe.closes")
private fun epubReadPadding(): Boolean = js("globalThis.yokanEpubProbe.paths.includes('unused-padding.bin')")
private fun holdNextEpubRead(): Unit = js("""(() => {
    const probe = globalThis.yokanEpubProbe;
    probe.gate = new Promise(resolve => { probe.release = resolve; });
    probe.entered = new Promise(resolve => { probe.enter = resolve; });
})()""")
private fun waitForEpubRead(): Promise<JsAny?> = js("globalThis.yokanEpubProbe.entered.then(() => null)")
private fun releaseEpubRead(): Unit = js("globalThis.yokanEpubProbe.release()")

Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/files/BrowserLocalLibraryImportVisibilityTest.kt

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

The implementation below defines BrowserLocalLibraryImportVisibilityTest, readChunks, twoEpisodes.

Read the setup, action and assertions in these cases before implementing their production paths:

  • parentFolderScansIgnoreCommittedFilesUntilTheWholeImportIsPublished

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

@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService
import eu.friedcutlet.yokan.services.library.LocalMediaImporter
import kotlin.js.JsAny
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class BrowserLocalLibraryImportVisibilityTest {
    @Test fun parentFolderScansIgnoreCommittedFilesUntilTheWholeImportIsPublished() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        settings.updateDb { it.copy(namedLocalFolders = listOf(DbLocalFolder("Everything", files.downloadRoot))) }
        val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))
        val source = browserMediaSelection(twoEpisodes())
        try {
            val second = source.files[1]
            val selection = LocalMediaSelection(listOf(source.files[0], object : LocalMediaInput {
                override val relativePath = second.relativePath
                override val sizeBytes = second.sizeBytes
                override suspend fun readChunks(consume: suspend (ByteArray) -> Unit) {
                    // The first file has committed to actual OPFS and is visible in its inventory.
                    assertEquals(0, scanner.scan().total)
                    assertTrue(db.mangas().isEmpty())
                    second.readChunks(consume)
                }
            }))
            LocalMediaImporter(files, settings).import(selection, DbItemType.Anime)
            assertEquals(1, scanner.scan().total)
            val title = db.mangas().single()
            assertEquals(DbItemType.Anime, title.itemType)
            assertEquals(2, db.chapters(title.id).size)
            assertEquals(0, scanner.scan().added)
            assertEquals(listOf(title.id), db.mangas().map { it.id })
        } finally { source.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }
}

private fun twoEpisodes(): JsAny = js("""(() => {
    const files = [1, 2].map(number => {
        const file = new File([new Uint8Array([number])], number + '.mp4');
        Object.defineProperty(file, 'webkitRelativePath', { value: 'Show/' + number + '.mp4' });
        return file;
    });
    return globalThis.yokanBrowserFiles.selectedMedia(files);
})()""")

Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/files/BrowserLocalLibraryScanTest.kt

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

The implementation below defines BrowserLocalLibraryScanTest.

Read the setup, action and assertions in these cases before implementing their production paths:

  • castSidecarsUseRealOpfsPortraitUrlsAndExplicitClear
  • nestedAnimeFilesUseSeasonSidecarsWithoutFolderOrPreviewChapters
  • episodeMetadataKeepsNumbersSeasonAndProgressInRealOpfsScans
  • animetailDetailsUseTheirOwnStatusMappingAndMergeLegacyArtworkFromOpfs
  • opfsListingsAndSharedScannerReadMetadataAndCoversWithoutSynchronousDiskReads
  • emptyDirectoriesStayReadableAcrossDeletionAndReload

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.library.DefaultLocalLibraryService
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class BrowserLocalLibraryScanTest {
    @Test fun castSidecarsUseRealOpfsPortraitUrlsAndExplicitClear() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val root = "${files.downloadRoot}/anime"
        try {
            files.writeBytesAsync("$root/Show/Episode 1.mp4", byteArrayOf(1))
            files.writeBytesAsync("$root/Show/actor.png", byteArrayOf(2, 3))
            files.writeBytesAsync("$root/Show/details.json", """{"cast":[{"name":"Actor","role":"Voice actor","character":"Hero","image_url":"actor.png"},{"name":"Other","image_url":"../private.png"}]}""".encodeToByteArray())
            val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root)))))
            val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))
            scanner.scan()
            val title = db.mangas().single()
            assertEquals(2, title.cast.size)
            assertEquals("Actor", title.cast[0].name)
            assertEquals("Hero", title.cast[0].character)
            assertTrue(assertNotNull(title.cast[0].imageUrl).contains("__yokan_files__/"))
            assertNull(title.cast[1].imageUrl)
            assertNull(title.customCoverImage)
            val chapter = db.chapters(title.id).single()
            db.upsertChapter(chapter.copy(isRead = true, lastPageRead = "1234"))
            files.writeBytesAsync("$root/Show/details.json", "{}".encodeToByteArray())
            scanner.scanFresh()
            assertEquals(title.cast, db.manga(title.id)?.cast)
            files.writeBytesAsync("$root/Show/details.json", """{"cast":[]}""".encodeToByteArray())
            scanner.scanFresh()
            assertEquals(emptyList(), db.manga(title.id)?.cast)
            assertEquals("1234", db.chapter(chapter.id)?.lastPageRead)
            assertContentEquals(byteArrayOf(2, 3), files.readBytesAsync("$root/Show/actor.png", 2))
        } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }

    @Test fun nestedAnimeFilesUseSeasonSidecarsWithoutFolderOrPreviewChapters() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val root = "${files.downloadRoot}/anime"
        try {
            val show = "$root/Show"
            for (path in listOf("Episode 3.mp4", "Season 0/Episode 1.mkv", "Season 1/Episode 1.mp4", "Season 1/Episode 2.mp4",
                "Season 1/deeper/Episode 99.mp4", ".hidden/Episode 50.mp4", "Season 1/.Episode 51.mp4", "Season 1/art/preview.png")) {
                files.writeBytesAsync("$show/$path", byteArrayOf(1))
            }
            files.writeBytesAsync("$show/episodes.json", """[{"episode_number":3,"name":"Finale"}]""".encodeToByteArray())
            files.writeBytesAsync("$show/Season 0/episodes.json", """[{"episode_number":1,"name":"Special"}]""".encodeToByteArray())
            files.writeBytesAsync("$show/Season 1/episodes.json", """[{"episode_number":1,"name":"Premiere","preview_url":"art/preview.png"}]""".encodeToByteArray())
            assertEquals(setOf("Episode 3.mp4", "Season 0", "Season 1", ".hidden", "episodes.json"),
                assertNotNull(files.listDirectoryEntries(show)).map { it.name }.toSet())
            assertNull(files.listDirectoryEntries("$show/missing"))
            val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root)))))
            val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))
            scanner.scan()
            val title = db.mangas().single()
            val episodes = db.chapters(title.id)
            assertEquals(4, episodes.size)
            assertEquals(setOf("Finale", "Special", "Premiere", "Episode 2"), episodes.map { it.name }.toSet())
            assertEquals(0, episodes.single { it.name == "Special" }.season)
            val premiere = episodes.single { it.name == "Premiere" }
            assertEquals(1, premiere.season)
            assertEquals(1.0, premiere.number)
            assertTrue(assertNotNull(premiere.thumbnailUrl).contains("__yokan_files__/"))
            assertTrue(episodes.all { it.archivePath.endsWith(".mp4") || it.archivePath.endsWith(".mkv") })
            db.upsertChapter(premiere.copy(isRead = true, isBookmarked = true, lastPageRead = "2345"))
            scanner.scanFresh()
            assertEquals(episodes.map { it.id }.toSet(), db.chapters(title.id).map { it.id }.toSet())
            assertEquals("2345", db.chapter(premiere.id)?.lastPageRead)
            assertTrue(db.chapter(premiere.id)?.isRead == true)
        } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }

    @Test fun episodeMetadataKeepsNumbersSeasonAndProgressInRealOpfsScans() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val root = "${files.downloadRoot}/anime"
        val season = "$root/Show/Season 2"
        try {
            files.writeBytesAsync("$season/Episode 12.5.mp4", byteArrayOf(1))
            files.writeBytesAsync("$season/Episode 13.mp4", byteArrayOf(2))
            files.writeBytesAsync("$season/preview.png", byteArrayOf(3, 4))
            files.writeBytesAsync("$season/details.json", """{"title":"Show Season Two"}""".encodeToByteArray())
            files.writeBytesAsync("$season/episodes.json", """[{"episode_number":12.5,"name":"Opening Night","date_upload":"2026-04-12","fillermark":true,"summary":"Local synopsis","preview_url":"preview.png"}]""".encodeToByteArray())
            val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root)))))
            val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))
            scanner.scan()
            // `Show` has no episode files of its own, so it is a Seasons title owning the season record.
            val show = db.mangas().single { it.parentId == null }
            assertEquals(DbFetchType.Seasons, show.fetchType)
            assertTrue(db.chapters(show.id).isEmpty())
            val title = db.mangas().single { it.parentId == show.id }
            assertEquals(2.0, title.seasonNumber)
            assertEquals("Show Season Two", title.name)
            assertEquals(2, db.chapters(title.id).size)
            val episode = db.chapters(title.id).first { it.number == 12.5 }
            assertEquals("Opening Night", episode.name)
            assertEquals("Episode 12.5", episode.numberingName)
            assertEquals(2, episode.season)
            assertTrue(episode.isFiller)
            assertEquals("Local synopsis", episode.description)
            assertEquals("2026-04-12", episode.dateUpload)
            assertTrue(assertNotNull(episode.thumbnailUrl).contains("__yokan_files__/"))
            db.upsertChapter(episode.copy(isRead = true, isBookmarked = true, lastPageRead = "42000"))
            files.writeBytesAsync("$season/episodes.json", """[{"episode_number":12.5,"name":"Another title","fillermark":false,"scanlator":"Group"}]""".encodeToByteArray())
            scanner.scanFresh()
            val updated = assertNotNull(db.chapter(episode.id))
            assertEquals("Another title", updated.name)
            assertEquals(episode.archivePath, updated.archivePath)
            assertEquals(12.5, updated.number)
            assertEquals(2, updated.season)
            assertFalse(updated.isFiller)
            assertEquals("Group", updated.scanlator)
            assertTrue(updated.isRead && updated.isBookmarked)
            assertEquals("42000", updated.lastPageRead)
            assertEquals(2, db.chapters(title.id).size)
            assertEquals(setOf(show.id, title.id), db.mangas().map { it.id }.toSet())
            assertContentEquals(byteArrayOf(1), files.readBytesAsync("$season/Episode 12.5.mp4", 1))
        } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }
    @Test fun animetailDetailsUseTheirOwnStatusMappingAndMergeLegacyArtworkFromOpfs() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val root = "${files.downloadRoot}/anime"
        try {
            files.writeBytesAsync("$root/Show/Episode 1.mp4", byteArrayOf(1))
            files.writeBytesAsync("$root/Show/metadata.json", """{"name":"Legacy","status":1,"imageUrl":"https://cover.test/image","language":"ja"}""".encodeToByteArray())
            files.writeBytesAsync("$root/Show/details.json", """{"title":"Animetail title","author":"Writer","genre":["Drama"],"status":1}""".encodeToByteArray())
            val db = InMemoryYokanDatabase(emptySnapshot().copy(settings = DbSettings(namedLocalFolders = listOf(DbLocalFolder("Anime", root)))))
            val scanner = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))
            scanner.scan()
            val title = db.mangas().single()
            assertEquals(DbItemType.Anime, title.itemType)
            assertEquals("Animetail title", title.name)
            assertEquals(DbStatus.Ongoing, title.status)
            assertEquals("Writer", title.author)
            assertEquals(listOf("Drama"), title.genre)
            assertEquals("https://cover.test/image", title.imageUrl)
            assertEquals("ja", title.lang)
            assertTrue(db.chapters(title.id).single().archivePath.endsWith("/Episode 1.mp4"))
            scanner.scanFresh()
            assertEquals(1, db.mangas().size)
            assertEquals(1, db.chapters(title.id).size)
            for ((value, status) in listOf(3 to DbStatus.Licensed, 7 to DbStatus.Upcoming)) {
                files.writeBytesAsync("$root/Show/details.json", "{\"title\":\"Animetail title\",\"status\":$value}".encodeToByteArray())
                scanner.scanFresh()
                assertEquals(status, db.manga(title.id)?.status)
                assertEquals(status.name, eu.friedcutlet.yokan.data.DefaultYokanRepository(db).manga(title.id)?.status?.name)
                assertEquals(1, db.chapters(title.id).size)
            }
        } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }
    @Test fun opfsListingsAndSharedScannerReadMetadataAndCoversWithoutSynchronousDiskReads() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val root = "${files.downloadRoot}/local"
        try {
            files.writeBytesAsync("$root/Title/metadata.json", "{\"name\":\"Offline title\",\"author\":\"Author\"}".encodeToByteArray())
            files.writeBytesAsync("$root/Title/cover.png", byteArrayOf(1, 2, 3))
            files.writeBytesAsync("$root/Title/Chapter 1/001.jpg", byteArrayOf(4, 5))
            assertEquals(listOf(LocalEntry("$root/Title", "Title", false)), files.listLocalEntries(root))
            assertNull(files.listLocalEntries("$root/missing"))
            val db = InMemoryYokanDatabase(emptySnapshot())
            val service = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id))
            assertEquals(1, service.scan().added)
            val title = db.mangas().single()
            assertEquals("Offline title", title.name)
            assertEquals("Author", title.author)
            assertContentEquals(byteArrayOf(1, 2, 3), title.customCoverImage)
            assertTrue(db.chapters(title.id).single().archivePath.endsWith("/Title/Chapter 1"))
            assertEquals(0, service.scan().added)
            assertEquals(1, db.chapters(title.id).size)
            assertFails { files.listLocalEntries("/yokan/profiles/p_00000000000000000000000000000000/downloads/local") }
        } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }

    @Test fun emptyDirectoriesStayReadableAcrossDeletionAndReload() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val root = "${files.downloadRoot}/local"
        val path = "$root/one.cbz"
        files.writeBytesAsync(path, byteArrayOf(1))
        assertEquals(listOf(LocalEntry(path, "one", true)), files.listLocalEntries(root))
        files.deleteRecursivelyAsync(path)
        assertTrue(files.exists(root))
        assertEquals(emptyList(), files.listLocalEntries(root))
        files.close()
        val reopened = createPlatformLocalFileService(id)
        try {
            reopened.prepare()
            assertTrue(reopened.exists(root))
            assertEquals(emptyList(), reopened.listLocalEntries(root))
        } finally { reopened.close(); deletePlatformProfileStorage(id, emptyList()) }
    }
}

Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/files/BrowserLocalMediaImportTest.kt

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

The implementation below defines BrowserLocalMediaImportTest, installPickerFixture, restorePickerFixture, sliceCalls, largestSlice, sawDirectoryPicker, smallSelection, cancelPicker, pickerCancellationClean, fetchImagePage and 1 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

  • standaloneImportedImagesProduceAReadableSinglePage
  • actualPickerAndOpfsCopyLargeFilesInBoundedChunksWithoutReadingWholeFiles
  • completedOpfsCopyRecoversAfterClosingStorageBeforeSettingsWereSaved
  • cancelledBrowserPickerRemovesItsInputAndResolvesWithoutRetainingFiles

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

@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.*
import eu.friedcutlet.yokan.services.library.*
import kotlin.js.JsAny
import kotlin.js.Promise
import kotlinx.coroutines.await
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class BrowserLocalMediaImportTest {
    @Test fun standaloneImportedImagesProduceAReadableSinglePage() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        try {
            val path = "${files.downloadRoot}/local-imports/image/manga/page.png"
            files.writeBytesAsync(path, byteArrayOf(1, 2, 3))
            val page = createPlatformLocalArchiveService(id).listPagesAsync(path).single()
            assertEquals("page.png", page.fileName)
            assertTrue(page.url.contains("__yokan_files__/"))
            assertTrue(fetchImagePage(page.url).await<JsAny?>().let { imagePageServed() })
        } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }

    @Test fun actualPickerAndOpfsCopyLargeFilesInBoundedChunksWithoutReadingWholeFiles() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        installPickerFixture()
        try {
            val selection = assertNotNull(pickLocalMedia(directory = true))
            try {
                val importer = LocalMediaImporter(files, settings)
                val folder = importer.import(selection, DbItemType.Anime)
                assertEquals(12L * 1024 * 1024 + 3, files.directorySize("${folder.path}/Show/Episode 1.mp4"))
                assertEquals(193, sliceCalls())
                assertEquals(65536, largestSlice())
                assertTrue(sawDirectoryPicker())
                assertTrue(importer.pending().isEmpty())
                assertFails { files.exists("/yokan/profiles/p_00000000000000000000000000000000/downloads/local-imports") }
                val scan = DefaultLocalLibraryService(db, files, createPlatformLocalArchiveService(id)).scan()
                assertEquals(1, scan.added)
                assertEquals(DbItemType.Anime, db.mangas().single().itemType)
                assertTrue(db.chapters().single().archivePath.endsWith("/Show/Episode 1.mp4"))
            } finally { selection.close() }
        } finally { restorePickerFixture(); files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }

    @Test fun completedOpfsCopyRecoversAfterClosingStorageBeforeSettingsWereSaved() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val db = InMemoryYokanDatabase(emptySnapshot())
        val settings = SettingsStore(DefaultYokanRepository(db), backgroundScope) {}
        val selection = browserMediaSelection(smallSelection())
        val importer = LocalMediaImporter(files, settings, persistSettings = { error("Save failed") })
        try {
            assertFailsWith<IllegalStateException> { importer.import(selection, DbItemType.Manga) }
            val pending = importer.pending().single()
            assertEquals(LocalImportPhase.Ready, pending.phase)
            settings.updateDb { it.copy(namedLocalFolders = emptyList()) }
            files.close()
            val reopened = createPlatformLocalFileService(id)
            try {
                val recovered = LocalMediaImporter(reopened, settings)
                val folder = recovered.recover(pending.id)
                assertContentEquals(byteArrayOf(1, 2, 3), reopened.readBytesAsync("${folder.path}/Chapter.cbz", 3))
                assertTrue(recovered.pending().isEmpty())
                assertEquals(listOf(folder), settings.db.value.configuredLocalFolders())
            } finally { reopened.close() }
        } finally { selection.close(); files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }

    @Test fun cancelledBrowserPickerRemovesItsInputAndResolvesWithoutRetainingFiles() = runTest {
        assertTrue(cancelPicker().await<JsAny?>().let { pickerCancellationClean() })
    }
}

private fun installPickerFixture(): Unit = js("""(() => {
    const prototype = HTMLInputElement.prototype;
    globalThis.yokanImportFixture = { click: prototype.click, calls: 0, maximum: 0, directory: false };
    prototype.click = function() {
        const state = globalThis.yokanImportFixture;
        state.directory = this.hasAttribute('webkitdirectory');
        const file = new File([new Uint8Array(12 * 1024 * 1024 + 3)], 'Episode 1.mp4');
        Object.defineProperty(file, 'webkitRelativePath', { value: 'Show/Episode 1.mp4' });
        file.arrayBuffer = () => { throw new Error('Whole media reads are forbidden'); };
        const slice = file.slice.bind(file);
        file.slice = (start, end) => { state.calls++; state.maximum = Math.max(state.maximum, end - start); return slice(start, end); };
        const transfer = new DataTransfer(); transfer.items.add(file); this.files = transfer.files;
        this.dispatchEvent(new Event('change'));
    };
})()""")
private fun restorePickerFixture(): Unit = js("HTMLInputElement.prototype.click = globalThis.yokanImportFixture.click")
private fun sliceCalls(): Int = js("globalThis.yokanImportFixture.calls")
private fun largestSlice(): Int = js("globalThis.yokanImportFixture.maximum")
private fun sawDirectoryPicker(): Boolean = js("globalThis.yokanImportFixture.directory")
private fun smallSelection(): JsAny = js("globalThis.yokanBrowserFiles.selectedMedia([new File([new Uint8Array([1,2,3])], 'Chapter.cbz')])")
private fun cancelPicker(): Promise<JsAny?> = js("""(() => {
    const prototype = HTMLInputElement.prototype, original = prototype.click;
    const count = document.querySelectorAll('input[type=file]').length;
    prototype.click = function() {};
    try {
        const picker = globalThis.yokanBrowserFiles.pickMedia(false);
        picker.cancel();
        return picker.result.then(result => {
            globalThis.yokanImportCancelClean = result === null && document.querySelectorAll('input[type=file]').length === count;
            return null;
        });
    } finally { prototype.click = original; }
})()""")
private fun pickerCancellationClean(): Boolean = js("globalThis.yokanImportCancelClean === true")
private fun fetchImagePage(url: String): Promise<JsAny?> = js("""fetch(url).then(async response => {
    const bytes = new Uint8Array(await response.arrayBuffer());
    globalThis.yokanImportImageServed = response.status === 200 && response.headers.get('Content-Type') === 'image/png' &&
        bytes.length === 3 && bytes[0] === 1 && bytes[1] === 2 && bytes[2] === 3;
    return null;
})""")
private fun imagePageServed(): Boolean = js("globalThis.yokanImportImageServed === true")

Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/files/BrowserStorageInteropTest.kt

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

The implementation below defines BrowserStorageInteropTest.

Read the setup, action and assertions in these cases before implementing their production paths:

  • streamedCbzCreationCrossesTheKotlinBoundaryAndPreservesTheArchiveOnReload
  • legacyBackupsRemainListedSizedAndReadable
  • profileDeletionJoinsStorageAndPreservesExplicitBackupExports
  • streamedFilesRoundTripThroughTheKotlinWasmBoundary
  • interruptedWriteKeepsItsPartialBytesAndReleasesWriter

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

package eu.friedcutlet.yokan.services.files

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.app.profiles.deletePlatformProfileStorage
import kotlinx.coroutines.test.runTest
import kotlin.test.*

class BrowserStorageInteropTest {
    @Test fun streamedCbzCreationCrossesTheKotlinBoundaryAndPreservesTheArchiveOnReload() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        val archives = createPlatformLocalArchiveService(id)
        files.prepare()
        val folder = "${files.downloadRoot}/Manga/Test/Title/CBZ"
        val path = "$folder.cbz"
        try {
            files.writeBytesAsync("$folder/0001.jpg", "first page".encodeToByteArray())
            files.writeBytesAsync("$folder/0002.png", "second page".encodeToByteArray())
            files.writeBytesAsync("$folder/metadata.json", "{\"name\":\"CBZ\"}".encodeToByteArray())
            files.writeBytesAsync("$folder/0001.jpg.complete", byteArrayOf())
            assertEquals(path, archives.zipDirectoryToCbzAsync(folder, deleteSource = true))
            assertFalse(files.exists(folder))
            assertTrue(files.exists(path))
            val bytes = files.readBytesAsync(path, 4096)
            assertContentEquals(byteArrayOf(80, 75, 3, 4), bytes.take(4).toByteArray())
            assertTrue(bytes.decodeToString().contains("metadata.json"))
            files.close()
            val reopened = createPlatformLocalFileService(id)
            try {
                reopened.prepare()
                assertContentEquals(bytes, reopened.readBytesAsync(path, 4096))
            } finally { reopened.deleteRecursivelyAsync(path); reopened.close() }
        } finally { files.close(); deletePlatformProfileStorage(id, emptyList()) }
    }
    @Test fun legacyBackupsRemainListedSizedAndReadable() = runTest {
        val files = createPlatformLocalFileService(ProfileId.Default)
        val folder = "${files.backupRoot}/interop-legacy"
        val path = "$folder/saved.json"
        try {
            files.writeBytes(path, "backup".encodeToByteArray())
            assertTrue(files.exists(folder))
            assertEquals(6L, files.directorySize(folder))
            assertEquals(listOf(path), files.listFiles(folder).map { it.path })
            assertContentEquals("backup".encodeToByteArray(), files.readBytes(path))
        } finally { files.deleteRecursivelyAsync(folder); files.close() }
    }

    @Test fun profileDeletionJoinsStorageAndPreservesExplicitBackupExports() = runTest {
        val id = ProfileId.random()
        val files = createPlatformLocalFileService(id)
        files.prepare()
        val path = "${files.downloadRoot}/Manga/Test/Title/Chapter/0001.jpg"
        val exported = "${files.backupRoot}/exported.json"
        files.writeBytesAsync(path, byteArrayOf(1, 2, 3))
        files.writeBytes(exported, "export".encodeToByteArray())
        assertFails { deletePlatformProfileStorage(id, listOf(exported)) }
        files.close()
        deletePlatformProfileStorage(id, listOf(exported))
        val reopened = createPlatformLocalFileService(id)
        try {
            reopened.prepare()
            assertFalse(reopened.exists(path))
            assertTrue(reopened.exists(exported))
            assertContentEquals("export".encodeToByteArray(), reopened.readBytes(exported))
        } finally {
            reopened.deleteRecursivelyAsync(exported)
            reopened.close()
            deletePlatformProfileStorage(id, emptyList())
        }
    }

    @Test fun streamedFilesRoundTripThroughTheKotlinWasmBoundary() = runTest {
        val files = createPlatformLocalFileService(ProfileId.Default)
        files.prepare()
        val folder = "${files.downloadRoot}/Manga/Test/Interop/Chapter"
        val partial = "$folder/0001.jpg.part"
        val final = "$folder/0001.jpg"
        try {
            files.writeChunks(partial) { write -> write("first".encodeToByteArray()); write("-second".encodeToByteArray()) }
            assertEquals(12L, files.directorySize(partial))
            assertTrue(files.promoteAsync(partial, final))
            assertFalse(files.exists(partial))
            assertContentEquals("first-second".encodeToByteArray(), files.readBytesAsync(final, 20))
            files.appendChunks(final) { it("-third".encodeToByteArray()) }
            assertContentEquals("first-second-third".encodeToByteArray(), files.readBytesAsync(final, 20))
            assertFails { files.readBytesAsync(final, 4) }
            files.writeBytesAsync("$folder/0001.jpg.complete", byteArrayOf())
            files.awaitPersistence()
            assertEquals(2, files.listFiles(folder).size)
        } finally {
            assertTrue(files.deleteRecursivelyAsync(folder))
            assertFalse(files.exists(folder))
            files.close()
        }
    }

    @Test fun interruptedWriteKeepsItsPartialBytesAndReleasesWriter() = runTest {
        val files = createPlatformLocalFileService(ProfileId.Default)
        files.prepare()
        val folder = "${files.downloadRoot}/Manga/Test/Interop/Interrupted"
        val path = "$folder/0001.jpg.part"
        try {
            assertFailsWith<IllegalStateException> {
                files.writeChunks(path) { write -> write("partial".encodeToByteArray()); error("Connection interrupted") }
            }
            assertContentEquals("partial".encodeToByteArray(), files.readBytesAsync(path, 20))
            files.appendChunks(path) { it("-resumed".encodeToByteArray()) }
            assertContentEquals("partial-resumed".encodeToByteArray(), files.readBytesAsync(path, 20))
        } finally { files.deleteRecursivelyAsync(folder); files.close() }
    }
}

Write composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/files/WasmLocalFileServiceTest.kt

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

The implementation below defines WasmLocalFileServiceTest, storedSizeMatchesDecodedLengthForEveryPaddingCase.

Read the setup, action and assertions in these cases before implementing their production paths:

  • storedSizeMatchesDecodedLengthForEveryPaddingCase
package eu.friedcutlet.yokan.services.files

import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.test.Test
import kotlin.test.assertEquals

@OptIn(ExperimentalEncodingApi::class)
class WasmLocalFileServiceTest {
    @Test
    fun storedSizeMatchesDecodedLengthForEveryPaddingCase() {
        for (size in 0..9) {
            assertEquals(size.toLong(), base64DecodedSize(Base64.encode(ByteArray(size) { it.toByte() })), "size $size")
        }
    }
}

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: import a loose manga folder, CBZ, EPUB, individual video and season directory; restart; open each offline; rescan after changing progress and metadata. Run archive/path/traversal tests, import visibility, concurrent-scan reconciliation, local season/playback and platform input tests. Browser and iOS file access require platform runs in addition to JVM tests.

Ready to move on?

Check the chapter’s verification gate before marking it complete.

Search chapters, reference and source filenames.