Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d6e59c285 | ||
|
|
07bc29bea4 | ||
|
|
5ce400e867 |
No files matched your search
@@ -12,6 +12,8 @@ Use **Test & save** to authenticate, list the selected folder, and save the shar
|
|||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
Implementation plan: [PLAN.md](PLAN.md).
|
Implementation plan: [PLAN.md](PLAN.md).
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -52,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("") }
|
||||||
@@ -62,6 +73,8 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
|||||||
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 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('\\', "")
|
||||||
@@ -72,9 +85,9 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
|||||||
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) {
|
||||||
@@ -100,8 +113,10 @@ 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()
|
||||||
|
visible = withContext(Dispatchers.Default) {
|
||||||
|
entries.asSequence()
|
||||||
.filter { it.name.contains(search, ignoreCase = true) }
|
.filter { it.name.contains(search, ignoreCase = true) }
|
||||||
.filter { filter.matches(it) }
|
.filter { filter.matches(it) }
|
||||||
.sortedWith(compareByDescending<RemoteEntry> { it.directory }.then(
|
.sortedWith(compareByDescending<RemoteEntry> { it.directory }.then(
|
||||||
@@ -113,49 +128,63 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
|||||||
))
|
))
|
||||||
.toList()
|
.toList()
|
||||||
}
|
}
|
||||||
|
|
||||||
Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
|
|
||||||
Text(saved.target.share, style = MaterialTheme.typography.headlineSmall)
|
|
||||||
Button(onClick = onConnections) { Text("Connections") }
|
|
||||||
}
|
}
|
||||||
Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
|
||||||
Button(onClick = { path = ""; search = "" }) { Text("Root") }
|
Column(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
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(saved.target.host, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
TextButton(onClick = { refresh++ }) { Text("Refresh") }
|
||||||
|
}
|
||||||
|
if (path.isNotEmpty()) Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
|
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") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
OutlinedTextField(search, { search = it }, label = { Text("Search files") }, singleLine = true, modifier = Modifier.fillMaxWidth())
|
||||||
|
Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
FileFilter.entries.forEach { option ->
|
||||||
|
FilterChip(selected = filter == option, onClick = { filter = option }, label = { Text(option.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,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
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 })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
||||||
OutlinedTextField(search, { search = it }, label = { Text("Search this folder") }, modifier = Modifier.weight(1f))
|
|
||||||
Button(onClick = { refresh++ }) { Text("Refresh") }
|
|
||||||
}
|
|
||||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
|
||||||
Button(onClick = { sort = SortMode.entries[(sort.ordinal + 1) % SortMode.entries.size] }) {
|
|
||||||
Text("Sort: ${sort.name}")
|
|
||||||
}
|
|
||||||
Button(onClick = { filter = FileFilter.entries[(filter.ordinal + 1) % FileFilter.entries.size] }) {
|
|
||||||
Text("Show: ${filter.name}")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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 if (entry.isImage()) selectedImage = entry
|
} else if (entry.isImage()) selectedImage = entry
|
||||||
else selectedFile = entry
|
else selectedFile = entry
|
||||||
}.padding(vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
|
}.padding(horizontal = 14.dp, vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
Text(if (entry.directory) "📁" else "📄")
|
Text(if (entry.directory) "▣" else if (entry.isImage()) "▧" else "▤", color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.titleLarge)
|
||||||
Column {
|
Column(Modifier.weight(1f)) {
|
||||||
Text(entry.name)
|
Text(entry.name, style = MaterialTheme.typography.bodyLarge)
|
||||||
if (!entry.directory) Text("${entry.size} B · ${formatDate(entry.modifiedAt)}", style = MaterialTheme.typography.bodySmall)
|
if (!entry.directory) Text("${formatSize(entry.size)} · ${formatDate(entry.modifiedAt)}", style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
Text("›", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -164,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"
|
||||||
|
}
|
||||||
@@ -12,7 +12,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.material3.Button
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
import androidx.compose.material3.MaterialTheme
|
import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
@@ -30,11 +30,19 @@ import androidx.compose.ui.unit.dp
|
|||||||
import androidx.compose.ui.viewinterop.AndroidView
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
import kotlinx.coroutines.CancellationException
|
import kotlinx.coroutines.CancellationException
|
||||||
import kotlinx.coroutines.Dispatchers
|
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.withContext
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
import java.nio.ByteBuffer
|
import java.nio.ByteBuffer
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun ImageViewer(saved: SavedShare, folder: String, images: List<RemoteEntry>, initial: RemoteEntry, onClose: () -> Unit) {
|
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)) }
|
var index by remember(folder, initial.name) { mutableStateOf(images.indexOfFirst { it.name == initial.name }.coerceAtLeast(0)) }
|
||||||
val entry = images[index]
|
val entry = images[index]
|
||||||
var drawable by remember { mutableStateOf<android.graphics.drawable.Drawable?>(null) }
|
var drawable by remember { mutableStateOf<android.graphics.drawable.Drawable?>(null) }
|
||||||
@@ -47,8 +55,8 @@ fun ImageViewer(saved: SavedShare, folder: String, images: List<RemoteEntry>, in
|
|||||||
error = null
|
error = null
|
||||||
loading = true
|
loading = true
|
||||||
try {
|
try {
|
||||||
val path = if (folder.isEmpty()) entry.name else "$folder\\${entry.name}"
|
val bytes = loader.load(entry.name)
|
||||||
val bytes = withContext(Dispatchers.IO) { SmbProbe().use { it.readImage(saved.target, path) } }
|
images.getOrNull(index + 1)?.let { loader.prefetch(it.name) }
|
||||||
drawable = withContext(Dispatchers.Default) {
|
drawable = withContext(Dispatchers.Default) {
|
||||||
ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(bytes))) { decoder, info, _ ->
|
ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(bytes))) { decoder, info, _ ->
|
||||||
val largestSide = maxOf(info.size.width, info.size.height)
|
val largestSide = maxOf(info.size.width, info.size.height)
|
||||||
@@ -67,10 +75,10 @@ fun ImageViewer(saved: SavedShare, folder: String, images: List<RemoteEntry>, in
|
|||||||
Column(Modifier.fillMaxSize()) {
|
Column(Modifier.fillMaxSize()) {
|
||||||
Row(Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween,
|
Row(Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
verticalAlignment = Alignment.CenterVertically) {
|
verticalAlignment = Alignment.CenterVertically) {
|
||||||
Button(onClick = onClose) { Text("Back") }
|
TextButton(onClick = onClose) { Text("‹ Folder") }
|
||||||
Text("${index + 1} / ${images.size}", style = MaterialTheme.typography.titleMedium)
|
Text("${index + 1} / ${images.size}", style = MaterialTheme.typography.titleMedium)
|
||||||
}
|
}
|
||||||
Text(entry.name, Modifier.padding(horizontal = 16.dp), style = MaterialTheme.typography.bodyMedium)
|
Text(entry.name, Modifier.padding(horizontal = 16.dp), style = MaterialTheme.typography.bodyMedium, maxLines = 1)
|
||||||
var drag by remember { mutableStateOf(0f) }
|
var drag by remember { mutableStateOf(0f) }
|
||||||
Box(Modifier.weight(1f).fillMaxWidth().pointerInput(index, images.size) {
|
Box(Modifier.weight(1f).fillMaxWidth().pointerInput(index, images.size) {
|
||||||
detectHorizontalDragGestures(
|
detectHorizontalDragGestures(
|
||||||
@@ -95,8 +103,45 @@ fun ImageViewer(saved: SavedShare, folder: String, images: List<RemoteEntry>, in
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Row(Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween) {
|
Row(Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||||
Button(enabled = index > 0, onClick = { index-- }) { Text("Previous") }
|
TextButton(enabled = index > 0, onClick = { index-- }) { Text("‹ Previous") }
|
||||||
Button(enabled = index < images.lastIndex, onClick = { index++ }) { Text("Next") }
|
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,8 @@ 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.layout.safeDrawingPadding
|
||||||
|
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 +18,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
|
||||||
@@ -37,7 +42,9 @@ import kotlinx.coroutines.withContext
|
|||||||
class MainActivity : ComponentActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
setContent { MaterialTheme(colorScheme = darkColorScheme()) { Surface { ProbeScreen() } } }
|
setContent { MaterialTheme(colorScheme = darkColorScheme()) {
|
||||||
|
Surface(Modifier.fillMaxSize().safeDrawingPadding()) { ProbeScreen() }
|
||||||
|
} }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,9 +52,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 +66,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 +102,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 +147,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 = {
|
||||||
|
pendingDelete = null
|
||||||
|
scope.launch {
|
||||||
try {
|
try {
|
||||||
store.delete(item.id)
|
savedShares = withContext(Dispatchers.IO) { store.delete(item.id); store.load() }
|
||||||
savedShares = store.load()
|
|
||||||
if (selectedId == item.id) selectedId = null
|
if (selectedId == item.id) selectedId = null
|
||||||
if (savedShares.isEmpty()) showConnectionForm = true
|
if (savedShares.isEmpty()) showConnectionForm = true
|
||||||
status = "Saved share removed."
|
status = "Saved share removed."
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
status = "Could not remove share: ${e.javaClass.simpleName}"
|
status = "Could not remove share: ${e.javaClass.simpleName}"
|
||||||
}
|
}
|
||||||
pendingDelete = null
|
}
|
||||||
}) { 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 {
|
||||||
|
Text("SMB Explorer", style = MaterialTheme.typography.headlineMedium)
|
||||||
|
Text("Your network shares", style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
if (savedShares.isNotEmpty() && !showConnectionForm) TextButton(onClick = { newConnection() }) { Text("+ Add") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 ->
|
items(savedShares, key = { "saved:${it.id}" }) { item ->
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
Surface(color = MaterialTheme.colorScheme.surfaceContainerLow, shape = MaterialTheme.shapes.large) {
|
||||||
Button(onClick = {
|
Row(Modifier.fillMaxWidth().padding(start = 18.dp, end = 8.dp, top = 10.dp, bottom = 10.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||||
loadConnection(item)
|
Text("▣", style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.primary)
|
||||||
browsing = item
|
Column(Modifier.weight(1f).clickable { loadConnection(item); browsing = item }
|
||||||
}, modifier = Modifier.weight(1f)) { Text("${item.target.host}/${item.target.share}") }
|
.padding(start = 16.dp, top = 8.dp, bottom = 8.dp)) {
|
||||||
TextButton(onClick = { loadConnection(item); showConnectionForm = true }) { Text("Edit") }
|
Text(item.target.share, style = MaterialTheme.typography.titleMedium)
|
||||||
TextButton(onClick = { pendingDelete = item }) { Text("Remove") }
|
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)) {
|
||||||
@@ -169,18 +208,19 @@ private fun ProbeScreen() {
|
|||||||
OutlinedTextField(port, { port = it }, label = { Text("Port") }, modifier = Modifier.weight(.4f))
|
OutlinedTextField(port, { port = it }, label = { Text("Port") }, modifier = Modifier.weight(.4f))
|
||||||
} }
|
} }
|
||||||
item { OutlinedTextField(share, { share = it }, label = { Text("Share") }, modifier = Modifier.fillMaxWidth()) }
|
item { OutlinedTextField(share, { share = it }, label = { Text("Share") }, modifier = Modifier.fillMaxWidth()) }
|
||||||
item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
item { OutlinedTextField(username, { username = it }, label = { Text("Username") }, modifier = Modifier.fillMaxWidth()) }
|
||||||
OutlinedTextField(username, { username = it }, label = { Text("Username") }, modifier = Modifier.weight(1f))
|
item { OutlinedTextField(domain, { domain = it }, label = { Text("Domain (optional)") }, modifier = Modifier.fillMaxWidth()) }
|
||||||
OutlinedTextField(domain, { domain = it }, label = { Text("Domain (optional)") }, modifier = Modifier.weight(1f))
|
|
||||||
} }
|
|
||||||
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)"}")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ 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 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,
|
||||||
@@ -69,34 +71,6 @@ 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,
|
||||||
@@ -123,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