feat(android): albums from the phone — several files shared at once are one link

Albums.encode and Grant.encode (live grants too) write what TS writes; the
album vector is resealed byte for byte from Kotlin. MediaUploader.uploadAlbum
seals and uploads one. The demo turns a multi-file share into an album and
its player lists an album's items and opens them in place. The live
cross-check uploads an album from Kotlin that TS opens.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-19 00:34:24 +02:00
parent 7d45be8712
commit 65d7a0646f
11 changed files with 202 additions and 33 deletions

View File

@@ -1,5 +1,6 @@
package no.zyon.shade.media
import no.zyon.shade.serialization.stringifyJson
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
@@ -23,6 +24,20 @@ private const val MAX_ALBUM_BYTES = 16L * 1024 * 1024
class Album(val title: String, val items: List<Grant>)
object Albums {
/** An album's plaintext, byte for byte what TS `encodeAlbum` writes. */
fun encode(album: Album): ByteArray {
if (album.title.length > MAX_TITLE) throw MediaFormatException("album title longer than $MAX_TITLE characters")
if (album.items.size > MAX_ALBUM_ITEMS) throw MediaFormatException("album holds more than $MAX_ALBUM_ITEMS items")
val o = LinkedHashMap<String, Any>()
o["kind"] = ALBUM_KIND
o["title"] = album.title
o["items"] = album.items.map { it.toJsonMap() }
return stringifyJson(o).toByteArray(Charsets.UTF_8)
}
/** The meta an album is sealed with: its type, and the title as its name. */
fun meta(title: String) = MediaMeta(mime = ALBUM_MIME, name = title)
/** Parse an album's plaintext, strictly: every item must be a valid grant. */
fun parse(bytes: ByteArray): Album {
val text = try {

View File

@@ -16,7 +16,17 @@ import java.util.Base64
const val MEDIA_GRANT_KIND = "shade.media-grant/v1"
const val LIVE_GRANT_KIND = "shade.live-grant/v1"
sealed class Grant
sealed class Grant {
/** The wire fields in TS `encodeGrant`'s order. */
internal abstract fun toJsonMap(): Map<String, Any>
/** Wire JSON, byte for byte what TS `encodeGrant` writes (field order fixed, meta canonical). */
fun encode(): String = stringifyJson(toJsonMap())
/** `pageUrl#shade=<base64url(json)>`: the link that opens it, the key in the fragment (never sent to a server). */
fun capabilityUrl(pageUrl: String): String =
"${pageUrl.substringBefore('#')}#shade=${b64u(encode().toByteArray(Charsets.UTF_8))}"
}
class MediaGrant(
val mediaId: ByteArray,
@@ -36,8 +46,7 @@ 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 {
override fun toJsonMap(): Map<String, Any> {
val o = LinkedHashMap<String, Any>()
o["kind"] = MEDIA_GRANT_KIND
o["mediaId"] = b64u(mediaId)
@@ -46,13 +55,9 @@ class MediaGrant(
url?.let { o["url"] = it }
readToken?.let { o["token"] = b64u(it) }
meta?.let { o["meta"] = MediaMeta.validate(it).toJsonMap() }
return stringifyJson(o)
return 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) =
@@ -72,7 +77,23 @@ class LiveGrant(
val meta: MediaMeta? = null,
/** Link mode: reads this epoch and every later one, unaided. */
val channelSecret: ByteArray? = null,
) : Grant()
) : Grant() {
override fun toJsonMap(): Map<String, Any> {
val o = LinkedHashMap<String, Any>()
o["kind"] = LIVE_GRANT_KIND
o["channelId"] = b64u(channelId)
o["signingKey"] = b64u(signingKey)
o["epoch"] = epoch
o["seq"] = seq
o["chainKey"] = b64u(chainKey)
o["stickyKey"] = b64u(stickyKey)
channelSecret?.let { o["channelSecret"] = b64u(it) }
url?.let { o["url"] = it }
readToken?.let { o["token"] = b64u(it) }
meta?.let { o["meta"] = MediaMeta.validate(it).toJsonMap() }
return o
}
}
internal fun b64u(b: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(b)

View File

@@ -92,6 +92,10 @@ class MediaUploader(
return putSealed(result, ByteArraySource(sealed), readToken, meta)
}
/** Seal and upload an album; the grant opens every item in it (a season, the photos of a trip). */
fun uploadAlbum(album: Album, readToken: ByteArray? = newReadToken()): MediaGrant =
uploadBytes(Albums.encode(album), Albums.meta(album.title), readToken)
/**
* 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

View File

@@ -1,5 +1,7 @@
package no.zyon.shade
import no.zyon.shade.media.Album
import no.zyon.shade.media.Albums
import no.zyon.shade.media.FileRangeSource
import no.zyon.shade.media.Grants
import no.zyon.shade.media.MediaGrant
@@ -109,11 +111,20 @@ class MediaLiveTest {
assertTrue(uploader.delete(photo.mediaId))
assertFalse(uploader.delete(photo.mediaId))
// The photos of a trip, shared at once: one album link for all of them.
val album = uploader.uploadAlbum(Album("Tur — «Lofoten»", listOf(film, fresh)))
album.open().use { r ->
val back = Albums.read(r)
assertEquals("Tur — «Lofoten»", back.title)
assertEquals(listOf(film.encode(), fresh.encode()), back.items.map { it.encode() })
}
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))
.put("album", album.capabilityUrl("https://watch.example/"))
.toString(),
)
sealedFile.delete()

View File

@@ -137,6 +137,7 @@ class MediaVectorTest {
fun liveFramesOpenFromTheLinkGrantAcrossARotation() {
val g = Grants.parse(byPrefix("live grant").single().getString("json")) as LiveGrant
assertNotNull(g.channelSecret)
assertEquals(byPrefix("live grant").single().getString("json"), g.encode())
val sub = LiveSubscriber(g)
for (v in byPrefix("live frame")) {
val f = sub.open(hex(v.getString("wire")))
@@ -193,6 +194,11 @@ class MediaVectorTest {
assertEquals(ALBUM_MIME, reader.meta.mime)
val album = Albums.read(reader)
assertEquals(v.getString("title"), album.title)
// And written back: the same plaintext, sealed to the same bytes.
val plain = Albums.encode(album)
assertEquals(v.getString("plaintext"), String(plain, Charsets.UTF_8))
val (resealed, _) = MediaSealer.withPinnedKeys(mediaId, mediaKey, Albums.meta(album.title), 4096).sealAll(plain)
assertEquals(v.getString("sealed"), toHex(resealed))
val kinds = v.getJSONArray("itemKinds")
val names = v.getJSONArray("itemNames")
assertEquals(kinds.length(), album.items.size)

View File

@@ -21,6 +21,9 @@ import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import no.zyon.shade.media.ALBUM_MIME
import no.zyon.shade.media.Album
import no.zyon.shade.media.Albums
import no.zyon.shade.media.LiveContent
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.MediaGrant
@@ -53,6 +56,10 @@ class PlayerActivity : Activity() {
private lateinit var logScroll: ScrollView
private lateinit var picture: ImageView
private lateinit var share: Button
private lateinit var albumList: LinearLayout
private lateinit var albumScroll: ScrollView
/** The album the item on screen came from, to go back to. */
private var album: Album? = null
/** The link playing now, to hand on. */
private var current: String? = null
@@ -95,6 +102,11 @@ class PlayerActivity : Activity() {
}
}
}
albumList = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
albumScroll = ScrollView(this).apply {
addView(albumList)
visibility = android.view.View.GONE
}
val bar = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
@@ -111,6 +123,7 @@ class PlayerActivity : Activity() {
addView(view, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
addView(logScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
addView(picture, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
addView(albumScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
},
)
linkFrom(intent)?.let {
@@ -138,6 +151,13 @@ class PlayerActivity : Activity() {
}
current = link
share.visibility = android.view.View.VISIBLE
album = null
open(grant)
}
/** Open a grant: from a link, or an item of the album on screen. */
private fun open(grant: no.zyon.shade.media.Grant) {
stop()
when (grant) {
is LiveGrant -> watch(grant)
is MediaGrant -> {
@@ -201,13 +221,54 @@ class PlayerActivity : Activity() {
if (atBottom) logScroll.post { logScroll.fullScroll(android.view.View.FOCUS_DOWN) }
}
private enum class View { PLAYER, LOG, PICTURE }
/**
* An album: its items as a list, each opening in place. Back returns to
* the list. Read already (it is small), so this needs no network.
*/
private fun showAlbum(a: Album) {
album = a
show(View.ALBUM)
status.text = "${a.title} · ${a.items.size} item(s) · end-to-end encrypted"
albumList.removeAllViews()
a.items.forEachIndexed { i, g ->
val meta = when (g) {
is MediaGrant -> g.meta
is LiveGrant -> g.meta
}
val kind = when {
g is LiveGrant -> "live"
Albums.isAlbum(g) -> "album"
else -> meta?.mime?.substringBefore('/') ?: "file"
}
albumList.addView(Button(this).apply {
text = "${meta?.name ?: "item ${i + 1}"} · $kind"
isAllCaps = false
gravity = Gravity.START or Gravity.CENTER_VERTICAL
setOnClickListener { open(g) }
})
}
}
@Deprecated("Activity.onBackPressed")
override fun onBackPressed() {
val a = album
if (a != null && albumScroll.visibility != android.view.View.VISIBLE) {
stop()
showAlbum(a)
return
}
@Suppress("DEPRECATION")
super.onBackPressed()
}
private enum class View { PLAYER, LOG, PICTURE, ALBUM }
private fun show(which: View) {
fun vis(on: Boolean) = if (on) android.view.View.VISIBLE else android.view.View.GONE
view.visibility = vis(which == View.PLAYER)
logScroll.visibility = vis(which == View.LOG)
picture.visibility = vis(which == View.PICTURE)
albumScroll.visibility = vis(which == View.ALBUM)
}
/**
@@ -245,6 +306,11 @@ class PlayerActivity : Activity() {
private fun start(f: ShadeFilm) {
film = f
val meta0 = f.reader.meta
if (meta0.mime == ALBUM_MIME) {
val read = runCatching { Albums.read(f.reader) }
read.fold(onSuccess = { showAlbum(it) }, onFailure = { status.text = "Cannot read the album: ${it.message}" })
return
}
if (meta0.mime?.startsWith("image/") == true) {
status.text = "${meta0.name ?: "picture"} · ${meta0.mime} · ${f.reader.size / 1024} KiB · end-to-end encrypted"
if (f.reader.size > MAX_PICTURE_BYTES) {

View File

@@ -26,6 +26,7 @@ import java.util.concurrent.Executors
*/
class ShareActivity : Activity() {
private val io = Executors.newSingleThreadExecutor()
private var album = "Shared"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -44,6 +45,12 @@ class ShareActivity : Activity() {
setText(Uploads.relay(this@ShareActivity) ?: "")
setTextColor(Color.WHITE)
}
val albumTitle = EditText(this).apply {
hint = "Album title"
setSingleLine()
setText("Shared ${java.text.DateFormat.getDateInstance().format(java.util.Date())}")
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() }
@@ -57,6 +64,10 @@ class ShareActivity : Activity() {
addView(files)
addView(label("Relay"))
addView(relay, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
if (uris.size > 1) {
addView(label("One link for all of them: an album"))
addView(albumTitle, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
}
addView(ownerId)
addView(copy)
addView(upload)
@@ -96,6 +107,7 @@ class ShareActivity : Activity() {
return@setOnClickListener
}
Uploads.setRelay(this, url)
album = albumTitle.text.toString().trim().ifEmpty { "Shared" }.take(512)
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 {
@@ -114,6 +126,7 @@ class ShareActivity : Activity() {
val svc = Intent(this, UploadService::class.java).apply {
clipData = clip
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
if (uris.size > 1) putExtra(UploadService.EXTRA_ALBUM, album)
}
startForegroundService(svc)
finish()

View File

@@ -13,6 +13,7 @@ import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.PowerManager
import no.zyon.shade.media.Album
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.UploadJobs
import no.zyon.shade.media.android.ShadeUpload
@@ -24,7 +25,8 @@ import java.util.concurrent.atomic.AtomicInteger
* 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.
* Several files shared at once become one album (one link for the photos of
* a trip). When a file is up, a notification opens it, or shares its link.
*/
class UploadService : Service() {
private val worker = Executors.newSingleThreadExecutor()
@@ -49,10 +51,11 @@ class UploadService : Service() {
jobs.prune()
for ((key, job) in jobs.unfinished()) {
if (job.server.isEmpty()) continue
enqueue(key, job.meta.name ?: "file") { onProgress ->
val name = job.meta.name ?: "file"
enqueue(key, name) { progress ->
Uploads.uploader(this, job.server).upload(jobs, key, job.source, job.meta, {
throw IllegalStateException("sealed copy missing")
}, onProgress = onProgress)
}) { acked, total -> progress(name, acked, total) }
}
}
}
@@ -61,19 +64,35 @@ class UploadService : Service() {
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 {
if (relay != null && uris.isNotEmpty()) {
val uploader = Uploads.uploader(this, relay)
val jobs = Uploads.jobs(this)
// Described now, while the share's read permission still holds.
val items = uris.mapNotNull { uri ->
try {
ShadeUpload.describe(this, uri)
} catch (e: Exception) {
failed(uri.lastPathSegment ?: "file", e)
continue
null
}
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)
}
val album = intent?.getStringExtra(EXTRA_ALBUM)
if (album != null && items.size > 1) {
// One link for all of them: each file is its own job, then the album of their grants.
val keys = items.map { ShadeUpload.jobKey(jobs, uploader, it) }
enqueue(keys.joinToString(","), album) { progress ->
val grants = items.mapIndexed { i, item ->
val label = "${i + 1}/${items.size} · ${item.meta.name ?: "file"}"
ShadeUpload.upload(this, uploader, jobs, item) { acked, total -> progress(label, acked, total) }
}
uploader.uploadAlbum(Album(album, grants))
}
} else {
for (item in items) {
val name = item.meta.name ?: "file"
enqueue(ShadeUpload.jobKey(jobs, uploader, item), name) { progress ->
ShadeUpload.upload(this, uploader, jobs, item) { acked, total -> progress(name, acked, total) }
}
}
}
}
@@ -81,19 +100,20 @@ class UploadService : Service() {
return START_REDELIVER_INTENT
}
private fun enqueue(key: String, name: String, run: ((Long, Long) -> Unit) -> MediaGrant) {
/** `run` reports progress as (what, acked, total). */
private fun enqueue(key: String, name: String, run: ((String, 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
var shown = ""
try {
val grant = run { acked, total ->
val grant = run { what, 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))
if ("$what $pct" != shown) {
shown = "$what $pct"
nm.notify(FOREGROUND_ID, progress(what, "${mib(acked)} of ${mib(total)} MiB", pct, 100))
}
}
uploaded(name, grant)
@@ -175,6 +195,9 @@ class UploadService : Service() {
private const val DONE = "uploaded"
private const val FOREGROUND_ID = 1
/** A share of several files becomes one album with this title. */
const val EXTRA_ALBUM = "no.zyon.shade.mediademo.ALBUM"
private fun mib(b: Long) = "%.1f".format(b / 1048576.0)
/** The relay's own watch page opens the link in a browser too. */