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:
@@ -128,7 +128,11 @@ New package **`@shade/media`** — see `docs/media.md`.
|
|||||||
type, duration and picture size; `KeystoreSecretFile` keeps the owner seed
|
type, duration and picture size; `KeystoreSecretFile` keeps the owner seed
|
||||||
under a Keystore key. The demo app takes shares from the gallery, uploads
|
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
|
them in a foreground service with progress, and offers the link to play or
|
||||||
share. Its minSdk is now 28.
|
share. Several files shared at once become one album link
|
||||||
|
(`MediaUploader.uploadAlbum`, `Albums.encode`, `Grant.encode` for live
|
||||||
|
grants too — the album vector now resealed byte for byte from Kotlin), and
|
||||||
|
the demo player lists an album's items and opens them in place.
|
||||||
|
Its minSdk is now 28.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package no.zyon.shade.media
|
package no.zyon.shade.media
|
||||||
|
|
||||||
|
import no.zyon.shade.serialization.stringifyJson
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONException
|
import org.json.JSONException
|
||||||
import org.json.JSONObject
|
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>)
|
class Album(val title: String, val items: List<Grant>)
|
||||||
|
|
||||||
object Albums {
|
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. */
|
/** Parse an album's plaintext, strictly: every item must be a valid grant. */
|
||||||
fun parse(bytes: ByteArray): Album {
|
fun parse(bytes: ByteArray): Album {
|
||||||
val text = try {
|
val text = try {
|
||||||
|
|||||||
@@ -16,7 +16,17 @@ import java.util.Base64
|
|||||||
const val MEDIA_GRANT_KIND = "shade.media-grant/v1"
|
const val MEDIA_GRANT_KIND = "shade.media-grant/v1"
|
||||||
const val LIVE_GRANT_KIND = "shade.live-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(
|
class MediaGrant(
|
||||||
val mediaId: ByteArray,
|
val mediaId: ByteArray,
|
||||||
@@ -36,8 +46,7 @@ class MediaGrant(
|
|||||||
|
|
||||||
fun open(): MediaReader = MediaReader.open(source(), keys())
|
fun open(): MediaReader = MediaReader.open(source(), keys())
|
||||||
|
|
||||||
/** Wire JSON, byte for byte what TS `encodeGrant` writes (field order fixed, meta canonical). */
|
override fun toJsonMap(): Map<String, Any> {
|
||||||
fun encode(): String {
|
|
||||||
val o = LinkedHashMap<String, Any>()
|
val o = LinkedHashMap<String, Any>()
|
||||||
o["kind"] = MEDIA_GRANT_KIND
|
o["kind"] = MEDIA_GRANT_KIND
|
||||||
o["mediaId"] = b64u(mediaId)
|
o["mediaId"] = b64u(mediaId)
|
||||||
@@ -46,13 +55,9 @@ class MediaGrant(
|
|||||||
url?.let { o["url"] = it }
|
url?.let { o["url"] = it }
|
||||||
readToken?.let { o["token"] = b64u(it) }
|
readToken?.let { o["token"] = b64u(it) }
|
||||||
meta?.let { o["meta"] = MediaMeta.validate(it).toJsonMap() }
|
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 {
|
companion object {
|
||||||
/** The grant for a file just sealed (and uploaded to `url`). */
|
/** The grant for a file just sealed (and uploaded to `url`). */
|
||||||
fun of(r: SealResult, url: String? = null, readToken: ByteArray? = null, meta: MediaMeta? = null) =
|
fun of(r: SealResult, url: String? = null, readToken: ByteArray? = null, meta: MediaMeta? = null) =
|
||||||
@@ -72,7 +77,23 @@ class LiveGrant(
|
|||||||
val meta: MediaMeta? = null,
|
val meta: MediaMeta? = null,
|
||||||
/** Link mode: reads this epoch and every later one, unaided. */
|
/** Link mode: reads this epoch and every later one, unaided. */
|
||||||
val channelSecret: ByteArray? = null,
|
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)
|
internal fun b64u(b: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(b)
|
||||||
|
|
||||||
|
|||||||
@@ -92,6 +92,10 @@ class MediaUploader(
|
|||||||
return putSealed(result, ByteArraySource(sealed), readToken, meta)
|
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
|
* 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
|
* in memory. The sealed copy is the caller's: keep it (with the returned
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package no.zyon.shade
|
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.FileRangeSource
|
||||||
import no.zyon.shade.media.Grants
|
import no.zyon.shade.media.Grants
|
||||||
import no.zyon.shade.media.MediaGrant
|
import no.zyon.shade.media.MediaGrant
|
||||||
@@ -109,11 +111,20 @@ class MediaLiveTest {
|
|||||||
assertTrue(uploader.delete(photo.mediaId))
|
assertTrue(uploader.delete(photo.mediaId))
|
||||||
assertFalse(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(
|
File(spec.getString("kotlinOut")).writeText(
|
||||||
JSONObject()
|
JSONObject()
|
||||||
.put("film", JSONObject().put("link", film.capabilityUrl("https://watch.example/")).put("sha256", sha256(plain)).put("size", plain.size))
|
.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("again", again.capabilityUrl("https://watch.example/"))
|
||||||
.put("photo", JSONObject().put("url", photo.url))
|
.put("photo", JSONObject().put("url", photo.url))
|
||||||
|
.put("album", album.capabilityUrl("https://watch.example/"))
|
||||||
.toString(),
|
.toString(),
|
||||||
)
|
)
|
||||||
sealedFile.delete()
|
sealedFile.delete()
|
||||||
|
|||||||
@@ -137,6 +137,7 @@ class MediaVectorTest {
|
|||||||
fun liveFramesOpenFromTheLinkGrantAcrossARotation() {
|
fun liveFramesOpenFromTheLinkGrantAcrossARotation() {
|
||||||
val g = Grants.parse(byPrefix("live grant").single().getString("json")) as LiveGrant
|
val g = Grants.parse(byPrefix("live grant").single().getString("json")) as LiveGrant
|
||||||
assertNotNull(g.channelSecret)
|
assertNotNull(g.channelSecret)
|
||||||
|
assertEquals(byPrefix("live grant").single().getString("json"), g.encode())
|
||||||
val sub = LiveSubscriber(g)
|
val sub = LiveSubscriber(g)
|
||||||
for (v in byPrefix("live frame")) {
|
for (v in byPrefix("live frame")) {
|
||||||
val f = sub.open(hex(v.getString("wire")))
|
val f = sub.open(hex(v.getString("wire")))
|
||||||
@@ -193,6 +194,11 @@ class MediaVectorTest {
|
|||||||
assertEquals(ALBUM_MIME, reader.meta.mime)
|
assertEquals(ALBUM_MIME, reader.meta.mime)
|
||||||
val album = Albums.read(reader)
|
val album = Albums.read(reader)
|
||||||
assertEquals(v.getString("title"), album.title)
|
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 kinds = v.getJSONArray("itemKinds")
|
||||||
val names = v.getJSONArray("itemNames")
|
val names = v.getJSONArray("itemNames")
|
||||||
assertEquals(kinds.length(), album.items.size)
|
assertEquals(kinds.length(), album.items.size)
|
||||||
|
|||||||
@@ -21,6 +21,9 @@ import androidx.media3.common.Player
|
|||||||
import androidx.media3.common.util.UnstableApi
|
import androidx.media3.common.util.UnstableApi
|
||||||
import androidx.media3.exoplayer.ExoPlayer
|
import androidx.media3.exoplayer.ExoPlayer
|
||||||
import androidx.media3.ui.PlayerView
|
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.LiveContent
|
||||||
import no.zyon.shade.media.LiveGrant
|
import no.zyon.shade.media.LiveGrant
|
||||||
import no.zyon.shade.media.MediaGrant
|
import no.zyon.shade.media.MediaGrant
|
||||||
@@ -53,6 +56,10 @@ class PlayerActivity : Activity() {
|
|||||||
private lateinit var logScroll: ScrollView
|
private lateinit var logScroll: ScrollView
|
||||||
private lateinit var picture: ImageView
|
private lateinit var picture: ImageView
|
||||||
private lateinit var share: Button
|
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. */
|
/** The link playing now, to hand on. */
|
||||||
private var current: String? = null
|
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 {
|
val bar = LinearLayout(this).apply {
|
||||||
orientation = LinearLayout.HORIZONTAL
|
orientation = LinearLayout.HORIZONTAL
|
||||||
gravity = Gravity.CENTER_VERTICAL
|
gravity = Gravity.CENTER_VERTICAL
|
||||||
@@ -111,6 +123,7 @@ class PlayerActivity : Activity() {
|
|||||||
addView(view, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
|
addView(view, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
|
||||||
addView(logScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
|
addView(logScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
|
||||||
addView(picture, 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 {
|
linkFrom(intent)?.let {
|
||||||
@@ -138,6 +151,13 @@ class PlayerActivity : Activity() {
|
|||||||
}
|
}
|
||||||
current = link
|
current = link
|
||||||
share.visibility = android.view.View.VISIBLE
|
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) {
|
when (grant) {
|
||||||
is LiveGrant -> watch(grant)
|
is LiveGrant -> watch(grant)
|
||||||
is MediaGrant -> {
|
is MediaGrant -> {
|
||||||
@@ -201,13 +221,54 @@ class PlayerActivity : Activity() {
|
|||||||
if (atBottom) logScroll.post { logScroll.fullScroll(android.view.View.FOCUS_DOWN) }
|
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) {
|
private fun show(which: View) {
|
||||||
fun vis(on: Boolean) = if (on) android.view.View.VISIBLE else android.view.View.GONE
|
fun vis(on: Boolean) = if (on) android.view.View.VISIBLE else android.view.View.GONE
|
||||||
view.visibility = vis(which == View.PLAYER)
|
view.visibility = vis(which == View.PLAYER)
|
||||||
logScroll.visibility = vis(which == View.LOG)
|
logScroll.visibility = vis(which == View.LOG)
|
||||||
picture.visibility = vis(which == View.PICTURE)
|
picture.visibility = vis(which == View.PICTURE)
|
||||||
|
albumScroll.visibility = vis(which == View.ALBUM)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -245,6 +306,11 @@ class PlayerActivity : Activity() {
|
|||||||
private fun start(f: ShadeFilm) {
|
private fun start(f: ShadeFilm) {
|
||||||
film = f
|
film = f
|
||||||
val meta0 = f.reader.meta
|
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) {
|
if (meta0.mime?.startsWith("image/") == true) {
|
||||||
status.text = "${meta0.name ?: "picture"} · ${meta0.mime} · ${f.reader.size / 1024} KiB · end-to-end encrypted"
|
status.text = "${meta0.name ?: "picture"} · ${meta0.mime} · ${f.reader.size / 1024} KiB · end-to-end encrypted"
|
||||||
if (f.reader.size > MAX_PICTURE_BYTES) {
|
if (f.reader.size > MAX_PICTURE_BYTES) {
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import java.util.concurrent.Executors
|
|||||||
*/
|
*/
|
||||||
class ShareActivity : Activity() {
|
class ShareActivity : Activity() {
|
||||||
private val io = Executors.newSingleThreadExecutor()
|
private val io = Executors.newSingleThreadExecutor()
|
||||||
|
private var album = "Shared"
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
@@ -44,6 +45,12 @@ class ShareActivity : Activity() {
|
|||||||
setText(Uploads.relay(this@ShareActivity) ?: "")
|
setText(Uploads.relay(this@ShareActivity) ?: "")
|
||||||
setTextColor(Color.WHITE)
|
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 ownerId = label("Owner key: …", 12f)
|
||||||
val copy = Button(this).apply { text = "Copy owner id"; isEnabled = false }
|
val copy = Button(this).apply { text = "Copy owner id"; isEnabled = false }
|
||||||
val upload = Button(this).apply { text = "Seal and upload"; isEnabled = uris.isNotEmpty() }
|
val upload = Button(this).apply { text = "Seal and upload"; isEnabled = uris.isNotEmpty() }
|
||||||
@@ -57,6 +64,10 @@ class ShareActivity : Activity() {
|
|||||||
addView(files)
|
addView(files)
|
||||||
addView(label("Relay"))
|
addView(label("Relay"))
|
||||||
addView(relay, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
|
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(ownerId)
|
||||||
addView(copy)
|
addView(copy)
|
||||||
addView(upload)
|
addView(upload)
|
||||||
@@ -96,6 +107,7 @@ class ShareActivity : Activity() {
|
|||||||
return@setOnClickListener
|
return@setOnClickListener
|
||||||
}
|
}
|
||||||
Uploads.setRelay(this, url)
|
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) {
|
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
|
||||||
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
|
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
|
||||||
} else {
|
} else {
|
||||||
@@ -114,6 +126,7 @@ class ShareActivity : Activity() {
|
|||||||
val svc = Intent(this, UploadService::class.java).apply {
|
val svc = Intent(this, UploadService::class.java).apply {
|
||||||
clipData = clip
|
clipData = clip
|
||||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
if (uris.size > 1) putExtra(UploadService.EXTRA_ALBUM, album)
|
||||||
}
|
}
|
||||||
startForegroundService(svc)
|
startForegroundService(svc)
|
||||||
finish()
|
finish()
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import android.os.Handler
|
|||||||
import android.os.IBinder
|
import android.os.IBinder
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
import android.os.PowerManager
|
import android.os.PowerManager
|
||||||
|
import no.zyon.shade.media.Album
|
||||||
import no.zyon.shade.media.MediaGrant
|
import no.zyon.shade.media.MediaGrant
|
||||||
import no.zyon.shade.media.UploadJobs
|
import no.zyon.shade.media.UploadJobs
|
||||||
import no.zyon.shade.media.android.ShadeUpload
|
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
|
* 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;
|
* 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.
|
* 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() {
|
class UploadService : Service() {
|
||||||
private val worker = Executors.newSingleThreadExecutor()
|
private val worker = Executors.newSingleThreadExecutor()
|
||||||
@@ -49,10 +51,11 @@ class UploadService : Service() {
|
|||||||
jobs.prune()
|
jobs.prune()
|
||||||
for ((key, job) in jobs.unfinished()) {
|
for ((key, job) in jobs.unfinished()) {
|
||||||
if (job.server.isEmpty()) continue
|
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, {
|
Uploads.uploader(this, job.server).upload(jobs, key, job.source, job.meta, {
|
||||||
throw IllegalStateException("sealed copy missing")
|
throw IllegalStateException("sealed copy missing")
|
||||||
}, onProgress = onProgress)
|
}) { acked, total -> progress(name, acked, total) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -61,19 +64,35 @@ class UploadService : Service() {
|
|||||||
lastStart = startId
|
lastStart = startId
|
||||||
val relay = Uploads.relay(this)
|
val relay = Uploads.relay(this)
|
||||||
val uris = intent?.let(::urisOf).orEmpty()
|
val uris = intent?.let(::urisOf).orEmpty()
|
||||||
if (relay != null) {
|
if (relay != null && uris.isNotEmpty()) {
|
||||||
for (uri in uris) {
|
val uploader = Uploads.uploader(this, relay)
|
||||||
// Described now, while the share's read permission still holds.
|
val jobs = Uploads.jobs(this)
|
||||||
val item = try {
|
// Described now, while the share's read permission still holds.
|
||||||
|
val items = uris.mapNotNull { uri ->
|
||||||
|
try {
|
||||||
ShadeUpload.describe(this, uri)
|
ShadeUpload.describe(this, uri)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
failed(uri.lastPathSegment ?: "file", e)
|
failed(uri.lastPathSegment ?: "file", e)
|
||||||
continue
|
null
|
||||||
}
|
}
|
||||||
val uploader = Uploads.uploader(this, relay)
|
}
|
||||||
val jobs = Uploads.jobs(this)
|
val album = intent?.getStringExtra(EXTRA_ALBUM)
|
||||||
enqueue(ShadeUpload.jobKey(jobs, uploader, item), item.meta.name ?: "file") { onProgress ->
|
if (album != null && items.size > 1) {
|
||||||
ShadeUpload.upload(this, uploader, jobs, item, onProgress)
|
// 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
|
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
|
if (!queued.add(key)) return
|
||||||
pending.incrementAndGet()
|
pending.incrementAndGet()
|
||||||
worker.execute {
|
worker.execute {
|
||||||
val wake = getSystemService(PowerManager::class.java).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "shade:upload")
|
val wake = getSystemService(PowerManager::class.java).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "shade:upload")
|
||||||
wake.acquire(6 * 3600_000L)
|
wake.acquire(6 * 3600_000L)
|
||||||
var shown = -1
|
var shown = ""
|
||||||
try {
|
try {
|
||||||
val grant = run { acked, total ->
|
val grant = run { what, acked, total ->
|
||||||
val pct = if (total > 0) (acked * 100 / total).toInt() else 0
|
val pct = if (total > 0) (acked * 100 / total).toInt() else 0
|
||||||
if (pct != shown) {
|
if ("$what $pct" != shown) {
|
||||||
shown = pct
|
shown = "$what $pct"
|
||||||
nm.notify(FOREGROUND_ID, progress(name, "${mib(acked)} of ${mib(total)} MiB", pct, 100))
|
nm.notify(FOREGROUND_ID, progress(what, "${mib(acked)} of ${mib(total)} MiB", pct, 100))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
uploaded(name, grant)
|
uploaded(name, grant)
|
||||||
@@ -175,6 +195,9 @@ class UploadService : Service() {
|
|||||||
private const val DONE = "uploaded"
|
private const val DONE = "uploaded"
|
||||||
private const val FOREGROUND_ID = 1
|
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)
|
private fun mib(b: Long) = "%.1f".format(b / 1048576.0)
|
||||||
|
|
||||||
/** The relay's own watch page opens the link in a browser too. */
|
/** The relay's own watch page opens the link in a browser too. */
|
||||||
|
|||||||
@@ -288,7 +288,9 @@ encrypted under a hardware-backed Keystore key.
|
|||||||
The demo app shows the whole flow: share a video, photo, song or document to «Share to
|
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
|
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
|
`--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
|
the finished notification plays the file or shares its link. Several files shared at
|
||||||
|
once become one album (`uploader.uploadAlbum(Album(title, grants))`), which the player
|
||||||
|
shows as a list. Android 15 limits
|
||||||
`dataSync` foreground services to 6 hours a day, which is a lot of film; a killed
|
`dataSync` foreground services to 6 hours a day, which is a lot of film; a killed
|
||||||
upload resumes when the service starts again.
|
upload resumes when the service starts again.
|
||||||
|
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import { createHash, randomBytes } from 'node:crypto';
|
|||||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { MediaClient, OwnerKey, fromCapabilityUrl, openGrant, toCapabilityUrl } from '../packages/shade-media/src/index.js';
|
import { MediaClient, OwnerKey, fromCapabilityUrl, openAlbum, openGrant, toCapabilityUrl } from '../packages/shade-media/src/index.js';
|
||||||
import type { MediaGrant } from '../packages/shade-media/src/index.js';
|
import type { MediaGrant } from '../packages/shade-media/src/index.js';
|
||||||
import { createMediaService, mediaMaxRequestBody } from '../packages/shade-media/src/server.js';
|
import { createMediaService, mediaMaxRequestBody } from '../packages/shade-media/src/server.js';
|
||||||
import { OFFSET_HEADER } from '../packages/shade-media/src/upload.js';
|
import { OFFSET_HEADER } from '../packages/shade-media/src/upload.js';
|
||||||
@@ -105,6 +105,7 @@ try {
|
|||||||
film: { link: string; sha256: string; size: number };
|
film: { link: string; sha256: string; size: number };
|
||||||
again: string;
|
again: string;
|
||||||
photo: { url: string };
|
photo: { url: string };
|
||||||
|
album: string;
|
||||||
};
|
};
|
||||||
const film = fromCapabilityUrl(out.film.link) as MediaGrant;
|
const film = fromCapabilityUrl(out.film.link) as MediaGrant;
|
||||||
const reader = await openGrant(film);
|
const reader = await openGrant(film);
|
||||||
@@ -112,13 +113,16 @@ try {
|
|||||||
check(sha256(await reader.read(0, reader.size)) === out.film.sha256, 'film bytes differ');
|
check(sha256(await reader.read(0, reader.size)) === out.film.sha256, 'film bytes differ');
|
||||||
check(reader.meta.name === 'Fra telefonen — «Kveld».mp4', `film name is ${reader.meta.name}`);
|
check(reader.meta.name === 'Fra telefonen — «Kveld».mp4', `film name is ${reader.meta.name}`);
|
||||||
check(out.again === out.film.link, 'putting the film again gave another link');
|
check(out.again === out.film.link, 'putting the film again gave another link');
|
||||||
|
const album = await openAlbum(fromCapabilityUrl(out.album) as MediaGrant);
|
||||||
|
check(album.title === 'Tur — «Lofoten»' && album.items.length === 2, `album is ${album.title} with ${album.items.length} items`);
|
||||||
|
check(toCapabilityUrl('https://watch.example/', album.items[0]!) === out.film.link, "the album's first item is not the film");
|
||||||
check((await fetch(out.photo.url, { method: 'HEAD' })).status === 404, 'the deleted photo is still served');
|
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)}`);
|
check(faults.lostAnswer === 1 && faults.refused === 1, `faults not hit: ${JSON.stringify(faults)}`);
|
||||||
const left = await new MediaClient(url, kotlinOwner).list();
|
const left = await new MediaClient(url, kotlinOwner).list();
|
||||||
check(left.items.length === 3, `Kotlin owner should have 3 files left (film, re-shared video, Android share), has ${left.items.length}`);
|
check(left.items.length === 4, `Kotlin owner should have 4 files left (film, re-shared video, album, Android share), has ${left.items.length}`);
|
||||||
console.log(
|
console.log(
|
||||||
`LIVE OK — Kotlin read the TS file; Kotlin film ${(out.film.size / MiB).toFixed(1)} MiB in ${faults.pieces} piece requests ` +
|
`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; a content:// share uploaded from Robolectric; photo deleted`,
|
`(${faults.starts} starts/resyncs, 1 lost answer, 1 refusal) read back by TS byte for byte; upload job killed and resumed; an album TS opens; a content:// share uploaded from Robolectric; photo deleted`,
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
server.stop(true);
|
server.stop(true);
|
||||||
|
|||||||
Reference in New Issue
Block a user