This commit is contained in:
1 parent
4b421fdebf
commit
fe72a53a23
20 files changed
+795
-52
No files matched your search
@@ -24,8 +24,8 @@ android {
|
||||
applicationId = "dev.alvin.smbexplorer"
|
||||
minSdk = 28
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "0.1"
|
||||
versionCode = 2
|
||||
versionName = "1.0.0-rc.1"
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
compileOptions {
|
||||
@@ -42,6 +42,9 @@ dependencies {
|
||||
implementation("androidx.compose.foundation:foundation")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||
implementation("com.hierynomus:smbj:0.15.0")
|
||||
implementation("androidx.media3:media3-exoplayer:1.11.1")
|
||||
implementation("androidx.media3:media3-ui:1.11.1")
|
||||
androidTestImplementation("androidx.test:runner:1.7.0")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<application android:label="SMB Explorer" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:usesCleartextTraffic="false" android:theme="@android:style/Theme.Material.NoActionBar">
|
||||
<application android:label="SMB Explorer" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:fullBackupContent="false" android:dataExtractionRules="@xml/data_extraction_rules" android:usesCleartextTraffic="false" android:theme="@android:style/Theme.Material.NoActionBar">
|
||||
<provider android:name=".VideoStreamProvider" android:authorities="dev.alvin.smbexplorer.stream" android:exported="false" android:grantUriPermissions="true" />
|
||||
<activity android:name=".MainActivity" android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
@@ -11,6 +11,10 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.delay
|
||||
import java.io.OutputStream
|
||||
|
||||
/** Reuses one authenticated share while browsing and retains recent folder listings. */
|
||||
class BrowseRepository(private val target: SmbTarget) {
|
||||
@@ -23,7 +27,7 @@ class BrowseRepository(private val target: SmbTarget) {
|
||||
|
||||
suspend fun list(path: String): ProbeResult = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
val listing = (session ?: SmbShareSession(target).also { session = it }).list(path)
|
||||
val listing = reconnectable { it.list(path) }
|
||||
synchronized(cache) {
|
||||
cache[path] = listing
|
||||
if (cache.size > 20) cache.remove(cache.keys.first())
|
||||
@@ -32,9 +36,55 @@ class BrowseRepository(private val target: SmbTarget) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun read(path: String): ByteArray = withContext(Dispatchers.IO) {
|
||||
suspend fun read(path: String, maxBytes: Long = 64L * 1024 * 1024): ByteArray = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
(session ?: SmbShareSession(target).also { session = it }).read(path)
|
||||
reconnectable { it.read(path, maxBytes) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> reconnectable(operation: (SmbShareSession) -> T): T {
|
||||
try { return operation(session ?: SmbShareSession(target).also { session = it }) }
|
||||
catch (first: Exception) {
|
||||
runCatching { session?.close() }
|
||||
session = null
|
||||
currentCoroutineContext().ensureActive()
|
||||
delay(300)
|
||||
return try { operation(SmbShareSession(target).also { session = it }) }
|
||||
catch (second: Exception) {
|
||||
runCatching { session?.close() }
|
||||
session = null
|
||||
throw second
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun download(path: String, output: OutputStream, progress: (Long, Long) -> Unit) = withContext(Dispatchers.IO) {
|
||||
val context = currentCoroutineContext()
|
||||
mutex.withLock {
|
||||
try {
|
||||
(session ?: SmbShareSession(target).also { session = it }).copy(path, output) { done, total ->
|
||||
context.ensureActive()
|
||||
progress(done, total)
|
||||
}
|
||||
context.ensureActive()
|
||||
} catch (e: Exception) {
|
||||
runCatching { session?.close() }
|
||||
session = null
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun delete(path: String, directory: Boolean) = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
try {
|
||||
(session ?: SmbShareSession(target).also { session = it }).delete(path, directory)
|
||||
synchronized(cache) { cache.clear() }
|
||||
} catch (e: Exception) {
|
||||
runCatching { session?.close() }
|
||||
session = null
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,14 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import android.os.Build
|
||||
import android.content.Intent
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
@@ -34,9 +41,14 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.Job
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CancellationException
|
||||
@@ -55,6 +67,7 @@ private enum class FileFilter { All, Images, Videos, Other, Folders }
|
||||
private val imageExtensions = setOf("jpg", "jpeg", "png", "gif", "webp", "heic", "heif", "bmp", "avif")
|
||||
private val videoExtensions = setOf("mp4", "mkv", "webm", "avi", "mov", "m4v", "ts", "mpeg", "mpg")
|
||||
private fun RemoteEntry.isImage() = !directory && name.substringAfterLast('.', "").lowercase() in imageExtensions
|
||||
private fun RemoteEntry.isVideo() = !directory && name.substringAfterLast('.', "").lowercase() in videoExtensions
|
||||
|
||||
private fun FileFilter.matches(entry: RemoteEntry): Boolean {
|
||||
val extension = entry.name.substringAfterLast('.', "").lowercase()
|
||||
@@ -67,6 +80,8 @@ private fun FileFilter.matches(entry: RemoteEntry): Boolean {
|
||||
}
|
||||
}
|
||||
|
||||
@androidx.annotation.OptIn(UnstableApi::class)
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
val repository = remember(saved.id) { BrowseRepository(saved.target) }
|
||||
@@ -76,19 +91,68 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
var search by remember { mutableStateOf("") }
|
||||
var sort by remember { mutableStateOf(SortMode.NameAsc) }
|
||||
var filter by remember { mutableStateOf(FileFilter.All) }
|
||||
var result by remember { mutableStateOf<ProbeResult?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var loading by remember { mutableStateOf(true) }
|
||||
var result by remember(saved.id, path) { mutableStateOf<ProbeResult?>(null) }
|
||||
var error by remember(saved.id, path) { mutableStateOf<String?>(null) }
|
||||
var loading by remember(saved.id, path) { mutableStateOf(true) }
|
||||
var selectedFile by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
var selectedImage by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
var selectedVideo by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
var sortOpen by remember { mutableStateOf(false) }
|
||||
var visible by remember { mutableStateOf(emptyList<RemoteEntry>()) }
|
||||
var visible by remember(saved.id, path) { mutableStateOf(emptyList<RemoteEntry>()) }
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var actionMessage by remember { mutableStateOf<String?>(null) }
|
||||
var downloadJob by remember { mutableStateOf<Job?>(null) }
|
||||
var downloadProgress by remember { mutableStateOf(0L to 0L) }
|
||||
var pendingDownload by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
var pendingRemoteDelete by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
val savePicker = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri ->
|
||||
val entry = pendingDownload
|
||||
pendingDownload = null
|
||||
if (uri != null && entry != null) {
|
||||
downloadJob = scope.launch {
|
||||
try {
|
||||
context.contentResolver.openOutputStream(uri, "w")?.use { stream ->
|
||||
repository.download(if (path.isEmpty()) entry.name else "$path\\${entry.name}", stream) { done, total ->
|
||||
downloadProgress = done to total
|
||||
}
|
||||
} ?: error("Could not open destination")
|
||||
actionMessage = "Downloaded ${entry.name}"
|
||||
} catch (e: CancellationException) {
|
||||
context.contentResolver.delete(uri, null, null)
|
||||
actionMessage = "Download cancelled"
|
||||
} catch (e: Exception) {
|
||||
context.contentResolver.delete(uri, null, null)
|
||||
actionMessage = "Download failed: ${e.message}"
|
||||
} finally { downloadJob = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun startDownload(entry: RemoteEntry) {
|
||||
downloadProgress = 0L to entry.size
|
||||
if (Build.VERSION.SDK_INT < 29) {
|
||||
pendingDownload = entry
|
||||
savePicker.launch(entry.name)
|
||||
} else downloadJob = scope.launch {
|
||||
try {
|
||||
DownloadStore.save(context, repository, if (path.isEmpty()) entry.name else "$path\\${entry.name}", entry.name) { done, total ->
|
||||
downloadProgress = done to total
|
||||
}
|
||||
actionMessage = "Downloaded ${entry.name} to Downloads"
|
||||
} catch (e: CancellationException) {
|
||||
actionMessage = "Download cancelled"
|
||||
} catch (e: Exception) {
|
||||
actionMessage = "Download failed: ${e.message}"
|
||||
} finally { downloadJob = null }
|
||||
}
|
||||
}
|
||||
|
||||
fun up() {
|
||||
path = path.substringBeforeLast('\\', "")
|
||||
search = ""
|
||||
}
|
||||
BackHandler(enabled = selectedImage == null) { if (path.isEmpty()) onConnections() else up() }
|
||||
BackHandler(enabled = selectedImage == null && selectedVideo == null) { if (path.isEmpty()) onConnections() else up() }
|
||||
|
||||
LaunchedEffect(saved.id, path, refresh) {
|
||||
loading = true
|
||||
@@ -111,16 +175,38 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
if (images.isNotEmpty()) ImageViewer(saved, repository, path, images, image) { selectedImage = null }
|
||||
return
|
||||
}
|
||||
selectedVideo?.let { video ->
|
||||
VideoViewer(saved, if (path.isEmpty()) video.name else "$path\\${video.name}") { selectedVideo = null }
|
||||
return
|
||||
}
|
||||
|
||||
selectedFile?.let { file ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { selectedFile = null },
|
||||
title = { Text(file.name) },
|
||||
text = { Text("Size: ${file.size} bytes\nModified: ${formatDate(file.modifiedAt)}\nPath: ${if (path.isEmpty()) file.name else "$path\\${file.name}"}") },
|
||||
confirmButton = { Button(onClick = { selectedFile = null }) { Text("Close") } },
|
||||
confirmButton = { Button(onClick = { selectedFile = null; startDownload(file) }) { Text("Download") } },
|
||||
dismissButton = { TextButton(onClick = { selectedFile = null; pendingRemoteDelete = file }) { Text("Delete…") } },
|
||||
)
|
||||
}
|
||||
|
||||
pendingRemoteDelete?.let { entry ->
|
||||
AlertDialog(onDismissRequest = { pendingRemoteDelete = null },
|
||||
title = { Text("Delete ${entry.name}?") },
|
||||
text = { Text(if (entry.directory) "Only an empty folder can be deleted." else "This file will be removed from the share.") },
|
||||
confirmButton = { Button(onClick = {
|
||||
pendingRemoteDelete = null
|
||||
scope.launch {
|
||||
try {
|
||||
repository.delete(if (path.isEmpty()) entry.name else "$path\\${entry.name}", entry.directory)
|
||||
refresh++
|
||||
actionMessage = "Deleted ${entry.name}"
|
||||
} catch (e: Exception) { actionMessage = "Delete failed: ${e.message}" }
|
||||
}
|
||||
}) { Text("Delete") } },
|
||||
dismissButton = { TextButton(onClick = { pendingRemoteDelete = null }) { Text("Cancel") } })
|
||||
}
|
||||
|
||||
LaunchedEffect(result, search, sort, filter) {
|
||||
val entries = result?.entries.orEmpty()
|
||||
visible = withContext(Dispatchers.Default) {
|
||||
@@ -136,10 +222,16 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
TextButton(onClick = { if (path.isEmpty()) onConnections() else up() }) { Text("‹ Back") }
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(if (path.isEmpty()) saved.target.share else path.substringAfterLast('\\'), style = MaterialTheme.typography.titleLarge)
|
||||
Text(if (path.isEmpty()) saved.target.share else path.substringAfterLast('\\'), style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(saved.target.host, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
|
||||
TextButton(onClick = { refresh++ }) { Text("Refresh") }
|
||||
TextButton(onClick = {
|
||||
context.cacheDir.resolve("thumbnails").listFiles()?.forEach { it.delete() }
|
||||
actionMessage = "Thumbnail cache cleared"
|
||||
}) { Text("Clear cache") }
|
||||
}
|
||||
if (path.isNotEmpty()) Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
TextButton(onClick = { path = ""; search = "" }) { Text(saved.target.share) }
|
||||
@@ -170,17 +262,26 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
}
|
||||
}
|
||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
actionMessage?.let { Text(it) }
|
||||
downloadJob?.let {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Downloading ${downloadProgress.first} / ${downloadProgress.second} bytes", Modifier.weight(1f))
|
||||
TextButton(onClick = { it.cancel() }) { Text("Cancel") }
|
||||
}
|
||||
}
|
||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
items(visible, key = { "$path/${it.name}" }) { entry ->
|
||||
Surface(Modifier.fillMaxWidth(), color = MaterialTheme.colorScheme.surfaceContainerLow, shape = MaterialTheme.shapes.medium) {
|
||||
Row(Modifier.fillMaxWidth().clickable {
|
||||
Row(Modifier.fillMaxWidth().combinedClickable(onLongClick = { pendingRemoteDelete = entry }, onClick = {
|
||||
if (entry.directory) {
|
||||
path = if (path.isEmpty()) entry.name else "$path\\${entry.name}"
|
||||
search = ""
|
||||
} else if (entry.isImage()) selectedImage = entry
|
||||
else if (entry.isVideo()) selectedVideo = entry
|
||||
else selectedFile = entry
|
||||
}.padding(horizontal = 14.dp, vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(if (entry.directory) "▣" else if (entry.isImage()) "▧" else "▤", color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.titleLarge)
|
||||
}).padding(horizontal = 14.dp, vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (entry.isImage()) Thumbnail(repository, saved.id, if (path.isEmpty()) entry.name else "$path\\${entry.name}", entry)
|
||||
else Text(if (entry.directory) "▣" else "▤", color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.titleLarge)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(entry.name, style = MaterialTheme.typography.bodyLarge)
|
||||
if (!entry.directory) Text("${formatSize(entry.size)} · ${formatDate(entry.modifiedAt)}", style = MaterialTheme.typography.bodySmall,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import java.io.OutputStream
|
||||
|
||||
/** Copies the advertised length or fails without reporting success. */
|
||||
internal fun copyExact(length: Long, output: OutputStream,
|
||||
read: (ByteArray, Long) -> Int,
|
||||
progress: (Long, Long) -> Unit) {
|
||||
require(length >= 0)
|
||||
val buffer = ByteArray(256 * 1024)
|
||||
var offset = 0L
|
||||
while (offset < length) {
|
||||
val count = read(buffer, offset)
|
||||
check(count in 1..minOf(buffer.size.toLong(), length - offset).toInt()) {
|
||||
"Remote file ended or changed before download completed"
|
||||
}
|
||||
output.write(buffer, 0, count)
|
||||
offset += count
|
||||
progress(offset, length)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.annotation.TargetApi
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import java.io.IOException
|
||||
|
||||
/** Publishes a download only after the SMB copy has completed. */
|
||||
object DownloadStore {
|
||||
@TargetApi(29)
|
||||
suspend fun save(context: Context, repository: BrowseRepository, path: String, name: String,
|
||||
progress: (Long, Long) -> Unit) {
|
||||
require(Build.VERSION.SDK_INT >= 29) { "Choose a destination on Android 9" }
|
||||
val resolver = context.contentResolver
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Downloads.DISPLAY_NAME, name)
|
||||
put(MediaStore.Downloads.MIME_TYPE, "application/octet-stream")
|
||||
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
|
||||
put(MediaStore.Downloads.IS_PENDING, 1)
|
||||
}
|
||||
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
||||
?: throw IOException("Could not create Downloads entry")
|
||||
try {
|
||||
resolver.openOutputStream(uri, "w")?.use { repository.download(path, it, progress) }
|
||||
?: throw IOException("Could not open Downloads entry")
|
||||
resolver.update(uri, ContentValues().apply { put(MediaStore.Downloads.IS_PENDING, 0) }, null, null)
|
||||
} catch (e: Exception) {
|
||||
resolver.delete(uri, null, null)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import android.graphics.drawable.Drawable
|
||||
import android.widget.ImageView
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTransformGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
@@ -30,9 +32,13 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -53,14 +59,28 @@ fun ImageViewer(saved: SavedShare, repository: BrowseRepository, folder: String,
|
||||
var drawable by remember { mutableStateOf<android.graphics.drawable.Drawable?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var loading by remember { mutableStateOf(true) }
|
||||
var original by remember(index) { mutableStateOf(false) }
|
||||
var fill by remember { mutableStateOf(false) }
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
var foreground by remember { mutableStateOf(lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, _ ->
|
||||
foreground = lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
var scale by remember(index) { mutableStateOf(1f) }
|
||||
var panX by remember(index) { mutableStateOf(0f) }
|
||||
var panY by remember(index) { mutableStateOf(0f) }
|
||||
BackHandler(onBack = onClose)
|
||||
|
||||
LaunchedEffect(saved.id, folder, entry.name) {
|
||||
LaunchedEffect(saved.id, folder, entry.name, original) {
|
||||
drawable = null
|
||||
error = null
|
||||
loading = true
|
||||
try {
|
||||
drawable = loader.load(entry.name)
|
||||
drawable = loader.load(entry.name, original)
|
||||
images.getOrNull(index + 1)?.let { loader.prefetch(it.name) }
|
||||
images.getOrNull(index - 1)?.let { loader.prefetch(it.name) }
|
||||
} catch (e: CancellationException) {
|
||||
@@ -80,15 +100,26 @@ fun ImageViewer(saved: SavedShare, repository: BrowseRepository, folder: String,
|
||||
}
|
||||
Text(entry.name, Modifier.padding(horizontal = 16.dp), style = MaterialTheme.typography.bodyMedium, maxLines = 1)
|
||||
var drag by remember { mutableStateOf(0f) }
|
||||
Box(Modifier.weight(1f).fillMaxWidth().pointerInput(index, images.size) {
|
||||
Box(Modifier.weight(1f).fillMaxWidth().pointerInput(index, images.size, scale) {
|
||||
detectHorizontalDragGestures(
|
||||
onHorizontalDrag = { _, amount -> drag += amount },
|
||||
onHorizontalDrag = { _, amount -> if (scale <= 1f) drag += amount else panX += amount },
|
||||
onDragEnd = {
|
||||
if (drag < -80 && index < images.lastIndex) index++
|
||||
if (drag > 80 && index > 0) index--
|
||||
drag = 0f
|
||||
},
|
||||
)
|
||||
}.pointerInput(index) {
|
||||
detectTransformGestures { _, pan, zoom, _ ->
|
||||
scale = (scale * zoom).coerceIn(1f, 4f)
|
||||
if (scale > 1f) { panX += pan.x; panY += pan.y }
|
||||
else { panX = 0f; panY = 0f }
|
||||
}
|
||||
}.pointerInput(index) {
|
||||
detectTapGestures(onDoubleTap = {
|
||||
scale = if (scale > 1f) 1f else 2f
|
||||
if (scale == 1f) { panX = 0f; panY = 0f }
|
||||
})
|
||||
}, contentAlignment = Alignment.Center) {
|
||||
if (loading) CircularProgressIndicator()
|
||||
error?.let { Text(it, Modifier.padding(24.dp), color = MaterialTheme.colorScheme.error) }
|
||||
@@ -96,14 +127,19 @@ fun ImageViewer(saved: SavedShare, repository: BrowseRepository, folder: String,
|
||||
AndroidView(factory = { context -> ImageView(context).apply { scaleType = ImageView.ScaleType.FIT_CENTER } },
|
||||
update = { view ->
|
||||
(view.drawable as? Animatable)?.stop()
|
||||
view.scaleType = if (fill) ImageView.ScaleType.CENTER_CROP else ImageView.ScaleType.FIT_CENTER
|
||||
view.setImageDrawable(current)
|
||||
(current as? Animatable)?.start()
|
||||
}, modifier = Modifier.fillMaxSize())
|
||||
if (foreground) (current as? Animatable)?.start()
|
||||
}, modifier = Modifier.fillMaxSize().graphicsLayer {
|
||||
scaleX = scale; scaleY = scale; translationX = panX; translationY = panY
|
||||
})
|
||||
DisposableEffect(current) { onDispose { (current as? Animatable)?.stop() } }
|
||||
}
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
TextButton(enabled = index > 0, onClick = { index-- }) { Text("‹ Previous") }
|
||||
TextButton(onClick = { fill = !fill }) { Text(if (fill) "Fit" else "Fill") }
|
||||
TextButton(onClick = { original = !original }) { Text(if (original) "Sampled" else "Original") }
|
||||
TextButton(enabled = index < images.lastIndex, onClick = { index++ }) { Text("Next ›") }
|
||||
}
|
||||
}
|
||||
@@ -136,13 +172,18 @@ private class ImageLoader(private val repository: BrowseRepository, private val
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun load(name: String): Drawable = decodeMutex.withLock {
|
||||
synchronized(decoded) { decoded[name] }?.let { return@withLock it }
|
||||
suspend fun load(name: String, original: Boolean = false): Drawable = decodeMutex.withLock {
|
||||
val key = "$name:$original"
|
||||
synchronized(decoded) { decoded[key] }?.let { return@withLock it }
|
||||
val data = bytes(name)
|
||||
val drawable = withContext(Dispatchers.Default) {
|
||||
ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(data))) { decoder, info, _ ->
|
||||
val largestSide = maxOf(info.size.width, info.size.height)
|
||||
if (largestSide > 4096) decoder.setTargetSampleSize((largestSide + 4095) / 4096)
|
||||
if (original) {
|
||||
require(info.size.width.toLong() * info.size.height <= 16_000_000) {
|
||||
"Original image exceeds the safe memory limit"
|
||||
}
|
||||
} else if (largestSide > 4096) decoder.setTargetSampleSize((largestSide + 4095) / 4096)
|
||||
}
|
||||
}
|
||||
if (drawable is BitmapDrawable) {
|
||||
@@ -153,7 +194,7 @@ private class ImageLoader(private val repository: BrowseRepository, private val
|
||||
decodedBytes -= oldest.value.bitmap.allocationByteCount
|
||||
decoded.remove(oldest.key)
|
||||
}
|
||||
decoded.put(name, drawable)?.let { decodedBytes -= it.bitmap.allocationByteCount }
|
||||
decoded.put(key, drawable)?.let { decodedBytes -= it.bitmap.allocationByteCount }
|
||||
decodedBytes += size
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.datasource.BaseDataSource
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.datasource.DataSpec
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import java.io.EOFException
|
||||
import java.io.IOException
|
||||
|
||||
/** A byte-positioned SMB source. Each Media3 open owns its remote handles. */
|
||||
@UnstableApi
|
||||
class SmbDataSource(private val target: SmbTarget, private val path: String) : BaseDataSource(false) {
|
||||
private var session: SmbShareSession? = null
|
||||
private var range: RemoteRange? = null
|
||||
private var position = 0L
|
||||
private var remaining = 0L
|
||||
private var uri: Uri? = null
|
||||
private var started = false
|
||||
|
||||
override fun open(dataSpec: DataSpec): Long {
|
||||
transferInitializing(dataSpec)
|
||||
try {
|
||||
val connected = SmbShareSession(target)
|
||||
session = connected
|
||||
val opened = connected.openRange(path)
|
||||
range = opened
|
||||
if (dataSpec.position > opened.length) throw EOFException("Seek past end of file")
|
||||
position = dataSpec.position
|
||||
remaining = if (dataSpec.length == C.LENGTH_UNSET.toLong()) opened.length - position
|
||||
else minOf(dataSpec.length, opened.length - position)
|
||||
uri = dataSpec.uri
|
||||
transferStarted(dataSpec)
|
||||
started = true
|
||||
return remaining
|
||||
} catch (e: Exception) {
|
||||
close()
|
||||
throw IOException("Could not open SMB video", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (length == 0) return 0
|
||||
if (remaining == 0L) return C.RESULT_END_OF_INPUT
|
||||
val handle = range ?: throw IOException("SMB video is closed")
|
||||
try {
|
||||
val requested = minOf(length.toLong(), remaining, 256L * 1024).toInt()
|
||||
val count = try { handle.read(buffer, position, requested) }
|
||||
catch (first: Exception) {
|
||||
runCatching { range?.close() }
|
||||
runCatching { session?.close() }
|
||||
session = SmbShareSession(target)
|
||||
range = session!!.openRange(path)
|
||||
range!!.read(buffer, position, requested)
|
||||
}
|
||||
if (count <= 0) throw EOFException("Remote video ended unexpectedly")
|
||||
position += count
|
||||
remaining -= count
|
||||
bytesTransferred(count)
|
||||
return count
|
||||
} catch (e: Exception) { throw IOException("SMB video read failed", e) }
|
||||
}
|
||||
|
||||
override fun getUri(): Uri? = uri
|
||||
|
||||
override fun close() {
|
||||
val wasOpen = started
|
||||
runCatching { range?.close() }
|
||||
runCatching { session?.close() }
|
||||
range = null
|
||||
session = null
|
||||
uri = null
|
||||
if (wasOpen) transferEnded()
|
||||
started = false
|
||||
}
|
||||
|
||||
class Factory(private val target: SmbTarget, private val path: String) : DataSource.Factory {
|
||||
override fun createDataSource(): DataSource = SmbDataSource(target, path)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import java.io.Closeable
|
||||
import java.security.MessageDigest
|
||||
import java.util.EnumSet
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.OutputStream
|
||||
import com.hierynomus.smbj.connection.Connection
|
||||
import com.hierynomus.smbj.session.Session
|
||||
|
||||
@@ -103,10 +104,39 @@ class SmbProbe : Closeable {
|
||||
/** Keeps the SMB session open while the viewer is visible. Call from one IO coroutine at a time. */
|
||||
class SmbShareSession(target: SmbTarget) : Closeable {
|
||||
private val client = SMBClient()
|
||||
private val connection: Connection = client.connect(target.host.trim(), target.port)
|
||||
private val session: Session = connection.authenticate(
|
||||
AuthenticationContext(target.username, target.password.toCharArray(), target.domain))
|
||||
private val share: DiskShare = session.connectShare(target.share.trim()) as DiskShare
|
||||
private val connection: Connection
|
||||
private val session: Session
|
||||
private val share: DiskShare
|
||||
|
||||
init {
|
||||
try {
|
||||
connection = client.connect(target.host.trim(), target.port)
|
||||
} catch (e: Exception) {
|
||||
client.close()
|
||||
throw e
|
||||
}
|
||||
try {
|
||||
session = connection.authenticate(
|
||||
AuthenticationContext(target.username, target.password.toCharArray(), target.domain))
|
||||
} catch (e: Exception) {
|
||||
connection.close()
|
||||
client.close()
|
||||
throw e
|
||||
}
|
||||
try {
|
||||
val connectedShare = session.connectShare(target.share.trim())
|
||||
if (connectedShare !is DiskShare) {
|
||||
connectedShare.close()
|
||||
throw IllegalArgumentException("The selected share is not a disk share")
|
||||
}
|
||||
share = connectedShare
|
||||
} catch (e: Exception) {
|
||||
session.close()
|
||||
connection.close()
|
||||
client.close()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
fun list(folder: String): ProbeResult {
|
||||
val start = System.nanoTime()
|
||||
@@ -135,6 +165,33 @@ class SmbShareSession(target: SmbTarget) : Closeable {
|
||||
} finally { file.close() }
|
||||
}
|
||||
|
||||
fun copy(path: String, output: OutputStream, progress: (Long, Long) -> Unit) {
|
||||
val file = share.openFile(normalize(path), EnumSet.of(AccessMask.GENERIC_READ),
|
||||
EnumSet.noneOf(FileAttributes::class.java), EnumSet.of(SMB2ShareAccess.FILE_SHARE_READ),
|
||||
SMB2CreateDisposition.FILE_OPEN, EnumSet.noneOf(SMB2CreateOptions::class.java))
|
||||
try {
|
||||
val length = file.length
|
||||
copyExact(length, output, { buffer, offset -> file.read(buffer, offset) }, progress)
|
||||
} finally { file.close() }
|
||||
}
|
||||
|
||||
fun delete(path: String, directory: Boolean) {
|
||||
val normalized = normalize(path)
|
||||
require(normalized.isNotEmpty()) { "Cannot delete share root" }
|
||||
if (directory) {
|
||||
val children = share.list(normalized).filter { it.fileName != "." && it.fileName != ".." }
|
||||
check(children.isEmpty()) { "Folder is not empty" }
|
||||
share.rmdir(normalized, false)
|
||||
} else share.rm(normalized)
|
||||
}
|
||||
|
||||
fun openRange(path: String): RemoteRange {
|
||||
val file = share.openFile(normalize(path), EnumSet.of(AccessMask.GENERIC_READ),
|
||||
EnumSet.noneOf(FileAttributes::class.java), EnumSet.of(SMB2ShareAccess.FILE_SHARE_READ),
|
||||
SMB2CreateDisposition.FILE_OPEN, EnumSet.noneOf(SMB2CreateOptions::class.java))
|
||||
return RemoteRange(file)
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
share.close()
|
||||
session.close()
|
||||
@@ -143,6 +200,12 @@ class SmbShareSession(target: SmbTarget) : Closeable {
|
||||
}
|
||||
}
|
||||
|
||||
class RemoteRange(private val file: File) : Closeable {
|
||||
val length: Long get() = file.length
|
||||
fun read(buffer: ByteArray, offset: Long, count: Int): Int = file.read(buffer, offset, 0, count)
|
||||
override fun close() = file.close()
|
||||
}
|
||||
|
||||
private fun FileIdBothDirectoryInformation.toEntry() = RemoteEntry(
|
||||
fileName,
|
||||
fileAttributes.toInt() and 0x10 != 0,
|
||||
@@ -150,7 +213,7 @@ private fun FileIdBothDirectoryInformation.toEntry() = RemoteEntry(
|
||||
lastWriteTime.toEpochMillis(),
|
||||
)
|
||||
|
||||
private fun normalize(path: String): String {
|
||||
internal fun normalize(path: String): String {
|
||||
val parts = path.replace('/', '\\').split('\\').filter { it.isNotEmpty() && it != "." }
|
||||
require(parts.none { it == ".." }) { "Parent path segments are not allowed" }
|
||||
return parts.joinToString("\\")
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.nio.ByteBuffer
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** Small images only: avoids reading large originals just to render a list row. */
|
||||
@Composable
|
||||
fun Thumbnail(repository: BrowseRepository, shareId: String, path: String, entry: RemoteEntry) {
|
||||
if (entry.size !in 1..(8L * 1024 * 1024)) return
|
||||
val context = LocalContext.current
|
||||
var bitmap by remember(path, entry.size, entry.modifiedAt) { mutableStateOf<Bitmap?>(null) }
|
||||
LaunchedEffect(path, entry.size, entry.modifiedAt) {
|
||||
bitmap = runCatching {
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(
|
||||
"$shareId:$path:${entry.size}:${entry.modifiedAt}".toByteArray())
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
val directory = File(context.cacheDir, "thumbnails").apply { mkdirs() }
|
||||
val file = File(directory, "$digest.png")
|
||||
if (file.exists()) return@runCatching withContext(Dispatchers.IO) { BitmapFactory.decodeFile(file.path) }
|
||||
val bytes = repository.read(path, 8L * 1024 * 1024)
|
||||
val decoded = withContext(Dispatchers.Default) {
|
||||
ImageDecoder.decodeBitmap(ImageDecoder.createSource(ByteBuffer.wrap(bytes))) { decoder, info, _ ->
|
||||
val side = maxOf(info.size.width, info.size.height)
|
||||
decoder.setTargetSampleSize((side / 96).coerceAtLeast(1))
|
||||
}
|
||||
}
|
||||
withContext(Dispatchers.IO) {
|
||||
file.outputStream().use { decoded.compress(Bitmap.CompressFormat.PNG, 90, it) }
|
||||
val files = directory.listFiles().orEmpty().sortedBy { it.lastModified() }
|
||||
var total = files.sumOf { it.length() }
|
||||
for (old in files) if (total > 32L * 1024 * 1024) {
|
||||
total -= old.length()
|
||||
old.delete()
|
||||
}
|
||||
}
|
||||
decoded
|
||||
}.getOrNull()
|
||||
}
|
||||
bitmap?.let { Image(it.asImageBitmap(), contentDescription = null, modifier = Modifier.size(48.dp)) }
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
import android.net.Uri
|
||||
import android.os.CancellationSignal
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.os.storage.StorageManager
|
||||
import android.database.Cursor
|
||||
import android.provider.OpenableColumns
|
||||
import android.database.MatrixCursor
|
||||
import java.io.FileNotFoundException
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/** Grants a receiving player random reads without exposing SMB credentials in the URI. */
|
||||
class VideoStreamProvider : ContentProvider() {
|
||||
companion object {
|
||||
private const val AUTHORITY = "dev.alvin.smbexplorer.stream"
|
||||
private val grants = ConcurrentHashMap<String, Pair<SmbTarget, String>>()
|
||||
|
||||
fun grant(target: SmbTarget, path: String): Uri {
|
||||
if (grants.size >= 8) grants.clear()
|
||||
val token = UUID.randomUUID().toString()
|
||||
grants[token] = target to path
|
||||
return Uri.Builder().scheme("content").authority(AUTHORITY).appendPath(token)
|
||||
.appendPath(path.substringAfterLast('\\')).build()
|
||||
}
|
||||
|
||||
fun revoke(uri: Uri) { uri.pathSegments.firstOrNull()?.let(grants::remove) }
|
||||
}
|
||||
|
||||
private fun entry(uri: Uri) = uri.pathSegments.firstOrNull()?.let(grants::get)
|
||||
?: throw FileNotFoundException("Video grant expired")
|
||||
|
||||
override fun onCreate() = true
|
||||
override fun getType(uri: Uri): String = "video/*"
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
|
||||
selectionArgs: Array<out String>?, sortOrder: String?): Cursor {
|
||||
val (target, path) = entry(uri)
|
||||
val columns = projection?.toList() ?: listOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)
|
||||
val cursor = MatrixCursor(columns.toTypedArray())
|
||||
val size = SmbShareSession(target).use { session -> session.openRange(path).use { it.length } }
|
||||
cursor.addRow(columns.map<String, Any?> { column -> when (column) {
|
||||
OpenableColumns.DISPLAY_NAME -> path.substringAfterLast('\\')
|
||||
OpenableColumns.SIZE -> size
|
||||
else -> null
|
||||
} }.toTypedArray())
|
||||
return cursor
|
||||
}
|
||||
|
||||
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
|
||||
if (mode != "r") throw FileNotFoundException("Read only")
|
||||
val (target, path) = entry(uri)
|
||||
val session = SmbShareSession(target)
|
||||
val range = try { session.openRange(path) } catch (e: Exception) { session.close(); throw e }
|
||||
val storage = context?.getSystemService(StorageManager::class.java)
|
||||
?: throw FileNotFoundException("Storage manager unavailable")
|
||||
return try {
|
||||
storage.openProxyFileDescriptor(ParcelFileDescriptor.MODE_READ_ONLY,
|
||||
object : android.os.ProxyFileDescriptorCallback() {
|
||||
override fun onGetSize(): Long = range.length
|
||||
override fun onRead(offset: Long, size: Int, data: ByteArray): Int =
|
||||
if (offset >= range.length) 0 else range.read(data, offset, minOf(size.toLong(), range.length - offset).toInt())
|
||||
override fun onRelease() { range.close(); session.close() }
|
||||
}, null)
|
||||
} catch (e: Exception) {
|
||||
range.close(); session.close(); throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.net.Uri
|
||||
import android.content.Intent
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.app.Activity
|
||||
import android.content.pm.ActivityInfo
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.exoplayer.source.ProgressiveMediaSource
|
||||
import androidx.media3.ui.PlayerView
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
|
||||
@UnstableApi
|
||||
@Composable
|
||||
fun VideoViewer(saved: SavedShare, path: String, onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val activity = context as? Activity
|
||||
var landscape by remember { mutableStateOf(false) }
|
||||
val preferences = remember { context.getSharedPreferences("video_positions", 0) }
|
||||
val key = "${saved.id}:$path"
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
fun openExternal() {
|
||||
val uri = VideoStreamProvider.grant(saved.target, path)
|
||||
try {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(uri, "video/*")
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
})
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
VideoStreamProvider.revoke(uri)
|
||||
error = "No external video player is installed"
|
||||
}
|
||||
}
|
||||
val player = remember(saved.id, path) {
|
||||
ExoPlayer.Builder(context).build().apply {
|
||||
val source = ProgressiveMediaSource.Factory(SmbDataSource.Factory(saved.target, path))
|
||||
.createMediaSource(MediaItem.fromUri(Uri.parse("smbmedia://local/video")))
|
||||
setMediaSource(source)
|
||||
seekTo(preferences.getLong(key, 0L))
|
||||
prepare()
|
||||
playWhenReady = true
|
||||
}
|
||||
}
|
||||
DisposableEffect(player) {
|
||||
val listener = object : Player.Listener {
|
||||
override fun onPlayerError(failure: PlaybackException) {
|
||||
error = "Playback failed: ${failure.message ?: failure.errorCodeName}"
|
||||
}
|
||||
}
|
||||
player.addListener(listener)
|
||||
onDispose {
|
||||
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
|
||||
preferences.edit().putLong(key, player.currentPosition).apply()
|
||||
player.removeListener(listener)
|
||||
player.release()
|
||||
}
|
||||
}
|
||||
BackHandler(onBack = onClose)
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
TextButton(onClick = onClose) { Text("‹ Folder") }
|
||||
Text(path.substringAfterLast('\\'))
|
||||
error?.let { Text(it) }
|
||||
TextButton(onClick = ::openExternal) { Text("Open in another player") }
|
||||
TextButton(onClick = {
|
||||
landscape = !landscape
|
||||
activity?.requestedOrientation = if (landscape) ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
|
||||
else ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
|
||||
}) { Text(if (landscape) "Portrait / auto" else "Landscape") }
|
||||
AndroidView(factory = { PlayerView(it).apply { this.player = player; useController = true } },
|
||||
modifier = Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<data-extraction-rules xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<cloud-backup>
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1,38 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class CopyStreamTest {
|
||||
@Test fun copiesExactLengthAndReportsProgress() {
|
||||
val source = byteArrayOf(1, 2, 3, 4, 5)
|
||||
val output = ByteArrayOutputStream()
|
||||
val progress = mutableListOf<Long>()
|
||||
copyExact(5, output, { buffer, offset ->
|
||||
val count = minOf(2, 5 - offset.toInt())
|
||||
source.copyInto(buffer, 0, offset.toInt(), offset.toInt() + count)
|
||||
count
|
||||
}) { done, total -> assertEquals(5L, total); progress += done }
|
||||
assertArrayEquals(source, output.toByteArray())
|
||||
assertEquals(listOf(2L, 4L, 5L), progress)
|
||||
}
|
||||
|
||||
@Test fun rejectsTruncatedSource() {
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
copyExact(3, ByteArrayOutputStream(), { _, _ -> 0 }) { _, _ -> }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun cancellationFromProgressStopsFurtherReads() {
|
||||
var reads = 0
|
||||
assertThrows(InterruptedException::class.java) {
|
||||
copyExact(4, ByteArrayOutputStream(), { buffer, _ -> reads++; buffer[0] = 1; 1 }) { _, _ ->
|
||||
throw InterruptedException()
|
||||
}
|
||||
}
|
||||
assertEquals(1, reads)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class RemotePathTest {
|
||||
@Test fun normalizesMixedSeparatorsAndCurrentDirectory() {
|
||||
assertEquals("photos\\2026\\image.jpg", normalize("/photos/./2026\\image.jpg"))
|
||||
}
|
||||
|
||||
@Test fun refusesParentTraversalBeforeMutation() {
|
||||
assertThrows(IllegalArgumentException::class.java) { normalize("photos/../private") }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user