feat(android): Share to Shade — a video from the gallery is sealed on the phone and uploaded

ShadeUpload turns a shared content:// URI into meta and an upload job;
KeystoreSecretFile keeps the owner seed under a Keystore key. The demo app
takes SEND/SEND_MULTIPLE of video, images, audio and documents, uploads in a
foreground service with progress, and its done notification plays the file
or shares the link; the player gets a Share button. The live cross-check
also uploads a content:// share under Robolectric.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-19 00:28:36 +02:00
parent b53dcd7813
commit 0a706cdb47
16 changed files with 733 additions and 11 deletions

View File

@@ -29,6 +29,10 @@ android {
testOptions {
unitTests.isIncludeAndroidResources = true
unitTests.all {
// ShadeUploadTest's live half is gated on this; as an input, a new relay reruns it.
it.inputs.property("shadeMediaLiveSpec", System.getenv("SHADE_MEDIA_LIVE_SPEC") ?: "")
}
}
}

View File

@@ -0,0 +1,104 @@
package no.zyon.shade.media.android
import android.content.Context
import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.provider.OpenableColumns
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaMeta
import no.zyon.shade.media.MediaUploader
import no.zyon.shade.media.UploadJobs
import java.io.FileNotFoundException
/**
* Sealing and uploading what the phone has — a video from the gallery, a
* photo, a recording, any document a share hands over as a `content://` URI.
* Blocking: run it off the main thread (in a foreground service for a film).
*/
object ShadeUpload {
/** What a share is: the URI, and the meta it will be sealed with. */
class Item(val uri: Uri, val size: Long, val meta: MediaMeta)
/**
* Name, type and size from the content resolver; duration and picture size
* read from the file itself (video, audio, images), so a library can show
* them without opening it. Nothing else — no location, no path — goes in.
*/
fun describe(context: Context, uri: Uri): Item {
val cr = context.contentResolver
var name: String? = null
var size = -1L
cr.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
if (c.moveToFirst()) {
c.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 && !c.isNull(it) }?.let { name = c.getString(it) }
c.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !c.isNull(it) }?.let { size = c.getLong(it) }
}
}
val mime = cr.getType(uri)?.takeIf { MIME_RE.matches(it) }
var durationMs: Long? = null
var width: Long? = null
var height: Long? = null
when {
mime?.startsWith("video/") == true || mime?.startsWith("audio/") == true -> runCatching {
MediaMetadataRetriever().apply { setDataSource(context, uri) }.let { r ->
try {
durationMs = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull()
val w = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toLongOrNull()
val h = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toLongOrNull()
val turned = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toIntOrNull()?.let { it % 180 != 0 } ?: false
// As it is shown: a portrait phone video is stored sideways.
width = if (turned) h else w
height = if (turned) w else h
} finally {
r.release()
}
}
}
mime?.startsWith("image/") == true -> runCatching {
val o = BitmapFactory.Options().apply { inJustDecodeBounds = true }
cr.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, o) }
if (o.outWidth > 0) {
width = o.outWidth.toLong()
height = o.outHeight.toLong()
}
}
}
val meta = MediaMeta(
mime = mime,
name = name?.let(::cleanName),
durationMs = durationMs,
width = width,
height = height,
)
return Item(uri, size, MediaMeta.validate(meta))
}
/**
* Seal and upload `item` as a job in `jobs` (see [MediaUploader.upload]):
* killed half-way, the same call resumes it; shared again, it gives the
* same link while the relay has the file.
*/
fun upload(
context: Context,
uploader: MediaUploader,
jobs: UploadJobs,
item: Item,
onProgress: ((Long, Long) -> Unit)? = null,
): MediaGrant {
return uploader.upload(jobs, jobKey(jobs, uploader, item), item.meta.name ?: item.uri.toString(), item.meta, {
context.contentResolver.openInputStream(item.uri) ?: throw FileNotFoundException("cannot open ${item.uri}")
}, onProgress = onProgress)
}
/** The job `item` is in `jobs` when uploaded with `uploader`: the relay, the URI, its size and name. */
fun jobKey(jobs: UploadJobs, uploader: MediaUploader, item: Item): String =
jobs.key(uploader.server, item.uri.toString(), item.size.toString(), item.meta.name ?: "")
private val MIME_RE = Regex("""^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$""", RegexOption.IGNORE_CASE)
/** A display name, not a path; control characters out (the meta refuses them). */
private fun cleanName(n: String): String? =
n.substringAfterLast('/').filter { it.code >= 0x20 && it.code != 0x7f }.take(1024).ifEmpty { null }
}

View File

@@ -0,0 +1,94 @@
package no.zyon.shade.media.android
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.database.MatrixCursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.provider.OpenableColumns
import androidx.test.core.app.ApplicationProvider
import no.zyon.shade.media.MediaOwner
import no.zyon.shade.media.MediaUploader
import no.zyon.shade.media.UploadJobs
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
import java.security.MessageDigest
import java.security.SecureRandom
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ShadeUploadTest {
/** A gallery: one video, served the way a share hands it over. */
class Gallery : ContentProvider() {
override fun onCreate() = true
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, args: Array<out String>?, sort: String?): Cursor =
MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)).apply { addRow(arrayOf<Any>(name, file!!.length())) }
override fun getType(uri: Uri) = "video/mp4"
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor = ParcelFileDescriptor.open(file!!, ParcelFileDescriptor.MODE_READ_ONLY)
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, selection: String?, args: Array<out String>?) = 0
override fun update(uri: Uri, values: ContentValues?, selection: String?, args: Array<out String>?) = 0
companion object {
var file: File? = null
var name = "VID_0042.mp4"
}
}
private val context = ApplicationProvider.getApplicationContext<android.app.Application>()
private val uri = Uri.parse("content://test.gallery/video/42")
private fun video(bytes: ByteArray): File {
Robolectric.setupContentProvider(Gallery::class.java, "test.gallery")
return File.createTempFile("vid", ".mp4").also {
it.writeBytes(bytes)
it.deleteOnExit()
Gallery.file = it
}
}
private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
@Test
fun describeTakesTheNameTypeAndSizeAndNothingElse() {
video(ByteArray(5000))
Gallery.name = "Kveld\u0007 på hytta.mp4"
val item = ShadeUpload.describe(context, uri)
assertEquals("Kveld på hytta.mp4", item.meta.name)
assertEquals("video/mp4", item.meta.mime)
assertEquals(5000L, item.size)
assertEquals(null, item.meta.createdAt)
assertEquals(null, item.meta.extra)
Gallery.name = "VID_0042.mp4"
}
/** Against a real TS relay — run by `bun run scripts/media-live-kotlin.ts`, skipped without it. */
@Test
fun aSharedVideoIsSealedFromItsUriAndUploaded() {
val specPath = System.getenv("SHADE_MEDIA_LIVE_SPEC")
assumeTrue("SHADE_MEDIA_LIVE_SPEC not set — live upload skipped", !specPath.isNullOrEmpty())
val spec = JSONObject(File(specPath!!).readText())
val seed = spec.getString("seed").chunked(2).map { it.toInt(16).toByte() }.toByteArray()
val uploader = MediaUploader(spec.getString("url"), MediaOwner(seed))
val jobs = UploadJobs(File(spec.getString("scratch"), "android-jobs"))
val bytes = ByteArray(20 * 1024 * 1024).also { SecureRandom().nextBytes(it) }
video(bytes)
val item = ShadeUpload.describe(context, uri)
val grant = ShadeUpload.upload(context, uploader, jobs, item)
grant.open().use { r ->
assertEquals("VID_0042.mp4", r.meta.name)
assertEquals(sha256(bytes), sha256(r.read(0, r.size.toInt())))
}
// Shared again: the same job, the same link.
assertEquals(grant.encode(), ShadeUpload.upload(context, uploader, jobs, ShadeUpload.describe(context, uri)).encode())
File(spec.getString("scratch"), "android-out.txt").writeText(grant.capabilityUrl("https://watch.example/"))
}
}