SyncIds.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/database/sync/SyncIds.kt
1package eu.friedcutlet.yokan.database.sync23import eu.friedcutlet.yokan.database.DbChapter4import eu.friedcutlet.yokan.database.DbHistory5import eu.friedcutlet.yokan.database.DbItemType6import eu.friedcutlet.yokan.database.DbManga7import eu.friedcutlet.yokan.database.DbTrack8import eu.friedcutlet.yokan.database.DbUpdate9import kotlin.random.Random1011/**12 * Stable 63-bit ids derived from natural keys, so the same title added on two devices is the same13 * row on the hub and merging is automatic. FNV-1a 64 over the key string, masked positive, never 0.14 * Entities without a natural key (categories) get a random id instead of a local counter.15 */16object SyncIds {17 private const val FNV_OFFSET: Long = -3750763034362895579L // 0xcbf29ce48422232518 private const val FNV_PRIME: Long = 1099511628211L1920 fun stable(key: String): Long {21 var h = FNV_OFFSET22 for (b in key.encodeToByteArray()) {23 h = h xor (b.toLong() and 0xff)24 h *= FNV_PRIME25 }26 val v = h and Long.MAX_VALUE27 return if (v == 0L) 1L else v28 }2930 fun random(): Long = Random.nextLong(1L, Long.MAX_VALUE)3132 fun manga(itemType: DbItemType, sourceKey: String, link: String): Long = stable("manga|${itemType.name}|$sourceKey|$link")33 fun chapter(mangaId: Long, url: String): Long = stable("chapter|$mangaId|$url")34 fun history(mangaId: Long): Long = stable("history|$mangaId")35 fun update(mangaId: Long, chapterId: Long): Long = stable("update|$mangaId|$chapterId")36 fun track(mangaId: Long, syncId: Int): Long = stable("track|$mangaId|$syncId")3738 /** Null when the row has no natural key yet (no link / source), in which case the caller falls back to [random]. */39 fun forManga(m: DbManga): Long? {40 val link = m.link?.takeIf { it.isNotBlank() } ?: return null41 val source = m.sourceId?.toString() ?: m.source?.takeIf { it.isNotBlank() } ?: return null42 return manga(m.itemType, source, link)43 }4445 fun forChapter(c: DbChapter): Long? {46 val mangaId = c.mangaId?.takeIf { it != 0L } ?: return null47 val key = c.url.takeIf { it.isNotBlank() } ?: c.archivePath.takeIf { it.isNotBlank() } ?: return null48 return chapter(mangaId, key)49 }5051 fun forHistory(h: DbHistory): Long? = h.mangaId?.takeIf { it != 0L }?.let(::history)5253 fun forUpdate(u: DbUpdate): Long? {54 val mangaId = u.mangaId?.takeIf { it != 0L } ?: return null55 val chapterId = u.chapterId?.takeIf { it != 0L } ?: return null56 return update(mangaId, chapterId)57 }5859 fun forTrack(t: DbTrack): Long? {60 val mangaId = t.mangaId?.takeIf { it != 0L } ?: return null61 val syncId = t.syncId ?: return null62 return track(mangaId, syncId)63 }64}65