1 Commits
Author SHA1 Message Date
Alvin-Zilverstand 232765e8d4 Add SMB image and GIF viewer
Build Android APKs / build (push) Successful in 1m23s
2026-11-14 09:01:01 +01:00
4 changed files with 144 additions and 3 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ Repeat after switching Wi-Fi off and back on. Record the Samba version, dialect,
Use **Test & save** to authenticate, list the selected folder, and save the share. When shares are saved, the app opens to a compact share list. Tap a share to browse it, **Edit** to change its connection fields, or **Add share** to open the new connection form. **Remove** deletes a saved entry after confirmation. The connection list, including passwords, is encrypted with a device-bound Android Keystore key. App backup is disabled because the key cannot be restored on another device. Use **Test & save** to authenticate, list the selected folder, and save the share. When shares are saved, the app opens to a compact share list. Tap a share to browse it, **Edit** to change its connection fields, or **Add share** to open the new connection form. **Remove** deletes a saved entry after confirmation. The connection list, including passwords, is encrypted with a device-bound Android Keystore key. App backup is disabled because the key cannot be restored on another device.
Tap a saved share to browse it. Folder rows open subfolders; the breadcrumb buttons navigate to parent folders or the root. Search filters the current listing, Sort cycles through name, date, and size with folders first, Show filters by file type, and Refresh reloads the current folder. File rows currently show details; media viewing and file actions are later phases. Tap a saved share to browse it. Folder rows open subfolders; the breadcrumb buttons navigate to parent folders or the root. Search filters the current listing, Sort cycles through name, date, and size with folders first, Show filters by file type, and Refresh reloads the current folder. Tap an image to open the full-screen viewer; swipe left or right to move through images and animated GIFs in the same folder. The viewer limits downloads to 64 MB per image. Other file rows show details; video viewing and file actions are later phases.
The current environment has not supplied a NAS address or credentials, so live compatibility and reconnect results remain to be measured on the device. The current environment has not supplied a NAS address or credentials, so live compatibility and reconnect results remain to be measured on the device.
@@ -37,6 +37,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 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 val videoExtensions = setOf("mp4", "mkv", "webm", "avi", "mov", "m4v", "ts", "mpeg", "mpg")
private fun RemoteEntry.isImage() = !directory && name.substringAfterLast('.', "").lowercase() in imageExtensions
private fun FileFilter.matches(entry: RemoteEntry): Boolean { private fun FileFilter.matches(entry: RemoteEntry): Boolean {
val extension = entry.name.substringAfterLast('.', "").lowercase() val extension = entry.name.substringAfterLast('.', "").lowercase()
@@ -60,12 +61,13 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
var error by remember { mutableStateOf<String?>(null) } var error by remember { mutableStateOf<String?>(null) }
var loading by remember { mutableStateOf(true) } var loading by remember { mutableStateOf(true) }
var selectedFile by remember { mutableStateOf<RemoteEntry?>(null) } var selectedFile by remember { mutableStateOf<RemoteEntry?>(null) }
var selectedImage by remember { mutableStateOf<RemoteEntry?>(null) }
fun up() { fun up() {
path = path.substringBeforeLast('\\', "") path = path.substringBeforeLast('\\', "")
search = "" search = ""
} }
BackHandler { if (path.isEmpty()) onConnections() else up() } BackHandler(enabled = selectedImage == null) { if (path.isEmpty()) onConnections() else up() }
LaunchedEffect(saved.id, path, refresh) { LaunchedEffect(saved.id, path, refresh) {
loading = true loading = true
@@ -82,6 +84,13 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
} }
} }
selectedImage?.let { image ->
val images = result?.entries.orEmpty().filter { it.isImage() }
.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.name })
if (images.isNotEmpty()) ImageViewer(saved, path, images, image) { selectedImage = null }
return
}
selectedFile?.let { file -> selectedFile?.let { file ->
AlertDialog( AlertDialog(
onDismissRequest = { selectedFile = null }, onDismissRequest = { selectedFile = null },
@@ -140,7 +149,8 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
if (entry.directory) { if (entry.directory) {
path = if (path.isEmpty()) entry.name else "$path\\${entry.name}" path = if (path.isEmpty()) entry.name else "$path\\${entry.name}"
search = "" search = ""
} else selectedFile = entry } else if (entry.isImage()) selectedImage = entry
else selectedFile = entry
}.padding(vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { }.padding(vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Text(if (entry.directory) "📁" else "📄") Text(if (entry.directory) "📁" else "📄")
Column { Column {
@@ -0,0 +1,102 @@
package dev.alvin.smbexplorer
import android.graphics.ImageDecoder
import android.graphics.drawable.Animatable
import android.widget.ImageView
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.nio.ByteBuffer
@Composable
fun ImageViewer(saved: SavedShare, folder: String, images: List<RemoteEntry>, initial: RemoteEntry, onClose: () -> Unit) {
var index by remember(folder, initial.name) { mutableStateOf(images.indexOfFirst { it.name == initial.name }.coerceAtLeast(0)) }
val entry = images[index]
var drawable by remember { mutableStateOf<android.graphics.drawable.Drawable?>(null) }
var error by remember { mutableStateOf<String?>(null) }
var loading by remember { mutableStateOf(true) }
BackHandler(onBack = onClose)
LaunchedEffect(saved.id, folder, entry.name) {
drawable = null
error = null
loading = true
try {
val path = if (folder.isEmpty()) entry.name else "$folder\\${entry.name}"
val bytes = withContext(Dispatchers.IO) { SmbProbe().use { it.readImage(saved.target, path) } }
drawable = withContext(Dispatchers.Default) {
ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(bytes))) { decoder, info, _ ->
val largestSide = maxOf(info.size.width, info.size.height)
if (largestSide > 4096) decoder.setTargetSampleSize((largestSide + 4095) / 4096)
}
}
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
error = "Could not open image: ${e.message ?: e.javaClass.simpleName}"
} finally {
loading = false
}
}
Column(Modifier.fillMaxSize()) {
Row(Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically) {
Button(onClick = onClose) { Text("Back") }
Text("${index + 1} / ${images.size}", style = MaterialTheme.typography.titleMedium)
}
Text(entry.name, Modifier.padding(horizontal = 16.dp), style = MaterialTheme.typography.bodyMedium)
var drag by remember { mutableStateOf(0f) }
Box(Modifier.weight(1f).fillMaxWidth().pointerInput(index, images.size) {
detectHorizontalDragGestures(
onHorizontalDrag = { _, amount -> drag += amount },
onDragEnd = {
if (drag < -80 && index < images.lastIndex) index++
if (drag > 80 && index > 0) index--
drag = 0f
},
)
}, contentAlignment = Alignment.Center) {
if (loading) CircularProgressIndicator()
error?.let { Text(it, Modifier.padding(24.dp), color = MaterialTheme.colorScheme.error) }
drawable?.let { current ->
AndroidView(factory = { context -> ImageView(context).apply { scaleType = ImageView.ScaleType.FIT_CENTER } },
update = { view ->
(view.drawable as? Animatable)?.stop()
view.setImageDrawable(current)
(current as? Animatable)?.start()
}, modifier = Modifier.fillMaxSize())
DisposableEffect(current) { onDispose { (current as? Animatable)?.stop() } }
}
}
Row(Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween) {
Button(enabled = index > 0, onClick = { index-- }) { Text("Previous") }
Button(enabled = index < images.lastIndex, onClick = { index++ }) { Text("Next") }
}
}
}
@@ -14,6 +14,7 @@ import com.hierynomus.mssmb2.SMB2CreateOptions
import java.io.Closeable import java.io.Closeable
import java.security.MessageDigest import java.security.MessageDigest
import java.util.EnumSet import java.util.EnumSet
import java.io.ByteArrayOutputStream
data class SmbTarget( data class SmbTarget(
val host: String, val host: String,
@@ -68,6 +69,34 @@ class SmbProbe : Closeable {
} }
} }
fun readImage(target: SmbTarget, path: String, maxBytes: Long = 64L * 1024 * 1024): ByteArray {
val connection = client.connect(target.host.trim(), target.port)
try {
val session = connection.authenticate(AuthenticationContext(target.username, target.password.toCharArray(), target.domain))
try {
val share = session.connectShare(target.share.trim()) as DiskShare
try {
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 {
require(file.length in 0..maxBytes) { "Image exceeds the 64 MB viewer limit" }
val output = ByteArrayOutputStream()
val buffer = ByteArray(64 * 1024)
var offset = 0L
while (offset < file.length) {
val count = file.read(buffer, offset)
require(count > 0) { "Image ended before all bytes were read" }
output.write(buffer, 0, count)
offset += count
}
return output.toByteArray()
} finally { file.close() }
} finally { share.close() }
} finally { session.close() }
} finally { connection.close() }
}
private fun readRanges(share: DiskShare, path: String): List<RangeResult> { private fun readRanges(share: DiskShare, path: String): List<RangeResult> {
val file: File = share.openFile( val file: File = share.openFile(
path, path,