TachiyomiBackupEncoder.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/TachiyomiBackupEncoder.kt
1package eu.friedcutlet.yokan.services.backup23import eu.friedcutlet.yokan.database.DbCategory4import eu.friedcutlet.yokan.database.DbChapter5import eu.friedcutlet.yokan.database.DbItemType6import eu.friedcutlet.yokan.database.DbManga7import eu.friedcutlet.yokan.database.DbStatus8import eu.friedcutlet.yokan.database.DbTrack9import eu.friedcutlet.yokan.database.DbTrackStatus10import eu.friedcutlet.yokan.database.effectiveFiller1112// ─────────────────────────────────────────────────────────────────────────────13// Animetail `Backup` protobuf writer (field numbers in ExternalBackupDecoders.kt).14// Mihon reads the manga half (1, 2, 101) and skips the rest; Aniyomi/Animetail15// read anime at 501-503 because 500 (isLegacy) is written as false. Values equal16// to the upstream Kotlin defaults are omitted like kotlinx ProtoBuf does; fields17// without a default upstream (source, url, names, syncId, …) are always written.18// Timestamps follow upstream units: dateAdded/dateUpload/dateFetch/lastRead and19// episode positions in milliseconds, lastModifiedAt in seconds.20// Novels have no Tachiyomi model and are skipped.21// ─────────────────────────────────────────────────────────────────────────────2223internal class ProtoWriter {24 private var buffer = ByteArray(256)25 private var size = 02627 private fun put(byte: Int) {28 if (size == buffer.size) buffer = buffer.copyOf(size * 2)29 buffer[size++] = byte.toByte()30 }3132 private fun rawVarint(value: Long) {33 var v = value34 while (v and 0x7FL.inv() != 0L) {35 put(((v and 0x7F) or 0x80).toInt())36 v = v ushr 737 }38 put(v.toInt())39 }4041 private fun tag(field: Int, wire: Int) = rawVarint(((field shl 3) or wire).toLong())4243 fun varint(field: Int, value: Long) {44 tag(field, 0)45 rawVarint(value)46 }4748 fun bytes(field: Int, value: ByteArray) {49 tag(field, 2)50 rawVarint(value.size.toLong())51 value.forEach { put(it.toInt()) }52 }5354 fun string(field: Int, value: String) = bytes(field, value.encodeToByteArray())5556 fun float(field: Int, value: Float) {57 tag(field, 5)58 val bits = value.toRawBits()59 repeat(4) { put(bits ushr (8 * it)) }60 }6162 fun message(field: Int, block: ProtoWriter.() -> Unit) = bytes(field, ProtoWriter().apply(block).toByteArray())6364 fun optVarint(field: Int, value: Long) { if (value != 0L) varint(field, value) }65 fun optTrue(field: Int, value: Boolean) { if (value) varint(field, 1) }66 fun optString(field: Int, value: String?) { if (!value.isNullOrEmpty()) string(field, value) }67 fun optFloat(field: Int, value: Float) { if (value != 0f) float(field, value) }6869 fun toByteArray(): ByteArray = buffer.copyOf(size)70}7172internal fun encodeTachiyomiBackup(payload: BackupSnapshot): ByteArray {73 val chaptersByTitle = payload.chapters.groupBy { it.mangaId }74 val chapterById = payload.chapters.associateBy { it.id }75 val historiesByTitle = payload.histories.groupBy { it.mangaId }76 val tracksByTitle = payload.tracks.groupBy { it.mangaId }77 val sourceById = payload.sources.associateBy { it.id }7879 // Upstream links titles to categories by `order`; re-number per type so orders are unique.80 fun categoriesOf(type: DbItemType): List<DbCategory> = payload.categories81 .filter { it.forItemType == type }82 .sortedWith(compareBy<DbCategory> { it.position ?: Int.MAX_VALUE }.thenBy { it.id })8384 fun sourceIdOf(manga: DbManga): Long = manga.sourceId?.takeIf { it in sourceById }85 // ponytail: hash of the source name for titles without an exported source row; collides only on name hash collisions.86 ?: (manga.source.orEmpty().hashCode().toLong() and 0x7FFF_FFFFL)8788 fun ProtoWriter.entry(manga: DbManga, anime: Boolean, categoryOrders: Map<Long, Long>) {89 varint(1, sourceIdOf(manga))90 string(2, manga.link.orEmpty())91 optString(3, manga.name)92 optString(4, manga.artist)93 optString(5, manga.author)94 optString(6, manga.description)95 manga.genre.orEmpty().forEach { string(7, it) }96 optVarint(8, tachiyomiStatusIndex(manga.status, anime).toLong())97 optString(9, manga.imageUrl)98 optVarint(13, manga.dateAdded ?: 0)99 chaptersByTitle[manga.id].orEmpty().forEachIndexed { index, item ->100 message(16) { writeChapter(item, index, anime) }101 }102 manga.categories.orEmpty().mapNotNull(categoryOrders::get).forEach { varint(17, it) }103 tracksByTitle[manga.id].orEmpty().forEach { writeTrack(it, anime) }104 if (!manga.favorite) varint(100, 0)105 historiesByTitle[manga.id].orEmpty().forEach { history ->106 val url = history.chapterId?.let(chapterById::get)?.url ?: return@forEach107 val readAt = history.date?.toLongOrNull() ?: return@forEach108 message(104) {109 string(1, url)110 varint(2, readAt)111 optVarint(3, (history.readingTimeSeconds ?: 0) * 1000L)112 }113 }114 optVarint(106, (manga.lastUpdate ?: 0) / 1000)115 }116117 fun ProtoWriter.section(type: DbItemType, titleField: Int, categoryField: Int, sourceField: Int) {118 val anime = type == DbItemType.Anime119 val categories = categoriesOf(type)120 val orders = categories.withIndex().associate { (index, category) -> category.id to index.toLong() }121 val titles = payload.mangas.filter { it.itemType == type }122 titles.forEach { manga -> message(titleField) { entry(manga, anime, orders) } }123 categories.forEachIndexed { index, category ->124 message(categoryField) {125 string(1, category.name)126 optVarint(2, index.toLong())127 }128 }129 titles.associate { sourceIdOf(it) to (it.source ?: it.sourceId?.let(sourceById::get)?.name).orEmpty() }130 .forEach { (id, name) ->131 message(sourceField) {132 optString(1, name)133 varint(2, id)134 }135 }136 }137138 return ProtoWriter().apply {139 section(DbItemType.Manga, titleField = 1, categoryField = 2, sourceField = 101)140 varint(500, 0) // isLegacy = false: anime lives at 501-503.141 section(DbItemType.Anime, titleField = 501, categoryField = 502, sourceField = 503)142 }.toByteArray()143}144145private fun ProtoWriter.writeChapter(chapter: DbChapter, index: Int, anime: Boolean) {146 string(1, chapter.url)147 string(2, chapter.name.orEmpty())148 optString(3, chapter.scanlator)149 optTrue(4, chapter.isRead)150 optTrue(5, chapter.isBookmarked)151 val progress = chapter.lastPageRead.toLongOrNull() ?: 0152 // Yokan pages are 1-based; Mihon stores the 0-based page index. Episodes are milliseconds on both sides.153 optVarint(6, if (anime) progress else (progress - 1).coerceAtLeast(0))154 optVarint(7, chapter.fetchedAt)155 optVarint(8, chapter.dateUpload.toLongOrNull() ?: 0)156 optFloat(9, chapter.number?.toFloat() ?: 0f)157 optVarint(10, index.toLong())158 optVarint(11, chapter.updatedAt / 1000)159 if (anime) {160 optTrue(501, chapter.effectiveFiller)161 optString(502, chapter.description)162 optString(503, chapter.thumbnailUrl)163 }164}165166private fun ProtoWriter.writeTrack(track: DbTrack, anime: Boolean) {167 val tracker = TachiyomiTrackers.firstOrNull { it.yokanId == track.syncId } ?: return168 message(18) {169 varint(1, tracker.id.toLong())170 varint(2, track.libraryId ?: 0)171 optString(4, track.trackingUrl)172 optString(5, track.title)173 optFloat(6, (track.lastChapterRead ?: 0).toFloat())174 optVarint(7, (track.totalChapter ?: 0).toLong())175 optFloat(8, (track.score ?: 0).toFloat())176 optVarint(9, tracker.code(track.status, anime).toLong())177 optVarint(10, track.startedReadingDate ?: 0)178 optVarint(11, track.finishedReadingDate ?: 0)179 optVarint(100, track.mediaId ?: 0)180 }181}182183/** Inverse of [tachiyomiStatus]: SManga/SAnime status constants. */184internal fun tachiyomiStatusIndex(status: DbStatus, anime: Boolean): Int = when (status) {185 DbStatus.Ongoing -> 1186 DbStatus.Completed -> 2187 DbStatus.Licensed -> 3188 DbStatus.PublishingFinished -> 4189 DbStatus.Canceled -> 5190 DbStatus.OnHiatus -> 6191 DbStatus.Upcoming -> if (anime) 7 else 0192 DbStatus.Unknown -> 0193}194195/**196 * Yokan tracker id ↔ Animetail `TrackerManager` id with that tracker's status197 * constants. Statuses are listed in their reading flavour; anime-only codes198 * (MAL/AniList/Kitsu `WATCHING = 11`, …) are listed explicitly.199 */200internal class TachiyomiTracker(val yokanId: Int, val id: Int, private val statuses: List<Pair<DbTrackStatus, Int>>) {201 fun code(status: DbTrackStatus, anime: Boolean): Int {202 val own = status.flavour(anime)203 val reading = status.flavour(anime = false)204 return listOf(own, own.withoutRepeat(), reading, reading.withoutRepeat())205 .firstNotNullOfOrNull { candidate -> statuses.firstOrNull { it.first == candidate }?.second } ?: 0206 }207208 fun status(code: Int, anime: Boolean): DbTrackStatus =209 (statuses.firstOrNull { it.second == code }?.first ?: DbTrackStatus.Reading).flavour(anime)210}211212private fun DbTrackStatus.flavour(anime: Boolean): DbTrackStatus = when (this) {213 DbTrackStatus.Reading, DbTrackStatus.Watching -> if (anime) DbTrackStatus.Watching else DbTrackStatus.Reading214 DbTrackStatus.PlanToRead, DbTrackStatus.PlanToWatch -> if (anime) DbTrackStatus.PlanToWatch else DbTrackStatus.PlanToRead215 DbTrackStatus.ReReading, DbTrackStatus.ReWatching -> if (anime) DbTrackStatus.ReWatching else DbTrackStatus.ReReading216 DbTrackStatus.Completed, DbTrackStatus.OnHold, DbTrackStatus.Dropped -> this217}218219private fun DbTrackStatus.withoutRepeat(): DbTrackStatus = when (this) {220 DbTrackStatus.ReReading -> DbTrackStatus.Reading221 DbTrackStatus.ReWatching -> DbTrackStatus.Watching222 else -> this223}224225private val R = DbTrackStatus.Reading226private val C = DbTrackStatus.Completed227private val H = DbTrackStatus.OnHold228private val D = DbTrackStatus.Dropped229private val P = DbTrackStatus.PlanToRead230private val RR = DbTrackStatus.ReReading231232internal val TachiyomiTrackers: List<TachiyomiTracker> = listOf(233 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)), // MyAnimeList234 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)), // AniList235 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)), // Kitsu236 TachiyomiTracker(4, 101, listOf(R to 1, C to 2, H to 3, D to 4, P to 5)), // Simkl237 TachiyomiTracker(5, 201, listOf(R to 1, C to 2, H to 3, D to 4, P to 5)), // Trakt238 TachiyomiTracker(10, 7, listOf(R to 0, P to 1, C to 2, D to 3, H to 4)), // MangaUpdates239 TachiyomiTracker(11, 4, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, RR to 6)), // Shikimori240 TachiyomiTracker(12, 5, listOf(P to 1, C to 2, R to 3, H to 4, D to 5)), // Bangumi241 TachiyomiTracker(13, 10, listOf(R to 0, C to 1, H to 2, D to 3, P to 4, RR to 5)), // Hikka242 TachiyomiTracker(14, 11, listOf(R to 1, C to 2, H to 3, D to 4, P to 5, RR to 6)), // MangaBaka243 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)), // TMDB244 TachiyomiTracker(20, 6, listOf(P to 1, R to 2, C to 3)), // Komga245 TachiyomiTracker(21, 8, listOf(P to 1, R to 2, C to 3)), // Kavita246 TachiyomiTracker(22, 9, listOf(P to 1, R to 2, C to 3)), // Suwayomi247 TachiyomiTracker(23, 102, listOf(P to 1, R to 2, C to 3)), // Jellyfin248)249