package eu.friedcutlet.yokan.services.backup import eu.friedcutlet.yokan.database.DbCategory import eu.friedcutlet.yokan.database.DbChapter import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbManga import eu.friedcutlet.yokan.database.DbStatus import eu.friedcutlet.yokan.database.DbTrack import eu.friedcutlet.yokan.database.DbTrackStatus import eu.friedcutlet.yokan.database.effectiveFiller // ───────────────────────────────────────────────────────────────────────────── // Animetail `Backup` protobuf writer (field numbers in ExternalBackupDecoders.kt). // Mihon reads the manga half (1, 2, 101) and skips the rest; Aniyomi/Animetail // read anime at 501-503 because 500 (isLegacy) is written as false. Values equal // to the upstream Kotlin defaults are omitted like kotlinx ProtoBuf does; fields // without a default upstream (source, url, names, syncId, …) are always written. // Timestamps follow upstream units: dateAdded/dateUpload/dateFetch/lastRead and // episode positions in milliseconds, lastModifiedAt in seconds. // Novels have no Tachiyomi model and are skipped. // ───────────────────────────────────────────────────────────────────────────── internal class ProtoWriter { private var buffer = ByteArray(256) private var size = 0 private fun put(byte: Int) { if (size == buffer.size) buffer = buffer.copyOf(size * 2) buffer[size++] = byte.toByte() } private fun rawVarint(value: Long) { var v = value while (v and 0x7FL.inv() != 0L) { put(((v and 0x7F) or 0x80).toInt()) v = v ushr 7 } put(v.toInt()) } private fun tag(field: Int, wire: Int) = rawVarint(((field shl 3) or wire).toLong()) fun varint(field: Int, value: Long) { tag(field, 0) rawVarint(value) } fun bytes(field: Int, value: ByteArray) { tag(field, 2) rawVarint(value.size.toLong()) value.forEach { put(it.toInt()) } } fun string(field: Int, value: String) = bytes(field, value.encodeToByteArray()) fun float(field: Int, value: Float) { tag(field, 5) val bits = value.toRawBits() repeat(4) { put(bits ushr (8 * it)) } } fun message(field: Int, block: ProtoWriter.() -> Unit) = bytes(field, ProtoWriter().apply(block).toByteArray()) fun optVarint(field: Int, value: Long) { if (value != 0L) varint(field, value) } fun optTrue(field: Int, value: Boolean) { if (value) varint(field, 1) } fun optString(field: Int, value: String?) { if (!value.isNullOrEmpty()) string(field, value) } fun optFloat(field: Int, value: Float) { if (value != 0f) float(field, value) } fun toByteArray(): ByteArray = buffer.copyOf(size) } internal fun encodeTachiyomiBackup(payload: BackupSnapshot): ByteArray { val chaptersByTitle = payload.chapters.groupBy { it.mangaId } val chapterById = payload.chapters.associateBy { it.id } val historiesByTitle = payload.histories.groupBy { it.mangaId } val tracksByTitle = payload.tracks.groupBy { it.mangaId } val sourceById = payload.sources.associateBy { it.id } // Upstream links titles to categories by `order`; re-number per type so orders are unique. fun categoriesOf(type: DbItemType): List = payload.categories .filter { it.forItemType == type } .sortedWith(compareBy { it.position ?: Int.MAX_VALUE }.thenBy { it.id }) fun sourceIdOf(manga: DbManga): Long = manga.sourceId?.takeIf { it in sourceById } // ponytail: hash of the source name for titles without an exported source row; collides only on name hash collisions. ?: (manga.source.orEmpty().hashCode().toLong() and 0x7FFF_FFFFL) fun ProtoWriter.entry(manga: DbManga, anime: Boolean, categoryOrders: Map) { varint(1, sourceIdOf(manga)) string(2, manga.link.orEmpty()) optString(3, manga.name) optString(4, manga.artist) optString(5, manga.author) optString(6, manga.description) manga.genre.orEmpty().forEach { string(7, it) } optVarint(8, tachiyomiStatusIndex(manga.status, anime).toLong()) optString(9, manga.imageUrl) optVarint(13, manga.dateAdded ?: 0) chaptersByTitle[manga.id].orEmpty().forEachIndexed { index, item -> message(16) { writeChapter(item, index, anime) } } manga.categories.orEmpty().mapNotNull(categoryOrders::get).forEach { varint(17, it) } tracksByTitle[manga.id].orEmpty().forEach { writeTrack(it, anime) } if (!manga.favorite) varint(100, 0) historiesByTitle[manga.id].orEmpty().forEach { history -> val url = history.chapterId?.let(chapterById::get)?.url ?: return@forEach val readAt = history.date?.toLongOrNull() ?: return@forEach message(104) { string(1, url) varint(2, readAt) optVarint(3, (history.readingTimeSeconds ?: 0) * 1000L) } } optVarint(106, (manga.lastUpdate ?: 0) / 1000) } fun ProtoWriter.section(type: DbItemType, titleField: Int, categoryField: Int, sourceField: Int) { val anime = type == DbItemType.Anime val categories = categoriesOf(type) val orders = categories.withIndex().associate { (index, category) -> category.id to index.toLong() } val titles = payload.mangas.filter { it.itemType == type } titles.forEach { manga -> message(titleField) { entry(manga, anime, orders) } } categories.forEachIndexed { index, category -> message(categoryField) { string(1, category.name) optVarint(2, index.toLong()) } } titles.associate { sourceIdOf(it) to (it.source ?: it.sourceId?.let(sourceById::get)?.name).orEmpty() } .forEach { (id, name) -> message(sourceField) { optString(1, name) varint(2, id) } } } return ProtoWriter().apply { section(DbItemType.Manga, titleField = 1, categoryField = 2, sourceField = 101) varint(500, 0) // isLegacy = false: anime lives at 501-503. section(DbItemType.Anime, titleField = 501, categoryField = 502, sourceField = 503) }.toByteArray() } private fun ProtoWriter.writeChapter(chapter: DbChapter, index: Int, anime: Boolean) { string(1, chapter.url) string(2, chapter.name.orEmpty()) optString(3, chapter.scanlator) optTrue(4, chapter.isRead) optTrue(5, chapter.isBookmarked) val progress = chapter.lastPageRead.toLongOrNull() ?: 0 // Yokan pages are 1-based; Mihon stores the 0-based page index. Episodes are milliseconds on both sides. optVarint(6, if (anime) progress else (progress - 1).coerceAtLeast(0)) optVarint(7, chapter.fetchedAt) optVarint(8, chapter.dateUpload.toLongOrNull() ?: 0) optFloat(9, chapter.number?.toFloat() ?: 0f) optVarint(10, index.toLong()) optVarint(11, chapter.updatedAt / 1000) if (anime) { optTrue(501, chapter.effectiveFiller) optString(502, chapter.description) optString(503, chapter.thumbnailUrl) } } private fun ProtoWriter.writeTrack(track: DbTrack, anime: Boolean) { val tracker = TachiyomiTrackers.firstOrNull { it.yokanId == track.syncId } ?: return message(18) { varint(1, tracker.id.toLong()) varint(2, track.libraryId ?: 0) optString(4, track.trackingUrl) optString(5, track.title) optFloat(6, (track.lastChapterRead ?: 0).toFloat()) optVarint(7, (track.totalChapter ?: 0).toLong()) optFloat(8, (track.score ?: 0).toFloat()) optVarint(9, tracker.code(track.status, anime).toLong()) optVarint(10, track.startedReadingDate ?: 0) optVarint(11, track.finishedReadingDate ?: 0) optVarint(100, track.mediaId ?: 0) } } /** Inverse of [tachiyomiStatus]: SManga/SAnime status constants. */ internal fun tachiyomiStatusIndex(status: DbStatus, anime: Boolean): Int = when (status) { DbStatus.Ongoing -> 1 DbStatus.Completed -> 2 DbStatus.Licensed -> 3 DbStatus.PublishingFinished -> 4 DbStatus.Canceled -> 5 DbStatus.OnHiatus -> 6 DbStatus.Upcoming -> if (anime) 7 else 0 DbStatus.Unknown -> 0 } /** * Yokan tracker id ↔ Animetail `TrackerManager` id with that tracker's status * constants. Statuses are listed in their reading flavour; anime-only codes * (MAL/AniList/Kitsu `WATCHING = 11`, …) are listed explicitly. */ internal class TachiyomiTracker(val yokanId: Int, val id: Int, private val statuses: List>) { fun code(status: DbTrackStatus, anime: Boolean): Int { val own = status.flavour(anime) val reading = status.flavour(anime = false) return listOf(own, own.withoutRepeat(), reading, reading.withoutRepeat()) .firstNotNullOfOrNull { candidate -> statuses.firstOrNull { it.first == candidate }?.second } ?: 0 } fun status(code: Int, anime: Boolean): DbTrackStatus = (statuses.firstOrNull { it.second == code }?.first ?: DbTrackStatus.Reading).flavour(anime) } private fun DbTrackStatus.flavour(anime: Boolean): DbTrackStatus = when (this) { DbTrackStatus.Reading, DbTrackStatus.Watching -> if (anime) DbTrackStatus.Watching else DbTrackStatus.Reading DbTrackStatus.PlanToRead, DbTrackStatus.PlanToWatch -> if (anime) DbTrackStatus.PlanToWatch else DbTrackStatus.PlanToRead DbTrackStatus.ReReading, DbTrackStatus.ReWatching -> if (anime) DbTrackStatus.ReWatching else DbTrackStatus.ReReading DbTrackStatus.Completed, DbTrackStatus.OnHold, DbTrackStatus.Dropped -> this } private fun DbTrackStatus.withoutRepeat(): DbTrackStatus = when (this) { DbTrackStatus.ReReading -> DbTrackStatus.Reading DbTrackStatus.ReWatching -> DbTrackStatus.Watching else -> this } private val R = DbTrackStatus.Reading private val C = DbTrackStatus.Completed private val H = DbTrackStatus.OnHold private val D = DbTrackStatus.Dropped private val P = DbTrackStatus.PlanToRead private val RR = DbTrackStatus.ReReading internal val TachiyomiTrackers: List = listOf( TachiyomiTracker(1, 1, listOf(R to 1, C to 2, H to 3, D to 4, P to 6, RR to 7, DbTrackStatus.Watching to 11, DbTrackStatus.PlanToWatch to 16, DbTrackStatus.ReWatching to 17)), // MyAnimeList TachiyomiTracker(2, 2, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, RR to 6, DbTrackStatus.Watching to 11, DbTrackStatus.PlanToWatch to 15, DbTrackStatus.ReWatching to 16)), // AniList TachiyomiTracker(3, 3, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, DbTrackStatus.Watching to 11, DbTrackStatus.PlanToWatch to 15)), // Kitsu TachiyomiTracker(4, 101, listOf(R to 1, C to 2, H to 3, D to 4, P to 5)), // Simkl TachiyomiTracker(5, 201, listOf(R to 1, C to 2, H to 3, D to 4, P to 5)), // Trakt TachiyomiTracker(10, 7, listOf(R to 0, P to 1, C to 2, D to 3, H to 4)), // MangaUpdates TachiyomiTracker(11, 4, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, RR to 6)), // Shikimori TachiyomiTracker(12, 5, listOf(P to 1, C to 2, R to 3, H to 4, D to 5)), // Bangumi TachiyomiTracker(13, 10, listOf(R to 0, C to 1, H to 2, D to 3, P to 4, RR to 5)), // Hikka TachiyomiTracker(14, 11, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, RR to 6)), // MangaBaka TachiyomiTracker(15, 200, listOf(DbTrackStatus.Watching to 11, C to 2, H to 3, D to 4, DbTrackStatus.PlanToWatch to 15, DbTrackStatus.ReWatching to 16)), // TMDB TachiyomiTracker(20, 6, listOf(P to 1, R to 2, C to 3)), // Komga TachiyomiTracker(21, 8, listOf(P to 1, R to 2, C to 3)), // Kavita TachiyomiTracker(22, 9, listOf(P to 1, R to 2, C to 3)), // Suwayomi TachiyomiTracker(23, 102, listOf(P to 1, R to 2, C to 3)), // Jellyfin )