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

@@ -122,6 +122,13 @@ New package **`@shade/media`** — see `docs/media.md`.
(against a new grant-encode vector). `scripts/media-live-kotlin.ts` runs it
against a real TS relay with a lost answer and a refused piece injected;
TS reads the film back byte for byte.
- **Share to Shade (Android).** `UploadJobs` lets an upload survive the app
being killed (sealed once, resumed with the same media id, one link per
shared file); `ShadeUpload` seals a shared `content://` URI with its name,
type, duration and picture size; `KeystoreSecretFile` keeps the owner seed
under a Keystore key. The demo app takes shares from the gallery, uploads
them in a foreground service with progress, and offers the link to play or
share. Its minSdk is now 28.
### Fixed

View File

@@ -0,0 +1,68 @@
package no.zyon.shade.keystore
import java.io.File
import java.io.IOException
import java.security.GeneralSecurityException
import java.security.SecureRandom
/**
* A small secret (a signing seed, a token) kept in a file, encrypted under a
* hardware-backed Android Keystore key that never leaves the secure element.
* For secrets the app uses without asking the user each time — a media owner
* key that signs every upload piece — so the key is not biometric-gated;
* use [KeystoreMasterKey] with `requireBiometric` for those that should be.
*
* File: `"SKS1" || nonce(12) || AES-256-GCM(secret)`, with the alias as AAD
* so a file cannot be swapped in under another alias. A backup restored to
* another phone carries the file but not the key: [read] then throws
* [SecretLostException] rather than handing back garbage.
*/
class KeystoreSecretFile(private val file: File, private val alias: String) {
private val key = KeystoreMasterKey(alias, requireBiometric = false)
class SecretLostException(message: String, cause: Throwable? = null) : IOException(message, cause)
/** The secret, or null if none was written. */
fun read(): ByteArray? {
if (!file.exists()) return null
val b = file.readBytes()
if (b.size < HEADER + 16 || !b.copyOfRange(0, 4).contentEquals(MAGIC)) throw SecretLostException("${file.name} is not a Keystore secret")
if (!key.exists()) throw SecretLostException("the Keystore key for ${file.name} is gone (restored from a backup, or the app's keys were cleared)")
return try {
val c = key.cipherForDecrypt(b.copyOfRange(4, HEADER))
c.updateAAD(alias.toByteArray(Charsets.UTF_8))
c.doFinal(b, HEADER, b.size - HEADER)
} catch (e: GeneralSecurityException) {
throw SecretLostException("${file.name} does not open under its Keystore key", e)
}
}
fun write(secret: ByteArray) {
val c = key.cipherForEncrypt()
c.updateAAD(alias.toByteArray(Charsets.UTF_8))
val ct = c.doFinal(secret)
val nonce = c.iv
check(nonce.size == 12) { "unexpected GCM nonce size ${nonce.size}" }
file.parentFile?.mkdirs()
val tmp = File(file.path + ".tmp")
tmp.writeBytes(MAGIC + nonce + ct)
if (!tmp.renameTo(file)) throw IOException("cannot write ${file.name}")
}
/** The secret, made with `size` random bytes on first use. */
fun getOrCreate(size: Int): ByteArray = read() ?: ByteArray(size).also {
SecureRandom().nextBytes(it)
write(it)
}
/** Remove the file and its key: the secret is gone for good. */
fun destroy() {
file.delete()
key.deleteKey()
}
private companion object {
val MAGIC = "SKS1".toByteArray(Charsets.US_ASCII)
const val HEADER = 4 + 12
}
}

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/"))
}
}

View File

@@ -42,7 +42,7 @@ class MediaUploader(
private val owner: MediaOwner,
private val timeoutMs: Int = 60_000,
) {
private val server = server.trimEnd('/')
val server = server.trimEnd('/')
fun mediaUrl(mediaId: ByteArray): String = "$server/v1/media/${hex(mediaId)}"
@@ -130,7 +130,7 @@ class MediaUploader(
val j = job ?: run {
val sealed = jobs.sealedFile(key)
val result = open().use { input -> sealed.outputStream().buffered().use { MediaSealer.sealStream(input, it, meta) } }
UploadJobs.Job(result, readToken, meta, source).also { jobs.save(key, it) }
UploadJobs.Job(result, readToken, meta, source, server = server).also { jobs.save(key, it) }
}
val grant = FileRangeSource(jobs.sealedFile(key)).use { putSealed(j.result, it, j.readToken, j.meta, onProgress) }
jobs.done(key, j, grant)
@@ -334,7 +334,7 @@ class MediaUploader(
}
private fun request(method: String, url: String, headers: Map<String, String>, body: ByteArray?): Answer {
val c = URL(url).openConnection() as HttpURLConnection
val c = java.net.URI(url).toURL().openConnection() as HttpURLConnection
try {
c.requestMethod = method
c.connectTimeout = timeoutMs

View File

@@ -36,6 +36,8 @@ class UploadJobs(private val dir: File) {
val source: String,
/** Set once the relay stored the file. */
val grant: MediaGrant? = null,
/** The relay it goes to, for resuming it after a restart. */
val server: String = "",
)
class BusyException(message: String) : Exception(message)
@@ -107,6 +109,7 @@ class UploadJobs(private val dir: File) {
MediaMeta.fromJson(o.getString("meta")),
o.optString("source"),
if (o.has("grant")) Grants.parse(o.getString("grant")) as? MediaGrant else null,
o.optString("server"),
)
} catch (e: JSONException) {
return null
@@ -122,6 +125,7 @@ class UploadJobs(private val dir: File) {
val o = JSONObject()
.put("v", 1)
.put("source", job.source)
.put("server", job.server)
.put(
"result",
JSONObject()
@@ -144,7 +148,7 @@ class UploadJobs(private val dir: File) {
/** The relay has it: keep the grant, drop the sealed copy. */
fun done(key: String, job: Job, grant: MediaGrant): Job {
val finished = Job(job.result, job.readToken, job.meta, job.source, grant)
val finished = Job(job.result, job.readToken, job.meta, job.source, grant, job.server)
save(key, finished)
sealedFile(key).delete()
return finished

View File

@@ -23,7 +23,7 @@ class UploadJobsTest {
val result = jobs.sealedFile(key).also { it.parentFile.mkdirs() }.outputStream().use {
MediaSealer.sealStream(ByteArray(200_000) { i -> i.toByte() }.inputStream(), it, meta)
}
return UploadJobs.Job(result, ByteArray(32) { 9 }, meta, "content://media/1")
return UploadJobs.Job(result, ByteArray(32) { 9 }, meta, "content://media/1", server = "https://relay")
}
@Test
@@ -48,6 +48,7 @@ class UploadJobsTest {
assertArrayEquals(job.result.mediaKey, back.result.mediaKey)
assertArrayEquals(job.readToken, back.readToken)
assertEquals("Kveld.mp4", back.meta.name)
assertEquals("https://relay", back.server)
assertEquals(listOf(key), jobs.unfinished().map { it.first })
// Cut short: not resumable.

View File

@@ -13,7 +13,7 @@ android {
defaultConfig {
applicationId = "no.zyon.shade.mediademo"
minSdk = 24
minSdk = 28 // the owner key lives in the Keystore (:shade-android-keystore)
targetSdk = 35
versionCode = 1
versionName = "4.15.0"
@@ -41,5 +41,6 @@ android {
dependencies {
implementation(project(":shade-android-media"))
implementation(project(":shade-android-keystore"))
implementation("androidx.media3:media3-ui:1.5.1")
}

View File

@@ -2,6 +2,11 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<!-- Uploading a film runs in the foreground, with its progress shown. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Cleartext is allowed so the demo can reach a relay on the LAN
(`shade media serve` speaks plain HTTP). The media is sealed end to
@@ -25,5 +30,25 @@
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<!-- Share a video, photo, song or document: sealed here, uploaded to your relay. -->
<activity
android:name=".ShareActivity"
android:exported="true"
android:label="Share to Shade"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="video/*" />
<data android:mimeType="image/*" />
<data android:mimeType="audio/*" />
<data android:mimeType="application/*" />
</intent-filter>
</activity>
<service
android:name=".UploadService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>

View File

@@ -35,7 +35,8 @@ import java.util.concurrent.Executors
* channel: live video/audio through ExoPlayer, a live log as scrolling text,
* live pictures (a webcam, a watched folder) one after another.
*
* The link comes from a share (`ACTION_SEND` text), from
* The link comes from a share (`ACTION_SEND` text), from an upload's
* notification (see [ShareActivity]), from
* `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link '<link>'`,
* or is pasted into the field. Opening the reader fetches the footer and
* trailer over the network, so it runs off the main thread.
@@ -51,6 +52,9 @@ class PlayerActivity : Activity() {
private lateinit var log: TextView
private lateinit var logScroll: ScrollView
private lateinit var picture: ImageView
private lateinit var share: Button
/** The link playing now, to hand on. */
private var current: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -82,11 +86,21 @@ class PlayerActivity : Activity() {
setBackgroundColor(Color.BLACK)
visibility = android.view.View.GONE
}
share = Button(this).apply {
text = "Share"
visibility = android.view.View.GONE
setOnClickListener {
current?.let { link ->
startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, link), "Share link"))
}
}
}
val bar = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
addView(field, LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f))
addView(open)
addView(share)
}
setContentView(
LinearLayout(this).apply {
@@ -122,6 +136,8 @@ class PlayerActivity : Activity() {
status.text = "Not a Shade link: ${it.message}"
return
}
current = link
share.visibility = android.view.View.VISIBLE
when (grant) {
is LiveGrant -> watch(grant)
is MediaGrant -> {

View File

@@ -0,0 +1,126 @@
package no.zyon.shade.mediademo
import android.Manifest
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.OpenableColumns
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import java.util.concurrent.Executors
/**
* «Share to Shade»: a video, photo, song or document shared from the gallery
* or a file manager is sealed on the phone and uploaded to your relay; the
* link to it comes back as a notification. The first time, enter the relay
* and add the owner id shown here to its owners
* (`shade media serve --owners <id>`).
*/
class ShareActivity : Activity() {
private val io = Executors.newSingleThreadExecutor()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val uris = UploadService.urisOf(intent)
val pad = (16 * resources.displayMetrics.density).toInt()
fun label(t: String, size: Float = 14f, color: Int = Color.LTGRAY) = TextView(this).apply {
text = t
textSize = size
setTextColor(color)
setPadding(0, pad / 2, 0, pad / 2)
}
val files = label(if (uris.isEmpty()) "Nothing to upload" else "${uris.size} file(s)", 16f, Color.WHITE)
val relay = EditText(this).apply {
hint = "http://192.168.1.10:3900"
setSingleLine()
setText(Uploads.relay(this@ShareActivity) ?: "")
setTextColor(Color.WHITE)
}
val ownerId = label("Owner key: …", 12f)
val copy = Button(this).apply { text = "Copy owner id"; isEnabled = false }
val upload = Button(this).apply { text = "Seal and upload"; isEnabled = uris.isNotEmpty() }
val note = label("Sealed on this phone: the relay stores only ciphertext, and the key travels in the link.", 12f)
setContentView(
LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Color.rgb(15, 17, 21))
setPadding(pad, pad, pad, pad)
addView(label("Share to Shade", 22f, Color.WHITE))
addView(files)
addView(label("Relay"))
addView(relay, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
addView(ownerId)
addView(copy)
addView(upload)
addView(note)
},
)
// Off the main thread: the Keystore may be a StrongBox chip, and names come from a provider.
io.execute {
val owner = runCatching { Uploads.owner(this) }
val names = uris.map { uri ->
runCatching {
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
if (!c.moveToFirst()) null else "${c.getString(0)} · ${"%.1f".format(c.getLong(1) / 1048576.0)} MiB"
}
}.getOrNull() ?: uri.lastPathSegment ?: "file"
}
runOnUiThread {
if (names.isNotEmpty()) files.text = names.joinToString("\n")
owner.fold(
onSuccess = { o ->
ownerId.text = "Owner key (add to the relay's owners):\n${o.id}"
copy.isEnabled = true
copy.setOnClickListener {
getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("Shade owner id", o.id))
}
},
onFailure = { ownerId.text = "No owner key: ${it.message}"; upload.isEnabled = false },
)
}
}
upload.setOnClickListener {
val url = relay.text.toString().trim()
if (!Regex("^https?://[^\\s/]+.*$").matches(url)) {
relay.error = "http(s)://host:port"
return@setOnClickListener
}
Uploads.setRelay(this, url)
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
} else {
send(uris)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
// Without notifications the upload still runs; only its progress and link are not shown.
send(UploadService.urisOf(intent))
}
private fun send(uris: List<android.net.Uri>) {
val clip = ClipData.newRawUri("shared", uris.first()).apply { uris.drop(1).forEach { addItem(ClipData.Item(it)) } }
val svc = Intent(this, UploadService::class.java).apply {
clipData = clip
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startForegroundService(svc)
finish()
}
override fun onDestroy() {
io.shutdown()
super.onDestroy()
}
}

View File

@@ -0,0 +1,196 @@
package no.zyon.shade.mediademo
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.PowerManager
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.UploadJobs
import no.zyon.shade.media.android.ShadeUpload
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
/**
* Seals and uploads shared files one after another, in the foreground (with
* a progress notification) so Android lets a film finish. A file that was
* sealed before the app was killed is resumed when the service starts again;
* one that was still being sealed is started over the next time it is shared.
* When a file is up, a notification opens it, or shares its link.
*/
class UploadService : Service() {
private val worker = Executors.newSingleThreadExecutor()
private val pending = AtomicInteger(0)
private val ids = AtomicInteger(100)
private val main = Handler(Looper.getMainLooper())
/** Jobs queued or running in this run, so a redelivered share is not done twice. Main thread only. */
private val queued = HashSet<String>()
private var lastStart = 0
private lateinit var nm: NotificationManager
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
nm = getSystemService(NotificationManager::class.java)
nm.createNotificationChannel(NotificationChannel(PROGRESS, "Uploads", NotificationManager.IMPORTANCE_LOW))
nm.createNotificationChannel(NotificationChannel(DONE, "Uploaded", NotificationManager.IMPORTANCE_DEFAULT))
goForeground(progress("Shade", "Preparing…", 0, 0))
// What an earlier run sealed but did not get up.
val jobs = Uploads.jobs(this)
jobs.prune()
for ((key, job) in jobs.unfinished()) {
if (job.server.isEmpty()) continue
enqueue(key, job.meta.name ?: "file") { onProgress ->
Uploads.uploader(this, job.server).upload(jobs, key, job.source, job.meta, {
throw IllegalStateException("sealed copy missing")
}, onProgress = onProgress)
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
lastStart = startId
val relay = Uploads.relay(this)
val uris = intent?.let(::urisOf).orEmpty()
if (relay != null) {
for (uri in uris) {
// Described now, while the share's read permission still holds.
val item = try {
ShadeUpload.describe(this, uri)
} catch (e: Exception) {
failed(uri.lastPathSegment ?: "file", e)
continue
}
val uploader = Uploads.uploader(this, relay)
val jobs = Uploads.jobs(this)
enqueue(ShadeUpload.jobKey(jobs, uploader, item), item.meta.name ?: "file") { onProgress ->
ShadeUpload.upload(this, uploader, jobs, item, onProgress)
}
}
}
if (pending.get() == 0) stopSelf(startId)
return START_REDELIVER_INTENT
}
private fun enqueue(key: String, name: String, run: ((Long, Long) -> Unit) -> MediaGrant) {
if (!queued.add(key)) return
pending.incrementAndGet()
worker.execute {
val wake = getSystemService(PowerManager::class.java).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "shade:upload")
wake.acquire(6 * 3600_000L)
var shown = -1
try {
val grant = run { acked, total ->
val pct = if (total > 0) (acked * 100 / total).toInt() else 0
if (pct != shown) {
shown = pct
nm.notify(FOREGROUND_ID, progress(name, "${mib(acked)} of ${mib(total)} MiB", pct, 100))
}
}
uploaded(name, grant)
} catch (e: UploadJobs.BusyException) {
// Already on its way in this run.
} catch (e: Exception) {
failed(name, e)
} finally {
wake.release()
pending.decrementAndGet()
// On the main thread, after any share that came in meanwhile has queued its files.
main.post {
queued.remove(key)
if (pending.get() == 0) stopSelf(lastStart)
}
}
}
}
private fun uploaded(name: String, grant: MediaGrant) {
val link = grant.capabilityUrl(watchPage(grant))
val open = PendingIntent.getActivity(
this, ids.get(),
Intent(this, PlayerActivity::class.java).putExtra("link", link).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val share = PendingIntent.getActivity(
this, ids.get() + 1,
Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, link), "Share $name"),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val n = builder(DONE)
.setSmallIcon(android.R.drawable.stat_sys_upload_done)
.setContentTitle(name)
.setContentText("Uploaded, end-to-end encrypted — tap to play")
.setContentIntent(open)
.setAutoCancel(true)
.addAction(Notification.Action.Builder(null, "Share link", share).build())
.build()
nm.notify(ids.getAndAdd(2), n)
}
private fun failed(name: String, e: Throwable) {
val n = builder(DONE)
.setSmallIcon(android.R.drawable.stat_notify_error)
.setContentTitle("$name was not uploaded")
.setContentText(e.message ?: e.javaClass.simpleName)
.setStyle(Notification.BigTextStyle().bigText(e.message ?: e.javaClass.simpleName))
.build()
nm.notify(ids.getAndAdd(2), n)
}
private fun progress(title: String, text: String, value: Int, max: Int): Notification =
builder(PROGRESS)
.setSmallIcon(android.R.drawable.stat_sys_upload)
.setContentTitle(title)
.setContentText(text)
.setOngoing(true)
.setProgress(max, value, max == 0)
.build()
private fun builder(channel: String): Notification.Builder = Notification.Builder(this, channel)
private fun goForeground(n: Notification) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(FOREGROUND_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
startForeground(FOREGROUND_ID, n)
}
}
override fun onDestroy() {
worker.shutdownNow()
super.onDestroy()
}
companion object {
private const val PROGRESS = "uploads"
private const val DONE = "uploaded"
private const val FOREGROUND_ID = 1
private fun mib(b: Long) = "%.1f".format(b / 1048576.0)
/** The relay's own watch page opens the link in a browser too. */
fun watchPage(grant: MediaGrant): String = grant.url!!.substringBefore("/v1/media/") + "/watch/"
fun urisOf(intent: Intent): List<Uri> {
val out = LinkedHashSet<Uri>()
intent.data?.let(out::add)
intent.clipData?.let { c -> for (i in 0 until c.itemCount) c.getItemAt(i).uri?.let(out::add) }
// A share names its files in EXTRA_STREAM (Android usually mirrors them into the clip).
@Suppress("DEPRECATION")
when (intent.action) {
Intent.ACTION_SEND -> (intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri)?.let(out::add)
Intent.ACTION_SEND_MULTIPLE -> intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.let(out::addAll)
}
return out.toList()
}
}
}

View File

@@ -0,0 +1,49 @@
package no.zyon.shade.mediademo
import android.content.Context
import no.zyon.shade.keystore.KeystoreSecretFile
import no.zyon.shade.media.MediaOwner
import no.zyon.shade.media.MediaUploader
import no.zyon.shade.media.UploadJobs
import java.io.File
/**
* Where the demo uploads to and as whom. The relay URL is not a secret and
* lives in prefs; the owner seed signs every upload and lives in a
* Keystore-encrypted file. The relay must list [owner]'s id among its owners
* (`shade media serve --owners <id>`), which the share screen shows to copy.
*/
object Uploads {
private const val PREFS = "shade-media-demo"
private const val RELAY = "relay"
fun relay(context: Context): String? =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(RELAY, null)?.takeIf { it.isNotBlank() }
fun setRelay(context: Context, url: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(RELAY, url.trim().trimEnd('/')).apply()
}
private fun secret(context: Context) = KeystoreSecretFile(File(context.filesDir, "media-owner.sks"), "shade-media-owner")
/**
* The owner key, made on first use. If its Keystore key is gone (the app's
* data restored onto another phone), a new owner is made: the relay must
* then be told the new id — the old one cannot be recovered by design.
*/
@Synchronized
fun owner(context: Context): MediaOwner {
val s = secret(context)
val seed = try {
s.getOrCreate(32)
} catch (e: KeystoreSecretFile.SecretLostException) {
s.destroy()
s.getOrCreate(32)
}
return MediaOwner(seed).also { seed.fill(0) }
}
fun jobs(context: Context) = UploadJobs(File(context.filesDir, "media-uploads"))
fun uploader(context: Context, relay: String) = MediaUploader(relay, owner(context))
}

View File

@@ -276,6 +276,22 @@ again: the media id is the same, so the relay picks up where it stopped, and a f
already has gives the same link without sending anything. The relay must list
`owner.id` among its owners.
`UploadJobs` does that bookkeeping: `uploader.upload(jobs, key, …)` seals once into an
app-private job directory (sealed copy + seal result, file key included — keep it in
`filesDir`), resumes after a kill with the same media id, and gives a finished job's
grant again unless the relay says the file is gone. On Android, `ShadeUpload.describe(
context, uri)` turns a shared `content://` URI into the meta to seal (name, type, size,
duration, picture size as shown — nothing else, no location) and `ShadeUpload.upload`
runs it as a job. `KeystoreSecretFile` (`:shade-android-keystore`) keeps the owner seed
encrypted under a hardware-backed Keystore key.
The demo app shows the whole flow: share a video, photo, song or document to «Share to
Shade», enter the relay once and add the owner id it shows to the relay's
`--owners`; a foreground service seals and uploads with a progress notification, and
the finished notification plays the file or shares its link. Android 15 limits
`dataSync` foreground services to 6 hours a day, which is a lot of film; a killed
upload resumes when the service starts again.
For playback, `:shade-android-media` hands a reader to Media3/ExoPlayer, so any
container ExoPlayer understands plays and seeks from a sealed file:
@@ -529,7 +545,9 @@ done in v1. A deployment that needs it can pad above this layer.
byte for byte (`MediaVectorTest`), owner signatures and encoded grants included.
- `bun run scripts/media-live-kotlin.ts`: the Kotlin uploader against a real TS relay,
with a lost answer and a refused piece injected; TS reads the 40 MiB film back
byte for byte (`MediaLiveTest`, skipped without the driver).
byte for byte (`MediaLiveTest`, skipped without the driver). The same run kills an
upload job after its first piece and resumes it, and uploads a video shared by its
`content://` URI under Robolectric (`ShadeUploadTest`).
- `bench/media.ts`: throughput, seek latency and live fan-out, written as
`bench/media.chart.json`.
- `bench/media-store.ts`: disk store against S3 (+ Postgres) through the real routes,

View File

@@ -11,7 +11,8 @@
* `SHADE_MEDIA_LIVE_SPEC` set. That test opens the TS file from its link,
* seals and uploads a 40 MiB film in pieces and a photo in one PUT, puts the
* film again (the relay already has it), runs an upload job that is "killed"
* after its first piece and resumed, and deletes the photo. This script
* after its first piece and resumed, and deletes the photo. Then the
* Robolectric `ShadeUploadTest` shares a video by its content:// URI. This script
* then opens the Kotlin film from its link with the TS reader and checks every
* byte, and that both faults were hit and recovered from.
*
@@ -91,6 +92,14 @@ try {
{ cwd: androidDir, env: { ...process.env, SHADE_MEDIA_LIVE_SPEC: specPath }, stdout: 'inherit', stderr: 'inherit' },
);
check((await gradle.exited) === 0, 'Kotlin MediaLiveTest failed');
// And on Android (Robolectric): a shared video, sealed from its content:// URI.
const robo = Bun.spawn(
['./gradlew', ':shade-android-media:testDebugUnitTest', '--tests', 'no.zyon.shade.media.android.ShadeUploadTest', '--console=plain'],
{ cwd: androidDir, env: { ...process.env, SHADE_MEDIA_LIVE_SPEC: specPath }, stdout: 'inherit', stderr: 'inherit' },
);
check((await robo.exited) === 0, 'Android ShadeUploadTest failed');
const shared = fromCapabilityUrl(await readFile(join(dir, 'android-out.txt'), 'utf8')) as MediaGrant;
check((await openGrant(shared)).meta.name === 'VID_0042.mp4', 'the shared video lost its name');
const out = JSON.parse(await readFile(kotlinOut, 'utf8')) as {
film: { link: string; sha256: string; size: number };
@@ -106,10 +115,10 @@ try {
check((await fetch(out.photo.url, { method: 'HEAD' })).status === 404, 'the deleted photo is still served');
check(faults.lostAnswer === 1 && faults.refused === 1, `faults not hit: ${JSON.stringify(faults)}`);
const left = await new MediaClient(url, kotlinOwner).list();
check(left.items.length === 2, `Kotlin owner should have 2 files left (film, re-shared video), has ${left.items.length}`);
check(left.items.length === 3, `Kotlin owner should have 3 files left (film, re-shared video, Android share), has ${left.items.length}`);
console.log(
`LIVE OK — Kotlin read the TS file; Kotlin film ${(out.film.size / MiB).toFixed(1)} MiB in ${faults.pieces} piece requests ` +
`(${faults.starts} starts/resyncs, 1 lost answer, 1 refusal) read back by TS byte for byte; upload job killed and resumed; photo deleted`,
`(${faults.starts} starts/resyncs, 1 lost answer, 1 refusal) read back by TS byte for byte; upload job killed and resumed; a content:// share uploaded from Robolectric; photo deleted`,
);
} finally {
server.stop(true);