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:
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 -> {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
Reference in New Issue
Block a user