Yokan / rebuild
Course 1 8624561

SourceCatalogServiceTest.kt

composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/SourceCatalogServiceTest.kt

test / fixture257 lines
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbSourceCodeLanguage5import eu.friedcutlet.yokan.domain.Manga6import eu.friedcutlet.yokan.services.files.LocalEntry7import eu.friedcutlet.yokan.services.files.LocalFileEntry8import eu.friedcutlet.yokan.services.files.LocalFileService9import eu.friedcutlet.yokan.services.http.HttpRequest10import eu.friedcutlet.yokan.services.http.HttpResponse11import eu.friedcutlet.yokan.services.http.HttpService12import kotlin.test.Test13import kotlin.test.assertEquals14import kotlin.test.assertNotNull15import kotlin.test.assertNull16import kotlin.test.assertTrue17import kotlinx.coroutines.test.runTest1819class SourceCatalogServiceTest {20    @Test21    fun resolvesAndFetchesPublishedAssetsFromHttpIndex() = runTest {22        val repoUrl = "https://example.test/repos/yokan/index.json"23        val sourceUrl = "https://example.test/repos/yokan/sources/manga/mangadex/source.js"24        val service = HttpSourceCatalogService(25            MapHttpService(26                mapOf(27                    repoUrl to RepositoryIndex.encodeToByteArray(),28                    sourceUrl to ExtensionSource.encodeToByteArray(),29                ),30            ),31        )3233        val source = assertNotNull(service.fetchSources(repoUrl, DbItemType.Manga).singleOrNull())3435        assertEquals(sourceUrl, source.sourceCodeUrl)36        assertEquals("https://example.test/icons/mangadex.png", source.iconUrl)37        assertEquals(DbItemType.Manga, source.itemType)38        assertEquals(ExtensionSource, service.fetchSourcePayload(source)?.decodeToString())39    }4041    @Test42    fun resolvesQueryFragmentAndDotSegments() = runTest {43        val repoUrl = "https://example.test/repos/yokan/indexes/index.json?token=secret#catalog"44        val service = HttpSourceCatalogService(45            MapHttpService(mapOf(repoUrl to RelativeReferenceIndex.encodeToByteArray())),46        )4748        val source = assertNotNull(service.fetchSources(repoUrl, DbItemType.Manga).singleOrNull())4950        assertEquals("https://example.test/repos/yokan/payloads/mangadex.js?raw=1", source.sourceCodeUrl)51        assertEquals("https://example.test/repos/yokan/indexes/icons/mangadex.png#icon", source.iconUrl)52    }5354    @Test55    fun loadsIndexAndPayloadThroughFileTransport() = runTest {56        val repoUrl = "file:///tmp/yokan-sauces/build/repository/manga_index.json"57        val sourceUrl = "file:///tmp/yokan-sauces/build/repository/sources/manga/mangadex/source.js"58        val files = MapLocalFileService(59            mapOf(60                repoUrl to RepositoryIndex.encodeToByteArray(),61                sourceUrl to ExtensionSource.encodeToByteArray(),62            ),63        )64        val service = HttpSourceCatalogService(MapHttpService(emptyMap()), files)6566        val source = assertNotNull(service.fetchSources(repoUrl, DbItemType.Manga).singleOrNull())6768        assertEquals(sourceUrl, source.sourceCodeUrl)69        assertEquals("file:///icons/mangadex.png", source.iconUrl)70        assertEquals(ExtensionSource, service.fetchSourcePayload(source)?.decodeToString())71    }7273    @Test74    fun officialLnReaderCatalogSelectsNovelRuntime() = runTest {75        val repoUrl = "https://example.test/plugins.min.json"76        val payloadUrl = "https://example.test/novelupdates.js"77        val index = """[{78            "id":"novelupdates", "name":"Novel Updates", "site":"https://www.novelupdates.com/",79            "lang":"English", "version":"0.9.9", "url":"$payloadUrl", "iconUrl":"https://example.test/icon.png"80        }]"""81        val service = HttpSourceCatalogService(MapHttpService(mapOf(82            repoUrl to index.encodeToByteArray(), payloadUrl to "exports.default = {};".encodeToByteArray(),83        )))84        val source = service.fetchSources(repoUrl, DbItemType.Novel).single()85        assertEquals(DbSourceCodeLanguage.LnReader, source.sourceCodeLanguage)86        assertEquals("en", source.lang)87        assertEquals("exports.default = {};", service.fetchSourcePayload(source)?.decodeToString())88    }8990    @Test91    fun mihonEntriesKeepUpstreamSourceIds() = runTest {92        val repoUrl = "https://example.test/repos/mihon/index.min.json"93        val service = HttpSourceCatalogService(94            MapHttpService(mapOf(repoUrl to MihonRepositoryIndex.encodeToByteArray())),95        )9697        val sources = service.fetchSources(repoUrl, DbItemType.Anime)9899        assertEquals(2, sources.size)100        assertEquals(101            listOf(102                """{"sourceId":"4864082317433034574"}""",103                """{"sourceId":"8842237058298566885"}""",104            ),105            sources.map { it.additionalParams },106        )107        assertEquals(sources.size, sources.map { it.id }.toSet().size)108    }109110    @Test111    fun readsGzipProtobufRepository() = runTest {112        val repoUrl = "https://example.test/repos/yokan/index.pb?token=secret#catalog"113        val service = HttpSourceCatalogService(114            MapHttpService(mapOf(repoUrl to ProtobufRepositoryIndex)),115        )116117        val source = assertNotNull(service.fetchSources(repoUrl, DbItemType.Manga).singleOrNull())118119        assertEquals("PB Source", source.name)120        assertEquals("https://example.test/pb", source.baseUrl)121        assertEquals("en", source.lang)122        assertEquals(12345L, source.id)123        assertEquals("""{"sourceId":"12345"}""", source.additionalParams)124        assertEquals("https://example.test/repos/yokan/payload.apk", source.sourceCodeUrl)125        assertEquals("https://example.test/repos/yokan/icons/pb.png", source.iconUrl)126        assertEquals("1.2.3", source.version)127        assertTrue(source.isNsfw)128        assertEquals(DbItemType.Manga, source.itemType)129        assertEquals(DbSourceCodeLanguage.Mihon, source.sourceCodeLanguage)130        assertTrue(service.validateRepository(repoUrl))131    }132133    @Test134    fun rejectsEmptyAndBlankPayloads() = runTest {135        val httpRepoUrl = "https://example.test/repos/yokan/index.json"136        val httpSourceUrl = "https://example.test/repos/yokan/sources/manga/mangadex/source.js"137        val httpService = HttpSourceCatalogService(138            MapHttpService(139                mapOf(140                    httpRepoUrl to RepositoryIndex.encodeToByteArray(),141                    httpSourceUrl to "   ".encodeToByteArray(),142                ),143            ),144        )145        val httpSource = assertNotNull(httpService.fetchSources(httpRepoUrl, DbItemType.Manga).singleOrNull())146        assertNull(httpService.fetchSourcePayload(httpSource))147148        val fileRepoUrl = "file:///tmp/yokan-sauces/build/repository/index.json"149        val fileSourceUrl = "file:///tmp/yokan-sauces/build/repository/sources/manga/mangadex/source.js"150        val fileService = HttpSourceCatalogService(151            MapHttpService(emptyMap()),152            MapLocalFileService(153                mapOf(154                    fileRepoUrl to RepositoryIndex.encodeToByteArray(),155                    fileSourceUrl to ByteArray(0),156                ),157            ),158        )159        val fileSource = assertNotNull(fileService.fetchSources(fileRepoUrl, DbItemType.Manga).singleOrNull())160        assertNull(fileService.fetchSourcePayload(fileSource))161    }162}163164private class MapHttpService(165    private val responses: Map<String, ByteArray>,166) : HttpService {167    override suspend fun request(request: HttpRequest): HttpResponse {168        val bytes = responses[request.url]169            ?: return HttpResponse(statusCode = 404, body = "")170        return HttpResponse(statusCode = 200, body = bytes.decodeToString(), bodyBytes = bytes)171    }172}173174private class MapLocalFileService(175    private val files: Map<String, ByteArray>,176) : LocalFileService {177    override val downloadRoot: String = ""178    override val backupRoot: String = ""179    override val cacheRoot: String = ""180181    override fun writeBytes(path: String, bytes: ByteArray) = error("Read-only fixture")182    override fun readBytes(path: String): ByteArray = files[path] ?: ByteArray(0)183    override fun canonicalPath(path: String): String = path.removePrefix("file://")184    override fun exists(path: String): Boolean = path in files185    override fun deleteRecursively(path: String): Boolean = false186    override fun directorySize(path: String): Long = 0L187    override fun openLocation(path: String): Boolean = false188    override fun listLocalEntries(root: String): List<LocalEntry>? = emptyList()189    override fun listFiles(root: String): List<LocalFileEntry> = emptyList()190}191192private const val RepositoryIndex = """193    [194      {195        "id": 810342358,196        "name": "MangaDex",197        "baseUrl": "https://mangadex.org",198        "lang": "en",199        "itemType": "Manga",200        "sourceCodeLanguage": "JavaScript",201        "sourceCodeUrl": "sources/manga/mangadex/source.js",202        "iconUrl": "/icons/mangadex.png",203        "version": "0.3.0"204      },205      {206        "id": 920451267,207        "name": "AnimePahe",208        "baseUrl": "https://animepahe.pw",209        "lang": "en",210        "itemType": "Anime",211        "sourceCodeLanguage": "JavaScript",212        "sourceCodeUrl": "sources/anime/animepahe/source.js",213        "version": "0.3.0"214      }215    ]216"""217218private const val RelativeReferenceIndex = """219    [220      {221        "id": 810342358,222        "name": "MangaDex",223        "baseUrl": "https://mangadex.org",224        "lang": "en",225        "itemType": "Manga",226        "sourceCodeLanguage": "JavaScript",227        "sourceCodeUrl": "../payloads/./mangadex.js?raw=1",228        "iconUrl": "./icons/../icons/mangadex.png#icon",229        "version": "0.3.0"230      }231    ]232"""233234private const val ExtensionSource = "class DefaultExtension extends MProvider {}"235236private const val MihonRepositoryIndex = """237    [238      {239        "name": "Aniyomi: MyReadingManga",240        "pkg": "eu.kanade.tachiyomi.animeextension.all.myreadingmanga",241        "apk": "aniyomi-all.myreadingmanga-v14.2.apk",242        "lang": "all",243        "code": 2,244        "version": "14.2",245        "nsfw": 1,246        "sources": [247          {"name": "MyReadingManga", "lang": "ar", "id": "4864082317433034574", "baseUrl": "https://myreadingmanga.info"},248          {"name": "MyReadingManga", "lang": "id", "id": "8842237058298566885", "baseUrl": "https://myreadingmanga.info"}249        ]250      }251    ]252"""253254private val ProtobufRepositoryIndex =255    "1f8b08000000000002ff5bc556cf55cbc513e0a4e05a51929a579c999f27c4955aaa57925a5ca2579024a5c9c55d905899939f98a29758902dc493999c9f57ac5f90a4579097be4a1e2e979558a4a165c46aa867a4676cc1eca4cdb1334188136868707e695172aa14536a9e927846494941b195be7e6a45626e414e2ad80aa0490026f04bc782000000".hexBytes()256257private fun String.hexBytes(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray()258

Search chapters, reference and source filenames.