Reuse SMB session and prefetch viewer images
Build Android APKs / build (push) Successful in 1m23s

This commit is contained in:
Alvin-Zilverstand committed 2026-11-14 10:44:44 +01:00
1 parent 232765e8d4
commit 5ce400e867
2 files changed
+84 -30

No files matched your search

@@ -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)
@@ -100,3 +108,40 @@ fun ImageViewer(saved: SavedShare, folder: String, images: List<RemoteEntry>, in
} }
} }
} }
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: SmbImageSession? = 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 ?: SmbImageSession(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()
}
}
}
@@ -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,41 @@ 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 SmbImageSession(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 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,