package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
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.LocalEpubChapter
import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.files.LocalFileService
import androidx.compose.ui.text.LinkAnnotation
import eu.friedcutlet.yokan.ui.screens.novel.NovelContentBlock
import eu.friedcutlet.yokan.ui.screens.novel.NovelImageSource
import eu.friedcutlet.yokan.ui.screens.novel.loadNovelDocument
import kotlin.test.assertContentEquals
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.withContext
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
@OptIn(ExperimentalCoroutinesApi::class)
class ProfileReaderContentTest {
@Test fun downloadedEpisodeUsesLocalMediaBeforeAnySourceExtraction() = runTest {
val f = Fixture(this)
try {
f.localFiles = listOf(LocalFileEntry("/A/episode/0001.mp4", "0001.mp4", 500, 0))
val video = f.content.videos(f.source, chapter.copy(archivePath = "/A/episode")).single()
assertEquals("file:///A/episode/0001.mp4", video.url)
assertEquals("Downloaded", video.quality)
assertEquals(0, f.factory.created)
f.fileExists = true
assertEquals("file:///A/movie.mp4", f.content.videos(null, chapter.copy(url = "/A/movie.mp4")).single().url)
} finally { f.close() }
}
@Test fun downloadedNovelHtmlIsReadOfflineWithoutSourceRuntime() = runTest {
val f = Fixture(this)
try {
f.localFiles = listOf(LocalFileEntry("/A/novel/0001.html", "0001.html", 100, 0))
f.localBytes = "
Offline novel chapter
".encodeToByteArray()
val parsed = loadNovelDocument(f.content, f.source, "Novel", chapter.copy(archivePath = "/A/novel")).parse()
assertEquals("Offline novel chapter", parsed.plainText)
assertEquals(0, f.factory.created)
} finally { f.close() }
}
@Test fun remotePagesMergeHeadersAndCacheOnlyInCapturedDatabase() = runTest {
val a = Fixture(this, "A")
val b = Fixture(this, "B")
try {
val pages = a.content.pages(a.source, chapter, false)
assertEquals(mapOf("User-Agent" to "A", "referer" to "page"), pages.single().headers)
assertEquals(listOf("A/page"), a.db.pageCache(10).single().urls)
assertTrue(b.db.pageCache(10).isEmpty())
assertEquals(pages, a.content.pages(a.source, chapter, false))
assertEquals(1, a.factory.created)
assertEquals(1, a.factory.disposed)
a.content.pages(a.source, chapter, true)
assertEquals(2, a.factory.created)
} finally { a.close(); b.close() }
}
@Test fun localArchiveUsesCapturedFilesWithoutAllocatingRuntime() = runTest {
val f = Fixture(this, "A")
try {
f.archivePages = listOf(DbPageUrl("file://A/local/1.jpg"))
val local = chapter.copy(archivePath = "/A/local/book.cbz#chapter")
assertEquals(f.archivePages, f.content.pages(f.source, local, false))
assertEquals(listOf("/A/local/book.cbz"), f.archivePaths)
assertEquals(0, f.factory.created)
assertTrue(f.db.pageCache(10).isEmpty())
} finally { f.close() }
}
@Test fun localImageAndContentUriKeepTheirOriginalAddress() = runTest {
val f = Fixture(this)
try {
f.fileExists = true
for ((path, expected) in listOf("/local/page.png" to "file:///local/page.png",
"content://books/page.png" to "content://books/page.png")) {
val pages = f.content.pages(null, chapter.copy(url = path), false)
assertEquals(expected, pages.single().url)
assertEquals("page.png", pages.single().fileName)
}
assertEquals(0, f.factory.created)
} finally { f.close() }
}
@Test fun headerFailurePreservesOfflineFallback() = runTest {
val f = Fixture(this)
try {
f.factory.headerAction = { error("Runtime unavailable") }
assertEquals(mapOf("User-Agent" to f.db.settings().userAgent), f.content.headers(f.source))
assertEquals(1, f.factory.disposed)
} finally { f.close() }
}
@Test fun episodeFailureDoesNotFabricateAStreamFromTheChapterUrl() = runTest {
val f = Fixture(this)
try {
f.factory.videoAction = { error("Extraction failed") }
assertFailsWith { f.content.videos(f.source, chapter) }
assertEquals(1, f.factory.disposed)
assertEquals("https://cdn.test/movie", f.content.videos(null, chapter.copy(url = "//cdn.test/movie")).single().url)
assertTrue(f.content.videos(null, chapter.copy(url = "/episode.html")).isEmpty())
} finally { f.close() }
}
@Test fun novelExtractionRetainsCleanedMarkupAndUsesCapturedRuntime() = runTest {
val f = Fixture(this, "A")
try {
assertEquals("A novel
", f.content.novelText(f.source, "Novel", chapter.url))
assertEquals(1, f.factory.cleaned)
assertEquals(1, f.factory.disposed)
assertEquals("inline text", f.content.novelText(null, "Novel", "inline text"))
assertEquals(1, f.factory.created)
} finally { f.close() }
}
@Test fun ownerCancellationDiscardsNonCancellablePageResultAndCache() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred()
val release = CompletableDeferred()
f.factory.pageAction = {
withContext(NonCancellable) { entered.complete(Unit); release.await() }
listOf(DbPageUrl("late"))
}
val request = async { f.content.pages(f.source, chapter, true) }
entered.await()
f.owner.cancel()
assertFalse(request.isCompleted)
release.complete(Unit)
assertFailsWith { request.await() }
f.close()
assertTrue(f.db.pageCache(10).isEmpty())
assertEquals(1, f.factory.disposed)
}
@Test fun retirementAdmissionDiscardsLatePagesEvenBeforeOwnerJobCancellation() = runTest {
val f = Fixture(this)
f.factory.pageAction = { f.open = false; listOf(DbPageUrl("late")) }
try {
assertFailsWith { f.content.pages(f.source, chapter, true) }
assertTrue(f.db.pageCache(10).isEmpty())
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun retirementDuringRuntimeFinalizationPreventsPageCacheWrite() = runTest {
val f = Fixture(this)
f.factory.finalizer = { f.open = false }
try {
assertFailsWith { f.content.pages(f.source, chapter, true) }
assertTrue(f.db.pageCache(10).isEmpty())
assertEquals(1, f.factory.disposed)
} finally { f.close() }
}
@Test fun lateHeadersCannotStartAnotherExtractionAfterCancellation() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred()
val release = CompletableDeferred()
var pageCalls = 0
f.factory.headerAction = {
withContext(NonCancellable) { entered.complete(Unit); release.await() }
emptyMap()
}
f.factory.pageAction = { pageCalls++; listOf(DbPageUrl("late")) }
val request = async { f.content.pages(f.source, chapter, true) }
entered.await(); f.owner.cancel(); release.complete(Unit)
assertFailsWith { request.await() }
f.close()
assertEquals(0, pageCalls)
assertTrue(f.db.pageCache(10).isEmpty())
assertEquals(1, f.factory.disposed)
}
@Test fun lateNovelHtmlCannotStartCleanupAfterCallerCancellation() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred()
val release = CompletableDeferred()
f.factory.htmlAction = {
withContext(NonCancellable) { entered.complete(Unit); release.await() }
"late"
}
val request = async { f.content.novelText(f.source, "Novel", chapter.url) }
entered.await(); request.cancel()
runCurrent()
assertFalse(request.isCompleted, "caller waits for its owned extraction")
release.complete(Unit)
request.join()
assertEquals(0, f.factory.cleaned)
assertEquals(1, f.factory.disposed)
assertTrue(f.owner.isActive)
f.close()
}
@Test fun callerCancellationJoinsRuntimeFinalizerAndLeavesOtherRequestsUsable() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred()
val finalizing = CompletableDeferred()
val release = CompletableDeferred()
f.factory.videoAction = { entered.complete(Unit); awaitCancellation() }
f.factory.finalizer = { finalizing.complete(Unit); release.await() }
val request = async { f.content.videos(f.source, chapter) }
entered.await(); request.cancel(); finalizing.await()
assertFalse(request.isCompleted)
release.complete(Unit); request.join()
assertEquals(1, f.factory.disposed)
f.factory.finalizer = {}
assertEquals(mapOf("User-Agent" to "A", "Referer" to "source"), f.content.headers(f.source))
assertTrue(f.owner.isActive)
f.close()
}
@Test fun closeJoinsRuntimeCleanupRejectsRetainedRequestsAndPreservesParent() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred()
val finalizing = CompletableDeferred()
val release = CompletableDeferred()
f.factory.videoAction = { entered.complete(Unit); awaitCancellation() }
f.factory.finalizer = { finalizing.complete(Unit); release.await() }
val request = async { f.content.videos(f.source, chapter) }
entered.await()
val closing = async { f.content.closeAndJoin() }
finalizing.await()
assertFalse(closing.isCompleted)
release.complete(Unit); closing.await()
assertFailsWith { request.await() }
assertTrue(f.owner.isActive)
assertFailsWith { f.content.pages(null, chapter, false) }
assertFailsWith { f.content.headers(f.source) }
assertFailsWith { f.content.videos(null, chapter) }
assertFailsWith { f.content.novelText(null, "Novel", "inline") }
assertEquals(1, f.factory.created)
assertTrue(f.archivePaths.isEmpty())
f.close()
}
@Test fun localNovelParsesCapturedChapterAndEmbeddedImagesWithoutExtension() = runTest {
val f = Fixture(this)
val other = Fixture(this, "B")
try {
f.epubChapters = listOf(LocalEpubChapter("First", "OEBPS/first.xhtml"), LocalEpubChapter("Second", "OEBPS/Text/second.xhtml"))
f.epubHtml = "Second
Next
"
f.epubResources["OEBPS/Images/cover art.png"] = byteArrayOf(1, 2, 3)
val opened = mutableListOf()
val parsed = loadNovelDocument(f.content, f.source, "Book", localNovel).parse(opened::add)
assertEquals("Second", assertIs(parsed.blocks[0]).text.text)
val paragraph = assertIs(parsed.blocks[1]).text
val link = assertIs(paragraph.getLinkAnnotations(0, paragraph.length).single().item)
link.linkInteractionListener?.onClick(link)
assertEquals(listOf("https://book.test/next"), opened)
assertContentEquals(byteArrayOf(1, 2, 3), assertIs(assertIs(parsed.blocks[2]).source).bytes)
assertEquals(listOf("/A/book.epub" to 1), f.epubChapterReads)
assertEquals(listOf("/A/book.epub" to "OEBPS/Images/cover art.png"), f.epubResourceReads)
assertEquals(0, f.factory.created)
assertTrue(other.epubChapterReads.isEmpty())
assertTrue(other.epubResourceReads.isEmpty())
} finally { f.close(); other.close() }
}
@Test fun blankLocalChapterFallsBackToRemoteMarkupWithItsLocalResources() = runTest {
val f = Fixture(this)
try {
f.epubHtml = " "
f.factory.htmlAction = { "Remote
" }
f.epubResources["OEBPS/Images/cover.png"] = byteArrayOf(4)
val parsed = loadNovelDocument(f.content, f.source, "Book", localNovel).parse()
assertEquals("Remote", assertIs(parsed.blocks[0]).text.text)
assertContentEquals(byteArrayOf(4), assertIs(assertIs(parsed.blocks[1]).source).bytes)
assertEquals(1, f.factory.created)
assertEquals(1, f.factory.disposed)
} finally { f.close() }
}
@Test fun malformedEpubIndexDefaultsToZeroAndMissingHrefDoesNotReadImages() = runTest {
val f = Fixture(this)
try {
f.epubChapters = emptyList()
f.epubHtml = "Local
"
val parsed = loadNovelDocument(f.content, f.source, "Book", localNovel.copy(archivePath = "/A/book.EPUB#bad")).parse()
assertEquals(listOf("/A/book.EPUB" to 0), f.epubChapterReads)
assertIs(assertIs(parsed.blocks[1]).source)
assertTrue(f.epubResourceReads.isEmpty())
} finally { f.close() }
}
@Test fun embeddedResourceCapabilityExpiresAfterParsingEvenWithALiveOwner() = runTest {
val f = Fixture(this)
try {
var retained: ProfileNovelContent? = null
f.content.novelContent(f.source, "Book", localNovel) { retained = it }
assertFailsWith { assertNotNull(retained).readEmbeddedResource("cover.png") }
assertTrue(f.epubResourceReads.isEmpty())
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun cancellationDuringEpubInventoryPreventsChapterReadAndParsing() = runTest {
val f = Fixture(this)
var parsed = false
f.beforeEpubInventory = { f.owner.cancel() }
try {
assertFailsWith {
f.content.novelContent(f.source, "Book", localNovel) { parsed = true }
}
assertTrue(f.epubChapterReads.isEmpty())
assertEquals(0, f.factory.created)
assertFalse(parsed)
} finally { f.close() }
}
@Test fun retirementDuringEpubReadPreventsFallbackAndParsing() = runTest {
val f = Fixture(this)
var parsed = false
f.epubHtml = ""
f.beforeEpubChapterRead = { f.open = false }
try {
assertFailsWith {
f.content.novelContent(f.source, "Book", localNovel) { parsed = true }
}
assertEquals(0, f.factory.created)
assertFalse(parsed)
} finally { f.close() }
}
@Test fun archiveFailureAfterRetirementIsCancellationAndCannotStartUiFallback() = runTest {
val f = Fixture(this)
f.beforeEpubChapterRead = { f.open = false; error("Archive failed after retirement") }
var fallback = false
try {
assertFailsWith {
eu.friedcutlet.yokan.services.catchingNonCancellation {
loadNovelDocument(f.content, f.source, "Book", localNovel)
}.getOrElse { fallback = true; throw it }
}
assertFalse(fallback)
assertEquals(0, f.factory.created)
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun retirementDuringEmbeddedImageReadRejectsTheEntireParsedResult() = runTest {
val f = Fixture(this)
f.epubHtml = "
"
f.beforeEpubResourceRead = { f.open = false }
try {
assertFailsWith { loadNovelDocument(f.content, f.source, "Book", localNovel) }
assertEquals(1, f.epubResourceReads.size)
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun parserFailurePreservesTheContentServiceAndParent() = runTest {
val f = Fixture(this)
try {
assertFailsWith {
f.content.novelContent(f.source, "Book", localNovel) { throw IllegalArgumentException("Malformed content") }
}
assertEquals("A epub", loadNovelDocument(f.content, f.source, "Book", localNovel).parse().plainText)
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun retiredContentCannotReadAnEpubOrStartParsing() = runTest {
val f = Fixture(this)
try {
f.content.closeAndJoin()
assertFailsWith {
f.content.novelContent(f.source, "Book", localNovel) { error("Retired parser") }
}
assertTrue(f.epubInventoryPaths.isEmpty())
assertTrue(f.epubChapterReads.isEmpty())
assertTrue(f.epubResourceReads.isEmpty())
} finally { f.close() }
}
internal class Fixture(
test: TestScope,
label: String = "A",
fileDispatcher: CoroutineDispatcher = StandardTestDispatcher(test.testScheduler),
) {
val owner = SupervisorJob()
val scope = CoroutineScope(owner + StandardTestDispatcher(test.testScheduler))
val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
sources = listOf(DbSource(id = 7, name = label, version = "1", isAdded = true)),
mangas = listOf(DbManga(id = 1, sourceId = 7)),
chapters = listOf(DbChapter(id = 10, mangaId = 1, url = "/chapter")),
pageCache = emptyList(),
))
val repository = DefaultYokanRepository(db)
val source = requireNotNull(repository.source(7))
val factory = RuntimeFactory(db, label)
var open = true
var archivePages = emptyList()
val archivePaths = mutableListOf()
var fileExists = false
var localFiles = emptyList()
var localBytes = byteArrayOf()
var epubChapters = listOf(LocalEpubChapter("Chapter", "OEBPS/Text/chapter.xhtml"), LocalEpubChapter("Next", "OEBPS/Text/next.xhtml"))
var epubHtml = "$label epub
"
val epubResources = mutableMapOf()
val epubInventoryPaths = mutableListOf()
val epubChapterReads = mutableListOf>()
val epubResourceReads = mutableListOf>()
var beforeEpubInventory: () -> Unit = {}
var beforeEpubChapterRead: () -> Unit = {}
var beforeEpubResourceRead: () -> Unit = {}
val files = object : LocalFileService {
override val downloadRoot = "/$label/downloads"
override val backupRoot = "/$label/backups"
override val cacheRoot = "/$label/cache"
override fun writeBytes(path: String, bytes: ByteArray) = error("Unexpected write")
override fun readBytes(path: String): ByteArray = error("Unexpected read")
override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray = localBytes
override fun canonicalPath(path: String) = path
override fun exists(path: String) = fileExists
override fun deleteRecursively(path: String) = error("Unexpected delete")
override fun directorySize(path: String) = 0L
override fun openLocation(path: String) = false
override fun listLocalEntries(root: String) = emptyList()
override fun listFiles(root: String) = localFiles
}
val archives = object : LocalArchiveService {
override fun listPages(archivePath: String): List {
archivePaths += archivePath
return archivePages
}
override fun listEpubChapters(archivePath: String): List {
epubInventoryPaths += archivePath
beforeEpubInventory()
return epubChapters
}
override fun readEpubChapter(archivePath: String, index: Int): String {
epubChapterReads += archivePath to index
beforeEpubChapterRead()
return epubHtml
}
override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? {
epubResourceReads += archivePath to resourcePath
beforeEpubResourceRead()
return epubResources[resourcePath]
}
override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? = null
}
val content = ProfileReaderContent(
ProfileId.Default, db, factory, ChapterPageResolver(repository, db, factory),
files, archives, scope, fileDispatcher, { open },
)
suspend fun close() { content.closeAndJoin(); owner.cancelAndJoin() }
}
internal class RuntimeFactory(val db: YokanDatabase, label: String) : ExtensionRuntimeFactory {
var created = 0
var disposed = 0
var cleaned = 0
var headerAction: suspend () -> Map = { mapOf("User-Agent" to label, "Referer" to "source") }
var pageAction: suspend () -> List = { listOf(DbPageUrl("$label/page", headers = mapOf("referer" to "page"))) }
var videoAction: suspend () -> List = { listOf(DbVideo(url = "$label/video", quality = "Auto", originalUrl = "$label/video")) }
var htmlAction: suspend () -> String = { "$label novel
" }
var finalizer: suspend () -> Unit = {}
override fun create(source: DbSource): ExtensionRuntimeService {
created++
return object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, db) {
override fun dispose() { disposed++ }
override suspend fun headers() = headerAction()
override suspend fun pageList(url: String) = pageAction()
override suspend fun videoList(url: String) = videoAction()
override suspend fun htmlContent(name: String, url: String) = htmlAction()
override suspend fun cleanHtmlContent(html: String): String { cleaned++; return html }
}
}
override suspend fun withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T {
val runtime = create(source)
try { return block(runtime) }
finally { withContext(NonCancellable) { try { finalizer() } finally { runtime.dispose() } } }
}
}
private companion object {
val chapter = Chapter(id = 10, mangaId = 1, name = "Chapter", url = "/chapter")
val localNovel = chapter.copy(archivePath = "/A/book.epub#1")
}
}