Compare commits
2
Commits
build-24-1
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7ff86768df | ||
|
|
fe72a53a23 |
No files matched your search
@@ -4,6 +4,8 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- '**'
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -35,6 +37,7 @@ jobs:
|
||||
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -n "$ANDROID_KEYSTORE_BASE64" ]]; then
|
||||
@@ -47,7 +50,12 @@ jobs:
|
||||
trap 'rm -f "$ANDROID_KEYSTORE_PATH"' EXIT
|
||||
fi
|
||||
chmod +x ./gradlew
|
||||
if [[ "$GITEA_REF" == refs/tags/* && -z "${ANDROID_KEYSTORE_PATH:-}" ]]; then
|
||||
echo "Stable tags require all release signing secrets" >&2
|
||||
exit 1
|
||||
fi
|
||||
./gradlew --no-daemon :app:assembleRelease :app:assembleDebug
|
||||
./gradlew --no-daemon :app:lintDebug :app:testDebugUnitTest
|
||||
|
||||
- name: Upload APKs
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -57,6 +65,7 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Create Gitea release with APK
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
shell: bash
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
@@ -65,27 +74,31 @@ jobs:
|
||||
COMMIT_SHA: ${{ gitea.sha }}
|
||||
RUN_ID: ${{ gitea.run_id }}
|
||||
RUN_ATTEMPT: ${{ gitea.run_attempt }}
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
: "${GITEA_TOKEN:?Gitea job token is unavailable}"
|
||||
tag="build-${RUN_ID}-${RUN_ATTEMPT}"
|
||||
release_apk=app/build/outputs/apk/release/app-release.apk
|
||||
if [[ -f "$release_apk" ]]; then
|
||||
apk="$release_apk"
|
||||
asset_name=smb-explorer-release.apk
|
||||
build_type='Signed release APK'
|
||||
else
|
||||
apk=app/build/outputs/apk/debug/app-debug.apk
|
||||
asset_name=smb-explorer-debug.apk
|
||||
build_type='Debug APK (installable test build; configure signing secrets for a signed release)'
|
||||
tag="${GITEA_REF#refs/tags/}"
|
||||
if [[ ! "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "Stable release tags must be vMAJOR.MINOR.PATCH" >&2
|
||||
exit 1
|
||||
fi
|
||||
version="$(python3 -c 'import json; print(json.load(open("app/build/outputs/apk/release/output-metadata.json"))["elements"][0]["versionName"])')"
|
||||
if [[ "$tag" != "v${version}" ]]; then
|
||||
echo "Tag $tag does not match APK version $version" >&2
|
||||
exit 1
|
||||
fi
|
||||
release_apk=app/build/outputs/apk/release/app-release.apk
|
||||
apk="$release_apk"
|
||||
asset_name="smb-explorer-${tag}.apk"
|
||||
build_type='Signed stable release APK'
|
||||
test -s "$apk"
|
||||
|
||||
api="${SERVER_URL%/}/api/v1/repos/${REPOSITORY}/releases"
|
||||
payload="$(mktemp)"
|
||||
response="$(mktemp)"
|
||||
trap 'rm -f "$payload" "$response"' EXIT
|
||||
TAG="$tag" BUILD_TYPE="$build_type" python3 -c 'import json, os, sys; json.dump({"tag_name": os.environ["TAG"], "target_commitish": os.environ["COMMIT_SHA"], "name": os.environ["TAG"], "body": os.environ["BUILD_TYPE"] + "\nCommit: " + os.environ["COMMIT_SHA"], "draft": False, "prerelease": True}, sys.stdout)' > "$payload"
|
||||
TAG="$tag" BUILD_TYPE="$build_type" python3 -c 'import json, os, sys; json.dump({"tag_name": os.environ["TAG"], "target_commitish": os.environ["COMMIT_SHA"], "name": os.environ["TAG"], "body": os.environ["BUILD_TYPE"] + "\nCommit: " + os.environ["COMMIT_SHA"], "draft": False, "prerelease": False}, sys.stdout)' > "$payload"
|
||||
curl --fail-with-body --silent --show-error \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H 'Content-Type: application/json' \
|
||||
|
||||
+4
-2
@@ -5,10 +5,12 @@ Thanks for helping improve SMB Explorer. Open an issue before a large change so
|
||||
## Development
|
||||
|
||||
1. Use JDK 17 and the Android SDK described in the [README](README.md).
|
||||
2. Make a focused change and build with `./gradlew :app:assembleDebug` (or `gradlew.bat` on Windows).
|
||||
3. Test SMB behavior against a share when possible. Include the Android version, device model, and file type or folder size relevant to the change.
|
||||
2. Make a focused change and build with `./gradlew :app:assembleDebug` (or `gradlew.bat` on Windows). For changes to saved connections, run `:app:connectedAndroidTest` on a device or emulator.
|
||||
3. Test browsing and image behavior against an SMB share when possible. The instrumented storage test does not exercise SMB. Include the Android version, device model, and file type or folder size relevant to the change.
|
||||
4. Open a pull request with a short summary, how you tested it, and any known limits.
|
||||
|
||||
For release changes, record the tested device/API level, SMB server conditions, measured timings, download integrity checks, and each video container/codec combination actually played and sought. A stable tag requires a signed APK, passing lint/build/tests, and owner review of the release commit and remaining limits.
|
||||
|
||||
The app stores saved connection credentials locally. Do not include passwords, keystores, NAS addresses, private file names, or unredacted logs/screenshots in issues or pull requests.
|
||||
|
||||
Code contributions are submitted under the repository's [GPL-3.0-only license](LICENSE). Keep third-party notices and license terms intact when adding dependencies or assets.
|
||||
@@ -1,5 +1,7 @@
|
||||
# S24 SMB Share Explorer — implementation plan
|
||||
|
||||
This is the first-release acceptance plan, not a description of the current app. See [README.md](README.md) for implemented behavior and [RELEASE_NOTES.md](RELEASE_NOTES.md) for current validation gaps. Offline files remain a later feature.
|
||||
|
||||
## Product goal and working assumptions
|
||||
|
||||
Build a fast, native-feeling Android file explorer for a Samba share hosted in a Debian container on home Wi-Fi. The Galaxy S24 is the primary performance test device, and Android 9 (API 28) is the minimum supported version. The first release supports browsing, searching within the current folder, downloading, deleting files and empty folders, and built-in video, image, and animated GIF viewing. Use authenticated SMB2/3 and no server-side companion app. The media library contains varied containers and codecs, so playback support must be established with a tested format matrix rather than a blanket claim.
|
||||
|
||||
@@ -1,25 +1,31 @@
|
||||
# SMB Explorer
|
||||
|
||||
An Android app for browsing SMB2/3 shares on a local network. It has a dark interface, encrypted saved connections, folder search and sorting, and an image viewer for photos and animated GIFs.
|
||||
An Android app for browsing SMB2/3 shares on a local network. The current source version is **1.0.0-rc.1** and requires Android 9 (API 28) or newer. It is a release candidate, not a verified stable release.
|
||||
|
||||
The app is under active development. See [PLAN.md](PLAN.md) for the planned file actions, video playback, and further performance work.
|
||||
See [PLAN.md](PLAN.md) for first-release acceptance criteria and [RELEASE_NOTES.md](RELEASE_NOTES.md) for validation status.
|
||||
|
||||
The launcher icon's editable source is [artwork/app-icon.svg](artwork/app-icon.svg); Android uses matching vector drawables for the adaptive and monochrome icon.
|
||||
|
||||
## What works now
|
||||
|
||||
- Save multiple SMB connections after testing them. Credentials are encrypted with a device-bound Android Keystore key; app backup is disabled.
|
||||
- Browse folders, use breadcrumbs, search the current folder, filter by file type, sort by name in either direction, newest/oldest, largest/smallest, or file type, and refresh a listing.
|
||||
- Browse folders, use breadcrumbs, search names in the current folder, filter by file type (all, images, videos, other files, or folders), sort by name in either direction, newest/oldest, largest/smallest, or file type, and refresh a listing. Folders appear before files.
|
||||
- Open images and animated GIFs, then swipe through images in the same folder. The viewer reads at most 64 MB per file.
|
||||
- Pinch or double tap to zoom and pan images, switch fit/fill, and request original resolution within a memory limit. Small images show cached thumbnails in visible rows; large files retain an icon to avoid reading the original for a thumbnail. The folder toolbar can clear the thumbnail cache.
|
||||
- Download files to system Downloads on Android 10 or newer, or choose a destination on Android 9. Progress and cancellation are shown. A failed or cancelled download removes its partial destination.
|
||||
- Long press a file or folder to confirm deletion. Only empty folders can be deleted; failed deletes remain visible as errors.
|
||||
- Play videos through Media3 with SMB byte-range reads, scrubbing, resume position, and standard player controls. An external-player action grants temporary seekable access through a content URI. Actual format support and external-player seeking have not been validated against the target library.
|
||||
- Reuse an SMB session while browsing and viewing images, keep up to 20 recent folder listings in memory, and preload nearby images in the viewer. Still images are decoded ahead of swipes within a bounded memory cache.
|
||||
|
||||
Video playback, downloads, deletion, thumbnails, and offline files are not implemented yet. Other files currently show their details.
|
||||
Offline files are not implemented. Search and filters only apply to the current folder; they do not search the share recursively.
|
||||
|
||||
## Install
|
||||
|
||||
Download the APK from the latest [Gitea release](https://codealvin.xyz/Alvin-Zilverstand/smb-explorer/releases). Without release signing secrets, the workflow attaches a debug-signed test APK; with them, it attaches a release-signed APK. Android 9 or newer is required.
|
||||
Stable releases will be published on the [Gitea releases page](https://codealvin.xyz/Alvin-Zilverstand/smb-explorer/releases) only after a signed `vMAJOR.MINOR.PATCH` tag passes the build. Ordinary pushes produce Actions artifacts. No stable APK has been published for this candidate.
|
||||
|
||||
On first launch, enter the NAS address, share name, and credentials, then tap **Test & save connection**. The device must be able to reach the SMB server, usually on port 445. Open the saved share from the home screen. The connection menu (`⋮`) contains **Edit connection** and **Remove connection**.
|
||||
On first launch, enter the NAS host name or IP address, share name, and credentials, then tap **Test & save connection**. The port defaults to 445; a domain and starting folder are optional. The device must be able to reach the SMB server over the local network. A successful test saves the connection and opens the share. Later, tap a saved share on the home screen to browse it. Its menu (`⋮`) contains **Edit connection** and **Remove connection**. Editing requires a successful connection test before the change is saved.
|
||||
|
||||
Saved connection details, including passwords, are encrypted locally with an Android Keystore key. They are device-bound and are not included in Android app backups. Keep a copy of the connection details elsewhere if you need to set up another device or reinstall the app.
|
||||
|
||||
## Build from source
|
||||
|
||||
@@ -31,11 +37,13 @@ Requirements: JDK 17, Android SDK platform 37, and Android build tools 36.0.0. S
|
||||
|
||||
On Windows, run `gradlew.bat :app:assembleDebug`. The APK is written to `app/build/outputs/apk/debug/app-debug.apk`. Install it with `adb install -r app/build/outputs/apk/debug/app-debug.apk`.
|
||||
|
||||
The optional **Advanced connection test** reads three 64 KiB ranges of a selected file and reports their hashes. It is a diagnostic tool, not part of normal browsing.
|
||||
The optional **Advanced connection test** accepts a file path on the share, reads up to three 64 KiB ranges, and reports their SHA-256 hashes. It does not save the connection. It is a diagnostic tool, not part of normal browsing.
|
||||
|
||||
To run the existing device test, connect an Android device or start an emulator and run `./gradlew :app:connectedAndroidTest` (or `gradlew.bat :app:connectedAndroidTest` on Windows). The test covers encrypted saved connection storage; it does not require an SMB server.
|
||||
|
||||
## Gitea builds and releases
|
||||
|
||||
Every branch push runs [the Android workflow](.gitea/workflows/android-build.yml) on a runner labelled `debian`. The job builds debug and release APKs, uploads them as an Actions artifact, and creates a Gitea pre-release tagged `build-<run ID>-<attempt>` with one installable APK. The runner needs outbound access to the action repositories, Gradle, Maven, and Android SDK downloads. The repository must allow the job token to write releases.
|
||||
Every branch push runs [the Android workflow](.gitea/workflows/android-build.yml) on a runner labelled `debian` and uploads APKs as Actions artifacts. A stable release is created only for a matching `vMAJOR.MINOR.PATCH` tag with complete signing secrets. The runner needs outbound access to action repositories, Gradle, Maven, and Android SDK downloads. The repository must allow the job token to write releases.
|
||||
|
||||
To attach a signed release APK instead of a debug APK, configure these repository Actions secrets:
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# 1.0.0-rc.1 validation record
|
||||
|
||||
This candidate is not approved for stable publication.
|
||||
|
||||
## Implemented in this candidate
|
||||
|
||||
- File downloads with byte progress, cancellation, and removal of partial local files.
|
||||
- Confirmed deletion of files and empty folders, with a nonempty-folder guard.
|
||||
- Media3 playback using seekable SMB byte reads, standard playback controls, saved resume positions, and a seekable content URI for external players.
|
||||
- Image pinch and double-tap zoom, pan, fit/fill, and bounded original-resolution option; small-image disk-cached thumbnails in visible folder rows.
|
||||
- Reconnection for read-only folder listings, image reads, and video byte reads; failed transfer sessions are discarded.
|
||||
- Explicit backup exclusions for credentials, including device transfer.
|
||||
- Tag-gated signed stable-release workflow; branch pushes yield build artifacts.
|
||||
|
||||
## Local verification, 14 November 2026
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| Debug and release Gradle assembly | Passed; release output is unsigned because signing secrets are unavailable |
|
||||
| Android lint | Passed |
|
||||
| JVM path and copy tests | 5 passed |
|
||||
| Encrypted-share instrumented test, physical SM-S921B (API 37) | 1 passed |
|
||||
| Encrypted-share instrumented test, Galaxy S24 AVD (API 37) | 1 passed |
|
||||
|
||||
## Still required before a stable release
|
||||
|
||||
- Actual SMB share access and permission to run non-destructive listing and range-read probes, plus a dedicated test folder for download/delete tests. NAS model, Samba settings, sample files, and credentials are not available in the build environment.
|
||||
- Android 9 device or emulator. The two connected targets both report API 37.
|
||||
- Release keystore and four CI signing secrets. No release-signed APK is available.
|
||||
- Video format matrix, seek and disconnect trials, external-player URI seeking, track selection and orientation controls. No format is claimed as verified.
|
||||
- Large-image thumbnail/zoom behavior, GIF background lifecycle, cancellation during blocked SMB reads, performance targets, and download integrity after Wi-Fi interruption.
|
||||
|
||||
The source version is deliberately `1.0.0-rc.1`. Do not push a stable `v1.0.0` tag until these items pass and the version name is changed to `1.0.0`.
|
||||
@@ -24,8 +24,8 @@ android {
|
||||
applicationId = "dev.alvin.smbexplorer"
|
||||
minSdk = 28
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "0.1"
|
||||
versionCode = 2
|
||||
versionName = "1.0.0-rc.1"
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
compileOptions {
|
||||
@@ -42,6 +42,9 @@ dependencies {
|
||||
implementation("androidx.compose.foundation:foundation")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||
implementation("com.hierynomus:smbj:0.15.0")
|
||||
implementation("androidx.media3:media3-exoplayer:1.11.1")
|
||||
implementation("androidx.media3:media3-ui:1.11.1")
|
||||
androidTestImplementation("androidx.test:runner:1.7.0")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<application android:label="SMB Explorer" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:usesCleartextTraffic="false" android:theme="@android:style/Theme.Material.NoActionBar">
|
||||
<application android:label="SMB Explorer" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:fullBackupContent="false" android:dataExtractionRules="@xml/data_extraction_rules" android:usesCleartextTraffic="false" android:theme="@android:style/Theme.Material.NoActionBar">
|
||||
<provider android:name=".VideoStreamProvider" android:authorities="dev.alvin.smbexplorer.stream" android:exported="false" android:grantUriPermissions="true" />
|
||||
<activity android:name=".MainActivity" android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
|
||||
@@ -11,6 +11,10 @@ import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.currentCoroutineContext
|
||||
import kotlinx.coroutines.ensureActive
|
||||
import kotlinx.coroutines.delay
|
||||
import java.io.OutputStream
|
||||
|
||||
/** Reuses one authenticated share while browsing and retains recent folder listings. */
|
||||
class BrowseRepository(private val target: SmbTarget) {
|
||||
@@ -23,7 +27,7 @@ class BrowseRepository(private val target: SmbTarget) {
|
||||
|
||||
suspend fun list(path: String): ProbeResult = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
val listing = (session ?: SmbShareSession(target).also { session = it }).list(path)
|
||||
val listing = reconnectable { it.list(path) }
|
||||
synchronized(cache) {
|
||||
cache[path] = listing
|
||||
if (cache.size > 20) cache.remove(cache.keys.first())
|
||||
@@ -32,9 +36,55 @@ class BrowseRepository(private val target: SmbTarget) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun read(path: String): ByteArray = withContext(Dispatchers.IO) {
|
||||
suspend fun read(path: String, maxBytes: Long = 64L * 1024 * 1024): ByteArray = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
(session ?: SmbShareSession(target).also { session = it }).read(path)
|
||||
reconnectable { it.read(path, maxBytes) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun <T> reconnectable(operation: (SmbShareSession) -> T): T {
|
||||
try { return operation(session ?: SmbShareSession(target).also { session = it }) }
|
||||
catch (first: Exception) {
|
||||
runCatching { session?.close() }
|
||||
session = null
|
||||
currentCoroutineContext().ensureActive()
|
||||
delay(300)
|
||||
return try { operation(SmbShareSession(target).also { session = it }) }
|
||||
catch (second: Exception) {
|
||||
runCatching { session?.close() }
|
||||
session = null
|
||||
throw second
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun download(path: String, output: OutputStream, progress: (Long, Long) -> Unit) = withContext(Dispatchers.IO) {
|
||||
val context = currentCoroutineContext()
|
||||
mutex.withLock {
|
||||
try {
|
||||
(session ?: SmbShareSession(target).also { session = it }).copy(path, output) { done, total ->
|
||||
context.ensureActive()
|
||||
progress(done, total)
|
||||
}
|
||||
context.ensureActive()
|
||||
} catch (e: Exception) {
|
||||
runCatching { session?.close() }
|
||||
session = null
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun delete(path: String, directory: Boolean) = withContext(Dispatchers.IO) {
|
||||
mutex.withLock {
|
||||
try {
|
||||
(session ?: SmbShareSession(target).also { session = it }).delete(path, directory)
|
||||
synchronized(cache) { cache.clear() }
|
||||
} catch (e: Exception) {
|
||||
runCatching { session?.close() }
|
||||
session = null
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,14 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import android.os.Build
|
||||
import android.content.Intent
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
@@ -34,9 +41,14 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.Job
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CancellationException
|
||||
@@ -55,6 +67,7 @@ private enum class FileFilter { All, Images, Videos, Other, Folders }
|
||||
private val imageExtensions = setOf("jpg", "jpeg", "png", "gif", "webp", "heic", "heif", "bmp", "avif")
|
||||
private val videoExtensions = setOf("mp4", "mkv", "webm", "avi", "mov", "m4v", "ts", "mpeg", "mpg")
|
||||
private fun RemoteEntry.isImage() = !directory && name.substringAfterLast('.', "").lowercase() in imageExtensions
|
||||
private fun RemoteEntry.isVideo() = !directory && name.substringAfterLast('.', "").lowercase() in videoExtensions
|
||||
|
||||
private fun FileFilter.matches(entry: RemoteEntry): Boolean {
|
||||
val extension = entry.name.substringAfterLast('.', "").lowercase()
|
||||
@@ -67,6 +80,8 @@ private fun FileFilter.matches(entry: RemoteEntry): Boolean {
|
||||
}
|
||||
}
|
||||
|
||||
@androidx.annotation.OptIn(UnstableApi::class)
|
||||
@OptIn(ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
val repository = remember(saved.id) { BrowseRepository(saved.target) }
|
||||
@@ -76,19 +91,69 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
var search by remember { mutableStateOf("") }
|
||||
var sort by remember { mutableStateOf(SortMode.NameAsc) }
|
||||
var filter by remember { mutableStateOf(FileFilter.All) }
|
||||
var result by remember { mutableStateOf<ProbeResult?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var loading by remember { mutableStateOf(true) }
|
||||
var result by remember(saved.id, path) { mutableStateOf<ProbeResult?>(null) }
|
||||
var error by remember(saved.id, path) { mutableStateOf<String?>(null) }
|
||||
var loading by remember(saved.id, path) { mutableStateOf(true) }
|
||||
var selectedFile by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
var selectedImage by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
var selectedVideo by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
var sortOpen by remember { mutableStateOf(false) }
|
||||
var visible by remember { mutableStateOf(emptyList<RemoteEntry>()) }
|
||||
var actionsOpen by remember { mutableStateOf(false) }
|
||||
var visible by remember(saved.id, path) { mutableStateOf(emptyList<RemoteEntry>()) }
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
var actionMessage by remember { mutableStateOf<String?>(null) }
|
||||
var downloadJob by remember { mutableStateOf<Job?>(null) }
|
||||
var downloadProgress by remember { mutableStateOf(0L to 0L) }
|
||||
var pendingDownload by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
var pendingRemoteDelete by remember { mutableStateOf<RemoteEntry?>(null) }
|
||||
val savePicker = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri ->
|
||||
val entry = pendingDownload
|
||||
pendingDownload = null
|
||||
if (uri != null && entry != null) {
|
||||
downloadJob = scope.launch {
|
||||
try {
|
||||
context.contentResolver.openOutputStream(uri, "w")?.use { stream ->
|
||||
repository.download(if (path.isEmpty()) entry.name else "$path\\${entry.name}", stream) { done, total ->
|
||||
downloadProgress = done to total
|
||||
}
|
||||
} ?: error("Could not open destination")
|
||||
actionMessage = "Downloaded ${entry.name}"
|
||||
} catch (e: CancellationException) {
|
||||
context.contentResolver.delete(uri, null, null)
|
||||
actionMessage = "Download cancelled"
|
||||
} catch (e: Exception) {
|
||||
context.contentResolver.delete(uri, null, null)
|
||||
actionMessage = "Download failed: ${e.message}"
|
||||
} finally { downloadJob = null }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun startDownload(entry: RemoteEntry) {
|
||||
downloadProgress = 0L to entry.size
|
||||
if (Build.VERSION.SDK_INT < 29) {
|
||||
pendingDownload = entry
|
||||
savePicker.launch(entry.name)
|
||||
} else downloadJob = scope.launch {
|
||||
try {
|
||||
DownloadStore.save(context, repository, if (path.isEmpty()) entry.name else "$path\\${entry.name}", entry.name) { done, total ->
|
||||
downloadProgress = done to total
|
||||
}
|
||||
actionMessage = "Downloaded ${entry.name} to Downloads"
|
||||
} catch (e: CancellationException) {
|
||||
actionMessage = "Download cancelled"
|
||||
} catch (e: Exception) {
|
||||
actionMessage = "Download failed: ${e.message}"
|
||||
} finally { downloadJob = null }
|
||||
}
|
||||
}
|
||||
|
||||
fun up() {
|
||||
path = path.substringBeforeLast('\\', "")
|
||||
search = ""
|
||||
}
|
||||
BackHandler(enabled = selectedImage == null) { if (path.isEmpty()) onConnections() else up() }
|
||||
BackHandler(enabled = selectedImage == null && selectedVideo == null) { if (path.isEmpty()) onConnections() else up() }
|
||||
|
||||
LaunchedEffect(saved.id, path, refresh) {
|
||||
loading = true
|
||||
@@ -111,16 +176,38 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
if (images.isNotEmpty()) ImageViewer(saved, repository, path, images, image) { selectedImage = null }
|
||||
return
|
||||
}
|
||||
selectedVideo?.let { video ->
|
||||
VideoViewer(saved, if (path.isEmpty()) video.name else "$path\\${video.name}") { selectedVideo = null }
|
||||
return
|
||||
}
|
||||
|
||||
selectedFile?.let { file ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { selectedFile = null },
|
||||
title = { Text(file.name) },
|
||||
text = { Text("Size: ${file.size} bytes\nModified: ${formatDate(file.modifiedAt)}\nPath: ${if (path.isEmpty()) file.name else "$path\\${file.name}"}") },
|
||||
confirmButton = { Button(onClick = { selectedFile = null }) { Text("Close") } },
|
||||
confirmButton = { Button(onClick = { selectedFile = null; startDownload(file) }) { Text("Download") } },
|
||||
dismissButton = { TextButton(onClick = { selectedFile = null; pendingRemoteDelete = file }) { Text("Delete…") } },
|
||||
)
|
||||
}
|
||||
|
||||
pendingRemoteDelete?.let { entry ->
|
||||
AlertDialog(onDismissRequest = { pendingRemoteDelete = null },
|
||||
title = { Text("Delete ${entry.name}?") },
|
||||
text = { Text(if (entry.directory) "Only an empty folder can be deleted." else "This file will be removed from the share.") },
|
||||
confirmButton = { Button(onClick = {
|
||||
pendingRemoteDelete = null
|
||||
scope.launch {
|
||||
try {
|
||||
repository.delete(if (path.isEmpty()) entry.name else "$path\\${entry.name}", entry.directory)
|
||||
refresh++
|
||||
actionMessage = "Deleted ${entry.name}"
|
||||
} catch (e: Exception) { actionMessage = "Delete failed: ${e.message}" }
|
||||
}
|
||||
}) { Text("Delete") } },
|
||||
dismissButton = { TextButton(onClick = { pendingRemoteDelete = null }) { Text("Cancel") } })
|
||||
}
|
||||
|
||||
LaunchedEffect(result, search, sort, filter) {
|
||||
val entries = result?.entries.orEmpty()
|
||||
visible = withContext(Dispatchers.Default) {
|
||||
@@ -132,14 +219,22 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Column(Modifier.fillMaxSize().padding(horizontal = 16.dp, vertical = 6.dp), verticalArrangement = Arrangement.spacedBy(4.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(if (path.isEmpty()) saved.target.share else path.substringAfterLast('\\'), style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(saved.target.host, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
TextButton(onClick = { refresh++ }) { Text("Refresh") }
|
||||
TextButton(onClick = { refresh++ }) { Text("↻") }
|
||||
TextButton(onClick = { actionsOpen = true }) { Text("⋮") }
|
||||
DropdownMenu(expanded = actionsOpen, onDismissRequest = { actionsOpen = false }) {
|
||||
DropdownMenuItem(text = { Text("Clear thumbnail cache") }, onClick = {
|
||||
actionsOpen = false
|
||||
context.cacheDir.resolve("thumbnails").listFiles()?.forEach { it.delete() }
|
||||
actionMessage = "Thumbnail cache cleared"
|
||||
})
|
||||
}
|
||||
}
|
||||
if (path.isNotEmpty()) Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
TextButton(onClick = { path = ""; search = "" }) { Text(saved.target.share) }
|
||||
@@ -170,17 +265,26 @@ fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) {
|
||||
}
|
||||
}
|
||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
|
||||
actionMessage?.let { Text(it) }
|
||||
downloadJob?.let {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text("Downloading ${downloadProgress.first} / ${downloadProgress.second} bytes", Modifier.weight(1f))
|
||||
TextButton(onClick = { it.cancel() }) { Text("Cancel") }
|
||||
}
|
||||
}
|
||||
LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||
items(visible, key = { "$path/${it.name}" }) { entry ->
|
||||
Surface(Modifier.fillMaxWidth(), color = MaterialTheme.colorScheme.surfaceContainerLow, shape = MaterialTheme.shapes.medium) {
|
||||
Row(Modifier.fillMaxWidth().clickable {
|
||||
Row(Modifier.fillMaxWidth().combinedClickable(onLongClick = { pendingRemoteDelete = entry }, onClick = {
|
||||
if (entry.directory) {
|
||||
path = if (path.isEmpty()) entry.name else "$path\\${entry.name}"
|
||||
search = ""
|
||||
} else if (entry.isImage()) selectedImage = entry
|
||||
else if (entry.isVideo()) selectedVideo = entry
|
||||
else selectedFile = entry
|
||||
}.padding(horizontal = 14.dp, vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(if (entry.directory) "▣" else if (entry.isImage()) "▧" else "▤", color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.titleLarge)
|
||||
}).padding(horizontal = 14.dp, vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
if (entry.isImage()) Thumbnail(repository, saved.id, if (path.isEmpty()) entry.name else "$path\\${entry.name}", entry)
|
||||
else Text(if (entry.directory) "▣" else "▤", color = MaterialTheme.colorScheme.primary, style = MaterialTheme.typography.titleLarge)
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(entry.name, style = MaterialTheme.typography.bodyLarge)
|
||||
if (!entry.directory) Text("${formatSize(entry.size)} · ${formatDate(entry.modifiedAt)}", style = MaterialTheme.typography.bodySmall,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import java.io.OutputStream
|
||||
|
||||
/** Copies the advertised length or fails without reporting success. */
|
||||
internal fun copyExact(length: Long, output: OutputStream,
|
||||
read: (ByteArray, Long) -> Int,
|
||||
progress: (Long, Long) -> Unit) {
|
||||
require(length >= 0)
|
||||
val buffer = ByteArray(256 * 1024)
|
||||
var offset = 0L
|
||||
while (offset < length) {
|
||||
val count = read(buffer, offset)
|
||||
check(count in 1..minOf(buffer.size.toLong(), length - offset).toInt()) {
|
||||
"Remote file ended or changed before download completed"
|
||||
}
|
||||
output.write(buffer, 0, count)
|
||||
offset += count
|
||||
progress(offset, length)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.annotation.TargetApi
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import java.io.IOException
|
||||
|
||||
/** Publishes a download only after the SMB copy has completed. */
|
||||
object DownloadStore {
|
||||
@TargetApi(29)
|
||||
suspend fun save(context: Context, repository: BrowseRepository, path: String, name: String,
|
||||
progress: (Long, Long) -> Unit) {
|
||||
require(Build.VERSION.SDK_INT >= 29) { "Choose a destination on Android 9" }
|
||||
val resolver = context.contentResolver
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Downloads.DISPLAY_NAME, name)
|
||||
put(MediaStore.Downloads.MIME_TYPE, "application/octet-stream")
|
||||
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
|
||||
put(MediaStore.Downloads.IS_PENDING, 1)
|
||||
}
|
||||
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
||||
?: throw IOException("Could not create Downloads entry")
|
||||
try {
|
||||
resolver.openOutputStream(uri, "w")?.use { repository.download(path, it, progress) }
|
||||
?: throw IOException("Could not open Downloads entry")
|
||||
resolver.update(uri, ContentValues().apply { put(MediaStore.Downloads.IS_PENDING, 0) }, null, null)
|
||||
} catch (e: Exception) {
|
||||
resolver.delete(uri, null, null)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import android.graphics.drawable.Drawable
|
||||
import android.widget.ImageView
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTransformGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
@@ -30,9 +32,13 @@ import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
@@ -53,14 +59,28 @@ fun ImageViewer(saved: SavedShare, repository: BrowseRepository, folder: String,
|
||||
var drawable by remember { mutableStateOf<android.graphics.drawable.Drawable?>(null) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var loading by remember { mutableStateOf(true) }
|
||||
var original by remember(index) { mutableStateOf(false) }
|
||||
var fill by remember { mutableStateOf(false) }
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
var foreground by remember { mutableStateOf(lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, _ ->
|
||||
foreground = lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
var scale by remember(index) { mutableStateOf(1f) }
|
||||
var panX by remember(index) { mutableStateOf(0f) }
|
||||
var panY by remember(index) { mutableStateOf(0f) }
|
||||
BackHandler(onBack = onClose)
|
||||
|
||||
LaunchedEffect(saved.id, folder, entry.name) {
|
||||
LaunchedEffect(saved.id, folder, entry.name, original) {
|
||||
drawable = null
|
||||
error = null
|
||||
loading = true
|
||||
try {
|
||||
drawable = loader.load(entry.name)
|
||||
drawable = loader.load(entry.name, original)
|
||||
images.getOrNull(index + 1)?.let { loader.prefetch(it.name) }
|
||||
images.getOrNull(index - 1)?.let { loader.prefetch(it.name) }
|
||||
} catch (e: CancellationException) {
|
||||
@@ -80,15 +100,26 @@ fun ImageViewer(saved: SavedShare, repository: BrowseRepository, folder: String,
|
||||
}
|
||||
Text(entry.name, Modifier.padding(horizontal = 16.dp), style = MaterialTheme.typography.bodyMedium, maxLines = 1)
|
||||
var drag by remember { mutableStateOf(0f) }
|
||||
Box(Modifier.weight(1f).fillMaxWidth().pointerInput(index, images.size) {
|
||||
Box(Modifier.weight(1f).fillMaxWidth().pointerInput(index, images.size, scale) {
|
||||
detectHorizontalDragGestures(
|
||||
onHorizontalDrag = { _, amount -> drag += amount },
|
||||
onHorizontalDrag = { _, amount -> if (scale <= 1f) drag += amount else panX += amount },
|
||||
onDragEnd = {
|
||||
if (drag < -80 && index < images.lastIndex) index++
|
||||
if (drag > 80 && index > 0) index--
|
||||
drag = 0f
|
||||
},
|
||||
)
|
||||
}.pointerInput(index) {
|
||||
detectTransformGestures { _, pan, zoom, _ ->
|
||||
scale = (scale * zoom).coerceIn(1f, 4f)
|
||||
if (scale > 1f) { panX += pan.x; panY += pan.y }
|
||||
else { panX = 0f; panY = 0f }
|
||||
}
|
||||
}.pointerInput(index) {
|
||||
detectTapGestures(onDoubleTap = {
|
||||
scale = if (scale > 1f) 1f else 2f
|
||||
if (scale == 1f) { panX = 0f; panY = 0f }
|
||||
})
|
||||
}, contentAlignment = Alignment.Center) {
|
||||
if (loading) CircularProgressIndicator()
|
||||
error?.let { Text(it, Modifier.padding(24.dp), color = MaterialTheme.colorScheme.error) }
|
||||
@@ -96,14 +127,19 @@ fun ImageViewer(saved: SavedShare, repository: BrowseRepository, folder: String,
|
||||
AndroidView(factory = { context -> ImageView(context).apply { scaleType = ImageView.ScaleType.FIT_CENTER } },
|
||||
update = { view ->
|
||||
(view.drawable as? Animatable)?.stop()
|
||||
view.scaleType = if (fill) ImageView.ScaleType.CENTER_CROP else ImageView.ScaleType.FIT_CENTER
|
||||
view.setImageDrawable(current)
|
||||
(current as? Animatable)?.start()
|
||||
}, modifier = Modifier.fillMaxSize())
|
||||
if (foreground) (current as? Animatable)?.start()
|
||||
}, modifier = Modifier.fillMaxSize().graphicsLayer {
|
||||
scaleX = scale; scaleY = scale; translationX = panX; translationY = panY
|
||||
})
|
||||
DisposableEffect(current) { onDispose { (current as? Animatable)?.stop() } }
|
||||
}
|
||||
}
|
||||
Row(Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween) {
|
||||
TextButton(enabled = index > 0, onClick = { index-- }) { Text("‹ Previous") }
|
||||
TextButton(onClick = { fill = !fill }) { Text(if (fill) "Fit" else "Fill") }
|
||||
TextButton(onClick = { original = !original }) { Text(if (original) "Sampled" else "Original") }
|
||||
TextButton(enabled = index < images.lastIndex, onClick = { index++ }) { Text("Next ›") }
|
||||
}
|
||||
}
|
||||
@@ -136,13 +172,18 @@ private class ImageLoader(private val repository: BrowseRepository, private val
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun load(name: String): Drawable = decodeMutex.withLock {
|
||||
synchronized(decoded) { decoded[name] }?.let { return@withLock it }
|
||||
suspend fun load(name: String, original: Boolean = false): Drawable = decodeMutex.withLock {
|
||||
val key = "$name:$original"
|
||||
synchronized(decoded) { decoded[key] }?.let { return@withLock it }
|
||||
val data = bytes(name)
|
||||
val drawable = withContext(Dispatchers.Default) {
|
||||
ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(data))) { decoder, info, _ ->
|
||||
val largestSide = maxOf(info.size.width, info.size.height)
|
||||
if (largestSide > 4096) decoder.setTargetSampleSize((largestSide + 4095) / 4096)
|
||||
if (original) {
|
||||
require(info.size.width.toLong() * info.size.height <= 16_000_000) {
|
||||
"Original image exceeds the safe memory limit"
|
||||
}
|
||||
} else if (largestSide > 4096) decoder.setTargetSampleSize((largestSide + 4095) / 4096)
|
||||
}
|
||||
}
|
||||
if (drawable is BitmapDrawable) {
|
||||
@@ -153,7 +194,7 @@ private class ImageLoader(private val repository: BrowseRepository, private val
|
||||
decodedBytes -= oldest.value.bitmap.allocationByteCount
|
||||
decoded.remove(oldest.key)
|
||||
}
|
||||
decoded.put(name, drawable)?.let { decodedBytes -= it.bitmap.allocationByteCount }
|
||||
decoded.put(key, drawable)?.let { decodedBytes -= it.bitmap.allocationByteCount }
|
||||
decodedBytes += size
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.media3.common.C
|
||||
import androidx.media3.datasource.BaseDataSource
|
||||
import androidx.media3.datasource.DataSource
|
||||
import androidx.media3.datasource.DataSpec
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import java.io.EOFException
|
||||
import java.io.IOException
|
||||
|
||||
/** A byte-positioned SMB source. Each Media3 open owns its remote handles. */
|
||||
@UnstableApi
|
||||
class SmbDataSource(private val target: SmbTarget, private val path: String) : BaseDataSource(false) {
|
||||
private var session: SmbShareSession? = null
|
||||
private var range: RemoteRange? = null
|
||||
private var position = 0L
|
||||
private var remaining = 0L
|
||||
private var uri: Uri? = null
|
||||
private var started = false
|
||||
|
||||
override fun open(dataSpec: DataSpec): Long {
|
||||
transferInitializing(dataSpec)
|
||||
try {
|
||||
val connected = SmbShareSession(target)
|
||||
session = connected
|
||||
val opened = connected.openRange(path)
|
||||
range = opened
|
||||
if (dataSpec.position > opened.length) throw EOFException("Seek past end of file")
|
||||
position = dataSpec.position
|
||||
remaining = if (dataSpec.length == C.LENGTH_UNSET.toLong()) opened.length - position
|
||||
else minOf(dataSpec.length, opened.length - position)
|
||||
uri = dataSpec.uri
|
||||
transferStarted(dataSpec)
|
||||
started = true
|
||||
return remaining
|
||||
} catch (e: Exception) {
|
||||
close()
|
||||
throw IOException("Could not open SMB video", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
|
||||
if (length == 0) return 0
|
||||
if (remaining == 0L) return C.RESULT_END_OF_INPUT
|
||||
val handle = range ?: throw IOException("SMB video is closed")
|
||||
try {
|
||||
val requested = minOf(length.toLong(), remaining, 256L * 1024).toInt()
|
||||
val count = try { handle.read(buffer, position, requested) }
|
||||
catch (first: Exception) {
|
||||
runCatching { range?.close() }
|
||||
runCatching { session?.close() }
|
||||
session = SmbShareSession(target)
|
||||
range = session!!.openRange(path)
|
||||
range!!.read(buffer, position, requested)
|
||||
}
|
||||
if (count <= 0) throw EOFException("Remote video ended unexpectedly")
|
||||
position += count
|
||||
remaining -= count
|
||||
bytesTransferred(count)
|
||||
return count
|
||||
} catch (e: Exception) { throw IOException("SMB video read failed", e) }
|
||||
}
|
||||
|
||||
override fun getUri(): Uri? = uri
|
||||
|
||||
override fun close() {
|
||||
val wasOpen = started
|
||||
runCatching { range?.close() }
|
||||
runCatching { session?.close() }
|
||||
range = null
|
||||
session = null
|
||||
uri = null
|
||||
if (wasOpen) transferEnded()
|
||||
started = false
|
||||
}
|
||||
|
||||
class Factory(private val target: SmbTarget, private val path: String) : DataSource.Factory {
|
||||
override fun createDataSource(): DataSource = SmbDataSource(target, path)
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import java.io.Closeable
|
||||
import java.security.MessageDigest
|
||||
import java.util.EnumSet
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.OutputStream
|
||||
import com.hierynomus.smbj.connection.Connection
|
||||
import com.hierynomus.smbj.session.Session
|
||||
|
||||
@@ -103,10 +104,39 @@ class SmbProbe : Closeable {
|
||||
/** Keeps the SMB session open while the viewer is visible. Call from one IO coroutine at a time. */
|
||||
class SmbShareSession(target: SmbTarget) : Closeable {
|
||||
private val client = SMBClient()
|
||||
private val connection: Connection = client.connect(target.host.trim(), target.port)
|
||||
private val session: Session = connection.authenticate(
|
||||
AuthenticationContext(target.username, target.password.toCharArray(), target.domain))
|
||||
private val share: DiskShare = session.connectShare(target.share.trim()) as DiskShare
|
||||
private val connection: Connection
|
||||
private val session: Session
|
||||
private val share: DiskShare
|
||||
|
||||
init {
|
||||
try {
|
||||
connection = client.connect(target.host.trim(), target.port)
|
||||
} catch (e: Exception) {
|
||||
client.close()
|
||||
throw e
|
||||
}
|
||||
try {
|
||||
session = connection.authenticate(
|
||||
AuthenticationContext(target.username, target.password.toCharArray(), target.domain))
|
||||
} catch (e: Exception) {
|
||||
connection.close()
|
||||
client.close()
|
||||
throw e
|
||||
}
|
||||
try {
|
||||
val connectedShare = session.connectShare(target.share.trim())
|
||||
if (connectedShare !is DiskShare) {
|
||||
connectedShare.close()
|
||||
throw IllegalArgumentException("The selected share is not a disk share")
|
||||
}
|
||||
share = connectedShare
|
||||
} catch (e: Exception) {
|
||||
session.close()
|
||||
connection.close()
|
||||
client.close()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
fun list(folder: String): ProbeResult {
|
||||
val start = System.nanoTime()
|
||||
@@ -135,6 +165,33 @@ class SmbShareSession(target: SmbTarget) : Closeable {
|
||||
} finally { file.close() }
|
||||
}
|
||||
|
||||
fun copy(path: String, output: OutputStream, progress: (Long, Long) -> Unit) {
|
||||
val file = share.openFile(normalize(path), EnumSet.of(AccessMask.GENERIC_READ),
|
||||
EnumSet.noneOf(FileAttributes::class.java), EnumSet.of(SMB2ShareAccess.FILE_SHARE_READ),
|
||||
SMB2CreateDisposition.FILE_OPEN, EnumSet.noneOf(SMB2CreateOptions::class.java))
|
||||
try {
|
||||
val length = file.length
|
||||
copyExact(length, output, { buffer, offset -> file.read(buffer, offset) }, progress)
|
||||
} finally { file.close() }
|
||||
}
|
||||
|
||||
fun delete(path: String, directory: Boolean) {
|
||||
val normalized = normalize(path)
|
||||
require(normalized.isNotEmpty()) { "Cannot delete share root" }
|
||||
if (directory) {
|
||||
val children = share.list(normalized).filter { it.fileName != "." && it.fileName != ".." }
|
||||
check(children.isEmpty()) { "Folder is not empty" }
|
||||
share.rmdir(normalized, false)
|
||||
} else share.rm(normalized)
|
||||
}
|
||||
|
||||
fun openRange(path: String): RemoteRange {
|
||||
val file = share.openFile(normalize(path), EnumSet.of(AccessMask.GENERIC_READ),
|
||||
EnumSet.noneOf(FileAttributes::class.java), EnumSet.of(SMB2ShareAccess.FILE_SHARE_READ),
|
||||
SMB2CreateDisposition.FILE_OPEN, EnumSet.noneOf(SMB2CreateOptions::class.java))
|
||||
return RemoteRange(file)
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
share.close()
|
||||
session.close()
|
||||
@@ -143,6 +200,12 @@ class SmbShareSession(target: SmbTarget) : Closeable {
|
||||
}
|
||||
}
|
||||
|
||||
class RemoteRange(private val file: File) : Closeable {
|
||||
val length: Long get() = file.length
|
||||
fun read(buffer: ByteArray, offset: Long, count: Int): Int = file.read(buffer, offset, 0, count)
|
||||
override fun close() = file.close()
|
||||
}
|
||||
|
||||
private fun FileIdBothDirectoryInformation.toEntry() = RemoteEntry(
|
||||
fileName,
|
||||
fileAttributes.toInt() and 0x10 != 0,
|
||||
@@ -150,7 +213,7 @@ private fun FileIdBothDirectoryInformation.toEntry() = RemoteEntry(
|
||||
lastWriteTime.toEpochMillis(),
|
||||
)
|
||||
|
||||
private fun normalize(path: String): String {
|
||||
internal fun normalize(path: String): String {
|
||||
val parts = path.replace('/', '\\').split('\\').filter { it.isNotEmpty() && it != "." }
|
||||
require(parts.none { it == ".." }) { "Parent path segments are not allowed" }
|
||||
return parts.joinToString("\\")
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.graphics.ImageDecoder
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.nio.ByteBuffer
|
||||
import java.io.File
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** Small images only: avoids reading large originals just to render a list row. */
|
||||
@Composable
|
||||
fun Thumbnail(repository: BrowseRepository, shareId: String, path: String, entry: RemoteEntry) {
|
||||
if (entry.size !in 1..(8L * 1024 * 1024)) return
|
||||
val context = LocalContext.current
|
||||
var bitmap by remember(path, entry.size, entry.modifiedAt) { mutableStateOf<Bitmap?>(null) }
|
||||
LaunchedEffect(path, entry.size, entry.modifiedAt) {
|
||||
bitmap = runCatching {
|
||||
val digest = MessageDigest.getInstance("SHA-256").digest(
|
||||
"$shareId:$path:${entry.size}:${entry.modifiedAt}".toByteArray())
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
val directory = File(context.cacheDir, "thumbnails").apply { mkdirs() }
|
||||
val file = File(directory, "$digest.png")
|
||||
if (file.exists()) return@runCatching withContext(Dispatchers.IO) { BitmapFactory.decodeFile(file.path) }
|
||||
val bytes = repository.read(path, 8L * 1024 * 1024)
|
||||
val decoded = withContext(Dispatchers.Default) {
|
||||
ImageDecoder.decodeBitmap(ImageDecoder.createSource(ByteBuffer.wrap(bytes))) { decoder, info, _ ->
|
||||
val side = maxOf(info.size.width, info.size.height)
|
||||
decoder.setTargetSampleSize((side / 96).coerceAtLeast(1))
|
||||
}
|
||||
}
|
||||
withContext(Dispatchers.IO) {
|
||||
file.outputStream().use { decoded.compress(Bitmap.CompressFormat.PNG, 90, it) }
|
||||
val files = directory.listFiles().orEmpty().sortedBy { it.lastModified() }
|
||||
var total = files.sumOf { it.length() }
|
||||
for (old in files) if (total > 32L * 1024 * 1024) {
|
||||
total -= old.length()
|
||||
old.delete()
|
||||
}
|
||||
}
|
||||
decoded
|
||||
}.getOrNull()
|
||||
}
|
||||
bitmap?.let { Image(it.asImageBitmap(), contentDescription = null, modifier = Modifier.size(48.dp)) }
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
import android.net.Uri
|
||||
import android.os.CancellationSignal
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.os.storage.StorageManager
|
||||
import android.database.Cursor
|
||||
import android.provider.OpenableColumns
|
||||
import android.database.MatrixCursor
|
||||
import java.io.FileNotFoundException
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/** Grants a receiving player random reads without exposing SMB credentials in the URI. */
|
||||
class VideoStreamProvider : ContentProvider() {
|
||||
companion object {
|
||||
private const val AUTHORITY = "dev.alvin.smbexplorer.stream"
|
||||
private val grants = ConcurrentHashMap<String, Pair<SmbTarget, String>>()
|
||||
|
||||
fun grant(target: SmbTarget, path: String): Uri {
|
||||
if (grants.size >= 8) grants.clear()
|
||||
val token = UUID.randomUUID().toString()
|
||||
grants[token] = target to path
|
||||
return Uri.Builder().scheme("content").authority(AUTHORITY).appendPath(token)
|
||||
.appendPath(path.substringAfterLast('\\')).build()
|
||||
}
|
||||
|
||||
fun revoke(uri: Uri) { uri.pathSegments.firstOrNull()?.let(grants::remove) }
|
||||
}
|
||||
|
||||
private fun entry(uri: Uri) = uri.pathSegments.firstOrNull()?.let(grants::get)
|
||||
?: throw FileNotFoundException("Video grant expired")
|
||||
|
||||
override fun onCreate() = true
|
||||
override fun getType(uri: Uri): String = "video/*"
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
|
||||
selectionArgs: Array<out String>?, sortOrder: String?): Cursor {
|
||||
val (target, path) = entry(uri)
|
||||
val columns = projection?.toList() ?: listOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)
|
||||
val cursor = MatrixCursor(columns.toTypedArray())
|
||||
val size = SmbShareSession(target).use { session -> session.openRange(path).use { it.length } }
|
||||
cursor.addRow(columns.map<String, Any?> { column -> when (column) {
|
||||
OpenableColumns.DISPLAY_NAME -> path.substringAfterLast('\\')
|
||||
OpenableColumns.SIZE -> size
|
||||
else -> null
|
||||
} }.toTypedArray())
|
||||
return cursor
|
||||
}
|
||||
|
||||
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
|
||||
if (mode != "r") throw FileNotFoundException("Read only")
|
||||
val (target, path) = entry(uri)
|
||||
val session = SmbShareSession(target)
|
||||
val range = try { session.openRange(path) } catch (e: Exception) { session.close(); throw e }
|
||||
val storage = context?.getSystemService(StorageManager::class.java)
|
||||
?: throw FileNotFoundException("Storage manager unavailable")
|
||||
return try {
|
||||
storage.openProxyFileDescriptor(ParcelFileDescriptor.MODE_READ_ONLY,
|
||||
object : android.os.ProxyFileDescriptorCallback() {
|
||||
override fun onGetSize(): Long = range.length
|
||||
override fun onRead(offset: Long, size: Int, data: ByteArray): Int =
|
||||
if (offset >= range.length) 0 else range.read(data, offset, minOf(size.toLong(), range.length - offset).toInt())
|
||||
override fun onRelease() { range.close(); session.close() }
|
||||
}, null)
|
||||
} catch (e: Exception) {
|
||||
range.close(); session.close(); throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import android.net.Uri
|
||||
import android.content.Intent
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.app.Activity
|
||||
import android.content.pm.ActivityInfo
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.media3.common.MediaItem
|
||||
import androidx.media3.common.PlaybackException
|
||||
import androidx.media3.common.Player
|
||||
import androidx.media3.exoplayer.ExoPlayer
|
||||
import androidx.media3.exoplayer.source.ProgressiveMediaSource
|
||||
import androidx.media3.ui.PlayerView
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
|
||||
@UnstableApi
|
||||
@Composable
|
||||
fun VideoViewer(saved: SavedShare, path: String, onClose: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val activity = context as? Activity
|
||||
var landscape by remember { mutableStateOf(false) }
|
||||
val preferences = remember { context.getSharedPreferences("video_positions", 0) }
|
||||
val key = "${saved.id}:$path"
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
fun openExternal() {
|
||||
val uri = VideoStreamProvider.grant(saved.target, path)
|
||||
try {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW).apply {
|
||||
setDataAndType(uri, "video/*")
|
||||
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
})
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
VideoStreamProvider.revoke(uri)
|
||||
error = "No external video player is installed"
|
||||
}
|
||||
}
|
||||
val player = remember(saved.id, path) {
|
||||
ExoPlayer.Builder(context).build().apply {
|
||||
val source = ProgressiveMediaSource.Factory(SmbDataSource.Factory(saved.target, path))
|
||||
.createMediaSource(MediaItem.fromUri(Uri.parse("smbmedia://local/video")))
|
||||
setMediaSource(source)
|
||||
seekTo(preferences.getLong(key, 0L))
|
||||
prepare()
|
||||
playWhenReady = true
|
||||
}
|
||||
}
|
||||
DisposableEffect(player) {
|
||||
val listener = object : Player.Listener {
|
||||
override fun onPlayerError(failure: PlaybackException) {
|
||||
error = "Playback failed: ${failure.message ?: failure.errorCodeName}"
|
||||
}
|
||||
}
|
||||
player.addListener(listener)
|
||||
onDispose {
|
||||
activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
|
||||
preferences.edit().putLong(key, player.currentPosition).apply()
|
||||
player.removeListener(listener)
|
||||
player.release()
|
||||
}
|
||||
}
|
||||
BackHandler(onBack = onClose)
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
TextButton(onClick = onClose) { Text("‹ Folder") }
|
||||
Text(path.substringAfterLast('\\'))
|
||||
error?.let { Text(it) }
|
||||
TextButton(onClick = ::openExternal) { Text("Open in another player") }
|
||||
TextButton(onClick = {
|
||||
landscape = !landscape
|
||||
activity?.requestedOrientation = if (landscape) ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
|
||||
else ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
|
||||
}) { Text(if (landscape) "Portrait / auto" else "Landscape") }
|
||||
AndroidView(factory = { PlayerView(it).apply { this.player = player; useController = true } },
|
||||
modifier = Modifier.fillMaxWidth().weight(1f))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<data-extraction-rules xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<cloud-backup>
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="sharedpref" path="." />
|
||||
<exclude domain="file" path="." />
|
||||
<exclude domain="database" path="." />
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
@@ -0,0 +1,38 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class CopyStreamTest {
|
||||
@Test fun copiesExactLengthAndReportsProgress() {
|
||||
val source = byteArrayOf(1, 2, 3, 4, 5)
|
||||
val output = ByteArrayOutputStream()
|
||||
val progress = mutableListOf<Long>()
|
||||
copyExact(5, output, { buffer, offset ->
|
||||
val count = minOf(2, 5 - offset.toInt())
|
||||
source.copyInto(buffer, 0, offset.toInt(), offset.toInt() + count)
|
||||
count
|
||||
}) { done, total -> assertEquals(5L, total); progress += done }
|
||||
assertArrayEquals(source, output.toByteArray())
|
||||
assertEquals(listOf(2L, 4L, 5L), progress)
|
||||
}
|
||||
|
||||
@Test fun rejectsTruncatedSource() {
|
||||
assertThrows(IllegalStateException::class.java) {
|
||||
copyExact(3, ByteArrayOutputStream(), { _, _ -> 0 }) { _, _ -> }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun cancellationFromProgressStopsFurtherReads() {
|
||||
var reads = 0
|
||||
assertThrows(InterruptedException::class.java) {
|
||||
copyExact(4, ByteArrayOutputStream(), { buffer, _ -> reads++; buffer[0] = 1; 1 }) { _, _ ->
|
||||
throw InterruptedException()
|
||||
}
|
||||
}
|
||||
assertEquals(1, reads)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package dev.alvin.smbexplorer
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertThrows
|
||||
import org.junit.Test
|
||||
|
||||
class RemotePathTest {
|
||||
@Test fun normalizesMixedSeparatorsAndCurrentDirectory() {
|
||||
assertEquals("photos\\2026\\image.jpg", normalize("/photos/./2026\\image.jpg"))
|
||||
}
|
||||
|
||||
@Test fun refusesParentTraversalBeforeMutation() {
|
||||
assertThrows(IllegalArgumentException::class.java) { normalize("photos/../private") }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user