package com.cottondb.voice import java.io.File import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import java.security.MessageDigest import java.util.concurrent.ConcurrentHashMap import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put /** A model's place in the store, in voice.model's words: absent, downloading, ready, failed. */ data class ModelState( val model: String, val state: String, val bytes: Long?, val bytesDone: Long, val path: String? = null, val why: String? = null, ) { fun json(): JsonObject = buildJsonObject { put("model", model) put("state", state) bytes?.let { put("bytes", it) } put("bytes_done", bytesDone) path?.let { put("path", it) } why?.let { put("why", it) } } } /** How the store reaches a file: one GET, from [from] bytes on (a Range request), answering the status and the body. */ fun interface Http { class Answer(val status: Int, val length: Long?, val body: InputStream) fun get(url: String, from: Long): Answer companion object { val urls = Http { url, from -> val c = URL(url).openConnection() as HttpURLConnection c.connectTimeout = 15_000 c.readTimeout = 30_000 c.instanceFollowRedirects = true if (from > 0) c.setRequestProperty("Range", "bytes=$from-") val status = c.responseCode Answer(status, c.contentLengthLong.takeIf { it >= 0 }, if (status >= 400) (c.errorStream ?: InputStream.nullInputStream()) else c.inputStream) } } } /** Whether a download may run now: any network, or only an unmetered one when the person keeps models off mobile data. */ interface Network { fun usable(mobileData: Boolean): Boolean } /** * The one model store on the phone: every Cotton app's dictation runs here, so a model is downloaded once. A model is * a folder under [root] holding its files; it is ready when every file is whole and matches its sha256 (a `.ready` * line names them). A file arrives as `.part` and resumes from what is there (a Range request); one whose * bytes do not match its sha256 is deleted and the model fails, never half-ready. A file the catalogue gives no url or * no sha256 is refused unread: nothing unverified is ever run. */ class ModelStore( val root: File, private val http: Http = Http.urls, private val network: Network, private val sleep: (Long) -> Unit = { Thread.sleep(it) }, private val attempts: Int = 40, ) { private val fetching = ConcurrentHashMap() fun folder(model: String): File = root.resolve(model.replace(Regex("[^A-Za-z0-9._-]"), "_")) fun ready(model: ModelEntry): Boolean { val mark = folder(model.id).resolve(".ready") return mark.isFile && mark.readText() == readyLine(model) && model.files.all { folder(model.id).resolve(it.name).isFile } } fun state(model: ModelEntry): ModelState { fetching[model.id]?.let { return it } val dir = folder(model.id) if (ready(model)) return ModelState(model.id, "ready", model.bytes, model.bytes ?: 0, dir.path) val done = model.files.sumOf { f -> dir.resolve(f.name).takeIf { it.isFile }?.length() ?: dir.resolve("${f.name}.part").takeIf { it.isFile }?.length() ?: 0L } val failed = dir.resolve(".failed").takeIf { it.isFile }?.readText() return ModelState(model.id, if (failed != null) "failed" else "absent", model.bytes, done, why = failed) } /** The path of a ready model's file, else null. */ fun path(model: ModelEntry, file: ModelFile): String? = if (ready(model)) folder(model.id).resolve(file.name).path else null fun remove(model: String) { folder(model).deleteRecursively() } /** * Fetch every file of [model], reporting each change to [progress]. Blocking: run it off the main thread. An * interrupted download (the network gone, a read timing out) waits for a usable network and resumes from its * `.part`, up to [attempts] times; mobile data is waited out unless [mobileData]. */ fun fetch(model: ModelEntry, mobileData: Boolean, stopped: () -> Boolean = { false }, progress: (ModelState) -> Unit): ModelState = // One fetch of a model at a time in this process: a second waits for the first, then finds it ready or resumes. synchronized(locks.computeIfAbsent(model.id) { Any() }) { fetchAlone(model, mobileData, stopped, progress) } private val locks = ConcurrentHashMap() private fun fetchAlone(model: ModelEntry, mobileData: Boolean, stopped: () -> Boolean, progress: (ModelState) -> Unit): ModelState { if (ready(model)) return state(model).also(progress) val unverifiable = model.files.firstOrNull { it.url == null || it.sha256 == null } if (unverifiable != null) return fail(model, "unverifiable", progress) val dir = folder(model.id).apply { mkdirs() } dir.resolve(".failed").delete() val total = model.bytes val doneBefore = { model.files.sumOf { f -> dir.resolve(f.name).takeIf { it.isFile }?.length() ?: dir.resolve("${f.name}.part").takeIf { it.isFile }?.length() ?: 0L } } fun say(state: String, why: String? = null) = ModelState(model.id, state, total, doneBefore(), why = why).also { fetching[model.id] = it; progress(it) } try { for (file in model.files) { val whole = dir.resolve(file.name) if (whole.isFile && sha256(whole) == file.sha256) continue whole.delete() val part = dir.resolve("${file.name}.part") var tries = 0 while (true) { // Stopped (WorkManager took the network away, or the person removed it): what came stays in the .part. if (stopped()) return state(model).also(progress) if (!network.usable(mobileData)) { say("downloading", if (network.usable(true)) "waiting_unmetered" else "waiting_network") sleep(2_000) if (++tries > attempts * 15) return fail(model, "offline", progress) continue } try { val digest = MessageDigest.getInstance("SHA-256") var have = if (part.isFile) part.length() else 0L if (have > 0) part.inputStream().use { it.feed(digest) } val answer = http.get(file.url!!, have) when { answer.status == 416 && file.bytes != null && have == file.bytes -> answer.body.close() answer.status == 206 && have > 0 -> answer.body.use { body -> part.appendFrom(body, digest, stopped) { n -> have += n; say("downloading") } } answer.status in 200..299 -> { // The server sent the whole file (no Range): start again from nothing. digest.reset(); have = 0 part.writeBytes(ByteArray(0)) answer.body.use { body -> part.appendFrom(body, digest, stopped) { n -> have += n; say("downloading") } } } else -> { answer.body.close(); throw IOException("${answer.status}") } } if (stopped()) return state(model).also(progress) val got = digest.digest().joinToString("") { "%02x".format(it) } if (got != file.sha256) { part.delete() return fail(model, "mismatch", progress) } if (!part.renameTo(whole)) throw IOException(whole.path) break } catch (e: IOException) { if (++tries > attempts) return fail(model, "interrupted", progress) say("downloading", "interrupted") sleep(minOf(30_000L, 1_000L shl minOf(tries, 5))) } } } dir.resolve(".ready").writeText(readyLine(model)) fetching.remove(model.id) return state(model).also(progress) } finally { fetching.remove(model.id) } } private fun fail(model: ModelEntry, why: String, progress: (ModelState) -> Unit): ModelState { fetching.remove(model.id) folder(model.id).apply { mkdirs() }.resolve(".failed").writeText(why) return state(model).also(progress) } private fun readyLine(model: ModelEntry) = model.files.joinToString("\n") { "${it.name} ${it.sha256}" } companion object { fun sha256(f: File): String = MessageDigest.getInstance("SHA-256").also { d -> f.inputStream().use { it.feed(d) } }.digest().joinToString("") { "%02x".format(it) } private fun InputStream.feed(d: MessageDigest) { val buf = ByteArray(1 shl 16) while (true) { val n = read(buf); if (n < 0) break; d.update(buf, 0, n) } } /** Append [body] to this file, hashing as it goes, telling [moved] every 256 KB or so. */ private fun File.appendFrom(body: InputStream, d: MessageDigest, stopped: () -> Boolean, moved: (Long) -> Unit) { java.io.FileOutputStream(this, true).use { out -> val buf = ByteArray(1 shl 16) var since = 0L while (!stopped()) { val n = body.read(buf) if (n < 0) break out.write(buf, 0, n); d.update(buf, 0, n) since += n if (since >= 256 * 1024) { moved(since); since = 0 } } out.flush() if (since > 0) moved(since) } } } }