generated from ali/HarmonyTemplate
提交 Haven Android 仓库源码 v5.87.79
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.hilt)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "sh.haven.core.rclone"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 26
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
}
|
||||
|
||||
// Include native libraries built from Go source by rclone-android:buildRcloneNative
|
||||
sourceSets {
|
||||
getByName("main") {
|
||||
jniLibs.srcDirs("${rootProject.projectDir}/rclone-android/jniLibs")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure Go native library is built before this module compiles
|
||||
tasks.configureEach {
|
||||
if (name == "preBuild") {
|
||||
dependsOn(gradle.includedBuild("rclone-android").task(":buildRcloneNative"))
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api("sh.haven:rclone-transport:0.1.0")
|
||||
implementation(project(":core:data"))
|
||||
implementation(libs.coroutines.core)
|
||||
implementation(libs.coroutines.android)
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.compiler)
|
||||
|
||||
testImplementation(libs.junit)
|
||||
testImplementation("org.json:json:20260814")
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,615 @@
|
||||
package sh.haven.core.rclone
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import sh.haven.rclone.bridge.RcloneBridge
|
||||
import java.io.File
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
private const val TAG = "RcloneClient"
|
||||
|
||||
/**
|
||||
* High-level Kotlin API over rclone's RC (Remote Control) JSON-RPC interface.
|
||||
* All methods are blocking and should be called from a background thread.
|
||||
*/
|
||||
@Singleton
|
||||
class RcloneClient @Inject constructor(
|
||||
@ApplicationContext private val context: Context,
|
||||
) {
|
||||
private var initialized = false
|
||||
|
||||
/** Initialize the rclone library. Safe to call multiple times. */
|
||||
fun initialize() {
|
||||
if (initialized) return
|
||||
val configDir = File(context.filesDir, "rclone")
|
||||
configDir.mkdirs()
|
||||
val configPath = File(configDir, "rclone.conf").absolutePath
|
||||
RcloneBridge.initialize(configPath)
|
||||
initialized = true
|
||||
Log.d(TAG, "Initialized with config: $configPath")
|
||||
}
|
||||
|
||||
/** Shut down the rclone library. */
|
||||
fun shutdown() {
|
||||
if (!initialized) return
|
||||
RcloneBridge.shutdown()
|
||||
initialized = false
|
||||
}
|
||||
|
||||
/**
|
||||
* Route outgoing rclone HTTP traffic through [socksUrl]
|
||||
* (e.g. `socks5://127.0.0.1:41234`) — typically the localhost SOCKS5
|
||||
* listener of one of Haven's per-profile WireGuard / Tailscale
|
||||
* tunnels (#149). Pass null to clear and route direct.
|
||||
*
|
||||
* Caveat: rclone caches HTTP clients per-fs, so this only reliably
|
||||
* affects fs instances created AFTER the call. The per-profile
|
||||
* connect path sets it before the first RPC for the profile.
|
||||
*/
|
||||
fun setProxy(socksUrl: String?) {
|
||||
RcloneBridge.setProxy(socksUrl)
|
||||
}
|
||||
|
||||
// ── Config operations ───────────────────────────────────────────────
|
||||
|
||||
/** List all configured remote names. */
|
||||
fun listRemotes(): List<String> {
|
||||
val result = rpc("config/listremotes")
|
||||
val remotes = result.optJSONArray("remotes") ?: return emptyList()
|
||||
return (0 until remotes.length()).map { remotes.getString(it) }
|
||||
}
|
||||
|
||||
/** Get configuration for a specific remote. */
|
||||
fun getRemoteConfig(name: String): Map<String, String> {
|
||||
val result = rpc("config/get", JSONObject().put("name", name))
|
||||
val map = mutableMapOf<String, String>()
|
||||
result.keys().forEach { key -> map[key] = result.optString(key, "") }
|
||||
return map
|
||||
}
|
||||
|
||||
/** List available provider types with their metadata. */
|
||||
fun listProviders(): List<ProviderInfo> {
|
||||
val result = rpc("config/providers")
|
||||
val providers = result.optJSONArray("providers") ?: return emptyList()
|
||||
return (0 until providers.length()).map { i ->
|
||||
val p = providers.getJSONObject(i)
|
||||
ProviderInfo(
|
||||
name = p.getString("Name"),
|
||||
description = p.getString("Description"),
|
||||
prefix = p.optString("Prefix", ""),
|
||||
options = parseOptions(p.optJSONArray("Options")),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new remote configuration.
|
||||
*
|
||||
* For OAuth providers, this initiates the OAuth flow. The returned
|
||||
* [ConfigState] may contain an [ConfigState.authUrl] that needs to be
|
||||
* opened in a browser.
|
||||
*/
|
||||
fun createRemote(
|
||||
name: String,
|
||||
type: String,
|
||||
parameters: Map<String, String> = emptyMap(),
|
||||
/**
|
||||
* Skip rclone's password-field obscuring. Set when [parameters] already
|
||||
* hold final (obscured) values — e.g. importing an existing rclone.conf
|
||||
* section (#251) — so passwords aren't double-obscured.
|
||||
*/
|
||||
noObscure: Boolean = false,
|
||||
/**
|
||||
* Run rclone's config in non-interactive mode. Required when creating a
|
||||
* remote with no user present to answer prompts — notably importing an
|
||||
* existing OAuth remote (drive/dropbox/onedrive/box/pcloud) whose token
|
||||
* is already in [parameters]: without this, `config/create` enters the
|
||||
* OAuth state machine and blocks the (JNI, non-cancellable) rpc call, so
|
||||
* the import dialog hangs forever (#269). Non-interactive makes it return
|
||||
* the state immediately instead of waiting on the browser flow.
|
||||
*/
|
||||
nonInteractive: Boolean = false,
|
||||
): ConfigState {
|
||||
val params = JSONObject()
|
||||
params.put("name", name)
|
||||
params.put("type", type)
|
||||
params.put("parameters", JSONObject(parameters))
|
||||
if (noObscure || nonInteractive) {
|
||||
params.put("opt", JSONObject().apply {
|
||||
if (noObscure) put("noObscure", true)
|
||||
if (nonInteractive) put("nonInteractive", true)
|
||||
})
|
||||
}
|
||||
val result = rpc("config/create", params)
|
||||
return parseConfigState(result)
|
||||
}
|
||||
|
||||
/** Update an existing remote's configuration. */
|
||||
fun updateRemote(name: String, parameters: Map<String, String>) {
|
||||
val params = JSONObject()
|
||||
params.put("name", name)
|
||||
params.put("parameters", JSONObject(parameters))
|
||||
rpc("config/update", params)
|
||||
}
|
||||
|
||||
/** Delete a remote configuration. */
|
||||
fun deleteRemote(name: String) {
|
||||
rpc("config/delete", JSONObject().put("name", name))
|
||||
}
|
||||
|
||||
// ── File operations ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* List entries in a directory.
|
||||
*
|
||||
* @param remote remote name (e.g. "gdrive")
|
||||
* @param path directory path within the remote (e.g. "/" or "Documents")
|
||||
*/
|
||||
fun listDirectory(remote: String, path: String): List<RcloneFileEntry> {
|
||||
val params = JSONObject()
|
||||
params.put("fs", "$remote:")
|
||||
params.put("remote", path.trimStart('/'))
|
||||
// Request per-file metadata so backends that carry a unix mode (sftp,
|
||||
// local) report real permissions instead of a generic default (#413).
|
||||
// Backends without metadata simply omit it; we fall back accordingly.
|
||||
params.put("opt", JSONObject().put("metadata", true))
|
||||
val result = rpc("operations/list", params)
|
||||
val list = result.optJSONArray("list") ?: return emptyList()
|
||||
return (0 until list.length()).map { i ->
|
||||
val item = list.getJSONObject(i)
|
||||
RcloneFileEntry(
|
||||
name = item.getString("Name"),
|
||||
path = item.getString("Path"),
|
||||
size = item.optLong("Size", 0),
|
||||
mimeType = item.optString("MimeType", ""),
|
||||
modTime = item.optString("ModTime", ""),
|
||||
isDir = item.optBoolean("IsDir", false),
|
||||
// rclone renders the mode as an octal string (e.g. "100644").
|
||||
// Only the low bits matter; the type char comes from IsDir.
|
||||
mode = item.optJSONObject("Metadata")
|
||||
?.optString("mode", "")
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
?.toIntOrNull(8),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Create a directory. */
|
||||
fun mkdir(remote: String, path: String) {
|
||||
val params = JSONObject()
|
||||
params.put("fs", "$remote:")
|
||||
params.put("remote", path.trimStart('/'))
|
||||
rpc("operations/mkdir", params)
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a single file between remotes or within a remote.
|
||||
*
|
||||
* For local filesystem paths, pass the absolute directory as the remote
|
||||
* and the filename as the path (e.g. srcRemote="/data/.../cache", srcPath="file.txt").
|
||||
* For cloud remotes, pass the remote name (e.g. "gdrive") and the full path.
|
||||
*/
|
||||
fun copyFile(
|
||||
srcRemote: String, srcPath: String,
|
||||
dstRemote: String, dstPath: String,
|
||||
) {
|
||||
val params = JSONObject()
|
||||
// Local paths (absolute) don't get a colon suffix; named remotes do
|
||||
params.put("srcFs", if (srcRemote.startsWith("/")) srcRemote else "$srcRemote:")
|
||||
params.put("srcRemote", srcPath.trimStart('/'))
|
||||
params.put("dstFs", if (dstRemote.startsWith("/")) dstRemote else "$dstRemote:")
|
||||
params.put("dstRemote", dstPath.trimStart('/'))
|
||||
rpc("operations/copyfile", params)
|
||||
}
|
||||
|
||||
/** Delete a single file. */
|
||||
fun deleteFile(remote: String, path: String) {
|
||||
val params = JSONObject()
|
||||
params.put("fs", "$remote:")
|
||||
params.put("remote", path.trimStart('/'))
|
||||
rpc("operations/deletefile", params)
|
||||
}
|
||||
|
||||
/** Delete a directory and all its contents. */
|
||||
fun deleteDir(remote: String, path: String) {
|
||||
val params = JSONObject()
|
||||
params.put("fs", "$remote:")
|
||||
params.put("remote", path.trimStart('/'))
|
||||
rpc("operations/purge", params)
|
||||
}
|
||||
|
||||
/** Get information about the remote (total/used/free space). */
|
||||
fun about(remote: String): RemoteInfo {
|
||||
val result = rpc("operations/about", JSONObject().put("fs", "$remote:"))
|
||||
return RemoteInfo(
|
||||
total = result.optLong("total", -1),
|
||||
used = result.optLong("used", -1),
|
||||
free = result.optLong("free", -1),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Move (rename) a single file within or between remotes.
|
||||
*
|
||||
* For local paths, pass the absolute directory as the remote.
|
||||
* For cloud remotes, pass the remote name (e.g. "gdrive").
|
||||
*/
|
||||
fun moveFile(
|
||||
srcRemote: String, srcPath: String,
|
||||
dstRemote: String, dstPath: String,
|
||||
) {
|
||||
val params = JSONObject()
|
||||
params.put("srcFs", if (srcRemote.startsWith("/")) srcRemote else "$srcRemote:")
|
||||
params.put("srcRemote", srcPath.trimStart('/'))
|
||||
params.put("dstFs", if (dstRemote.startsWith("/")) dstRemote else "$dstRemote:")
|
||||
params.put("dstRemote", dstPath.trimStart('/'))
|
||||
rpc("operations/movefile", params)
|
||||
}
|
||||
|
||||
/** Generate a public link for a file or directory. */
|
||||
fun publicLink(remote: String, path: String): String {
|
||||
val params = JSONObject()
|
||||
params.put("fs", "$remote:")
|
||||
params.put("remote", path.trimStart('/'))
|
||||
val result = rpc("operations/publiclink", params)
|
||||
return result.getString("url")
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate total size of a directory tree.
|
||||
*
|
||||
* Uses operations/list with recurse + filesOnly + stripped metadata instead of
|
||||
* operations/size, which can be very slow on some backends due to per-file stat calls.
|
||||
* Also enables fast-list (UseListR) for backends that support single-call recursive listing.
|
||||
*/
|
||||
fun directorySize(remote: String, path: String): DirectorySize {
|
||||
val params = JSONObject()
|
||||
params.put("fs", "$remote:")
|
||||
params.put("remote", path.trimStart('/'))
|
||||
params.put("opt", JSONObject().apply {
|
||||
put("recurse", true)
|
||||
put("filesOnly", true)
|
||||
put("noModTime", true)
|
||||
put("noMimeType", true)
|
||||
})
|
||||
params.put("_config", JSONObject().put("UseListR", true))
|
||||
val result = rpc("operations/list", params)
|
||||
val list = result.optJSONArray("list") ?: return DirectorySize(0, 0)
|
||||
var totalBytes = 0L
|
||||
for (i in 0 until list.length()) {
|
||||
totalBytes += list.getJSONObject(i).optLong("Size", 0)
|
||||
}
|
||||
return DirectorySize(count = list.length().toLong(), bytes = totalBytes)
|
||||
}
|
||||
|
||||
// ── Remote capabilities ────────────────────────────────────────────
|
||||
|
||||
private val capabilitiesCache = mutableMapOf<String, RemoteCapabilities>()
|
||||
|
||||
/** Query what features a remote supports. Cached per remote name. */
|
||||
fun getCapabilities(remote: String): RemoteCapabilities {
|
||||
capabilitiesCache[remote]?.let { return it }
|
||||
val result = rpc("operations/fsinfo", JSONObject().put("fs", "$remote:"))
|
||||
val features = result.optJSONObject("Features") ?: return RemoteCapabilities()
|
||||
val caps = RemoteCapabilities(
|
||||
publicLink = features.optBoolean("PublicLink", false),
|
||||
move = features.optBoolean("Move", false),
|
||||
copy = features.optBoolean("Copy", false),
|
||||
purge = features.optBoolean("Purge", false),
|
||||
about = features.optBoolean("About", false),
|
||||
)
|
||||
capabilitiesCache[remote] = caps
|
||||
return caps
|
||||
}
|
||||
|
||||
// ── Transfer stats ──────────────────────────────────────────────────
|
||||
|
||||
/** Get current transfer statistics. */
|
||||
fun getStats(): TransferStats {
|
||||
val result = rpc("core/stats")
|
||||
return TransferStats(
|
||||
bytes = result.optLong("bytes", 0),
|
||||
totalBytes = result.optLong("totalBytes", 0),
|
||||
speed = result.optDouble("speed", 0.0),
|
||||
transfers = result.optInt("transfers", 0),
|
||||
totalTransfers = result.optInt("totalTransfers", 0),
|
||||
errors = result.optInt("errors", 0),
|
||||
deletes = result.optInt("deletes", 0),
|
||||
deletedDirs = result.optInt("deletedDirs", 0),
|
||||
lastError = result.optString("lastError", ""),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-file errors from rclone's completed-transfer list (`core/transferred`).
|
||||
* `core/stats.lastError` is only rclone's bare error string — the object name
|
||||
* lives in rclone's log line, never in the stats fields — so a failed sync's
|
||||
* connection-log entry couldn't name the offending file. Each `transferred`
|
||||
* entry carries both `name` and `error`, so this recovers `<file>: <error>`
|
||||
* for the audit log (#157).
|
||||
*
|
||||
* Read without a stats group, matching [getStats]/[resetStats] which also act
|
||||
* on the global accounting that async jobs aggregate into. Returns only the
|
||||
* entries that actually errored; empty on any RPC failure.
|
||||
*/
|
||||
fun getErroredTransfers(): List<TransferError> {
|
||||
if (!initialized) return emptyList()
|
||||
return try {
|
||||
val arr = rpc("core/transferred").optJSONArray("transferred")
|
||||
?: return emptyList()
|
||||
buildList {
|
||||
for (i in 0 until arr.length()) {
|
||||
val o = arr.optJSONObject(i) ?: continue
|
||||
val err = o.optString("error", "")
|
||||
if (err.isNotEmpty()) {
|
||||
add(TransferError(name = o.optString("name", ""), error = err))
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "core/transferred failed: ${e.message}")
|
||||
emptyList()
|
||||
}
|
||||
}
|
||||
|
||||
// ── Sync operations ──────────────────────────────────────────────
|
||||
|
||||
/** Active sync job ID, stored here (singleton) so it survives ViewModel recreation. */
|
||||
@Volatile
|
||||
var activeSyncJobId: Long? = null
|
||||
|
||||
/**
|
||||
* Start an async rclone sync/copy/move operation.
|
||||
* Returns the job ID for status polling.
|
||||
*/
|
||||
fun startSync(config: SyncConfig): Long {
|
||||
check(initialized) { "RcloneClient.initialize() must be called first" }
|
||||
val params = JSONObject()
|
||||
params.put("srcFs", config.srcFs)
|
||||
params.put("dstFs", config.dstFs)
|
||||
params.put("_async", true)
|
||||
|
||||
// Build filter object
|
||||
val filters = config.filters
|
||||
if (filters.includePatterns.isNotEmpty() || filters.excludePatterns.isNotEmpty()
|
||||
|| filters.minSize != null || filters.maxSize != null
|
||||
) {
|
||||
val filterObj = JSONObject()
|
||||
if (filters.includePatterns.isNotEmpty()) {
|
||||
filterObj.put("IncludeRule", org.json.JSONArray(filters.includePatterns))
|
||||
}
|
||||
if (filters.excludePatterns.isNotEmpty()) {
|
||||
filterObj.put("ExcludeRule", org.json.JSONArray(filters.excludePatterns))
|
||||
}
|
||||
filters.minSize?.let { filterObj.put("MinSize", it) }
|
||||
filters.maxSize?.let { filterObj.put("MaxSize", it) }
|
||||
params.put("_filter", filterObj)
|
||||
}
|
||||
|
||||
// Build config object (dry run, bandwidth limit)
|
||||
if (config.dryRun || filters.bandwidthLimit != null) {
|
||||
val configObj = JSONObject()
|
||||
if (config.dryRun) configObj.put("DryRun", true)
|
||||
filters.bandwidthLimit?.let { configObj.put("BwLimit", it) }
|
||||
params.put("_config", configObj)
|
||||
}
|
||||
|
||||
val result = rpc(config.mode.rcMethod, params)
|
||||
val jobId = result.getLong("jobid")
|
||||
activeSyncJobId = jobId
|
||||
return jobId
|
||||
}
|
||||
|
||||
/** Query the status of an async rclone job. */
|
||||
fun getJobStatus(jobId: Long): SyncJobStatus {
|
||||
check(initialized) { "RcloneClient.initialize() must be called first" }
|
||||
val result = rpc("job/status", JSONObject().put("jobid", jobId))
|
||||
return SyncJobStatus(
|
||||
jobId = jobId,
|
||||
finished = result.optBoolean("finished", false),
|
||||
success = result.optBoolean("success", false),
|
||||
error = result.optString("error", "").ifEmpty { null },
|
||||
duration = result.optDouble("duration", 0.0),
|
||||
)
|
||||
}
|
||||
|
||||
/** Cancel a running async rclone job. */
|
||||
fun cancelJob(jobId: Long) {
|
||||
check(initialized) { "RcloneClient.initialize() must be called first" }
|
||||
try {
|
||||
rpc("job/stop", JSONObject().put("jobid", jobId))
|
||||
} catch (_: Exception) {
|
||||
// Job may already be finished
|
||||
}
|
||||
if (activeSyncJobId == jobId) activeSyncJobId = null
|
||||
}
|
||||
|
||||
/** Reset global transfer statistics (call before starting a new sync). */
|
||||
fun resetStats() {
|
||||
if (!initialized) return
|
||||
try {
|
||||
rpc("core/stats-reset", JSONObject())
|
||||
} catch (_: Exception) {
|
||||
// Not critical
|
||||
}
|
||||
}
|
||||
|
||||
// ── Media server ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Start a local HTTP server that streams files from the given remote
|
||||
* via rclone VFS. Returns the port number the server is listening on.
|
||||
* The server binds to 127.0.0.1 (loopback only).
|
||||
*/
|
||||
fun startMediaServer(remote: String, preferredPort: Int = 0): Int {
|
||||
check(initialized) { "RcloneClient.initialize() must be called first" }
|
||||
val result = RcloneBridge.startMediaServer(remote, preferredPort.toLong())
|
||||
if (!result.isOk) {
|
||||
val error = try {
|
||||
JSONObject(result.output).optString("error", result.output)
|
||||
} catch (_: Exception) {
|
||||
result.output
|
||||
}
|
||||
throw RcloneException("startMediaServer", result.status, error)
|
||||
}
|
||||
return JSONObject(result.output).getInt("port")
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current media server port for the given remote, or null if not running.
|
||||
* Does not start a new server.
|
||||
*/
|
||||
fun mediaServerPort(remote: String): Int? {
|
||||
if (!initialized) return null
|
||||
val result = RcloneBridge.mediaServerStatus()
|
||||
if (!result.isOk) return null
|
||||
val json = JSONObject(result.output)
|
||||
val port = json.optInt("port", 0)
|
||||
if (port == 0) return null
|
||||
val running = json.optString("remote", "")
|
||||
return if (running == remote) port else null
|
||||
}
|
||||
|
||||
/** Stop the local media streaming HTTP server if running. */
|
||||
fun stopMediaServer() {
|
||||
if (!initialized) return
|
||||
RcloneBridge.stopMediaServer()
|
||||
}
|
||||
|
||||
// ── DLNA server ──────────────────────────────────────────────────
|
||||
|
||||
@Volatile
|
||||
var activeDlnaServerId: String? = null
|
||||
|
||||
/**
|
||||
* Start a DLNA media server for the given remote.
|
||||
* Requires the `cmd/serve/dlna` import in the Go bridge.
|
||||
* Returns the server ID for later stopping.
|
||||
*/
|
||||
fun startDlnaServer(remote: String, friendlyName: String = "Haven"): String {
|
||||
check(initialized) { "RcloneClient.initialize() must be called first" }
|
||||
val params = JSONObject()
|
||||
params.put("type", "dlna")
|
||||
params.put("fs", "$remote:")
|
||||
params.put("opt", JSONObject().put("name", friendlyName))
|
||||
val result = rpc("serve/start", params)
|
||||
val id = result.getString("id")
|
||||
activeDlnaServerId = id
|
||||
return id
|
||||
}
|
||||
|
||||
/** Stop the DLNA media server if running. */
|
||||
fun stopDlnaServer() {
|
||||
val id = activeDlnaServerId ?: return
|
||||
try {
|
||||
rpc("serve/stop", JSONObject().put("id", id))
|
||||
} catch (_: Exception) {
|
||||
// Server may already be stopped
|
||||
}
|
||||
activeDlnaServerId = null
|
||||
}
|
||||
|
||||
/** Check whether the DLNA server is still running. */
|
||||
fun dlnaServerStatus(): Boolean {
|
||||
val id = activeDlnaServerId ?: return false
|
||||
return try {
|
||||
val result = rpc("serve/list")
|
||||
val list = result.optJSONArray("list") ?: return false
|
||||
(0 until list.length()).any {
|
||||
list.getJSONObject(it).optString("id") == id
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// ── Internal ────────────────────────────────────────────────────────
|
||||
|
||||
private fun rpc(method: String, params: JSONObject = JSONObject()): JSONObject {
|
||||
check(initialized) { "RcloneClient.initialize() must be called first" }
|
||||
val result = RcloneBridge.rpc(method, params.toString())
|
||||
if (!result.isOk) {
|
||||
val error = try {
|
||||
JSONObject(result.output).optString("error", result.output)
|
||||
} catch (_: Exception) {
|
||||
result.output
|
||||
}
|
||||
Log.w(TAG, "RPC $method failed (${result.status}): $error")
|
||||
throw RcloneException(method, result.status, error)
|
||||
}
|
||||
return try {
|
||||
JSONObject(result.output)
|
||||
} catch (_: Exception) {
|
||||
JSONObject()
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseOptions(arr: JSONArray?): List<ProviderOption> {
|
||||
if (arr == null) return emptyList()
|
||||
return (0 until arr.length()).map { i ->
|
||||
val o = arr.getJSONObject(i)
|
||||
ProviderOption(
|
||||
name = o.getString("Name"),
|
||||
help = o.optString("Help", ""),
|
||||
provider = o.optString("Provider", ""),
|
||||
default = scalarDefault(o),
|
||||
required = o.optBoolean("Required", false),
|
||||
isPassword = o.optBoolean("IsPassword", false),
|
||||
advanced = o.optBoolean("Advanced", false),
|
||||
type = o.optString("Type", "string"),
|
||||
examples = parseExamples(o.optJSONArray("Examples")),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseExamples(arr: JSONArray?): List<ProviderOptionExample> {
|
||||
if (arr == null) return emptyList()
|
||||
return (0 until arr.length()).map { i ->
|
||||
val e = arr.getJSONObject(i)
|
||||
ProviderOptionExample(
|
||||
value = e.optString("Value", ""),
|
||||
help = e.optString("Help", ""),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseConfigState(json: JSONObject): ConfigState {
|
||||
return ConfigState(
|
||||
state = json.optString("State", ""),
|
||||
option = json.optJSONObject("Option")?.let { opt ->
|
||||
ConfigOption(
|
||||
name = opt.optString("Name", ""),
|
||||
help = opt.optString("Help", ""),
|
||||
default = scalarDefault(opt),
|
||||
required = opt.optBoolean("Required", false),
|
||||
isPassword = opt.optBoolean("IsPassword", false),
|
||||
type = opt.optString("Type", ""),
|
||||
)
|
||||
},
|
||||
error = json.optString("error", ""),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an rclone option's `Default` as a scalar string. rclone returns list/map
|
||||
* defaults as JSON (`[]` / `{}`); `optString` would coerce those to the literal
|
||||
* "[]"/"{}", which then pre-fills the field and gets sent back as a bogus value,
|
||||
* breaking config verification (#295). Only scalar defaults (string/number/bool)
|
||||
* are real values; anything else (array, object, JSON null, absent) becomes "".
|
||||
*/
|
||||
internal fun scalarDefault(o: JSONObject): String =
|
||||
o.opt("Default").let { dv ->
|
||||
if (dv == null || dv == JSONObject.NULL || dv is JSONArray || dv is JSONObject) ""
|
||||
else dv.toString()
|
||||
}
|
||||
|
||||
class RcloneException(
|
||||
val method: String,
|
||||
val statusCode: Int,
|
||||
val error: String,
|
||||
) : Exception("rclone $method failed ($statusCode): $error")
|
||||
@@ -0,0 +1,69 @@
|
||||
package sh.haven.core.rclone
|
||||
|
||||
/** One remote section parsed from an `rclone.conf` file (#251). */
|
||||
data class ParsedRemote(
|
||||
val name: String,
|
||||
/** rclone backend type, e.g. "drive", "s3". Empty if the section had no `type`. */
|
||||
val type: String,
|
||||
/** Remaining config keys verbatim (already-obscured secrets included). */
|
||||
val params: Map<String, String>,
|
||||
)
|
||||
|
||||
/** Outcome of parsing an `rclone.conf` (#251). */
|
||||
sealed interface RcloneConfigParseResult {
|
||||
data class Success(val remotes: List<ParsedRemote>) : RcloneConfigParseResult
|
||||
|
||||
/**
|
||||
* The file is a password-encrypted rclone config (`RCLONE_ENCRYPT_V0`).
|
||||
* We can't import it without the config password, which v1 doesn't ask for.
|
||||
*/
|
||||
data object Encrypted : RcloneConfigParseResult
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the standard INI-shaped `rclone.conf` so a user can import their
|
||||
* Linux remotes into Haven without re-configuring them (#251).
|
||||
*
|
||||
* Single-line `key = value` only — which is all rclone writes; OAuth tokens
|
||||
* sit on one line as raw JSON, so we split on the FIRST `=` to keep values
|
||||
* (base64, `=`-padded tokens) intact. Values are copied verbatim, including
|
||||
* already-obscured passwords, so the import must create remotes with
|
||||
* `noObscure` to avoid double-obscuring.
|
||||
*/
|
||||
object RcloneConfigParser {
|
||||
|
||||
fun parse(text: String): RcloneConfigParseResult {
|
||||
val remotes = mutableListOf<ParsedRemote>()
|
||||
var name: String? = null
|
||||
var type = ""
|
||||
var params = mutableMapOf<String, String>()
|
||||
|
||||
fun flush() {
|
||||
name?.let { remotes += ParsedRemote(it, type, params) }
|
||||
name = null
|
||||
type = ""
|
||||
params = mutableMapOf()
|
||||
}
|
||||
|
||||
for (raw in text.lineSequence()) {
|
||||
val line = raw.trim()
|
||||
if (line.isEmpty()) continue
|
||||
if (line.startsWith("#") || line.startsWith(";")) continue
|
||||
if (line.startsWith("RCLONE_ENCRYPT_V0")) return RcloneConfigParseResult.Encrypted
|
||||
|
||||
if (line.startsWith("[") && line.endsWith("]")) {
|
||||
flush()
|
||||
name = line.substring(1, line.length - 1).trim()
|
||||
continue
|
||||
}
|
||||
|
||||
val eq = line.indexOf('=')
|
||||
if (eq <= 0 || name == null) continue // stray line outside a section, or no key
|
||||
val key = line.substring(0, eq).trim()
|
||||
val value = line.substring(eq + 1).trim()
|
||||
if (key.equals("type", ignoreCase = true)) type = value else params[key] = value
|
||||
}
|
||||
flush()
|
||||
return RcloneConfigParseResult.Success(remotes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package sh.haven.core.rclone
|
||||
|
||||
/**
|
||||
* rclone providers Haven configures via the OAuth browser flow — the token is
|
||||
* obtained interactively, with no credentials typed up front. Every other
|
||||
* provider is treated as a CREDENTIALS provider: its required options are
|
||||
* collected in the connection editor and written via `config/create` (#181,
|
||||
* e.g. Filen needs email/password/api_key; also unblocks s3/b2/mega/sftp/…).
|
||||
*/
|
||||
val RCLONE_OAUTH_PROVIDERS: Set<String> = setOf("drive", "dropbox", "onedrive", "box", "pcloud")
|
||||
|
||||
/** Metadata about an rclone storage provider (e.g. Google Drive, S3). */
|
||||
data class ProviderInfo(
|
||||
/** Internal name, e.g. "drive", "s3", "dropbox". */
|
||||
val name: String,
|
||||
/** Human-readable description. */
|
||||
val description: String,
|
||||
/** Prefix for this provider's environment variables. */
|
||||
val prefix: String,
|
||||
/** Configuration options supported by this provider. */
|
||||
val options: List<ProviderOption>,
|
||||
)
|
||||
|
||||
/** A single configuration option for a provider. */
|
||||
data class ProviderOption(
|
||||
val name: String,
|
||||
val help: String,
|
||||
val provider: String,
|
||||
val default: String,
|
||||
val required: Boolean,
|
||||
val isPassword: Boolean,
|
||||
val advanced: Boolean,
|
||||
val type: String,
|
||||
val examples: List<ProviderOptionExample>,
|
||||
)
|
||||
|
||||
/** Example value for a provider option (shown in dropdowns). */
|
||||
data class ProviderOptionExample(
|
||||
val value: String,
|
||||
val help: String,
|
||||
)
|
||||
|
||||
/** A file or directory entry returned by rclone's operations/list. */
|
||||
data class RcloneFileEntry(
|
||||
val name: String,
|
||||
val path: String,
|
||||
val size: Long,
|
||||
val mimeType: String,
|
||||
val modTime: String,
|
||||
val isDir: Boolean,
|
||||
/**
|
||||
* Unix permission bits parsed from rclone's per-file `Metadata.mode`
|
||||
* (octal), or null when the backend exposes no unix mode (most cloud
|
||||
* remotes). Only the low 12 bits (rwx + setuid/setgid/sticky) are
|
||||
* meaningful; the type is taken from [isDir].
|
||||
*/
|
||||
val mode: Int? = null,
|
||||
)
|
||||
|
||||
/** Space usage information for a remote. */
|
||||
data class RemoteInfo(
|
||||
val total: Long,
|
||||
val used: Long,
|
||||
val free: Long,
|
||||
)
|
||||
|
||||
/** Current transfer statistics. */
|
||||
data class TransferStats(
|
||||
val bytes: Long,
|
||||
val totalBytes: Long,
|
||||
val speed: Double,
|
||||
val transfers: Int,
|
||||
val totalTransfers: Int,
|
||||
val errors: Int,
|
||||
val deletes: Int = 0,
|
||||
val deletedDirs: Int = 0,
|
||||
/**
|
||||
* Last per-file error message rclone recorded (empty string when no
|
||||
* error has occurred). Surfaced from `core/stats.lastError` so the
|
||||
* connection log can tell the user *which file* caused a sync
|
||||
* suppression rather than just "1 error" (#158).
|
||||
*/
|
||||
val lastError: String = "",
|
||||
) {
|
||||
val fraction: Float
|
||||
get() = if (totalBytes > 0) (bytes.toFloat() / totalBytes).coerceIn(0f, 1f) else 0f
|
||||
}
|
||||
|
||||
/**
|
||||
* A single completed transfer that rclone recorded as failed, read from the
|
||||
* `core/transferred` rc call. Unlike [TransferStats.lastError] (rclone's bare
|
||||
* error string with no path), each entry carries the object [name], so the
|
||||
* connection log can name the offending file (#157).
|
||||
*/
|
||||
data class TransferError(
|
||||
val name: String,
|
||||
val error: String,
|
||||
)
|
||||
|
||||
/** State returned by config/create during interactive configuration. */
|
||||
data class ConfigState(
|
||||
val state: String,
|
||||
val option: ConfigOption?,
|
||||
val error: String,
|
||||
) {
|
||||
/** Extract an OAuth URL from the option help text, if present. */
|
||||
val authUrl: String?
|
||||
get() = option?.help?.let { help ->
|
||||
val urlRegex = Regex("""https?://\S+""")
|
||||
urlRegex.find(help)?.value
|
||||
}
|
||||
}
|
||||
|
||||
/** A configuration question requiring user input. */
|
||||
data class ConfigOption(
|
||||
val name: String,
|
||||
val help: String,
|
||||
val default: String,
|
||||
val required: Boolean,
|
||||
val isPassword: Boolean,
|
||||
val type: String,
|
||||
)
|
||||
|
||||
// ── Remote capabilities ─────────────────────────────────────────────
|
||||
|
||||
/** Feature flags for a remote, from operations/fsinfo. */
|
||||
data class RemoteCapabilities(
|
||||
val publicLink: Boolean = false,
|
||||
val move: Boolean = false,
|
||||
val copy: Boolean = false,
|
||||
val purge: Boolean = false,
|
||||
val about: Boolean = false,
|
||||
)
|
||||
|
||||
/** Size of a directory tree, from operations/size. */
|
||||
data class DirectorySize(
|
||||
val count: Long,
|
||||
val bytes: Long,
|
||||
)
|
||||
|
||||
// ── Sync operations ─────────────────────────────────────────────────
|
||||
|
||||
enum class SyncMode(val rcMethod: String, val label: String) {
|
||||
COPY("sync/copy", "Copy"),
|
||||
SYNC("sync/sync", "Sync"),
|
||||
MOVE("sync/move", "Move"),
|
||||
}
|
||||
|
||||
data class SyncFilters(
|
||||
val includePatterns: List<String> = emptyList(),
|
||||
val excludePatterns: List<String> = emptyList(),
|
||||
val minSize: String? = null,
|
||||
val maxSize: String? = null,
|
||||
val bandwidthLimit: String? = null,
|
||||
)
|
||||
|
||||
data class SyncConfig(
|
||||
val srcFs: String,
|
||||
val dstFs: String,
|
||||
val mode: SyncMode,
|
||||
val filters: SyncFilters = SyncFilters(),
|
||||
val dryRun: Boolean = false,
|
||||
)
|
||||
|
||||
data class SyncJobStatus(
|
||||
val jobId: Long,
|
||||
val finished: Boolean,
|
||||
val success: Boolean,
|
||||
val error: String?,
|
||||
val duration: Double,
|
||||
)
|
||||
|
||||
data class SyncProgress(
|
||||
val jobId: Long,
|
||||
val mode: SyncMode,
|
||||
val bytes: Long,
|
||||
val totalBytes: Long,
|
||||
val speed: Double,
|
||||
val eta: Long,
|
||||
val transfersCompleted: Int,
|
||||
val totalTransfers: Int,
|
||||
val errors: Int,
|
||||
val deletes: Int,
|
||||
val deletedDirs: Int,
|
||||
val finished: Boolean,
|
||||
val success: Boolean,
|
||||
val errorMessage: String?,
|
||||
val dryRun: Boolean,
|
||||
) {
|
||||
val fraction: Float
|
||||
get() = if (totalBytes > 0) (bytes.toFloat() / totalBytes).coerceIn(0f, 1f) else 0f
|
||||
|
||||
val etaFormatted: String
|
||||
get() {
|
||||
if (eta <= 0) return ""
|
||||
val h = eta / 3600
|
||||
val m = (eta % 3600) / 60
|
||||
val s = eta % 60
|
||||
return when {
|
||||
h > 0 -> "${h}h${m}m"
|
||||
m > 0 -> "${m}m${s}s"
|
||||
else -> "${s}s"
|
||||
}
|
||||
}
|
||||
}
|
||||
+321
@@ -0,0 +1,321 @@
|
||||
package sh.haven.core.rclone
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import sh.haven.core.data.db.entities.ConnectionLog
|
||||
import sh.haven.core.data.repository.ConnectionLogRepository
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.Future
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.TimeoutException
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
private const val TAG = "RcloneSessionMgr"
|
||||
|
||||
/** OAuth flow timeout — no browser callback within this window = abort. */
|
||||
private const val OAUTH_TIMEOUT_MS = 5L * 60 * 1000
|
||||
|
||||
@Singleton
|
||||
class RcloneSessionManager @Inject constructor(
|
||||
private val client: RcloneClient,
|
||||
@ApplicationContext private val context: Context,
|
||||
private val connectionLogRepository: ConnectionLogRepository,
|
||||
) {
|
||||
|
||||
data class SessionState(
|
||||
val sessionId: String,
|
||||
val profileId: String,
|
||||
val label: String,
|
||||
val status: Status,
|
||||
val remoteName: String = "",
|
||||
val provider: String = "",
|
||||
/**
|
||||
* Populated when [status] is [Status.ERROR] — the underlying
|
||||
* exception's message, surfaced verbatim so the UI can show
|
||||
* "rclone: invalid client_id" instead of the silent-spinner
|
||||
* behaviour we used to have.
|
||||
*/
|
||||
val errorMessage: String? = null,
|
||||
) {
|
||||
enum class Status { CONNECTING, CONNECTED, DISCONNECTED, ERROR }
|
||||
}
|
||||
|
||||
private val _sessions = MutableStateFlow<Map<String, SessionState>>(emptyMap())
|
||||
val sessions: StateFlow<Map<String, SessionState>> = _sessions.asStateFlow()
|
||||
|
||||
/**
|
||||
* Worker pool for blocking OAuth `config/create` calls. Cached
|
||||
* pool because the gomobile binding doesn't honour Java thread
|
||||
* interrupts: when an OAuth times out, the worker thread is
|
||||
* effectively leaked until process restart. A bounded pool would
|
||||
* deadlock once the leak count hit the bound; cached + daemon
|
||||
* threads keeps retries working at the cost of letting a few stuck
|
||||
* threads sit there until app restart. Documented limitation.
|
||||
*/
|
||||
private val oauthExecutor = Executors.newCachedThreadPool { r ->
|
||||
Thread(r, "rclone-oauth").apply { isDaemon = true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Single-thread scheduler for the per-session timeout watchers.
|
||||
* One thread is plenty because watchers do almost nothing — they
|
||||
* call `Future.get(timeout)` and dispatch the result.
|
||||
*/
|
||||
private val oauthWatchExecutor = Executors.newSingleThreadExecutor { r ->
|
||||
Thread(r, "rclone-oauth-watch").apply { isDaemon = true }
|
||||
}
|
||||
|
||||
/** Tracks in-flight OAuth futures so cancelPendingOAuth can reach them. */
|
||||
private val oauthFutures = ConcurrentHashMap<String, Future<*>>()
|
||||
|
||||
fun registerSession(profileId: String, label: String): String {
|
||||
val sessionId = UUID.randomUUID().toString()
|
||||
_sessions.update { map ->
|
||||
map + (sessionId to SessionState(
|
||||
sessionId = sessionId,
|
||||
profileId = profileId,
|
||||
label = label,
|
||||
status = SessionState.Status.CONNECTING,
|
||||
))
|
||||
}
|
||||
return sessionId
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect a session by initializing rclone and verifying the remote
|
||||
* is accessible. For OAuth providers, this starts the auth flow in
|
||||
* the background and opens the browser automatically.
|
||||
*/
|
||||
fun connectSession(
|
||||
sessionId: String,
|
||||
remoteName: String,
|
||||
provider: String,
|
||||
) {
|
||||
_sessions.value[sessionId]
|
||||
?: throw IllegalStateException("Session $sessionId not found")
|
||||
|
||||
Log.d(TAG, "Connecting rclone session: remote=$remoteName provider=$provider")
|
||||
|
||||
// Ensure rclone is initialized
|
||||
client.initialize()
|
||||
|
||||
// Check if remote is configured and working
|
||||
val remotes = client.listRemotes()
|
||||
Log.d(TAG, "Configured remotes: $remotes")
|
||||
|
||||
if (remoteName in remotes) {
|
||||
// Remote exists — verify it works
|
||||
try {
|
||||
client.listDirectory(remoteName, "")
|
||||
// It works — mark connected
|
||||
markConnected(sessionId, remoteName, provider)
|
||||
return
|
||||
} catch (e: RcloneException) {
|
||||
if ("token" in e.error.lowercase()) {
|
||||
Log.w(TAG, "Remote '$remoteName' has invalid token, deleting for re-auth")
|
||||
client.deleteRemote(remoteName)
|
||||
} else {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remote needs to be created (with OAuth). This blocks until the user
|
||||
// completes the browser flow, so run it on a background thread and
|
||||
// open the browser automatically.
|
||||
Log.d(TAG, "Starting OAuth flow for '$remoteName' (type=$provider)")
|
||||
startOAuthFlow(sessionId, remoteName, provider)
|
||||
}
|
||||
|
||||
private fun startOAuthFlow(sessionId: String, remoteName: String, provider: String) {
|
||||
// Monitor logcat for the auth URL in a separate thread.
|
||||
// Failures here mark the session ERROR with a useful message
|
||||
// — previously this branch only logged and the user saw an
|
||||
// endless spinner with no idea what went wrong.
|
||||
val urlMonitor = Thread({
|
||||
var process: Process? = null
|
||||
try {
|
||||
process = Runtime.getRuntime().exec(arrayOf(
|
||||
"logcat", "-v", "raw", "-s", "GoLog:*",
|
||||
))
|
||||
val reader = process.inputStream.bufferedReader()
|
||||
var line: String?
|
||||
while (reader.readLine().also { line = it } != null) {
|
||||
val authUrlMatch = Regex("""(http://127\.0\.0\.1:53682/auth\?state=\S+)""")
|
||||
.find(line ?: "")
|
||||
if (authUrlMatch != null) {
|
||||
val url = authUrlMatch.groupValues[1]
|
||||
Log.d(TAG, "Captured OAuth URL: $url")
|
||||
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
try {
|
||||
context.startActivity(intent)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
Log.e(TAG, "No browser to open OAuth URL", e)
|
||||
failSession(
|
||||
sessionId,
|
||||
"No browser app installed to handle the OAuth login. Install a browser (e.g. Chrome, Firefox), then retry.",
|
||||
)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (_: InterruptedException) {
|
||||
// Expected on success/teardown — the createRemote thread
|
||||
// interrupts us in its finally block.
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "URL monitor failed", e)
|
||||
failSession(
|
||||
sessionId,
|
||||
"Couldn't capture the OAuth URL from rclone — check Settings → Connection log for details.",
|
||||
)
|
||||
} finally {
|
||||
process?.destroy()
|
||||
}
|
||||
}, "rclone-url-monitor").apply { isDaemon = true }
|
||||
urlMonitor.start()
|
||||
|
||||
// Run config/create on a worker thread, watched by a separate
|
||||
// future-aware watcher so timeout + cancel can both interrupt
|
||||
// the wait without depending on the gomobile binding to honour
|
||||
// Java interrupts (which it doesn't). On any terminal state —
|
||||
// success, timeout, cancel, exception — surface a useful
|
||||
// SessionState.errorMessage and audit-log the event.
|
||||
logOAuthEvent(sessionId, "OAuth started for '$remoteName' (provider=$provider)")
|
||||
val future: Future<*> = oauthExecutor.submit {
|
||||
client.createRemote(remoteName, provider)
|
||||
}
|
||||
oauthFutures[sessionId] = future
|
||||
|
||||
oauthWatchExecutor.execute {
|
||||
try {
|
||||
future.get(OAUTH_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
Log.d(TAG, "OAuth completed for '$remoteName'")
|
||||
markConnected(sessionId, remoteName, provider)
|
||||
logOAuthEvent(sessionId, "OAuth completed for '$remoteName'")
|
||||
} catch (_: TimeoutException) {
|
||||
Log.w(TAG, "OAuth timed out after ${OAUTH_TIMEOUT_MS / 1000}s for '$remoteName'")
|
||||
future.cancel(true) // best-effort interrupt; gomobile may not honour
|
||||
val msg = "OAuth timed out after ${OAUTH_TIMEOUT_MS / 60_000} minutes — no callback received from the browser. Tap Re-authenticate to try again."
|
||||
failSession(sessionId, msg)
|
||||
logOAuthEvent(sessionId, "OAuth timed out for '$remoteName'", failed = true)
|
||||
} catch (_: java.util.concurrent.CancellationException) {
|
||||
Log.i(TAG, "OAuth cancelled by user for '$remoteName'")
|
||||
failSession(sessionId, "OAuth cancelled.")
|
||||
logOAuthEvent(sessionId, "OAuth cancelled by user for '$remoteName'", failed = true)
|
||||
} catch (e: java.util.concurrent.ExecutionException) {
|
||||
val cause = e.cause ?: e
|
||||
Log.e(TAG, "OAuth failed for '$remoteName'", cause)
|
||||
val msg = "rclone OAuth failed: ${cause.message ?: cause.javaClass.simpleName}"
|
||||
failSession(sessionId, msg)
|
||||
logOAuthEvent(sessionId, msg, failed = true)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "OAuth watcher unexpected exception for '$remoteName'", e)
|
||||
val msg = "rclone OAuth watcher failed: ${e.message ?: e.javaClass.simpleName}"
|
||||
failSession(sessionId, msg)
|
||||
logOAuthEvent(sessionId, msg, failed = true)
|
||||
} finally {
|
||||
urlMonitor.interrupt()
|
||||
oauthFutures.remove(sessionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel the in-flight OAuth flow for [sessionId], if any. Marks
|
||||
* the session ERROR and best-effort interrupts the worker thread.
|
||||
* The underlying gomobile call may still be running; that thread
|
||||
* will be reclaimed on app restart.
|
||||
*/
|
||||
fun cancelPendingOAuth(sessionId: String) {
|
||||
val future = oauthFutures[sessionId] ?: return
|
||||
Log.i(TAG, "User cancelled OAuth for session $sessionId")
|
||||
future.cancel(true)
|
||||
}
|
||||
|
||||
/** Append an OAuth lifecycle event to the per-profile audit log. */
|
||||
private fun logOAuthEvent(sessionId: String, message: String, failed: Boolean = false) {
|
||||
val profileId = _sessions.value[sessionId]?.profileId ?: return
|
||||
// Best-effort, fire-and-forget — audit must never break the
|
||||
// OAuth path. Using runBlocking on the watcher thread is fine
|
||||
// because Room writes are quick and the watcher is dedicated.
|
||||
try {
|
||||
kotlinx.coroutines.runBlocking {
|
||||
connectionLogRepository.logEvent(
|
||||
profileId = profileId,
|
||||
status = if (failed) ConnectionLog.Status.FAILED else ConnectionLog.Status.CONNECTED,
|
||||
details = message,
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "audit insert for OAuth event failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
/** Mark a session ERROR with a human-readable [message]. */
|
||||
private fun failSession(sessionId: String, message: String) {
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(
|
||||
status = SessionState.Status.ERROR,
|
||||
errorMessage = message,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
private fun markConnected(sessionId: String, remoteName: String, provider: String) {
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(
|
||||
status = SessionState.Status.CONNECTED,
|
||||
remoteName = remoteName,
|
||||
provider = provider,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fun updateStatus(sessionId: String, status: SessionState.Status) {
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(status = status))
|
||||
}
|
||||
}
|
||||
|
||||
fun removeSession(sessionId: String) {
|
||||
_sessions.update { it - sessionId }
|
||||
}
|
||||
|
||||
fun removeAllSessionsForProfile(profileId: String) {
|
||||
// Cancel any in-flight OAuth for the sessions being removed so a
|
||||
// disconnect mid-auth doesn't leave the worker blocking for the
|
||||
// full timeout (#363).
|
||||
_sessions.value.values
|
||||
.filter { it.profileId == profileId }
|
||||
.forEach { cancelPendingOAuth(it.sessionId) }
|
||||
_sessions.update { map -> map.filterValues { it.profileId != profileId } }
|
||||
}
|
||||
|
||||
fun getSessionsForProfile(profileId: String): List<SessionState> =
|
||||
_sessions.value.values.filter { it.profileId == profileId }
|
||||
|
||||
fun getRemoteNameForProfile(profileId: String): String? =
|
||||
_sessions.value.values
|
||||
.firstOrNull { it.profileId == profileId && it.status == SessionState.Status.CONNECTED }
|
||||
?.remoteName
|
||||
|
||||
fun isProfileConnected(profileId: String): Boolean =
|
||||
_sessions.value.values.any {
|
||||
it.profileId == profileId && it.status == SessionState.Status.CONNECTED
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package sh.haven.core.rclone
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class RcloneConfigParserTest {
|
||||
|
||||
private fun remotes(text: String) =
|
||||
(RcloneConfigParser.parse(text) as RcloneConfigParseResult.Success).remotes
|
||||
|
||||
@Test
|
||||
fun `parses two remotes with type and params`() {
|
||||
val conf = """
|
||||
[gdrive]
|
||||
type = drive
|
||||
scope = drive
|
||||
token = {"access_token":"ya29"}
|
||||
|
||||
[backup]
|
||||
type = s3
|
||||
provider = AWS
|
||||
access_key_id = AKIA123
|
||||
""".trimIndent()
|
||||
|
||||
val r = remotes(conf)
|
||||
assertEquals(listOf("gdrive", "backup"), r.map { it.name })
|
||||
assertEquals("drive", r[0].type)
|
||||
assertEquals("drive", r[0].params["scope"])
|
||||
assertEquals("AKIA123", r[1].params["access_key_id"])
|
||||
// `type` is lifted out of params.
|
||||
assertTrue(!r[0].params.containsKey("type"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `value containing equals is kept whole`() {
|
||||
// OAuth tokens / base64 secrets carry '=' — split only on the first.
|
||||
val r = remotes("[d]\ntype = drive\ntoken = {\"a\":\"x=y==\"}")
|
||||
assertEquals("{\"a\":\"x=y==\"}", r[0].params["token"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `comments and blank lines are ignored`() {
|
||||
val conf = """
|
||||
# my rclone config
|
||||
; another comment
|
||||
|
||||
[r]
|
||||
type = ftp
|
||||
host = example.org
|
||||
""".trimIndent()
|
||||
val r = remotes(conf)
|
||||
assertEquals(1, r.size)
|
||||
assertEquals("example.org", r[0].params["host"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `encrypted config is detected`() {
|
||||
val conf = "# Encrypted rclone configuration File\n\nRCLONE_ENCRYPT_V0:abc123def=="
|
||||
assertTrue(RcloneConfigParser.parse(conf) is RcloneConfigParseResult.Encrypted)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `section without type yields empty type`() {
|
||||
val r = remotes("[weird]\nfoo = bar")
|
||||
assertEquals("", r[0].type)
|
||||
assertEquals("bar", r[0].params["foo"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `empty input yields no remotes`() {
|
||||
assertTrue(remotes("").isEmpty())
|
||||
assertTrue(remotes(" \n\n# only a comment").isEmpty())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package sh.haven.core.rclone
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/**
|
||||
* Regression test for #295: rclone option `Default` values that are JSON
|
||||
* arrays/objects must not leak into the field as literal "[]"/"{}".
|
||||
*/
|
||||
class ScalarDefaultTest {
|
||||
|
||||
private fun withDefault(value: Any?) =
|
||||
JSONObject().apply { if (value != null) put("Default", value) }
|
||||
|
||||
@Test
|
||||
fun `empty array default becomes empty string`() {
|
||||
assertEquals("", scalarDefault(withDefault(JSONArray())))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `populated array default becomes empty string`() {
|
||||
assertEquals("", scalarDefault(withDefault(JSONArray(listOf("a", "b")))))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `object default becomes empty string`() {
|
||||
assertEquals("", scalarDefault(withDefault(JSONObject().apply { put("k", "v") })))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `missing default becomes empty string`() {
|
||||
assertEquals("", scalarDefault(JSONObject()))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `json null default becomes empty string`() {
|
||||
assertEquals("", scalarDefault(withDefault(JSONObject.NULL)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `string default is preserved`() {
|
||||
assertEquals("hello", scalarDefault(withDefault("hello")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `numeric default is stringified`() {
|
||||
assertEquals("42", scalarDefault(withDefault(42)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `boolean default is stringified`() {
|
||||
assertEquals("true", scalarDefault(withDefault(true)))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user