package eu.friedcutlet.yokan.services.backup import eu.friedcutlet.yokan.database.DbCategory 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.DbSource import eu.friedcutlet.yokan.database.DbStatus import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackStatus import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import eu.friedcutlet.yokan.database.seedDatabaseSnapshot import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue import kotlinx.coroutines.test.runTest class TachiyomiBackupEncoderTest { /** Marks "gzip" with the magic bytes so the decoder's sniffing path is exercised on every target. */ private object FakeGzip : BackupCompression { override fun compress(data: ByteArray, level: Int): ByteArray = byteArrayOf(0x1F, 0x8B.toByte()) + data override fun decompress(data: ByteArray): ByteArray = data.copyOfRange(2, data.size) } private val mangaDexId = 2499283573021220255L private fun library(): YokanDatabaseSnapshot = seedDatabaseSnapshot().copy( sources = listOf( DbSource(id = mangaDexId, name = "MangaDex", itemType = DbItemType.Manga), DbSource(id = 77, name = "AniSrc", itemType = DbItemType.Anime), ), categories = listOf( DbCategory(id = 10, name = "Reading", forItemType = DbItemType.Manga, position = 0), DbCategory(id = 11, name = "Later", forItemType = DbItemType.Manga, position = 1), DbCategory(id = 20, name = "Watching", forItemType = DbItemType.Anime, position = 0), ), mangas = listOf( DbManga( id = 1, name = "Solo Leveling", link = "/manga/solo", imageUrl = "https://img/solo.jpg", description = "Hunters.", author = "Chugong", artist = "Dubu", status = DbStatus.Completed, itemType = DbItemType.Manga, genre = listOf("Action", "Fantasy"), favorite = true, source = "MangaDex", sourceId = mangaDexId, dateAdded = 1_700_000_000_000, lastUpdate = 1_710_000_000_000, categories = listOf(11L), ), DbManga(id = 4, name = "History only", link = "/manga/h", favorite = false, source = "MangaDex", sourceId = mangaDexId), DbManga( id = 2, name = "Frieren", link = "/anime/frieren", status = DbStatus.Ongoing, itemType = DbItemType.Anime, favorite = true, source = "AniSrc", sourceId = 77, categories = listOf(20L), ), DbManga(id = 3, name = "Novel X", itemType = DbItemType.Novel, favorite = true, source = "NovSrc"), ), chapters = listOf( DbChapter( id = 100, mangaId = 1, name = "Chapter 1", url = "/c1", dateUpload = "1600000000000", isRead = true, lastPageRead = "1", number = 1.0, updatedAt = 1_650_000_000_000, ), DbChapter(id = 101, mangaId = 1, name = "Chapter 2", url = "/c2", isBookmarked = true, lastPageRead = "18", number = 2.5), DbChapter( id = 200, mangaId = 2, name = "Episode 1", url = "/e1", isRead = true, lastPageRead = "1440000", fillerOverride = true, description = "Intro", ), DbChapter(id = 300, mangaId = 3, name = "Novel chapter", url = "/n1"), ), histories = listOf( DbHistory(id = 1, mangaId = 1, chapterId = 101, itemType = DbItemType.Manga, date = "1700000123000", readingTimeSeconds = 90), DbHistory(id = 2, mangaId = 2, chapterId = 200, itemType = DbItemType.Anime, date = "1700000456000"), ), tracks = listOf( DbTrack( id = 1, mediaId = 151807, mangaId = 1, syncId = 2, title = "Solo", lastChapterRead = 2, totalChapter = 200, score = 85, status = DbTrackStatus.ReReading, trackingUrl = "https://anilist.co/manga/151807", ), DbTrack(id = 2, mediaId = 52991, mangaId = 2, syncId = 1, lastChapterRead = 1, status = DbTrackStatus.Watching, itemType = DbItemType.Anime), DbTrack(id = 3, mangaId = 1, syncId = 6, status = DbTrackStatus.Reading), // metadata pseudo-tracker: no upstream id ), ) @Test fun gzippedExportRoundTripsThroughTheDecoder() = runTest { val export = BackupExporter(FakeGzip).export(library(), BackupOptions(format = BackupFormat.Tachiyomi)) assertTrue(export.fileName.endsWith(".tachibk"), export.fileName) assertTrue(export.compressed) assertEquals("application/octet-stream", export.contentType) val snapshot = BackupDecoder(FakeGzip).decode(export.bytes).snapshot assertEquals(listOf("Solo Leveling", "History only", "Frieren"), snapshot.mangas.map { it.name }) val solo = snapshot.mangas.first { it.name == "Solo Leveling" } assertEquals("MangaDex", solo.source) assertEquals("/manga/solo", solo.link) assertEquals(DbStatus.Completed, solo.status) assertEquals(listOf("Action", "Fantasy"), solo.genre) assertEquals("Chugong", solo.author) assertEquals("Dubu", solo.artist) assertEquals(1_700_000_000_000, solo.dateAdded) assertEquals(1_710_000_000_000, solo.lastUpdate) assertTrue(solo.favorite) assertFalse(snapshot.mangas.first { it.name == "History only" }.favorite) val frieren = snapshot.mangas.first { it.name == "Frieren" } assertEquals(DbItemType.Anime, frieren.itemType) assertEquals("AniSrc", frieren.source) val categoryById = snapshot.categories.associateBy { it.id } assertEquals(listOf("Reading", "Later"), snapshot.categories.filter { it.forItemType == DbItemType.Manga }.map { it.name }) assertEquals(listOf("Later"), solo.categories.orEmpty().map { categoryById.getValue(it).name }) assertEquals(listOf("Watching"), frieren.categories.orEmpty().map { categoryById.getValue(it).name }) assertEquals(DbItemType.Anime, categoryById.getValue(frieren.categories!!.single()).forItemType) val chapters = snapshot.chapters.associateBy { it.url } assertEquals(setOf("/c1", "/c2", "/e1"), chapters.keys) chapters.getValue("/c1").let { assertTrue(it.isRead) assertEquals("1", it.lastPageRead) assertEquals("1600000000000", it.dateUpload) assertEquals(1.0, it.number) } chapters.getValue("/c2").let { assertTrue(it.isBookmarked) assertFalse(it.isRead) assertEquals("18", it.lastPageRead) assertEquals(2.5, it.number) } chapters.getValue("/e1").let { assertTrue(it.isRead) assertEquals("1440000", it.lastPageRead) assertTrue(it.isFiller) assertEquals("Intro", it.description) assertEquals(frieren.id, it.mangaId) } val histories = snapshot.histories.associateBy { it.mangaId } histories.getValue(solo.id).let { assertEquals(chapters.getValue("/c2").id, it.chapterId) assertEquals("1700000123000", it.date) assertEquals(90, it.readingTimeSeconds) } histories.getValue(frieren.id).let { assertEquals(chapters.getValue("/e1").id, it.chapterId) assertEquals("1700000456000", it.date) assertEquals(DbItemType.Anime, it.itemType) } assertEquals(2, snapshot.tracks.size) snapshot.tracks.single { it.mangaId == solo.id }.let { assertEquals(2, it.syncId) assertEquals(151807L, it.mediaId) assertEquals(DbTrackStatus.ReReading, it.status) assertEquals(85, it.score) assertEquals(2, it.lastChapterRead) assertEquals(200, it.totalChapter) assertEquals("https://anilist.co/manga/151807", it.trackingUrl) assertNull(it.libraryId) } snapshot.tracks.single { it.mangaId == frieren.id }.let { assertEquals(1, it.syncId) assertEquals(52991L, it.mediaId) assertEquals(DbTrackStatus.Watching, it.status) assertEquals(DbItemType.Anime, it.itemType) } } @Test fun compressionLevelZeroWritesRawProtobufThatStillDecodes() = runTest { val export = BackupExporter(FakeGzip).export(library(), BackupOptions(format = BackupFormat.Tachiyomi, compressionLevel = 0)) assertTrue(export.fileName.endsWith(".proto"), export.fileName) assertFalse(export.compressed) assertFalse(FakeGzip.looksGzipped(export.bytes)) val snapshot = BackupDecoder(FakeGzip).decode(export.bytes).snapshot assertEquals(listOf("Solo Leveling", "History only", "Frieren"), snapshot.mangas.map { it.name }) assertEquals(3, snapshot.chapters.size) } @Test fun fieldNumbersFollowAnimetailBackupModels() { val raw = BackupExporter(FakeGzip).export(library(), BackupOptions(format = BackupFormat.Tachiyomi, compressionLevel = 0)).bytes val top = fields(raw) // Backup: 1 manga, 2 categories, 101 sources, 500 isLegacy=false, 501-503 anime; never the legacy 3/4/103. assertEquals(2, top.all(1).size) assertTrue(top.all(1).all { it.wire == 2 }) assertEquals(2, top.all(2).size) assertEquals(1, top.all(101).size) top.one(500).let { assertEquals(0, it.wire); assertEquals(0L, it.varint) } assertEquals(1, top.all(501).size) assertEquals(1, top.all(502).size) assertEquals(1, top.all(503).size) assertTrue(top.all(3).isEmpty() && top.all(4).isEmpty() && top.all(103).isEmpty()) assertFalse(raw.decodeToString().contains("Novel"), "novels have no Tachiyomi model") // BackupManga val solo = fields(top.all(1)[0].bytes) assertEquals(mangaDexId, solo.one(1).varint) assertEquals("/manga/solo", solo.one(2).text) assertEquals("Solo Leveling", solo.one(3).text) assertEquals("Dubu", solo.one(4).text) assertEquals("Chugong", solo.one(5).text) assertEquals("Hunters.", solo.one(6).text) assertEquals(listOf("Action", "Fantasy"), solo.all(7).map { it.text }) assertEquals(2L, solo.one(8).varint) // SManga.COMPLETED assertEquals("https://img/solo.jpg", solo.one(9).text) assertEquals(1_700_000_000_000, solo.one(13).varint) // millis assertEquals(2, solo.all(16).size) solo.all(17).let { orders -> assertEquals(listOf(1L), orders.map { it.varint }); assertTrue(orders.all { it.wire == 0 }) } assertEquals(1, solo.all(18).size) // metadata pseudo-tracker skipped assertTrue(solo.all(100).isEmpty(), "favorite=true is the upstream default") assertEquals(1_710_000_000L, solo.one(106).varint) // seconds fields(top.all(1)[1].bytes).one(100).let { assertEquals(0, it.wire); assertEquals(0L, it.varint) } // BackupChapter val chapter1 = fields(solo.all(16)[0].bytes) assertEquals("/c1", chapter1.one(1).text) assertEquals("Chapter 1", chapter1.one(2).text) assertEquals(1L, chapter1.one(4).varint) assertTrue(chapter1.all(6).isEmpty(), "Yokan page 1 is Mihon index 0 (default)") assertEquals(1_600_000_000_000, chapter1.one(8).varint) chapter1.one(9).let { assertEquals(5, it.wire); assertEquals(1f, Float.fromBits(it.fixed32)) } assertTrue(chapter1.all(10).isEmpty()) assertEquals(1_650_000_000L, chapter1.one(11).varint) val chapter2 = fields(solo.all(16)[1].bytes) assertEquals(1L, chapter2.one(5).varint) assertEquals(17L, chapter2.one(6).varint) assertEquals(2.5f, Float.fromBits(chapter2.one(9).fixed32)) assertEquals(1L, chapter2.one(10).varint) // BackupTracking val track = fields(solo.one(18).bytes) assertEquals(2L, track.one(1).varint) // TrackerManager.ANILIST assertEquals(0L, track.one(2).varint) // required libraryId assertEquals("https://anilist.co/manga/151807", track.one(4).text) assertEquals("Solo", track.one(5).text) assertEquals(2f, Float.fromBits(track.one(6).fixed32)) assertEquals(200L, track.one(7).varint) assertEquals(85f, Float.fromBits(track.one(8).fixed32)) assertEquals(6L, track.one(9).varint) // Anilist.REREADING assertEquals(151807L, track.one(100).varint) // BackupHistory val history = fields(solo.one(104).bytes) assertEquals("/c2", history.one(1).text) assertEquals(1_700_000_123_000, history.one(2).varint) assertEquals(90_000L, history.one(3).varint) // BackupCategory / BackupSource fields(top.all(2)[0].bytes).let { assertEquals("Reading", it.one(1).text); assertTrue(it.all(2).isEmpty()) } fields(top.all(2)[1].bytes).let { assertEquals("Later", it.one(1).text); assertEquals(1L, it.one(2).varint) } fields(top.one(101).bytes).let { assertEquals("MangaDex", it.one(1).text); assertEquals(mangaDexId, it.one(2).varint) } // BackupAnime / BackupEpisode / BackupAnimeTracking / BackupAnimeHistory val anime = fields(top.one(501).bytes) assertEquals(77L, anime.one(1).varint) assertEquals("Frieren", anime.one(3).text) assertEquals(1L, anime.one(8).varint) assertEquals(listOf(0L), anime.all(17).map { it.varint }) val episode = fields(anime.one(16).bytes) assertEquals(1L, episode.one(4).varint) // seen assertEquals(1_440_000L, episode.one(6).varint) // lastSecondSeen, millis assertEquals(1L, episode.one(501).varint) // fillermark assertEquals("Intro", episode.one(502).text) // summary fields(anime.one(18).bytes).let { assertEquals(1L, it.one(1).varint); assertEquals(11L, it.one(9).varint) } // MAL WATCHING fields(anime.one(104).bytes).let { assertEquals("/e1", it.one(1).text); assertEquals(1_700_000_456_000, it.one(2).varint) } fields(top.one(502).bytes).let { assertEquals("Watching", it.one(1).text) } fields(top.one(503).bytes).let { assertEquals("AniSrc", it.one(1).text); assertEquals(77L, it.one(2).varint) } } @Test fun emptyAndNovelOnlyBackupsEncodeOnlyTheLegacyFlag() = runTest { assertContentEquals(byteArrayOf(0xA0.toByte(), 0x1F, 0x00), encodeTachiyomiBackup(BackupSnapshot(createdAtMillis = 1))) // Categories are exported even when empty (as Mihon does); drop them so only novels remain. val novelsOnly = library().let { it.copy(mangas = it.mangas.filter { m -> m.itemType == DbItemType.Novel }, categories = emptyList()) } val export = BackupExporter(FakeGzip).export(novelsOnly, BackupOptions(format = BackupFormat.Tachiyomi, compressionLevel = 0)) assertContentEquals(byteArrayOf(0xA0.toByte(), 0x1F, 0x00), export.bytes) // Nothing restorable: the decoder reports an invalid backup instead of an empty restore. assertFailsWith { BackupDecoder(FakeGzip).decode(export.bytes) } } private class Field(val number: Int, val wire: Int, val varint: Long = 0, val bytes: ByteArray = ByteArray(0), val fixed32: Int = 0) { val text: String get() = bytes.decodeToString() } private fun fields(bytes: ByteArray): List { val reader = ProtoReader(bytes) return buildList { while (reader.hasMore()) { val (number, wire) = reader.readTag() add( when (wire) { 0 -> Field(number, wire, varint = reader.readVarint()) 2 -> Field(number, wire, bytes = reader.readBytes()) 5 -> Field(number, wire, fixed32 = reader.readFixed32()) else -> error("Unexpected wire type $wire for field $number") }, ) } } } private fun List.all(number: Int): List = filter { it.number == number } private fun List.one(number: Int): Field = single { it.number == number } }