feat(android): MediaUploader — a phone puts films on a relay, in resumable pieces
MediaOwner signs owner requests and MediaUploader speaks the piece protocol of media put (window, retries, resync after a lost answer). MediaSealer .sealStream seals a film to a file; MediaGrant.encode/capabilityUrl make the link to share. Owner signatures and encoded grants are pinned by new vectors; scripts/media-live-kotlin.ts runs the uploader against a real TS relay with a lost answer and a refused piece injected. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -61,7 +61,10 @@ data class MediaMeta(
|
||||
val extra: Map<String, String>? = null,
|
||||
) {
|
||||
/** `JSON.stringify` of the TS-validated object — same key order, same bytes. */
|
||||
fun toJson(): String {
|
||||
fun toJson(): String = stringifyJson(toJsonMap())
|
||||
|
||||
/** The fields in `toJson`'s order, for embedding in a larger JSON (a grant). */
|
||||
internal fun toJsonMap(): Map<String, Any> {
|
||||
val m = LinkedHashMap<String, Any>()
|
||||
mime?.let { m["mime"] = it }
|
||||
name?.let { m["name"] = it }
|
||||
@@ -70,7 +73,7 @@ data class MediaMeta(
|
||||
height?.let { m["height"] = it }
|
||||
createdAt?.let { m["createdAt"] = it }
|
||||
extra?.let { m["extra"] = LinkedHashMap(it) }
|
||||
return stringifyJson(m)
|
||||
return m
|
||||
}
|
||||
|
||||
companion object {
|
||||
@@ -289,6 +292,29 @@ class MediaSealer private constructor(
|
||||
internal fun withPinnedKeys(mediaId: ByteArray, mediaKey: ByteArray, meta: MediaMeta, segmentSize: Int) =
|
||||
MediaSealer(mediaId, mediaKey, segmentSize, meta)
|
||||
|
||||
/**
|
||||
* Seal a stream (a film from the gallery, a recording) to `out`, one
|
||||
* segment in memory at a time. Neither stream is closed.
|
||||
*/
|
||||
fun sealStream(
|
||||
input: java.io.InputStream,
|
||||
out: java.io.OutputStream,
|
||||
meta: MediaMeta = MediaMeta(),
|
||||
segmentSize: Int = DEFAULT_SEGMENT_SIZE,
|
||||
): SealResult {
|
||||
val sealer = MediaSealer(meta, segmentSize)
|
||||
val buf = ByteArray(segmentSize)
|
||||
while (true) {
|
||||
val n = input.read(buf)
|
||||
if (n < 0) break
|
||||
if (n > 0) sealer.push(buf.copyOf(n)).forEach { out.write(it) }
|
||||
}
|
||||
val (rest, result) = sealer.finish()
|
||||
rest.forEach { out.write(it) }
|
||||
out.flush()
|
||||
return result
|
||||
}
|
||||
|
||||
/** Seal bytes already in memory. */
|
||||
fun sealBytes(plaintext: ByteArray, meta: MediaMeta = MediaMeta(), segmentSize: Int = DEFAULT_SEGMENT_SIZE): Pair<ByteArray, SealResult> =
|
||||
MediaSealer(meta, segmentSize).sealAll(plaintext)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import no.zyon.shade.serialization.stringifyJson
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.net.URI
|
||||
@@ -34,6 +35,29 @@ class MediaGrant(
|
||||
}
|
||||
|
||||
fun open(): MediaReader = MediaReader.open(source(), keys())
|
||||
|
||||
/** Wire JSON, byte for byte what TS `encodeGrant` writes (field order fixed, meta canonical). */
|
||||
fun encode(): String {
|
||||
val o = LinkedHashMap<String, Any>()
|
||||
o["kind"] = MEDIA_GRANT_KIND
|
||||
o["mediaId"] = b64u(mediaId)
|
||||
o["key"] = b64u(mediaKey)
|
||||
o["root"] = rootDigest.joinToString("") { "%02x".format(it) }
|
||||
url?.let { o["url"] = it }
|
||||
readToken?.let { o["token"] = b64u(it) }
|
||||
meta?.let { o["meta"] = MediaMeta.validate(it).toJsonMap() }
|
||||
return stringifyJson(o)
|
||||
}
|
||||
|
||||
/** `pageUrl#shade=<base64url(json)>`: the link that opens this file, the key in the fragment (never sent to a server). */
|
||||
fun capabilityUrl(pageUrl: String): String =
|
||||
"${pageUrl.substringBefore('#')}#shade=${b64u(encode().toByteArray(Charsets.UTF_8))}"
|
||||
|
||||
companion object {
|
||||
/** The grant for a file just sealed (and uploaded to `url`). */
|
||||
fun of(r: SealResult, url: String? = null, readToken: ByteArray? = null, meta: MediaMeta? = null) =
|
||||
MediaGrant(r.mediaId, r.mediaKey, r.rootDigest, url, readToken, meta)
|
||||
}
|
||||
}
|
||||
|
||||
class LiveGrant(
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import com.google.crypto.tink.subtle.Ed25519Sign
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Who may upload to a relay and delete from it: an Ed25519 key and nothing
|
||||
* else (mirror of `@shade/media` owner.ts). Requests are signed over a fixed
|
||||
* string naming the operation, so a signature for one request cannot be
|
||||
* replayed as another, and over a timestamp the relay accepts within ten
|
||||
* minutes of its own clock.
|
||||
*/
|
||||
class MediaOwner(seed: ByteArray) {
|
||||
private val seed = seed.copyOf()
|
||||
private val signer = Ed25519Sign(seed)
|
||||
val publicKey: ByteArray = Ed25519Sign.KeyPair.newKeyPairFromSeed(seed).publicKey
|
||||
|
||||
init {
|
||||
require(seed.size == 32) { "owner seed must be 32 bytes" }
|
||||
}
|
||||
|
||||
/** The key as a relay's owner lists name it (`--owners`, `SHADE_MEDIA_OWNERS`). */
|
||||
val id: String get() = b64u(publicKey)
|
||||
|
||||
/** The seed, for keeping — in the Keystore-backed storage, never in plain prefs. */
|
||||
fun exportSeed(): ByteArray = seed.copyOf()
|
||||
|
||||
fun headers(op: OwnerOp, at: Long = System.currentTimeMillis()): Map<String, String> = mapOf(
|
||||
OWNER_HEADER to id,
|
||||
AT_HEADER to at.toString(),
|
||||
SIGNATURE_HEADER to b64u(signer.sign(message(op, at))),
|
||||
)
|
||||
|
||||
companion object {
|
||||
const val OWNER_HEADER = "x-shade-owner"
|
||||
const val AT_HEADER = "x-shade-at"
|
||||
const val SIGNATURE_HEADER = "x-shade-signature"
|
||||
const val READ_HASH_HEADER = "x-shade-read-hash"
|
||||
const val READ_TOKEN_HEADER = "x-shade-read"
|
||||
|
||||
fun generate(): MediaOwner = MediaOwner(ByteArray(32).also { SecureRandom().nextBytes(it) })
|
||||
|
||||
/** The exact bytes signed for `op` at `at` — shared with TS through `test-vectors/media.json`. */
|
||||
fun message(op: OwnerOp, at: Long): ByteArray = when (op) {
|
||||
is OwnerOp.Put -> "shade.media-put/v1|${op.id}|${op.size}|${op.readTokenHash}|$at"
|
||||
is OwnerOp.Upload -> "shade.media-upload/v1|${op.id}|${op.size}|${op.readTokenHash}|$at"
|
||||
is OwnerOp.Piece -> "shade.media-piece/v1|${op.id}|${op.offset}|${op.length}|$at"
|
||||
is OwnerOp.Abort -> "shade.media-abort/v1|${op.id}|$at"
|
||||
is OwnerOp.Delete -> "shade.media-delete/v1|${op.id}|$at"
|
||||
OwnerOp.List -> "shade.media-list/v1|$at"
|
||||
}.toByteArray(Charsets.UTF_8)
|
||||
}
|
||||
}
|
||||
|
||||
/** What an owner signs. `readTokenHash` is the hex SHA-256 of the read token, or "" for public ciphertext. */
|
||||
sealed class OwnerOp {
|
||||
data class Put(val id: String, val size: Long, val readTokenHash: String) : OwnerOp()
|
||||
data class Upload(val id: String, val size: Long, val readTokenHash: String) : OwnerOp()
|
||||
data class Piece(val id: String, val offset: Long, val length: Long) : OwnerOp()
|
||||
data class Abort(val id: String) : OwnerOp()
|
||||
data class Delete(val id: String) : OwnerOp()
|
||||
object List : OwnerOp()
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.channels.FileChannel
|
||||
import java.nio.file.StandardOpenOption
|
||||
|
||||
/** Where sealed bytes come from: a size and byte ranges, nothing else. */
|
||||
interface RangeSource {
|
||||
@@ -21,6 +26,20 @@ class ByteArraySource(private val bytes: ByteArray) : RangeSource {
|
||||
}
|
||||
}
|
||||
|
||||
/** A sealed file on disk — a film too large to hold, uploaded a piece at a time. Safe to read from several threads. */
|
||||
class FileRangeSource(file: File) : RangeSource, Closeable {
|
||||
private val ch = FileChannel.open(file.toPath(), StandardOpenOption.READ)
|
||||
override fun size(): Long = ch.size()
|
||||
override fun read(offset: Long, length: Int): ByteArray {
|
||||
val buf = ByteBuffer.allocate(length.coerceAtMost((size() - offset).coerceAtLeast(0).toInt()))
|
||||
while (buf.hasRemaining()) {
|
||||
if (ch.read(buf, offset + buf.position()) < 0) break
|
||||
}
|
||||
return if (buf.hasRemaining()) buf.array().copyOf(buf.position()) else buf.array()
|
||||
}
|
||||
override fun close() = ch.close()
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP Range reads against the Shade media routes (or any Range-capable
|
||||
* server). The read token, when the grant carries one, rides in
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
package no.zyon.shade.media
|
||||
|
||||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
import java.util.ArrayDeque
|
||||
import java.util.TreeSet
|
||||
import java.util.concurrent.ExecutorCompletionService
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
/** Files up to this size go up in one PUT; larger ones in pieces (mirror of `@shade/media` upload.ts). */
|
||||
const val DEFAULT_CHUNK_BYTES = 16L * 1024 * 1024
|
||||
const val OFFSET_HEADER = "x-shade-offset"
|
||||
|
||||
/** Failed tries in a row before a resumable upload gives up. */
|
||||
private const val MAX_TRIES = 8
|
||||
|
||||
/** The relay is restarting, overloaded or the network dropped: try again. */
|
||||
private class Transient(message: String) : IOException(message)
|
||||
|
||||
class MediaUploadException(message: String) : IOException(message)
|
||||
|
||||
/**
|
||||
* Upload sealed files to a Shade relay — mirror of the TS `MediaClient`, so a
|
||||
* phone can share a film or a video it recorded. Blocking: call it off the
|
||||
* main thread.
|
||||
*
|
||||
* A file above [DEFAULT_CHUNK_BYTES] goes in pieces, up to the relay's
|
||||
* window of them in flight. A dropped connection or a relay restart costs
|
||||
* the pieces in flight, not the upload: a failed piece is sent again after
|
||||
* asking the relay whether it landed after all. Calling [putSealed] again
|
||||
* with the same seal result and the same sealed file (after the app was
|
||||
* killed, say) resumes where the relay got to, since the media id is the same.
|
||||
*/
|
||||
class MediaUploader(
|
||||
server: String,
|
||||
private val owner: MediaOwner,
|
||||
private val timeoutMs: Int = 60_000,
|
||||
) {
|
||||
private val server = server.trimEnd('/')
|
||||
|
||||
fun mediaUrl(mediaId: ByteArray): String = "$server/v1/media/${hex(mediaId)}"
|
||||
|
||||
/**
|
||||
* Upload an already sealed file; `body` must be exactly `result.sealedSize`
|
||||
* bytes. `readToken`: what viewers must present — a fresh random one by
|
||||
* default, `null` for public ciphertext. `onProgress(acked, total)` after
|
||||
* each piece the relay has.
|
||||
*/
|
||||
fun putSealed(
|
||||
result: SealResult,
|
||||
body: RangeSource,
|
||||
readToken: ByteArray? = newReadToken(),
|
||||
meta: MediaMeta? = null,
|
||||
onProgress: ((Long, Long) -> Unit)? = null,
|
||||
): MediaGrant {
|
||||
val size = body.size()
|
||||
if (size != result.sealedSize) throw MediaFormatException("body is $size bytes, the seal produced ${result.sealedSize}")
|
||||
val readTokenHash = readToken?.let { hex(MessageDigest.getInstance("SHA-256").digest(it)) } ?: ""
|
||||
val id = hex(result.mediaId)
|
||||
val url = mediaUrl(result.mediaId)
|
||||
if (size <= DEFAULT_CHUNK_BYTES) {
|
||||
val bytes = body.read(0, size.toInt())
|
||||
val headers = owner.headers(OwnerOp.Put(id, size, readTokenHash)) +
|
||||
mapOf("content-type" to "application/vnd.shade.smf1") +
|
||||
(if (readTokenHash != "") mapOf(MediaOwner.READ_HASH_HEADER to readTokenHash) else emptyMap())
|
||||
val res = try {
|
||||
request("PUT", url, headers, bytes)
|
||||
} catch (e: IOException) {
|
||||
throw MediaUploadException("upload failed: ${e.message}")
|
||||
}
|
||||
if (res.status != 201) throw MediaUploadException("upload failed: HTTP ${res.status} ${res.text()}")
|
||||
onProgress?.invoke(size, size)
|
||||
} else {
|
||||
Pieces("$url/upload", id, size, readTokenHash, body, onProgress).run()
|
||||
}
|
||||
return MediaGrant.of(result, url, readToken, meta)
|
||||
}
|
||||
|
||||
/** Seal in memory and upload — a photo, a short clip, a document. */
|
||||
fun uploadBytes(plaintext: ByteArray, meta: MediaMeta = MediaMeta(), readToken: ByteArray? = newReadToken()): MediaGrant {
|
||||
val (sealed, result) = MediaSealer.sealBytes(plaintext, meta)
|
||||
return putSealed(result, ByteArraySource(sealed), readToken, meta)
|
||||
}
|
||||
|
||||
/**
|
||||
* Seal `input` into `sealedFile` and upload it — a film without holding it
|
||||
* in memory. The sealed copy is the caller's: keep it (with the returned
|
||||
* seal result) until this returns, to resume with [putSealed] if it fails.
|
||||
*/
|
||||
fun uploadStream(
|
||||
input: java.io.InputStream,
|
||||
sealedFile: File,
|
||||
meta: MediaMeta = MediaMeta(),
|
||||
readToken: ByteArray? = newReadToken(),
|
||||
onProgress: ((Long, Long) -> Unit)? = null,
|
||||
): MediaGrant {
|
||||
val result = sealedFile.outputStream().buffered().use { MediaSealer.sealStream(input, it, meta) }
|
||||
return FileRangeSource(sealedFile).use { putSealed(result, it, readToken, meta, onProgress) }
|
||||
}
|
||||
|
||||
/** Remove one of your files from the relay; false if it was not there. */
|
||||
fun delete(mediaId: ByteArray): Boolean {
|
||||
val res = request("DELETE", mediaUrl(mediaId), owner.headers(OwnerOp.Delete(hex(mediaId))), null)
|
||||
if (res.status == 404) return false
|
||||
if (res.status !in 200..299) throw MediaUploadException("delete failed: HTTP ${res.status} ${res.text()}")
|
||||
return true
|
||||
}
|
||||
|
||||
private inner class Pieces(
|
||||
private val at: String,
|
||||
private val id: String,
|
||||
private val size: Long,
|
||||
private val readTokenHash: String,
|
||||
private val body: RangeSource,
|
||||
private val onProgress: ((Long, Long) -> Unit)?,
|
||||
) {
|
||||
private inner class Status(json: JSONObject) {
|
||||
val chunk = json.getLong("chunk")
|
||||
val window = json.optInt("window", 1).coerceAtLeast(1)
|
||||
val received = json.getLong("received")
|
||||
val landed: Set<Long> = json.optJSONArray("landed")?.let { a -> (0 until a.length()).map { a.getLong(it) }.toSet() } ?: emptySet()
|
||||
val complete = json.optBoolean("complete", false)
|
||||
fun has(offset: Long) = offset < received || (offset / chunk) in landed
|
||||
}
|
||||
|
||||
/** A request that got no answer (refused, reset, timed out) is worth repeating. */
|
||||
private fun send(method: String, headers: Map<String, String>, body: ByteArray?): Answer =
|
||||
try {
|
||||
request(method, at, headers, body)
|
||||
} catch (e: IOException) {
|
||||
throw Transient(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
|
||||
private fun fail(res: Answer, what: String): Nothing {
|
||||
if (res.status >= 500 || res.status == 429) throw Transient("$what: HTTP ${res.status} ${res.text()}")
|
||||
throw MediaUploadException("upload failed: $what: HTTP ${res.status} ${res.text()}")
|
||||
}
|
||||
|
||||
/** Retry `fn` while it fails transiently, with backoff; `fn` learns which try it is. */
|
||||
private fun <T> retrying(fn: (attempt: Int) -> T): T {
|
||||
var attempt = 0
|
||||
while (true) {
|
||||
try {
|
||||
return fn(attempt)
|
||||
} catch (e: Transient) {
|
||||
if (attempt + 1 >= MAX_TRIES) throw MediaUploadException("upload failed after $MAX_TRIES tries: ${e.message}")
|
||||
attempt++
|
||||
Thread.sleep(minOf(30_000L, 500L shl attempt))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Start the upload, or learn how far it got. */
|
||||
private fun status(): Status {
|
||||
val headers = owner.headers(OwnerOp.Upload(id, size, readTokenHash)) +
|
||||
mapOf("x-shade-size" to size.toString()) +
|
||||
(if (readTokenHash != "") mapOf(MediaOwner.READ_HASH_HEADER to readTokenHash) else emptyMap())
|
||||
val res = send("POST", headers, ByteArray(0))
|
||||
if (res.status != 200 && res.status != 201) fail(res, "start")
|
||||
return try {
|
||||
Status(JSONObject(res.body))
|
||||
} catch (e: JSONException) {
|
||||
throw Transient("start: the relay's answer is not JSON")
|
||||
}
|
||||
}
|
||||
|
||||
private var chunk = 0L
|
||||
|
||||
/** One piece until the relay has it; true once the relay stored the whole file. */
|
||||
private fun sendPiece(offset: Long): Boolean = retrying { attempt ->
|
||||
if (attempt > 0) {
|
||||
// It may have landed before the connection dropped: ask before sending it again.
|
||||
val st = status()
|
||||
if (st.complete) return@retrying true
|
||||
if (st.has(offset)) return@retrying false
|
||||
}
|
||||
val length = minOf(chunk, size - offset)
|
||||
val piece = body.read(offset, length.toInt())
|
||||
if (piece.size.toLong() != length) throw MediaFormatException("the file shrank: read ${piece.size} of $length bytes at $offset")
|
||||
val res = send(
|
||||
"PUT",
|
||||
owner.headers(OwnerOp.Piece(id, offset, length)) +
|
||||
mapOf("content-type" to "application/octet-stream", OFFSET_HEADER to offset.toString()),
|
||||
piece,
|
||||
)
|
||||
when (res.status) {
|
||||
201 -> true
|
||||
200 -> false
|
||||
// Ahead of the window (pieces before it are still on the way): later.
|
||||
409 -> {
|
||||
val error = try { JSONObject(res.body).optString("error") } catch (e: JSONException) { "" }
|
||||
if (error == "OFFSET") throw Transient("piece ahead of the upload")
|
||||
throw MediaUploadException("upload failed: HTTP 409 ${res.text()}")
|
||||
}
|
||||
else -> fail(res, "piece at $offset")
|
||||
}
|
||||
}
|
||||
|
||||
private inner class Outcome(val offset: Long, val done: Boolean, val error: Throwable?)
|
||||
|
||||
fun run() {
|
||||
val opened = retrying { status() }
|
||||
if (opened.complete) {
|
||||
onProgress?.invoke(size, size)
|
||||
return
|
||||
}
|
||||
chunk = opened.chunk
|
||||
val window = opened.window
|
||||
var acked = 0L
|
||||
var complete = false
|
||||
val todo = ArrayDeque<Long>()
|
||||
var off = 0L
|
||||
while (off < size) {
|
||||
if (opened.has(off)) acked += minOf(chunk, size - off) else todo.add(off)
|
||||
off += chunk
|
||||
}
|
||||
onProgress?.invoke(acked, size)
|
||||
|
||||
val pool = Executors.newFixedThreadPool(window) { r -> Thread(r, "shade-upload").apply { isDaemon = true } }
|
||||
val done = ExecutorCompletionService<Outcome>(pool)
|
||||
val flying = TreeSet<Long>()
|
||||
var failure: Throwable? = null
|
||||
/**
|
||||
* The relay takes `window` pieces past what it has from the start, so a
|
||||
* piece is only sent within `window` of the first one not yet answered:
|
||||
* one slow piece holds the window, rather than pieces past it bouncing.
|
||||
*/
|
||||
fun mayLaunch(): Boolean {
|
||||
if (todo.isEmpty() || flying.size >= window) return false
|
||||
val lowest = if (flying.isEmpty()) todo.first() else minOf(todo.first(), flying.first())
|
||||
return todo.first() < lowest + window * chunk
|
||||
}
|
||||
try {
|
||||
while (!complete && failure == null && (todo.isNotEmpty() || flying.isNotEmpty())) {
|
||||
while (mayLaunch()) {
|
||||
val o = todo.removeFirst()
|
||||
flying.add(o)
|
||||
done.submit {
|
||||
try {
|
||||
Outcome(o, sendPiece(o), null)
|
||||
} catch (e: Throwable) {
|
||||
Outcome(o, false, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
val r = done.take().get()
|
||||
flying.remove(r.offset)
|
||||
if (r.error != null) {
|
||||
failure = failure ?: r.error
|
||||
continue
|
||||
}
|
||||
if (r.done) complete = true
|
||||
acked += minOf(chunk, size - r.offset)
|
||||
if (!complete) onProgress?.invoke(acked, size)
|
||||
}
|
||||
while (flying.isNotEmpty()) flying.remove(done.take().get().offset)
|
||||
} finally {
|
||||
pool.shutdownNow()
|
||||
}
|
||||
failure?.let { throw it }
|
||||
if (!complete) {
|
||||
// Every piece is in but no answer said so (they crossed a completion
|
||||
// that failed and was retried): an empty piece at the end finishes it.
|
||||
retrying {
|
||||
val res = send("PUT", owner.headers(OwnerOp.Piece(id, size, 0)) + mapOf(OFFSET_HEADER to size.toString()), ByteArray(0))
|
||||
if (res.status != 201) fail(res, "finish")
|
||||
}
|
||||
}
|
||||
onProgress?.invoke(size, size)
|
||||
}
|
||||
}
|
||||
|
||||
private class Answer(val status: Int, val body: String, private val contentType: String) {
|
||||
/**
|
||||
* What a refusal says, for an error message: the relay's JSON as it is,
|
||||
* but not an HTML error page (a proxy's) poured into a log.
|
||||
*/
|
||||
fun text(): String {
|
||||
if (contentType.contains("text/html") || body.trimStart().startsWith("<")) return ""
|
||||
return if (body.length > 300) "${body.take(300)}…" else body
|
||||
}
|
||||
}
|
||||
|
||||
private fun request(method: String, url: String, headers: Map<String, String>, body: ByteArray?): Answer {
|
||||
val c = URL(url).openConnection() as HttpURLConnection
|
||||
try {
|
||||
c.requestMethod = method
|
||||
c.connectTimeout = timeoutMs
|
||||
c.readTimeout = timeoutMs
|
||||
c.useCaches = false
|
||||
for ((k, v) in headers) c.setRequestProperty(k, v)
|
||||
if (body != null) {
|
||||
c.doOutput = true
|
||||
c.setFixedLengthStreamingMode(body.size)
|
||||
c.outputStream.use { it.write(body) }
|
||||
}
|
||||
val status = c.responseCode
|
||||
val stream = if (status >= 400) c.errorStream else c.inputStream
|
||||
val text = stream?.use { String(it.readBytes(), Charsets.UTF_8) } ?: ""
|
||||
return Answer(status, text, c.contentType ?: "")
|
||||
} finally {
|
||||
c.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val rng = SecureRandom()
|
||||
|
||||
fun newReadToken(): ByteArray = ByteArray(32).also { rng.nextBytes(it) }
|
||||
|
||||
private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package no.zyon.shade
|
||||
|
||||
import no.zyon.shade.media.FileRangeSource
|
||||
import no.zyon.shade.media.Grants
|
||||
import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaOwner
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.MediaUploader
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
import java.security.SecureRandom
|
||||
|
||||
/**
|
||||
* Live cross-check of [MediaUploader] against the real TS relay — skipped
|
||||
* unless `SHADE_MEDIA_LIVE_SPEC` points at the spec file a TS driver wrote.
|
||||
*
|
||||
* Run it via `bun run scripts/media-live-kotlin.ts`: the driver serves
|
||||
* `createMediaService` with two faults injected on the pieces, uploads a file
|
||||
* with the TS client and writes `{ url, seed, tsLink, tsSha256, scratch,
|
||||
* kotlinOut }`. This test opens the TS file, uploads a film in pieces and a
|
||||
* photo in one PUT, and records the links in `kotlinOut`; the driver then
|
||||
* reads the film back with the TS reader.
|
||||
*/
|
||||
class MediaLiveTest {
|
||||
|
||||
private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
|
||||
|
||||
private fun fromHex(s: String) =
|
||||
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||
|
||||
@Test
|
||||
fun uploadsInPiecesThroughFaultsForTsToRead() {
|
||||
val specPath = System.getenv("SHADE_MEDIA_LIVE_SPEC")
|
||||
assumeTrue("SHADE_MEDIA_LIVE_SPEC not set — live cross-check skipped", !specPath.isNullOrEmpty())
|
||||
val spec = JSONObject(File(specPath!!).readText())
|
||||
val uploader = MediaUploader(spec.getString("url"), MediaOwner(fromHex(spec.getString("seed"))))
|
||||
|
||||
// Read what TS uploaded, from its link.
|
||||
val tsGrant = Grants.fromCapabilityUrl(spec.getString("tsLink")) as MediaGrant
|
||||
tsGrant.open().use { r -> assertEquals(spec.getString("tsSha256"), sha256(r.read(0, r.size.toInt()))) }
|
||||
|
||||
// A film from the phone: sealed to a file, up in three pieces (16 MiB each),
|
||||
// through a lost answer on the second and a refusal of the third.
|
||||
val plain = ByteArray(40 * 1024 * 1024).also { SecureRandom().nextBytes(it) }
|
||||
val sealedFile = File(spec.getString("scratch"), "film.smf")
|
||||
val meta = MediaMeta(name = "Fra telefonen — «Kveld».mp4", mime = "video/mp4", durationMs = 61_500, width = 1080, height = 1920)
|
||||
val progress = mutableListOf<Long>()
|
||||
val token = MediaUploader.newReadToken()
|
||||
val result = sealedFile.outputStream().buffered().use { MediaSealer.sealStream(plain.inputStream(), it, meta) }
|
||||
val film = FileRangeSource(sealedFile).use { body ->
|
||||
uploader.putSealed(result, body, token, meta) { acked, total ->
|
||||
synchronized(progress) { progress += acked }
|
||||
assertEquals(result.sealedSize, total)
|
||||
}
|
||||
}
|
||||
assertEquals(result.sealedSize, progress.last())
|
||||
assertTrue("progress only grows: $progress", progress.zipWithNext().all { (a, b) -> a <= b })
|
||||
film.open().use { r -> assertEquals(sha256(plain), sha256(r.read(0, r.size.toInt()))) }
|
||||
|
||||
// The same film again (the app was killed after the upload): the relay
|
||||
// already has it, nothing is sent, the link is the same.
|
||||
val again = FileRangeSource(sealedFile).use { uploader.putSealed(result, it, token, meta) }
|
||||
assertEquals(film.capabilityUrl("https://watch.example/"), again.capabilityUrl("https://watch.example/"))
|
||||
|
||||
// A photo: one PUT; then deleted.
|
||||
val photo = uploader.uploadBytes(ByteArray(300_000).also { SecureRandom().nextBytes(it) }, MediaMeta(name = "IMG_0001.jpg", mime = "image/jpeg"))
|
||||
photo.open().use { assertEquals("IMG_0001.jpg", it.meta.name) }
|
||||
assertTrue(uploader.delete(photo.mediaId))
|
||||
assertFalse(uploader.delete(photo.mediaId))
|
||||
|
||||
File(spec.getString("kotlinOut")).writeText(
|
||||
JSONObject()
|
||||
.put("film", JSONObject().put("link", film.capabilityUrl("https://watch.example/")).put("sha256", sha256(plain)).put("size", plain.size))
|
||||
.put("again", again.capabilityUrl("https://watch.example/"))
|
||||
.put("photo", JSONObject().put("url", photo.url))
|
||||
.toString(),
|
||||
)
|
||||
sealedFile.delete()
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,10 @@ import no.zyon.shade.media.MediaGrant
|
||||
import no.zyon.shade.media.MediaIntegrityException
|
||||
import no.zyon.shade.media.MediaKeys
|
||||
import no.zyon.shade.media.MediaMeta
|
||||
import no.zyon.shade.media.MediaOwner
|
||||
import no.zyon.shade.media.MediaReader
|
||||
import no.zyon.shade.media.MediaSealer
|
||||
import no.zyon.shade.media.OwnerOp
|
||||
import no.zyon.shade.media.Subtitles
|
||||
import no.zyon.shade.media.chainStep
|
||||
import no.zyon.shade.media.decodeFrame
|
||||
@@ -228,4 +230,48 @@ class MediaVectorTest {
|
||||
Subtitles.of(MediaMeta(extra = mapOf("shade.subtitles" to """[{"lang":"no; x","grant":{}}]""")))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ownerSignaturesMatchTheRelaysByteForByte() {
|
||||
val v = byPrefix("owner:").single()
|
||||
val owner = MediaOwner(hex(v.getString("seed")))
|
||||
assertEquals(v.getString("owner"), owner.id)
|
||||
val at = v.getLong("at")
|
||||
val requests = v.getJSONArray("requests")
|
||||
for (i in 0 until requests.length()) {
|
||||
val r = requests.getJSONObject(i)
|
||||
val op = when (r.getString("op")) {
|
||||
"put" -> OwnerOp.Put(r.getString("id"), r.getLong("size"), r.getString("readTokenHash"))
|
||||
"upload" -> OwnerOp.Upload(r.getString("id"), r.getLong("size"), r.getString("readTokenHash"))
|
||||
"piece" -> OwnerOp.Piece(r.getString("id"), r.getLong("offset"), r.getLong("length"))
|
||||
"abort" -> OwnerOp.Abort(r.getString("id"))
|
||||
"delete" -> OwnerOp.Delete(r.getString("id"))
|
||||
"list" -> OwnerOp.List
|
||||
else -> error("unknown op ${r.getString("op")}")
|
||||
}
|
||||
assertEquals(r.getString("message"), String(MediaOwner.message(op, at)))
|
||||
val want = r.getJSONObject("headers")
|
||||
val got = owner.headers(op, at)
|
||||
assertEquals(want.keySet(), got.keys)
|
||||
for (k in got.keys) assertEquals("${r.getString("op")} $k", want.getString(k), got[k])
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun grantsEncodeToTheSameJsonAndLinkAsTs() {
|
||||
val v = byPrefix("grant encode:").single()
|
||||
val g = MediaGrant(
|
||||
hex(v.getString("mediaId")),
|
||||
hex(v.getString("mediaKey")),
|
||||
hex(v.getString("rootDigest")),
|
||||
v.getString("url"),
|
||||
hex(v.getString("readToken")),
|
||||
MediaMeta.fromJson(v.getString("meta")),
|
||||
)
|
||||
assertEquals(v.getString("json"), g.encode())
|
||||
assertEquals(v.getString("link"), g.capabilityUrl(v.getString("pageUrl")))
|
||||
// And back.
|
||||
val back = Grants.fromCapabilityUrl(v.getString("link")) as MediaGrant
|
||||
assertEquals(v.getString("json"), back.encode())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user