Add a real share action to every artifact item
Give each gallery image cell and each per-visit file row its own share control: a 48dp IconButton with an accurate "Share <name>" content description drawn as a sibling of the item's tap handler, so sharing never opens the image or the item. Sharing fetches the artifact through the existing client into a scoped cache file (cache/shared-artifacts/), exposed via a non-exported FileProvider declared with the new res/xml/file_paths.xml, and sends it through ACTION_SEND. When the fetch returns nothing the action falls back to sharing the resolved link as text. Cache files are named deterministically per artifact so re-sharing overwrites instead of growing without bound, and a failed or unreachable fetch cannot crash. The artifact-to-file naming, mime/extension table and the file-vs-link fallback decision are factored into ArtifactSharing.kt and covered by the new ArtifactSharingTest.kt. The existing open and copy-link actions are unchanged; the viewer's action scrim alpha is shared as ARTIFACT_ACTION_SCRIM_ALPHA. android/README.md documents the provider and the share flow. No new dependency is added.
This commit is contained in:
@@ -1760,3 +1760,63 @@ Not verified in this pass: a real hardware fold (the emulator is the 2076x2152
|
||||
inner display at 390 dpi); an Android 8/9 device branch (the `layoutInDisplayCutout
|
||||
Mode = SHORT_EDGES` fallback is compiled and lint-guarded but only the API 36 path
|
||||
ran).
|
||||
|
||||
## Share every artifact, from the grid cells and the per-visit rows (16 Oct 2026)
|
||||
|
||||
Every artifact item now carries a real share action: each image cell in a gallery
|
||||
grid (`ArtifactTile`) and each non-image row (`ArtifactRow`) has its own
|
||||
`ArtifactShareButton`. It is a child `IconButton` — its own 48dp hit area — so a
|
||||
tap on it consumes the gesture and never opens the image or the item, and its
|
||||
content description is `Share <name>`.
|
||||
|
||||
Sharing is not a stub. The new `ui/graph/ArtifactSharing.kt` fetches the resolved
|
||||
artifact through the app's existing client (`AppViewModel.fetchArtifactBytes` →
|
||||
`PipelinesClient.fetchBytes`, the shared OkHttp client) into
|
||||
`cacheDir/shared-artifacts/` and hands the file to the platform chooser through the
|
||||
declared `androidx.core.content.FileProvider` (`${applicationId}.fileprovider`,
|
||||
scoped by `res/xml/file_paths.xml` to that one cache subdirectory, not exported).
|
||||
The intent is `ACTION_SEND` with `EXTRA_STREAM`, `ClipData.newUri`, MIME
|
||||
`shareMimeType(contentType, fileName)` and `FLAG_GRANT_READ_URI_PERMISSION`, so the
|
||||
receiving app gets the actual bytes. When the fetch fails the artifact's resolved
|
||||
link is shared as `text/plain` instead (`shareDelivery`). The cache is bounded:
|
||||
`pruneSharedArtifacts` drops entries older than a day and enforces a 64 MiB cap,
|
||||
oldest first. No new dependency: `FileProvider` comes from the already-declared
|
||||
`androidx.core.ktx` and the share glyph from the already-declared
|
||||
`material-icons-extended`.
|
||||
|
||||
- `gradle :app:testDebugUnitTest` → **157 tests, 0 failures**; the 7 new ones are
|
||||
`ArtifactSharingTest` (file/link fallback decision, artifact-to-file naming:
|
||||
content-type/url extension, suffix de-duplication, path sanitisation, per-url
|
||||
distinctness, and `shareMimeType`).
|
||||
- `gradle :app:assembleDebug` → succeeded, `app-debug.apk` 18,283,787 bytes,
|
||||
sha256 `52ad15a6…`.
|
||||
- On `emulator-5554` (density 390) against the live server, run 91's summary: the
|
||||
uiautomator dump shows a clickable share node of `117x117px` = **48dp** with a
|
||||
`Share …` content description beside every preview; the grid and the `.mp4` row
|
||||
were captured (validated by `scripts/capture_png.sh -s emulator-5554`) to
|
||||
`grid_cell_share.png` and `list_row_share.png`.
|
||||
- Tapping a cell's share launched the chooser with the fetched file — logcat
|
||||
`ActivityTaskManager: START u0 {act=android.intent.action.SEND … clip={image/png
|
||||
…}}` (image/png), and the sharesheet showed a live preview of the actual PNG
|
||||
(`share_intent_image_png.png`). The `.mp4` row's share resolved to
|
||||
`clip={video/mp4 …}`; the cached files are
|
||||
`viewer_01_viewer_open_2f01f94a.png` and `viewer_viewer_gestures_8e1a3ba4.mp4`
|
||||
under `cache/shared-artifacts/`.
|
||||
- Fallback exercised live: with `adb shell cmd connectivity airplane-mode enable`
|
||||
(10.0.2.2 unreachable), tapping share opened the chooser titled **Sharing link**
|
||||
with the resolved `http://10.0.2.2:8080/artifacts/91/1/viewer/viewer_gestures.mp4`
|
||||
as text (`share_fallback_link.png`); `adb logcat -d` held 0 `FATAL EXCEPTION`.
|
||||
Airplane mode was then disabled and the app reconnected.
|
||||
- Open and copy-link are unchanged and still enabled on both items.
|
||||
- **APK publish.** `~/.local/share/pipelines/data/artifacts/94/1/pipelines-debug-wip-d339827.apk`
|
||||
(`d339827` = `git rev-parse --short HEAD`), sha256 `52ad15a6…`; `curl -I
|
||||
http://10.0.0.75:8080/artifacts/94/1/pipelines-debug-wip-d339827.apk` returned
|
||||
`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
|
||||
`Content-Length: 18283787` (18 MB, over the 8 MiB inventory cap, so direct URL
|
||||
only). `10.0.0.75` is `scripts/lan-address.py`'s output; `10.0.0.249` served it
|
||||
too.
|
||||
|
||||
Not verified in this pass: receiving the shared file inside a third-party app (the
|
||||
chooser was observed, not an app's import); the 24 h / 64 MiB prune bound was not
|
||||
reached on the emulator (only two small files were written).
|
||||
|
||||
|
||||
@@ -28,6 +28,23 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!--
|
||||
The only exported-URI surface: fetched artifacts are shared out of
|
||||
the app cache through ACTION_SEND. The provider is not exported
|
||||
and grants read access per-uri (FLAG_GRANT_READ_URI_PERMISSION), and
|
||||
file_paths.xml scopes it to the single `shared-artifacts` cache
|
||||
subdirectory. No other app-visible file path is exposed.
|
||||
-->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
package net.awan.pipelines.ui.graph
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.core.content.FileProvider
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* How a share action delivers an artifact. [File] streams the fetched bytes to a
|
||||
* cache file and hands it to the platform's [Intent.ACTION_SEND]; [Link] is the
|
||||
* fallback used when the fetch failed (or returned nothing), so a receiver still
|
||||
* gets the artifact's resolved link as text instead of a failed share.
|
||||
*/
|
||||
internal enum class ShareDelivery { File, Link }
|
||||
|
||||
/**
|
||||
* The delivery a share attempt uses for [bytes]: absent or empty bytes fall back
|
||||
* to [ShareDelivery.Link]. Pure, so the fallback decision is unit-tested without
|
||||
* a device or a network.
|
||||
*/
|
||||
internal fun shareDelivery(bytes: ByteArray?): ShareDelivery =
|
||||
if (bytes == null || bytes.isEmpty()) ShareDelivery.Link else ShareDelivery.File
|
||||
|
||||
/**
|
||||
* Canonical (mime, extension) pairs for the artifact formats the app can name;
|
||||
* the single format table shared by [artifactExtension] and [shareMimeType] so
|
||||
* the two never disagree.
|
||||
*/
|
||||
private val ARTIFACT_FORMATS: List<Pair<String, String>> = listOf(
|
||||
"image/png" to "png",
|
||||
"image/jpeg" to "jpg",
|
||||
"image/webp" to "webp",
|
||||
"image/gif" to "gif",
|
||||
"image/bmp" to "bmp",
|
||||
"image/svg+xml" to "svg",
|
||||
"text/plain" to "txt",
|
||||
"text/markdown" to "md",
|
||||
"application/json" to "json",
|
||||
"text/csv" to "csv",
|
||||
"text/html" to "html",
|
||||
"application/pdf" to "pdf",
|
||||
"application/zip" to "zip",
|
||||
)
|
||||
|
||||
private val EXTENSION_BY_MIME: Map<String, String> = ARTIFACT_FORMATS.toMap()
|
||||
private val MIME_BY_EXTENSION: Map<String, String> = ARTIFACT_FORMATS.associate { (mime, ext) -> ext to mime }
|
||||
|
||||
/** Longest base name kept before the url-derived suffix (keeps paths well under limits). */
|
||||
private const val MAX_BASE_CHARS = 48
|
||||
|
||||
/**
|
||||
* The name a shared artifact is cached and sent under: a filesystem-safe form of
|
||||
* its own [name] (or "artifact" when blank), a short stable suffix derived from
|
||||
* its [url] so two artifacts with the same name never collide, and an extension
|
||||
* from [contentType] or the url. Pure, so the naming is unit-tested without a
|
||||
* device; deterministic, so re-sharing the same artifact overwrites its file
|
||||
* instead of accumulating copies.
|
||||
*/
|
||||
internal fun artifactFileName(name: String, url: String, contentType: String?): String {
|
||||
val extension = artifactExtension(contentType, url)
|
||||
val sanitized = sanitizeArtifactName(name)
|
||||
// Drop a trailing extension that matches the one we append, so a name that
|
||||
// already carries its suffix is not doubled (`shot.png` -> `shot_<id>.png`).
|
||||
val base = if (sanitized.endsWith(".$extension", ignoreCase = true)) {
|
||||
sanitized.dropLast(extension.length + 1)
|
||||
} else {
|
||||
sanitized
|
||||
}.ifBlank { "artifact" }
|
||||
return "${base}_${Integer.toHexString(url.hashCode())}.$extension"
|
||||
}
|
||||
|
||||
/**
|
||||
* A filesystem-safe artifact name: path separators and any character outside the
|
||||
* portable `[A-Za-z0-9._-]` set become `_`, leading/trailing punctuation is
|
||||
* trimmed and the result is capped at [MAX_BASE_CHARS]. Pure.
|
||||
*/
|
||||
internal fun sanitizeArtifactName(name: String): String =
|
||||
name.trim()
|
||||
.map { if (it.isLetterOrDigit() || it == '.' || it == '-' || it == '_') it else '_' }
|
||||
.joinToString("")
|
||||
.trim('.', '_', '-')
|
||||
.take(MAX_BASE_CHARS)
|
||||
|
||||
/**
|
||||
* The extension (without the dot) an artifact is shared under: the canonical one
|
||||
* for its normalised [contentType], else the url's own last-segment extension
|
||||
* when it is a short alphanumeric token, else "bin". Pure.
|
||||
*/
|
||||
internal fun artifactExtension(contentType: String?, url: String): String {
|
||||
val mime = contentType?.substringBefore(';')?.trim()?.lowercase().orEmpty()
|
||||
EXTENSION_BY_MIME[mime]?.let { return it }
|
||||
val fromUrl = url.substringAfterLast('/', "").substringAfterLast('.', "").lowercase()
|
||||
if (fromUrl.isNotEmpty() && fromUrl.length <= 5 && fromUrl.all { it.isLetterOrDigit() }) return fromUrl
|
||||
return "bin"
|
||||
}
|
||||
|
||||
/**
|
||||
* The MIME type a shared artifact is sent as: its normalised [contentType] when
|
||||
* present, else one inferred from [fileName]'s extension, else the generic
|
||||
* binary type. Pure, so the value the platform intent carries is unit-tested.
|
||||
*/
|
||||
internal fun shareMimeType(contentType: String, fileName: String): String {
|
||||
val mime = contentType.substringBefore(';').trim().lowercase()
|
||||
if (mime.isNotEmpty()) return mime
|
||||
return MIME_BY_EXTENSION[fileName.substringAfterLast('.', "").lowercase()]
|
||||
?: "application/octet-stream"
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches [url]'s resolved artifact through the app's existing client and shares
|
||||
* it: the bytes go to the app cache and out through [Intent.ACTION_SEND]-with-
|
||||
* stream (via the declared [FileProvider]); when the fetch fails (offline server,
|
||||
* non-2xx, empty body) the artifact's link is shared as text instead. Never
|
||||
* throws: an unreachable server degrades to the link.
|
||||
*/
|
||||
internal suspend fun shareArtifact(
|
||||
context: Context,
|
||||
url: String,
|
||||
name: String,
|
||||
contentType: String?,
|
||||
fetchBytes: suspend (String) -> ByteArray?,
|
||||
) {
|
||||
val bytes = runCatching { fetchBytes(url) }.getOrNull()
|
||||
// A fetched file is preferred; a failed fetch, an unwritable cache or a
|
||||
// provider that cannot hand the file out all degrade to the link.
|
||||
val sharedFile = shareDelivery(bytes) == ShareDelivery.File &&
|
||||
runCatching { shareFile(context, bytes!!, url, name, contentType) }.getOrDefault(false)
|
||||
if (!sharedFile) shareLink(context, url)
|
||||
}
|
||||
|
||||
/** Writes the fetched bytes and launches the file share; false when no uri could be built. */
|
||||
private suspend fun shareFile(
|
||||
context: Context,
|
||||
bytes: ByteArray,
|
||||
url: String,
|
||||
name: String,
|
||||
contentType: String?,
|
||||
): Boolean {
|
||||
val file = withContext(Dispatchers.IO) {
|
||||
val dir = File(context.applicationContext.cacheDir, SHARED_ARTIFACT_DIR)
|
||||
dir.mkdirs()
|
||||
pruneSharedArtifacts(dir)
|
||||
File(dir, artifactFileName(name, url, contentType)).also { it.writeBytes(bytes) }
|
||||
}
|
||||
val uri = runCatching {
|
||||
FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
|
||||
}.getOrNull() ?: return false
|
||||
val intent = Intent(Intent.ACTION_SEND).apply {
|
||||
type = shareMimeType(contentType.orEmpty(), file.name)
|
||||
putExtra(Intent.EXTRA_STREAM, uri)
|
||||
putExtra(Intent.EXTRA_TITLE, name)
|
||||
// A ClipData carrying the same uri lets the sharesheet read the stream
|
||||
// (for its preview and to look up the resolved type) without a separate
|
||||
// grant; the flag still covers targets that only read EXTRA_STREAM.
|
||||
clipData = ClipData.newUri(context.contentResolver, name, uri)
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
}
|
||||
launchShare(context, intent)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun shareLink(context: Context, url: String) {
|
||||
val intent = Intent(Intent.ACTION_SEND).apply {
|
||||
type = "text/plain"
|
||||
putExtra(Intent.EXTRA_TEXT, url)
|
||||
clipData = ClipData.newPlainText(null, url)
|
||||
}
|
||||
launchShare(context, intent)
|
||||
}
|
||||
|
||||
/** Shows the platform chooser for [intent], tolerating a missing handler. */
|
||||
private fun launchShare(context: Context, intent: Intent) {
|
||||
runCatching { context.startActivity(Intent.createChooser(intent, null)) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounds the shared-artifact cache directory: entries older than [ttlMillis] are
|
||||
* dropped, and if the survivors still exceed [maxBytes] the oldest go first.
|
||||
* Keeps a long session's shared files from growing without bound; missing or
|
||||
* empty directories are a no-op.
|
||||
*/
|
||||
internal fun pruneSharedArtifacts(
|
||||
dir: File,
|
||||
now: Long = System.currentTimeMillis(),
|
||||
ttlMillis: Long = SHARED_ARTIFACT_TTL_MILLIS,
|
||||
maxBytes: Long = MAX_CACHED_SHARE_BYTES,
|
||||
) {
|
||||
val files = dir.listFiles()?.filter { it.isFile } ?: return
|
||||
val fresh = files.filter { now - it.lastModified() < ttlMillis }
|
||||
files.forEach { if (it !in fresh) it.delete() }
|
||||
var total = fresh.sumOf { it.length() }
|
||||
if (total <= maxBytes) return
|
||||
fresh.sortedBy { it.lastModified() }.forEach { file ->
|
||||
if (total <= maxBytes) return
|
||||
val size = file.length()
|
||||
if (file.delete()) total -= size
|
||||
}
|
||||
}
|
||||
|
||||
/** The app cache subdirectory shared artifact files are written to. */
|
||||
private const val SHARED_ARTIFACT_DIR = "shared-artifacts"
|
||||
|
||||
/** Shared artifact files are pruned after a day and capped at 64 MiB on disk. */
|
||||
private const val SHARED_ARTIFACT_TTL_MILLIS = 24L * 60 * 60 * 1000
|
||||
private const val MAX_CACHED_SHARE_BYTES = 64L * 1024 * 1024
|
||||
|
||||
/** Opacity of the scrim that backs an action over a bright artifact image. */
|
||||
internal const val ARTIFACT_ACTION_SCRIM_ALPHA = 0.5f
|
||||
@@ -279,7 +279,7 @@ private fun ArtifactViewerActions(
|
||||
// legible over a bright image; over the black backdrop it is invisible.
|
||||
Row(
|
||||
modifier = modifier.background(
|
||||
color = MaterialTheme.colorScheme.scrim.copy(alpha = ACTION_SCRIM_ALPHA),
|
||||
color = MaterialTheme.colorScheme.scrim.copy(alpha = ARTIFACT_ACTION_SCRIM_ALPHA),
|
||||
shape = CircleShape,
|
||||
),
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
@@ -316,9 +316,6 @@ private const val ZOOM_EPSILON = 0.01f
|
||||
/** Fraction of the viewport height a downward swipe must cross to dismiss. */
|
||||
private const val SWIPE_DISMISS_FRACTION = 0.22f
|
||||
|
||||
/** Opacity of the scrim capsule that backs the top action row over the image. */
|
||||
private const val ACTION_SCRIM_ALPHA = 0.5f
|
||||
|
||||
/**
|
||||
* The size [image] is drawn at to fit inside [viewport] with its aspect ratio
|
||||
* preserved, never upscaling past 1:1 (a small image keeps its native size).
|
||||
|
||||
@@ -3,6 +3,7 @@ package net.awan.pipelines.ui.graph
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
@@ -12,11 +13,13 @@ import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.automirrored.filled.OpenInNew
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
@@ -26,6 +29,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -36,6 +40,7 @@ import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.launch
|
||||
import net.awan.pipelines.data.protocol.RunStep
|
||||
import net.awan.pipelines.data.protocol.StageArtifact
|
||||
import net.awan.pipelines.data.transport.ServerUrl
|
||||
@@ -143,7 +148,7 @@ internal fun ArtifactGallery(
|
||||
}
|
||||
}
|
||||
others.forEach { artifact ->
|
||||
ArtifactRow(artifact, configuredServerUrl)
|
||||
ArtifactRow(artifact, configuredServerUrl, fetchArtifactBytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -211,6 +216,15 @@ private fun ArtifactTile(
|
||||
fetchBytes = fetchArtifactBytes,
|
||||
size = tile,
|
||||
)
|
||||
// The share control is its own hit area over the thumbnail: it consumes
|
||||
// the tap, so sharing never falls through to open the full-size view.
|
||||
ArtifactShareButton(
|
||||
artifact = artifact,
|
||||
resolved = resolved,
|
||||
fetchArtifactBytes = fetchArtifactBytes,
|
||||
modifier = Modifier.align(Alignment.TopEnd),
|
||||
scrim = true,
|
||||
)
|
||||
}
|
||||
|
||||
// The tap opens the full-screen viewer (one shared instance across the run
|
||||
@@ -226,11 +240,12 @@ private fun ArtifactTile(
|
||||
}
|
||||
}
|
||||
|
||||
/** One non-image artifact: a file glyph, name, size/type and open/copy actions. */
|
||||
/** One non-image artifact: a file glyph, name, size/type and open/share/copy actions. */
|
||||
@Composable
|
||||
private fun ArtifactRow(
|
||||
artifact: StageArtifact,
|
||||
configuredServerUrl: String,
|
||||
fetchArtifactBytes: suspend (String) -> ByteArray?,
|
||||
) {
|
||||
val text = pipelinesText()
|
||||
val context = LocalContext.current
|
||||
@@ -287,10 +302,55 @@ private fun ArtifactRow(
|
||||
) {
|
||||
Icon(Icons.Default.ContentCopy, contentDescription = "Copy link to ${artifact.name}")
|
||||
}
|
||||
ArtifactShareButton(
|
||||
artifact = artifact,
|
||||
resolved = resolved,
|
||||
fetchArtifactBytes = fetchArtifactBytes,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The share action every artifact item carries (the gallery's image cells and
|
||||
* its file rows): a 48dp [IconButton] target, an accurate content description,
|
||||
* and a click that launches the platform share chooser. It is the item's own
|
||||
* child action, so a tap on it never opens the image or the item. [scrim] adds
|
||||
* the translucent backing the viewer uses so the icon stays legible over a
|
||||
* bright image.
|
||||
*/
|
||||
@Composable
|
||||
private fun ArtifactShareButton(
|
||||
artifact: StageArtifact,
|
||||
resolved: String?,
|
||||
fetchArtifactBytes: suspend (String) -> ByteArray?,
|
||||
modifier: Modifier = Modifier,
|
||||
scrim: Boolean = false,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
IconButton(
|
||||
onClick = {
|
||||
resolved?.let { url ->
|
||||
scope.launch {
|
||||
shareArtifact(context, url, artifact.name, artifact.contentType, fetchArtifactBytes)
|
||||
}
|
||||
}
|
||||
},
|
||||
enabled = resolved != null,
|
||||
modifier = if (scrim) {
|
||||
modifier.background(
|
||||
MaterialTheme.colorScheme.scrim.copy(alpha = ARTIFACT_ACTION_SCRIM_ALPHA),
|
||||
CircleShape,
|
||||
)
|
||||
} else {
|
||||
modifier
|
||||
},
|
||||
) {
|
||||
Icon(Icons.Default.Share, contentDescription = "Share ${artifact.name.ifBlank { "artifact" }}")
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the resolved artifact url externally, tolerating a missing handler. */
|
||||
internal fun openArtifact(context: Context, url: String?) {
|
||||
if (url == null) return
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
Scopes the FileProvider to the single cache subdirectory the share action
|
||||
writes fetched artifacts into; no other app path is shareable.
|
||||
-->
|
||||
<paths>
|
||||
<cache-path name="shared-artifacts" path="shared-artifacts/" />
|
||||
</paths>
|
||||
@@ -0,0 +1,71 @@
|
||||
package net.awan.pipelines.ui.graph
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Pure-logic tests for the artifact share action: the file the fetched bytes are
|
||||
* written as and the file/link fallback decision, both independent of a device.
|
||||
*/
|
||||
class ArtifactSharingTest {
|
||||
|
||||
private val imageUrl = "/artifacts/60/4/00_start.png"
|
||||
|
||||
@Test
|
||||
fun shareDeliveryIsAFileOnlyWhenTheFetchReturnedBytes() {
|
||||
assertEquals(ShareDelivery.File, shareDelivery(byteArrayOf(1, 2, 3)))
|
||||
assertEquals(ShareDelivery.Link, shareDelivery(null))
|
||||
assertEquals(ShareDelivery.Link, shareDelivery(ByteArray(0)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun artifactFileNameUsesTheContentTypeExtensionAndDropsADuplicateSuffix() {
|
||||
val file = artifactFileName("00_start.png", imageUrl, "image/png")
|
||||
assertTrue(file.startsWith("00_start_"))
|
||||
assertTrue(file.endsWith(".png"))
|
||||
// The `_<url hash>` suffix appears exactly once, so the name is not doubled.
|
||||
assertTrue(file.count { it == '.' } == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun artifactFileNameFallsBackToTheUrlExtensionWhenTheContentTypeIsBlank() {
|
||||
val file = artifactFileName("report", "/artifacts/9/1/report.pdf", null)
|
||||
assertTrue(file.startsWith("report_"))
|
||||
assertTrue(file.endsWith(".pdf"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun artifactFileNameSanitizesUnsafeNames() {
|
||||
val file = artifactFileName("../../etc/passwd", "/artifacts/9/1/passwd", "text/plain")
|
||||
assertTrue(file.none { it == '/' })
|
||||
assertTrue(!file.contains(".."))
|
||||
assertTrue(file.contains("etc_passwd"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun artifactFileNameIsTheSameForTheSameArtifactAndDistinctForDifferentUrls() {
|
||||
val a = artifactFileName("shot.png", imageUrl, "image/png")
|
||||
val b = artifactFileName("shot.png", imageUrl, "image/png")
|
||||
val other = artifactFileName("shot.png", "/artifacts/60/5/shot.png", "image/png")
|
||||
assertEquals(a, b)
|
||||
assertNotEquals(a, other)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun artifactExtensionPrefersTheContentTypeThenTheUrlThenBin() {
|
||||
assertEquals("jpg", artifactExtension("image/jpeg; charset=binary", imageUrl))
|
||||
assertEquals("pdf", artifactExtension("", "/x/report.pdf"))
|
||||
assertEquals("bin", artifactExtension("", "/x/no-extension"))
|
||||
assertEquals("bin", artifactExtension(null, "/x/"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shareMimeTypePrefersTheContentTypeThenTheFileNameExtension() {
|
||||
assertEquals("image/png", shareMimeType("image/png", "shot_1.png"))
|
||||
assertEquals("image/jpeg", shareMimeType(" image/jpeg ; q=1 ", "shot_1.jpg"))
|
||||
assertEquals("application/pdf", shareMimeType("", "report_2.pdf"))
|
||||
assertEquals("application/octet-stream", shareMimeType("", "odd_3.xyz"))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user