Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07bc29bea4 | ||
|
|
5ce400e867 | ||
|
|
232765e8d4 |
No files matched your search
@@ -10,7 +10,9 @@ 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 share list opens without waiting for credential decryption on the UI thread. While browsing, the app reuses the SMB connection and keeps up to 20 recent folder listings in memory so returning to a folder shows its files immediately while the listing refreshes. Search and sorting run off the UI thread. Image viewing uses a separate persistent connection, a 24 MB in-memory read cache, and prefetches the next image.
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package dev.alvin.smbexplorer
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
/** Reuses one authenticated share while browsing and retains recent folder listings. */
|
||||||
|
class BrowseRepository(private val target: SmbTarget) {
|
||||||
|
private val mutex = Mutex()
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
private var session: SmbShareSession? = null
|
||||||
|
private val cache = LinkedHashMap<String, ProbeResult>(20, .75f, true)
|
||||||
|
|
||||||
|
fun cached(path: String): ProbeResult? = synchronized(cache) { cache[path] }
|
||||||
|
|
||||||
|
suspend fun list(path: String): ProbeResult = withContext(Dispatchers.IO) {
|
||||||
|
mutex.withLock {
|
||||||
|
val listing = (session ?: SmbShareSession(target).also { session = it }).list(path)
|
||||||
|
synchronized(cache) {
|
||||||
|
cache[path] = listing
|
||||||
|
if (cache.size > 20) cache.remove(cache.keys.first())
|
||||||
|
}
|
||||||
|
listing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close() {
|
||||||
|
scope.launch {
|
||||||
|
mutex.withLock { session?.close(); session = null }
|
||||||
|
scope.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,23 +8,32 @@ import androidx.compose.foundation.layout.Column
|
|||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.Button
|
import androidx.compose.material3.Button
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
|
import androidx.compose.material3.FilterChip
|
||||||
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableIntStateOf
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
@@ -37,6 +46,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()
|
||||||
@@ -51,6 +61,8 @@ private fun FileFilter.matches(entry: RemoteEntry): Boolean {
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||||
|
val repository = remember(saved.id) { BrowseRepository(saved.target) }
|
||||||
|
DisposableEffect(repository) { onDispose { repository.close() } }
|
||||||
var path by remember(saved.id) { mutableStateOf(saved.folder.trim('/', '\\').replace('/', '\\')) }
|
var path by remember(saved.id) { mutableStateOf(saved.folder.trim('/', '\\').replace('/', '\\')) }
|
||||||
var refresh by remember { mutableIntStateOf(0) }
|
var refresh by remember { mutableIntStateOf(0) }
|
||||||
var search by remember { mutableStateOf("") }
|
var search by remember { mutableStateOf("") }
|
||||||
@@ -60,19 +72,22 @@ 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) }
|
||||||
|
var sortOpen by remember { mutableStateOf(false) }
|
||||||
|
var visible by remember { mutableStateOf(emptyList<RemoteEntry>()) }
|
||||||
|
|
||||||
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
|
||||||
error = null
|
error = null
|
||||||
result = null
|
result = repository.cached(path)
|
||||||
try {
|
try {
|
||||||
result = withContext(Dispatchers.IO) { SmbProbe().use { it.run(saved.target, path, null) } }
|
result = repository.list(path)
|
||||||
} catch (e: CancellationException) {
|
} catch (e: CancellationException) {
|
||||||
throw e
|
throw e
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -82,6 +97,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 },
|
||||||
@@ -91,62 +113,79 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
val visible = remember(result, search, sort, filter) { result?.entries.orEmpty()
|
LaunchedEffect(result, search, sort, filter) {
|
||||||
.asSequence()
|
val entries = result?.entries.orEmpty()
|
||||||
.filter { it.name.contains(search, ignoreCase = true) }
|
visible = withContext(Dispatchers.Default) {
|
||||||
.filter { filter.matches(it) }
|
entries.asSequence()
|
||||||
.sortedWith(compareByDescending<RemoteEntry> { it.directory }.then(
|
.filter { it.name.contains(search, ignoreCase = true) }
|
||||||
when (sort) {
|
.filter { filter.matches(it) }
|
||||||
SortMode.Name -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.name }
|
.sortedWith(compareByDescending<RemoteEntry> { it.directory }.then(
|
||||||
SortMode.Date -> compareByDescending { it.modifiedAt }
|
when (sort) {
|
||||||
SortMode.Size -> compareByDescending { it.size }
|
SortMode.Name -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.name }
|
||||||
},
|
SortMode.Date -> compareByDescending { it.modifiedAt }
|
||||||
))
|
SortMode.Size -> compareByDescending { it.size }
|
||||||
.toList()
|
},
|
||||||
|
))
|
||||||
|
.toList()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
Text(saved.target.share, style = MaterialTheme.typography.headlineSmall)
|
TextButton(onClick = { if (path.isEmpty()) onConnections() else up() }) { Text("‹ Back") }
|
||||||
Button(onClick = onConnections) { Text("Connections") }
|
Column(Modifier.weight(1f)) {
|
||||||
|
Text(if (path.isEmpty()) saved.target.share else path.substringAfterLast('\\'), style = MaterialTheme.typography.titleLarge)
|
||||||
|
Text(saved.target.host, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
TextButton(onClick = { refresh++ }) { Text("Refresh") }
|
||||||
}
|
}
|
||||||
Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
if (path.isNotEmpty()) Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
Button(onClick = { path = ""; search = "" }) { Text("Root") }
|
TextButton(onClick = { path = ""; search = "" }) { Text(saved.target.share) }
|
||||||
var prefix = ""
|
var prefix = ""
|
||||||
path.split('\\').filter(String::isNotEmpty).forEach { segment ->
|
path.split('\\').filter(String::isNotEmpty).forEach { segment ->
|
||||||
prefix = if (prefix.isEmpty()) segment else "$prefix\\$segment"
|
prefix = if (prefix.isEmpty()) segment else "$prefix\\$segment"
|
||||||
val destination = prefix
|
val destination = prefix
|
||||||
Button(onClick = { path = destination; search = "" }) { Text(segment) }
|
TextButton(onClick = { path = destination; search = "" }) { Text("› $segment") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
OutlinedTextField(search, { search = it }, label = { Text("Search files") }, singleLine = true, modifier = Modifier.fillMaxWidth())
|
||||||
OutlinedTextField(search, { search = it }, label = { Text("Search this folder") }, modifier = Modifier.weight(1f))
|
Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
Button(onClick = { refresh++ }) { Text("Refresh") }
|
FileFilter.entries.forEach { option ->
|
||||||
}
|
FilterChip(selected = filter == option, onClick = { filter = option }, label = { Text(option.name) })
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
}
|
||||||
Button(onClick = { sort = SortMode.entries[(sort.ordinal + 1) % SortMode.entries.size] }) {
|
}
|
||||||
Text("Sort: ${sort.name}")
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||||
}
|
Text(if (loading && result == null) "Opening folder…" else "${visible.size} items", style = MaterialTheme.typography.bodySmall,
|
||||||
Button(onClick = { filter = FileFilter.entries[(filter.ordinal + 1) % FileFilter.entries.size] }) {
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
Text("Show: ${filter.name}")
|
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
if (loading && result != null) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp)
|
||||||
|
TextButton(onClick = { sortOpen = true }) { Text("Sort: ${sort.name} ▾") }
|
||||||
|
DropdownMenu(expanded = sortOpen, onDismissRequest = { sortOpen = false }) {
|
||||||
|
SortMode.entries.forEach { option ->
|
||||||
|
DropdownMenuItem(text = { Text(option.name) }, onClick = { sort = option; sortOpen = false })
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (loading) Text("Loading…")
|
|
||||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||||
result?.let { Text("${visible.size} of ${it.entries.size} entries · ${it.listingMs} ms") }
|
LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
LazyColumn {
|
|
||||||
items(visible, key = { "$path/${it.name}" }) { entry ->
|
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().clickable {
|
||||||
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
|
||||||
}.padding(vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
else selectedFile = entry
|
||||||
Text(if (entry.directory) "📁" else "📄")
|
}.padding(horizontal = 14.dp, vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
Column {
|
Text(if (entry.directory) "▣" else if (entry.isImage()) "▧" else "▤", color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.titleLarge)
|
||||||
Text(entry.name)
|
Column(Modifier.weight(1f)) {
|
||||||
if (!entry.directory) Text("${entry.size} B · ${formatDate(entry.modifiedAt)}", style = MaterialTheme.typography.bodySmall)
|
Text(entry.name, style = MaterialTheme.typography.bodyLarge)
|
||||||
|
if (!entry.directory) Text("${formatSize(entry.size)} · ${formatDate(entry.modifiedAt)}", style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
|
Text("›", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -154,3 +193,8 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun formatDate(timestamp: Long): String = if (timestamp <= 0) "Unknown" else DateFormat.getDateTimeInstance().format(Date(timestamp))
|
private fun formatDate(timestamp: Long): String = if (timestamp <= 0) "Unknown" else DateFormat.getDateTimeInstance().format(Date(timestamp))
|
||||||
|
private fun formatSize(bytes: Long): String = when {
|
||||||
|
bytes >= 1_048_576 -> "%.1f MB".format(bytes / 1_048_576.0)
|
||||||
|
bytes >= 1024 -> "%.1f KB".format(bytes / 1024.0)
|
||||||
|
else -> "$bytes B"
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
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.TextButton
|
||||||
|
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.CoroutineScope
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ImageViewer(saved: SavedShare, folder: String, images: List<RemoteEntry>, initial: RemoteEntry, onClose: () -> Unit) {
|
||||||
|
val loader = remember(saved.id, folder) { ImageLoader(saved.target, folder) }
|
||||||
|
DisposableEffect(loader) { onDispose { loader.close() } }
|
||||||
|
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 bytes = loader.load(entry.name)
|
||||||
|
images.getOrNull(index + 1)?.let { loader.prefetch(it.name) }
|
||||||
|
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) {
|
||||||
|
TextButton(onClick = onClose) { Text("‹ Folder") }
|
||||||
|
Text("${index + 1} / ${images.size}", style = MaterialTheme.typography.titleMedium)
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
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) {
|
||||||
|
TextButton(enabled = index > 0, onClick = { index-- }) { Text("‹ Previous") }
|
||||||
|
TextButton(enabled = index < images.lastIndex, onClick = { index++ }) { Text("Next ›") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class ImageLoader(private val target: SmbTarget, private val folder: String) {
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||||
|
private val mutex = Mutex()
|
||||||
|
private var session: SmbShareSession? = null
|
||||||
|
private val cache = LinkedHashMap<String, ByteArray>(4, .75f, true)
|
||||||
|
private var cacheBytes = 0L
|
||||||
|
|
||||||
|
suspend fun load(name: String): ByteArray = withContext(Dispatchers.IO) {
|
||||||
|
mutex.withLock {
|
||||||
|
cache[name]?.let { return@withLock it }
|
||||||
|
val path = if (folder.isEmpty()) name else "$folder\\$name"
|
||||||
|
val bytes = (session ?: SmbShareSession(target).also { session = it }).read(path)
|
||||||
|
if (bytes.size <= 24 * 1024 * 1024) {
|
||||||
|
while (cacheBytes + bytes.size > 24L * 1024 * 1024) {
|
||||||
|
val oldest = cache.entries.first()
|
||||||
|
cacheBytes -= oldest.value.size
|
||||||
|
cache.remove(oldest.key)
|
||||||
|
}
|
||||||
|
cache[name] = bytes
|
||||||
|
cacheBytes += bytes.size
|
||||||
|
}
|
||||||
|
bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun prefetch(name: String) {
|
||||||
|
scope.launch { runCatching { load(name) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close() {
|
||||||
|
scope.launch {
|
||||||
|
mutex.withLock { session?.close(); session = null; cache.clear() }
|
||||||
|
scope.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.Row
|
|||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
@@ -16,17 +17,20 @@ import androidx.compose.material3.Button
|
|||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.darkColorScheme
|
import androidx.compose.material3.darkColorScheme
|
||||||
import androidx.compose.material3.OutlinedTextField
|
import androidx.compose.material3.OutlinedTextField
|
||||||
import androidx.compose.material3.OutlinedButton
|
|
||||||
import androidx.compose.material3.Surface
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.material3.DropdownMenu
|
||||||
|
import androidx.compose.material3.DropdownMenuItem
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.rememberCoroutineScope
|
import androidx.compose.runtime.rememberCoroutineScope
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
@@ -45,9 +49,9 @@ class MainActivity : ComponentActivity() {
|
|||||||
private fun ProbeScreen() {
|
private fun ProbeScreen() {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val store = remember { SavedShareStore(context) }
|
val store = remember { SavedShareStore(context) }
|
||||||
val initialShares = remember { runCatching { store.load() } }
|
var savedShares by remember { mutableStateOf(emptyList<SavedShare>()) }
|
||||||
var savedShares by remember { mutableStateOf(initialShares.getOrDefault(emptyList())) }
|
var loadingShares by remember { mutableStateOf(true) }
|
||||||
var showConnectionForm by remember { mutableStateOf(savedShares.isEmpty()) }
|
var showConnectionForm by remember { mutableStateOf(false) }
|
||||||
var selectedId by remember { mutableStateOf<String?>(null) }
|
var selectedId by remember { mutableStateOf<String?>(null) }
|
||||||
var pendingDelete by remember { mutableStateOf<SavedShare?>(null) }
|
var pendingDelete by remember { mutableStateOf<SavedShare?>(null) }
|
||||||
var browsing by remember { mutableStateOf<SavedShare?>(null) }
|
var browsing by remember { mutableStateOf<SavedShare?>(null) }
|
||||||
@@ -59,12 +63,22 @@ private fun ProbeScreen() {
|
|||||||
var domain by remember { mutableStateOf("") }
|
var domain by remember { mutableStateOf("") }
|
||||||
var folder by remember { mutableStateOf("") }
|
var folder by remember { mutableStateOf("") }
|
||||||
var sample by remember { mutableStateOf("") }
|
var sample by remember { mutableStateOf("") }
|
||||||
var status by remember { mutableStateOf(initialShares.exceptionOrNull()?.let { "Could not read saved shares: ${it.javaClass.simpleName}" } ?: "Enter a share and run the compatibility probe.") }
|
var status by remember { mutableStateOf("") }
|
||||||
var entries by remember { mutableStateOf(emptyList<RemoteEntry>()) }
|
var entries by remember { mutableStateOf(emptyList<RemoteEntry>()) }
|
||||||
var running by remember { mutableStateOf(false) }
|
var running by remember { mutableStateOf(false) }
|
||||||
|
var showAdvanced by remember { mutableStateOf(false) }
|
||||||
|
var shareMenuId by remember { mutableStateOf<String?>(null) }
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val valid = host.isNotBlank() && share.isNotBlank() && (port.toIntOrNull()?.let { it in 1..65535 } == true)
|
val valid = host.isNotBlank() && share.isNotBlank() && (port.toIntOrNull()?.let { it in 1..65535 } == true)
|
||||||
|
|
||||||
|
LaunchedEffect(store) {
|
||||||
|
val loaded = withContext(Dispatchers.IO) { runCatching { store.load() } }
|
||||||
|
savedShares = loaded.getOrDefault(emptyList())
|
||||||
|
showConnectionForm = savedShares.isEmpty()
|
||||||
|
status = loaded.exceptionOrNull()?.let { "Could not read saved shares: ${it.javaClass.simpleName}" } ?: ""
|
||||||
|
loadingShares = false
|
||||||
|
}
|
||||||
|
|
||||||
fun loadConnection(item: SavedShare) {
|
fun loadConnection(item: SavedShare) {
|
||||||
selectedId = item.id
|
selectedId = item.id
|
||||||
host = item.target.host
|
host = item.target.host
|
||||||
@@ -85,6 +99,7 @@ private fun ProbeScreen() {
|
|||||||
entries = emptyList()
|
entries = emptyList()
|
||||||
status = "Enter a new share."
|
status = "Enter a new share."
|
||||||
showConnectionForm = true
|
showConnectionForm = true
|
||||||
|
showAdvanced = false
|
||||||
}
|
}
|
||||||
|
|
||||||
fun runProbe(saveOnSuccess: Boolean) {
|
fun runProbe(saveOnSuccess: Boolean) {
|
||||||
@@ -129,39 +144,60 @@ private fun ProbeScreen() {
|
|||||||
title = { Text("Remove saved share?") },
|
title = { Text("Remove saved share?") },
|
||||||
text = { Text("${item.target.host}/${item.target.share} will be removed from this device.") },
|
text = { Text("${item.target.host}/${item.target.share} will be removed from this device.") },
|
||||||
confirmButton = { Button(onClick = {
|
confirmButton = { Button(onClick = {
|
||||||
try {
|
|
||||||
store.delete(item.id)
|
|
||||||
savedShares = store.load()
|
|
||||||
if (selectedId == item.id) selectedId = null
|
|
||||||
if (savedShares.isEmpty()) showConnectionForm = true
|
|
||||||
status = "Saved share removed."
|
|
||||||
} catch (e: Exception) {
|
|
||||||
status = "Could not remove share: ${e.javaClass.simpleName}"
|
|
||||||
}
|
|
||||||
pendingDelete = null
|
pendingDelete = null
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
savedShares = withContext(Dispatchers.IO) { store.delete(item.id); store.load() }
|
||||||
|
if (selectedId == item.id) selectedId = null
|
||||||
|
if (savedShares.isEmpty()) showConnectionForm = true
|
||||||
|
status = "Saved share removed."
|
||||||
|
} catch (e: Exception) {
|
||||||
|
status = "Could not remove share: ${e.javaClass.simpleName}"
|
||||||
|
}
|
||||||
|
}
|
||||||
}) { Text("Remove") } },
|
}) { Text("Remove") } },
|
||||||
dismissButton = { Button(onClick = { pendingDelete = null }) { Text("Cancel") } },
|
dismissButton = { Button(onClick = { pendingDelete = null }) { Text("Cancel") } },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
LazyColumn(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
LazyColumn(Modifier.fillMaxSize().padding(horizontal = 18.dp, vertical = 20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||||
item { Text("SMB Explorer", style = MaterialTheme.typography.headlineMedium) }
|
item {
|
||||||
item { Text("Your shares", style = MaterialTheme.typography.titleLarge) }
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||||
if (savedShares.isEmpty()) item { Text("No shares saved yet.") }
|
Column {
|
||||||
items(savedShares, key = { "saved:${it.id}" }) { item ->
|
Text("SMB Explorer", style = MaterialTheme.typography.headlineMedium)
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
Text("Your network shares", style = MaterialTheme.typography.bodyMedium,
|
||||||
Button(onClick = {
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
loadConnection(item)
|
}
|
||||||
browsing = item
|
if (savedShares.isNotEmpty() && !showConnectionForm) TextButton(onClick = { newConnection() }) { Text("+ Add") }
|
||||||
}, modifier = Modifier.weight(1f)) { Text("${item.target.host}/${item.target.share}") }
|
}
|
||||||
TextButton(onClick = { loadConnection(item); showConnectionForm = true }) { Text("Edit") }
|
}
|
||||||
TextButton(onClick = { pendingDelete = item }) { Text("Remove") }
|
if (loadingShares) item { Text("Loading shares…") }
|
||||||
|
if (savedShares.isEmpty() && !showConnectionForm && !loadingShares) item { Text("Add a share to start browsing.") }
|
||||||
|
items(savedShares, key = { "saved:${it.id}" }) { item ->
|
||||||
|
Surface(color = MaterialTheme.colorScheme.surfaceContainerLow, shape = MaterialTheme.shapes.large) {
|
||||||
|
Row(Modifier.fillMaxWidth().padding(start = 18.dp, end = 8.dp, top = 10.dp, bottom = 10.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("▣", style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.primary)
|
||||||
|
Column(Modifier.weight(1f).clickable { loadConnection(item); browsing = item }
|
||||||
|
.padding(start = 16.dp, top = 8.dp, bottom = 8.dp)) {
|
||||||
|
Text(item.target.share, style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text(item.target.host, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
style = MaterialTheme.typography.bodySmall)
|
||||||
|
}
|
||||||
|
TextButton(onClick = { shareMenuId = item.id }) { Text("⋮") }
|
||||||
|
DropdownMenu(expanded = shareMenuId == item.id, onDismissRequest = { shareMenuId = null }) {
|
||||||
|
DropdownMenuItem(text = { Text("Edit connection") }, onClick = {
|
||||||
|
shareMenuId = null; loadConnection(item); showConnectionForm = true
|
||||||
|
})
|
||||||
|
DropdownMenuItem(text = { Text("Remove connection") }, onClick = {
|
||||||
|
shareMenuId = null; pendingDelete = item
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!showConnectionForm) item { OutlinedButton(onClick = { newConnection() }) { Text("Add share") } }
|
|
||||||
if (showConnectionForm) {
|
if (showConnectionForm) {
|
||||||
item { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
item { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||||
Text(if (selectedId == null) "Add share" else "Edit share", style = MaterialTheme.typography.titleLarge)
|
Text(if (selectedId == null) "New connection" else "Edit connection", style = MaterialTheme.typography.titleLarge)
|
||||||
if (savedShares.isNotEmpty()) TextButton(onClick = { showConnectionForm = false }) { Text("Cancel") }
|
if (savedShares.isNotEmpty()) TextButton(onClick = { showConnectionForm = false }) { Text("Cancel") }
|
||||||
} }
|
} }
|
||||||
item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
@@ -175,12 +211,15 @@ private fun ProbeScreen() {
|
|||||||
} }
|
} }
|
||||||
item { OutlinedTextField(password, { password = it }, label = { Text("Password") }, visualTransformation = PasswordVisualTransformation(), modifier = Modifier.fillMaxWidth()) }
|
item { OutlinedTextField(password, { password = it }, label = { Text("Password") }, visualTransformation = PasswordVisualTransformation(), modifier = Modifier.fillMaxWidth()) }
|
||||||
item { OutlinedTextField(folder, { folder = it }, label = { Text("Folder path (optional)") }, modifier = Modifier.fillMaxWidth()) }
|
item { OutlinedTextField(folder, { folder = it }, label = { Text("Folder path (optional)") }, modifier = Modifier.fillMaxWidth()) }
|
||||||
item { OutlinedTextField(sample, { sample = it }, label = { Text("Large file path for range reads (optional)") }, modifier = Modifier.fillMaxWidth()) }
|
item { Button(enabled = !running && valid, onClick = { runProbe(true) }, modifier = Modifier.fillMaxWidth()) {
|
||||||
item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
Text(if (running) "Connecting…" else "Test & save connection")
|
||||||
Button(enabled = !running && valid, onClick = { runProbe(true) }) { Text(if (running) "Running…" else "Test & save") }
|
|
||||||
Button(enabled = !running && valid, onClick = { runProbe(false) }) { Text("Run probe") }
|
|
||||||
} }
|
} }
|
||||||
item { Text(status) }
|
item { TextButton(onClick = { showAdvanced = !showAdvanced }) { Text(if (showAdvanced) "Hide connection test" else "Advanced connection test") } }
|
||||||
|
if (showAdvanced) {
|
||||||
|
item { OutlinedTextField(sample, { sample = it }, label = { Text("File path for range reads") }, modifier = Modifier.fillMaxWidth()) }
|
||||||
|
item { Button(enabled = !running && valid, onClick = { runProbe(false) }) { Text("Run probe") } }
|
||||||
|
}
|
||||||
|
item { Text(status, color = MaterialTheme.colorScheme.onSurfaceVariant) }
|
||||||
items(entries, key = { "entry:${it.name}" }) { entry ->
|
items(entries, key = { "entry:${it.name}" }) { entry ->
|
||||||
Text("${if (entry.directory) "📁" else "📄"} ${entry.name} ${if (entry.directory) "" else "(${entry.size} B)"}")
|
Text("${if (entry.directory) "📁" else "📄"} ${entry.name} ${if (entry.directory) "" else "(${entry.size} B)"}")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ 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
|
||||||
|
import com.hierynomus.smbj.connection.Connection
|
||||||
|
import com.hierynomus.smbj.session.Session
|
||||||
|
|
||||||
data class SmbTarget(
|
data class SmbTarget(
|
||||||
val host: String,
|
val host: String,
|
||||||
@@ -94,6 +97,49 @@ class SmbProbe : Closeable {
|
|||||||
override fun close() = client.close()
|
override fun close() = client.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 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
|
||||||
|
|
||||||
|
fun list(folder: String): ProbeResult {
|
||||||
|
val start = System.nanoTime()
|
||||||
|
val entries = share.list(normalize(folder))
|
||||||
|
.filter { it.fileName != "." && it.fileName != ".." }
|
||||||
|
.map { it.toEntry() }
|
||||||
|
return ProbeResult(entries, (System.nanoTime() - start) / 1_000_000, emptyList())
|
||||||
|
}
|
||||||
|
|
||||||
|
fun read(path: String, maxBytes: Long = 64L * 1024 * 1024): ByteArray {
|
||||||
|
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(file.length.toInt())
|
||||||
|
val buffer = ByteArray(256 * 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() }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
share.close()
|
||||||
|
session.close()
|
||||||
|
connection.close()
|
||||||
|
client.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun FileIdBothDirectoryInformation.toEntry() = RemoteEntry(
|
private fun FileIdBothDirectoryInformation.toEntry() = RemoteEntry(
|
||||||
fileName,
|
fileName,
|
||||||
fileAttributes.toInt() and 0x10 != 0,
|
fileAttributes.toInt() and 0x10 != 0,
|
||||||
|
|||||||
Reference in new issue
Block a user