package eu.friedcutlet.yokan.database.sync 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.DbTrack import eu.friedcutlet.yokan.database.DbUpdate import kotlin.random.Random /** * Stable 63-bit ids derived from natural keys, so the same title added on two devices is the same * row on the hub and merging is automatic. FNV-1a 64 over the key string, masked positive, never 0. * Entities without a natural key (categories) get a random id instead of a local counter. */ object SyncIds { private const val FNV_OFFSET: Long = -3750763034362895579L // 0xcbf29ce484222325 private const val FNV_PRIME: Long = 1099511628211L fun stable(key: String): Long { var h = FNV_OFFSET for (b in key.encodeToByteArray()) { h = h xor (b.toLong() and 0xff) h *= FNV_PRIME } val v = h and Long.MAX_VALUE return if (v == 0L) 1L else v } fun random(): Long = Random.nextLong(1L, Long.MAX_VALUE) fun manga(itemType: DbItemType, sourceKey: String, link: String): Long = stable("manga|${itemType.name}|$sourceKey|$link") fun chapter(mangaId: Long, url: String): Long = stable("chapter|$mangaId|$url") fun history(mangaId: Long): Long = stable("history|$mangaId") fun update(mangaId: Long, chapterId: Long): Long = stable("update|$mangaId|$chapterId") fun track(mangaId: Long, syncId: Int): Long = stable("track|$mangaId|$syncId") /** Null when the row has no natural key yet (no link / source), in which case the caller falls back to [random]. */ fun forManga(m: DbManga): Long? { val link = m.link?.takeIf { it.isNotBlank() } ?: return null val source = m.sourceId?.toString() ?: m.source?.takeIf { it.isNotBlank() } ?: return null return manga(m.itemType, source, link) } fun forChapter(c: DbChapter): Long? { val mangaId = c.mangaId?.takeIf { it != 0L } ?: return null val key = c.url.takeIf { it.isNotBlank() } ?: c.archivePath.takeIf { it.isNotBlank() } ?: return null return chapter(mangaId, key) } fun forHistory(h: DbHistory): Long? = h.mangaId?.takeIf { it != 0L }?.let(::history) fun forUpdate(u: DbUpdate): Long? { val mangaId = u.mangaId?.takeIf { it != 0L } ?: return null val chapterId = u.chapterId?.takeIf { it != 0L } ?: return null return update(mangaId, chapterId) } fun forTrack(t: DbTrack): Long? { val mangaId = t.mangaId?.takeIf { it != 0L } ?: return null val syncId = t.syncId ?: return null return track(mangaId, syncId) } }