mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
Intergrated syncthing (#1442)
This commit is contained in:
1 parent
5b7e401b11
commit
8c09b2c6a8
34 files changed
+2492
-7
No files matched your search
@@ -58,6 +58,7 @@ class App : Application() {
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
|
||||
com.droiddeck.launcher.sync.Syncthing.init(this)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ object OrphanReaper {
|
||||
|
||||
fun release(pid: Int) { kept.remove(pid) }
|
||||
|
||||
fun reap(reason: String): Int {
|
||||
fun reap(reason: String, matching: (String) -> Boolean = { true }): Int {
|
||||
val me = android.os.Process.myPid()
|
||||
val uid = android.os.Process.myUid()
|
||||
val spared = descendants(kept)
|
||||
@@ -21,6 +21,7 @@ object OrphanReaper {
|
||||
if (pid == me || pid <= 1 || pid in spared) return@forEach
|
||||
if (uidOf(pid) != uid) return@forEach
|
||||
val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (e: Exception) { "?" }
|
||||
if (!matching(name)) return@forEach
|
||||
try {
|
||||
android.os.Process.killProcess(pid)
|
||||
killed++
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import android.content.Context
|
||||
import java.security.SecureRandom
|
||||
|
||||
object SyncPrefs {
|
||||
const val RUN_WHILE_OPEN = "open"
|
||||
const val RUN_BACKGROUND = "background"
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("syncthing", Context.MODE_PRIVATE)
|
||||
|
||||
fun enabled(context: Context): Boolean = prefs(context).getBoolean("enabled", false)
|
||||
fun setEnabled(context: Context, on: Boolean) { prefs(context).edit().putBoolean("enabled", on).apply() }
|
||||
|
||||
fun runMode(context: Context): String =
|
||||
prefs(context).getString("run", RUN_WHILE_OPEN).takeIf { it == RUN_BACKGROUND } ?: RUN_WHILE_OPEN
|
||||
fun setRunMode(context: Context, mode: String) { prefs(context).edit().putString("run", mode).apply() }
|
||||
|
||||
fun wifiOnly(context: Context): Boolean = prefs(context).getBoolean("wifi-only", false)
|
||||
fun setWifiOnly(context: Context, on: Boolean) { prefs(context).edit().putBoolean("wifi-only", on).apply() }
|
||||
|
||||
fun pauseInGames(context: Context): Boolean = prefs(context).getBoolean("pause-in-games", false)
|
||||
fun setPauseInGames(context: Context, on: Boolean) { prefs(context).edit().putBoolean("pause-in-games", on).apply() }
|
||||
|
||||
fun userPaused(context: Context): Boolean = prefs(context).getBoolean("paused", false)
|
||||
fun setUserPaused(context: Context, on: Boolean) { prefs(context).edit().putBoolean("paused", on).apply() }
|
||||
|
||||
/** Whether DroidDeck has paused all devices through the API and must resume them. */
|
||||
fun pauseApplied(context: Context): Boolean = prefs(context).getBoolean("pause-applied", false)
|
||||
fun setPauseApplied(context: Context, on: Boolean) { prefs(context).edit().putBoolean("pause-applied", on).apply() }
|
||||
|
||||
fun guiPassword(context: Context): String = prefs(context).getString("gui-password", null) ?: randomToken().also {
|
||||
prefs(context).edit().putString("gui-password", it).apply()
|
||||
}
|
||||
|
||||
fun clearIdentity(context: Context) { prefs(context).edit().remove("gui-password").apply() }
|
||||
|
||||
internal fun randomToken(length: Int = 32): String {
|
||||
val alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||
val random = SecureRandom()
|
||||
return String(CharArray(length) { alphabet[random.nextInt(alphabet.length)] })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkCapabilities
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.core.HostProcess
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.OrphanReaper
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.security.SecureRandom
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
object Syncthing {
|
||||
enum class Phase { OFF, STARTING, RUNNING, STOPPING, FAILED }
|
||||
enum class AutoPause { WIFI, GAME }
|
||||
|
||||
const val FAILURE_MISSING = "binary-missing"
|
||||
private const val FAILURE_POLICY = "Stopped because a folder outside DroidDeck's storage could not be paused"
|
||||
private const val FAILURE_PAUSE = "Stopped because Syncthing could not be paused"
|
||||
private const val FAILURE_STILL_RUNNING = "The previous Syncthing process did not exit"
|
||||
private const val TAG = "Syncthing"
|
||||
private const val GRACE_MS = 60_000L
|
||||
private const val ENFORCE_ATTEMPTS = 3
|
||||
private const val LOG_LIMIT = 4L shl 20
|
||||
private const val FOLDER_ID_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789"
|
||||
|
||||
var enabled by mutableStateOf(false); private set
|
||||
var phase by mutableStateOf(Phase.OFF); private set
|
||||
var snapshot by mutableStateOf<SyncSnapshot?>(null); private set
|
||||
var failure by mutableStateOf<String?>(null); private set
|
||||
var ports by mutableStateOf<SyncthingPorts?>(null); private set
|
||||
var apiKeyTail by mutableStateOf<String?>(null); private set
|
||||
var userPaused by mutableStateOf(false); private set
|
||||
var autoPause by mutableStateOf<AutoPause?>(null); private set
|
||||
/** Whether Syncthing has confirmed every device is paused, as opposed to a pause only being requested. */
|
||||
var devicesPaused by mutableStateOf(false); private set
|
||||
val pauseRequested get() = userPaused || autoPause != null
|
||||
/** Bumped to ask the Setup page to show the Sync tab. */
|
||||
var openRequests by mutableStateOf(0)
|
||||
private set
|
||||
var openPending = false
|
||||
|
||||
fun requestOpen() {
|
||||
openPending = true
|
||||
openRequests++
|
||||
}
|
||||
|
||||
val needsAttention get() = phase == Phase.FAILED || snapshot?.needsAttention == true
|
||||
|
||||
/** Called on the main thread whenever the state above changes; the background service follows it. */
|
||||
@Volatile var onChange: (() -> Unit)? = null
|
||||
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val worker = Executors.newSingleThreadExecutor { Thread(it, "syncthing") }
|
||||
private lateinit var app: Context
|
||||
@Volatile private var process: Process? = null
|
||||
@Volatile private var api: SyncthingApi? = null
|
||||
@Volatile private var generation = 0
|
||||
@Volatile private var onWifi = true
|
||||
private var visible = 0
|
||||
private var foreground = false
|
||||
private val watchers = AtomicInteger()
|
||||
private val pauseFailures = AtomicInteger()
|
||||
private val pauseLock = Any()
|
||||
private val leaveForeground = Runnable { foreground = false; evaluate() }
|
||||
|
||||
fun home(context: Context) = File(context.filesDir, "syncthing")
|
||||
fun folderRoot(context: Context) = File(context.getExternalFilesDir(null) ?: context.filesDir, "Sync")
|
||||
fun logFile(context: Context) = File(home(context), "syncthing.log")
|
||||
private fun config(context: Context) = File(home(context), "config.xml")
|
||||
private fun guiSocket(context: Context) = File(home(context), "gui.sock")
|
||||
private fun binary(context: Context) = File(context.applicationInfo.nativeLibraryDir, "libsyncthingnative.so")
|
||||
|
||||
/** DroidDeck's own storage: its private data directory and its folder on each shared volume. */
|
||||
fun storageRoots(context: Context): List<File> =
|
||||
listOf(context.dataDir) + context.getExternalFilesDirs(null).filterNotNull().mapNotNull { it.parentFile }
|
||||
|
||||
fun guard(context: Context) = SyncthingGuard(folderRoot(context), storageRoots(context), listOf(home(context)))
|
||||
|
||||
fun init(application: Application) {
|
||||
app = application.applicationContext
|
||||
userPaused = SyncPrefs.userPaused(app)
|
||||
enabled = SyncPrefs.enabled(app)
|
||||
val previous = Thread.getDefaultUncaughtExceptionHandler()
|
||||
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||
runCatching { process?.destroyForcibly() }
|
||||
previous?.uncaughtException(thread, error) ?: Runtime.getRuntime().halt(2)
|
||||
}
|
||||
application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
|
||||
override fun onActivityStarted(activity: Activity) {
|
||||
visible++
|
||||
main.removeCallbacks(leaveForeground)
|
||||
if (!foreground) { foreground = true; evaluate() }
|
||||
}
|
||||
override fun onActivityStopped(activity: Activity) {
|
||||
visible = (visible - 1).coerceAtLeast(0)
|
||||
if (visible == 0) main.postDelayed(leaveForeground, GRACE_MS)
|
||||
}
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
|
||||
override fun onActivityResumed(activity: Activity) {}
|
||||
override fun onActivityPaused(activity: Activity) {}
|
||||
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
|
||||
override fun onActivityDestroyed(activity: Activity) {}
|
||||
})
|
||||
val connectivity = app.getSystemService(ConnectivityManager::class.java)
|
||||
onWifi = connectivity?.activeNetwork?.let { connectivity.getNetworkCapabilities(it) }?.let(::isWifi) ?: false
|
||||
runCatching {
|
||||
connectivity?.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) { networkChanged(isWifi(caps)) }
|
||||
override fun onLost(network: Network) { networkChanged(false) }
|
||||
})
|
||||
}
|
||||
evaluate()
|
||||
}
|
||||
|
||||
private fun isWifi(caps: NetworkCapabilities) =
|
||||
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
|
||||
|
||||
private fun networkChanged(wifi: Boolean) {
|
||||
if (wifi == onWifi) return
|
||||
onWifi = wifi
|
||||
worker.execute { api?.let { applyPause(it) } }
|
||||
}
|
||||
|
||||
/** Starts or stops Syncthing to match the settings and whether DroidDeck is on screen. */
|
||||
fun evaluate() {
|
||||
if (Looper.myLooper() != Looper.getMainLooper()) { main.post { evaluate() }; return }
|
||||
val enabled = SyncPrefs.enabled(app)
|
||||
val background = SyncPrefs.runMode(app) == SyncPrefs.RUN_BACKGROUND
|
||||
if (enabled && background) SyncthingService.start(app) else SyncthingService.stop(app)
|
||||
if (enabled && (background || foreground)) start() else stop()
|
||||
}
|
||||
|
||||
fun setEnabled(context: Context, on: Boolean, forget: Boolean = false) {
|
||||
if (on && !LinuxRuntime.isInstalled(context)) return
|
||||
SyncPrefs.setEnabled(context, on)
|
||||
enabled = on
|
||||
if (on && phase == Phase.FAILED) phase = Phase.OFF
|
||||
evaluate()
|
||||
if (!on && forget) worker.execute {
|
||||
if (process != null) return@execute
|
||||
home(context).deleteRecursively()
|
||||
SyncPrefs.clearIdentity(context)
|
||||
SyncPrefs.setPauseApplied(context, false)
|
||||
}
|
||||
}
|
||||
|
||||
fun setPaused(context: Context, paused: Boolean) {
|
||||
SyncPrefs.setUserPaused(context, paused)
|
||||
userPaused = paused
|
||||
changed()
|
||||
worker.execute { api?.let { applyPause(it) } }
|
||||
}
|
||||
|
||||
fun settingsChanged() {
|
||||
evaluate()
|
||||
worker.execute { api?.let { applyPause(it) } }
|
||||
}
|
||||
|
||||
fun restart() {
|
||||
stop()
|
||||
evaluate()
|
||||
}
|
||||
|
||||
fun reset(context: Context) {
|
||||
stop()
|
||||
worker.execute {
|
||||
if (process != null) return@execute
|
||||
home(context).deleteRecursively()
|
||||
SyncPrefs.clearIdentity(context)
|
||||
SyncPrefs.setPauseApplied(context, false)
|
||||
main.post { evaluate() }
|
||||
}
|
||||
}
|
||||
|
||||
fun regenerateApiKey() {
|
||||
worker.execute {
|
||||
val current = api ?: return@execute
|
||||
val key = SyncPrefs.randomToken()
|
||||
runCatching { current.setApiKey(key) }.onSuccess {
|
||||
api = SyncthingApi(current.socket, key)
|
||||
main.post { apiKeyTail = key.takeLast(4); changed() }
|
||||
}.onFailure { Log.w(TAG, "API key change failed", it) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds a folder at [path] shared with [devices]; pass the offered folder's [id] to accept a share. */
|
||||
fun addFolder(context: Context, path: File, label: String, devices: List<String>, id: String = newFolderId(), onDone: (Boolean) -> Unit) {
|
||||
worker.execute {
|
||||
val ok = runCatching {
|
||||
val client = api ?: error("Syncthing is not running")
|
||||
check(guard(context).allows(path.path)) { "${path.path} is outside DroidDeck's storage" }
|
||||
path.mkdirs()
|
||||
client.addFolder(client.defaultFolder().apply {
|
||||
put("id", id)
|
||||
put("label", label)
|
||||
put("path", path.path)
|
||||
put("devices", JSONArray(devices.map { JSONObject().put("deviceID", it) }))
|
||||
})
|
||||
}.onFailure { Log.w(TAG, "add folder failed", it) }.isSuccess
|
||||
main.post { onDone(ok) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun newFolderId(): String {
|
||||
val random = SecureRandom()
|
||||
fun part() = (1..5).map { FOLDER_ID_CHARS[random.nextInt(FOLDER_ID_CHARS.length)] }.joinToString("")
|
||||
return "${part()}-${part()}"
|
||||
}
|
||||
|
||||
fun removeFolder(id: String) {
|
||||
worker.execute { api?.let { a -> runCatching { a.removeFolder(id) }.onFailure { Log.w(TAG, "remove $id failed", it) } } }
|
||||
}
|
||||
|
||||
/** Starts a loopback proxy for the in-app web UI, which can't reach Syncthing's private socket itself. */
|
||||
fun webUiProxy(context: Context): SyncthingProxy? {
|
||||
if (phase != Phase.RUNNING) return null
|
||||
val token = Base64.encodeToString("${SyncthingConfig.GUI_USER}:${SyncPrefs.guiPassword(context)}".toByteArray(), Base64.NO_WRAP)
|
||||
return runCatching { SyncthingProxy(guiSocket(context), "Basic $token") }.onFailure { Log.w(TAG, "web UI proxy failed", it) }.getOrNull()
|
||||
}
|
||||
|
||||
/** UI screens showing live status call this so the status refreshes faster while they're visible. */
|
||||
fun watch(): () -> Unit {
|
||||
watchers.incrementAndGet()
|
||||
return { watchers.decrementAndGet() }
|
||||
}
|
||||
|
||||
private fun start() {
|
||||
if (phase == Phase.STARTING || phase == Phase.RUNNING) return
|
||||
if (phase == Phase.FAILED && failure == FAILURE_MISSING) return
|
||||
val gen = ++generation
|
||||
phase = Phase.STARTING
|
||||
failure = null
|
||||
changed()
|
||||
worker.execute { launch(gen) }
|
||||
}
|
||||
|
||||
private fun stop() {
|
||||
if (phase == Phase.OFF) return
|
||||
val gen = ++generation
|
||||
phase = if (process != null || phase == Phase.STARTING) Phase.STOPPING else Phase.OFF
|
||||
changed()
|
||||
worker.execute {
|
||||
shutdown()
|
||||
val stopped = process == null
|
||||
main.post {
|
||||
if (gen != generation) return@post
|
||||
if (stopped) { phase = Phase.OFF; snapshot = null; ports = null } else { phase = Phase.FAILED; failure = FAILURE_STILL_RUNNING }
|
||||
changed()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun launch(gen: Int) {
|
||||
val context = app
|
||||
try {
|
||||
if (!binary(context).isFile) throw SyncthingFailure(FAILURE_MISSING)
|
||||
if (process != null) throw SyncthingFailure(FAILURE_STILL_RUNNING)
|
||||
val name = binary(context).name
|
||||
OrphanReaper.reap("stale Syncthing") { it.substringAfterLast('/') == name }
|
||||
home(context).mkdirs()
|
||||
folderRoot(context).mkdirs()
|
||||
if (!config(context).isFile) generate(context)
|
||||
val picked = SyncthingPortPicker.pick()
|
||||
val guard = guard(context)
|
||||
val paused = SyncPrefs.userPaused(context) || autoPauseReason() != null
|
||||
SyncthingConfig.apply(config(context), picked, guiSocket(context), folderRoot(context), paused, guard::allows)
|
||||
if (paused) SyncPrefs.setPauseApplied(context, true)
|
||||
val key = SyncthingConfig.apiKey(config(context)) ?: throw SyncthingFailure("config.xml has no API key")
|
||||
if (gen != generation) return
|
||||
rotateLog(context)
|
||||
val child = ProcessBuilder(binary(context).path, "serve", "--no-browser", "--no-restart")
|
||||
.redirectErrorStream(true)
|
||||
.also { environment(context, it.environment()) }
|
||||
.start()
|
||||
process = child
|
||||
OrphanReaper.keep(HostProcess.pidOf(child))
|
||||
pump(gen, child, logFile(context))
|
||||
pauseFailures.set(0)
|
||||
val client = SyncthingApi(guiSocket(context), key)
|
||||
val deadline = System.currentTimeMillis() + 60_000
|
||||
while (!client.ping()) {
|
||||
if (gen != generation) return
|
||||
if (!child.isAlive) throw SyncthingFailure("Syncthing exited during start (${child.exitValue()})")
|
||||
if (System.currentTimeMillis() > deadline) throw SyncthingFailure("Syncthing did not answer on ${guiSocket(context).name}")
|
||||
Thread.sleep(250)
|
||||
}
|
||||
api = client
|
||||
main.post {
|
||||
if (gen == generation) { ports = picked; apiKeyTail = key.takeLast(4); devicesPaused = paused; phase = Phase.RUNNING; changed() }
|
||||
}
|
||||
Thread({ poll(gen, guard) }, "syncthing-status").start()
|
||||
Thread({ enforce(gen, guard) }, "syncthing-guard").start()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "start failed", e)
|
||||
shutdown()
|
||||
val reason = (e as? SyncthingFailure)?.message ?: e.toString()
|
||||
main.post { if (gen == generation) { phase = Phase.FAILED; failure = reason; changed() } }
|
||||
}
|
||||
}
|
||||
|
||||
private fun generate(context: Context) {
|
||||
val output = File(home(context), "generate.log")
|
||||
val child = ProcessBuilder(binary(context).path, "generate", "--gui-user", SyncthingConfig.GUI_USER, "--gui-password", "-")
|
||||
.redirectErrorStream(true)
|
||||
.redirectOutput(output)
|
||||
.also { environment(context, it.environment()) }
|
||||
.start()
|
||||
val pid = HostProcess.pidOf(child)
|
||||
OrphanReaper.keep(pid)
|
||||
try {
|
||||
child.outputStream.bufferedWriter().use { it.write(SyncPrefs.guiPassword(context) + "\n") }
|
||||
if (!child.waitFor(60, TimeUnit.SECONDS) || child.exitValue() != 0 || !config(context).isFile) {
|
||||
child.destroy()
|
||||
val last = runCatching { output.readLines().lastOrNull { it.isNotBlank() } }.getOrNull().orEmpty()
|
||||
throw SyncthingFailure("syncthing generate failed: $last")
|
||||
}
|
||||
} finally {
|
||||
output.delete()
|
||||
OrphanReaper.release(pid)
|
||||
}
|
||||
}
|
||||
|
||||
private fun environment(context: Context, env: MutableMap<String, String>) {
|
||||
listOf("LD_PRELOAD", "LD_AUDIT", "LD_LIBRARY_PATH").forEach { env.remove(it) }
|
||||
env["STHOMEDIR"] = home(context).path
|
||||
env["HOME"] = folderRoot(context).path
|
||||
env["STNOUPGRADE"] = "1"
|
||||
env["STNODEFAULTFOLDER"] = "1"
|
||||
env["STMONITORED"] = "1"
|
||||
env["SQLITE_TMPDIR"] = context.cacheDir.path
|
||||
env["STVERSIONEXTRA"] = "DroidDeck"
|
||||
}
|
||||
|
||||
private fun rotateLog(context: Context) {
|
||||
val log = logFile(context)
|
||||
if (log.length() > 0) log.renameTo(File(log.parentFile, "syncthing.old.log"))
|
||||
}
|
||||
|
||||
private fun pump(gen: Int, child: Process, log: File) {
|
||||
Thread({
|
||||
var last = ""
|
||||
runCatching {
|
||||
log.appendText("")
|
||||
child.inputStream.bufferedReader().useLines { lines ->
|
||||
lines.forEach { line ->
|
||||
if (line.isNotBlank()) last = line
|
||||
if (log.length() < LOG_LIMIT) log.appendText(line + "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
val code = runCatching { child.waitFor() }.getOrDefault(-1)
|
||||
OrphanReaper.release(HostProcess.pidOf(child))
|
||||
main.post {
|
||||
if (process !== child) return@post
|
||||
process = null
|
||||
if (gen == generation && phase == Phase.RUNNING) {
|
||||
api = null
|
||||
phase = Phase.FAILED; failure = "Syncthing stopped ($code): $last"; snapshot = null; changed()
|
||||
}
|
||||
}
|
||||
}, "syncthing-output").start()
|
||||
}
|
||||
|
||||
private fun shutdown() {
|
||||
val child = process ?: return
|
||||
api?.let { runCatching { it.shutdown() } }
|
||||
api = null
|
||||
if (!child.waitFor(10, TimeUnit.SECONDS)) {
|
||||
child.destroy()
|
||||
if (!child.waitFor(3, TimeUnit.SECONDS)) {
|
||||
child.destroyForcibly()
|
||||
child.waitFor(3, TimeUnit.SECONDS)
|
||||
}
|
||||
}
|
||||
if (child.isAlive) {
|
||||
Log.w(TAG, "Syncthing did not exit")
|
||||
return
|
||||
}
|
||||
process = null
|
||||
}
|
||||
|
||||
private fun poll(gen: Int, guard: SyncthingGuard) {
|
||||
var previous: Pair<Long, Pair<Long, Long>>? = null
|
||||
var myId: String? = null
|
||||
while (gen == generation) {
|
||||
val client = api ?: return
|
||||
applyPause(client)
|
||||
try {
|
||||
val id = myId ?: client.myId().also { myId = it }
|
||||
val connections = client.connections()
|
||||
val total = connections.optJSONObject("total")
|
||||
val now = System.currentTimeMillis()
|
||||
val bytes = (total?.optLong("inBytesTotal") ?: 0L) to (total?.optLong("outBytesTotal") ?: 0L)
|
||||
val rates = previous?.let { (at, was) ->
|
||||
val seconds = ((now - at) / 1000.0).coerceAtLeast(0.5)
|
||||
((bytes.first - was.first).coerceAtLeast(0) / seconds).toLong() to ((bytes.second - was.second).coerceAtLeast(0) / seconds).toLong()
|
||||
} ?: (0L to 0L)
|
||||
previous = now to bytes
|
||||
val snap = collect(client, guard, id, connections, rates)
|
||||
main.post { if (gen == generation) { snapshot = snap; changed() } }
|
||||
} catch (e: PolicyFailure) {
|
||||
failClosed(gen, e)
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "status poll failed: $e")
|
||||
}
|
||||
Thread.sleep(if (watchers.get() > 0) 2_000 else 10_000)
|
||||
}
|
||||
}
|
||||
|
||||
private fun collect(client: SyncthingApi, guard: SyncthingGuard, myId: String, connections: org.json.JSONObject, rates: Pair<Long, Long>): SyncSnapshot {
|
||||
val names = SyncthingParse.deviceNames(client.devices(), myId)
|
||||
val config = client.folders()
|
||||
val folders = (0 until config.length()).map { config.getJSONObject(it) }.map { f ->
|
||||
val id = f.getString("id")
|
||||
val path = f.optString("path")
|
||||
val blocked = !guard.allows(path)
|
||||
if (blocked && !f.optBoolean("paused")) pauseFolder(client, id)
|
||||
val paused = blocked || f.optBoolean("paused")
|
||||
val status = if (paused) null else runCatching { client.folderStatus(id) }.getOrElse { SyncthingParse.unreadableStatus() }
|
||||
SyncthingParse.folder(f, status, blocked, names)
|
||||
}
|
||||
val conns = connections.optJSONObject("connections")
|
||||
val stats = runCatching { client.deviceStats() }.getOrNull()
|
||||
val devices = names.map { (id, name) ->
|
||||
val c = conns?.optJSONObject(id)
|
||||
val seen = stats?.optJSONObject(id)?.optString("lastSeen")?.let(::parseTime)
|
||||
SyncDevice(id, name, c?.optBoolean("connected") == true, c?.optString("address")?.takeIf { it.isNotEmpty() }, seen)
|
||||
}
|
||||
return SyncSnapshot(
|
||||
myId, folders, devices,
|
||||
runCatching { SyncthingParse.pendingFolders(client.pendingFolders(), names) }.getOrDefault(emptyList()),
|
||||
runCatching { SyncthingParse.pendingDevices(client.pendingDevices()) }.getOrDefault(emptyList()),
|
||||
rates.first, rates.second,
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseTime(s: String): Long? = runCatching {
|
||||
java.time.OffsetDateTime.parse(s).toInstant().toEpochMilli().takeIf { it > 86_400_000L }
|
||||
}.getOrNull()
|
||||
|
||||
/** Pauses any folder outside DroidDeck's storage as soon as Syncthing saves its config, and stops Syncthing if it can't. */
|
||||
private fun enforce(gen: Int, guard: SyncthingGuard) {
|
||||
var since = 0L
|
||||
var pending = true
|
||||
var failures = 0
|
||||
while (gen == generation) {
|
||||
val client = api ?: return
|
||||
try {
|
||||
if (!pending) {
|
||||
val (last, saved) = client.waitForConfigSaved(since, 60)
|
||||
since = last
|
||||
pending = saved
|
||||
}
|
||||
if (pending && gen == generation) {
|
||||
applyPause(client)
|
||||
val folders = client.folders()
|
||||
for (i in 0 until folders.length()) {
|
||||
val f = folders.getJSONObject(i)
|
||||
if (!f.optBoolean("paused") && !guard.allows(f.optString("path"))) pauseFolder(client, f.getString("id"))
|
||||
}
|
||||
pending = false
|
||||
}
|
||||
failures = 0
|
||||
} catch (e: PolicyFailure) {
|
||||
failClosed(gen, e)
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
if (pending && ++failures >= ENFORCE_ATTEMPTS) {
|
||||
failClosed(gen, PolicyFailure(e))
|
||||
return
|
||||
}
|
||||
Thread.sleep(2_000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun pauseFolder(client: SyncthingApi, id: String) {
|
||||
try {
|
||||
client.pauseFolder(id)
|
||||
} catch (e: Exception) {
|
||||
throw PolicyFailure(e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun failClosed(gen: Int, cause: Exception, reason: String = FAILURE_POLICY) {
|
||||
Log.w(TAG, reason, cause)
|
||||
worker.execute {
|
||||
if (gen != generation) return@execute
|
||||
shutdown()
|
||||
main.post { if (gen == generation) { phase = Phase.FAILED; failure = reason; snapshot = null; changed() } }
|
||||
}
|
||||
}
|
||||
|
||||
// Runs from the worker, poll and enforce threads; serialised so an older decision can't land after a newer one.
|
||||
private fun applyPause(client: SyncthingApi) = synchronized(pauseLock) {
|
||||
val context = app
|
||||
val auto = autoPauseReason()
|
||||
val want = SyncPrefs.userPaused(context) || auto != null
|
||||
var held = SyncPrefs.pauseApplied(context) && !(want && hasUnpausedPeer(client))
|
||||
if (want != held) {
|
||||
runCatching { if (want) client.pauseAll() else client.resumeAll() }
|
||||
.onSuccess { SyncPrefs.setPauseApplied(context, want); held = want; pauseFailures.set(0) }
|
||||
.onFailure { Log.w(TAG, "pause change failed", it); if (want) pauseFailures.incrementAndGet() }
|
||||
}
|
||||
if (auto != autoPause || held != devicesPaused) main.post { autoPause = auto; devicesPaused = held; changed() }
|
||||
if (want && !held && pauseFailures.get() >= ENFORCE_ATTEMPTS) failClosed(generation, IllegalStateException(FAILURE_PAUSE), FAILURE_PAUSE)
|
||||
}
|
||||
|
||||
// An unreadable peer list counts as unpaused, so a required pause is reasserted rather than assumed.
|
||||
private fun hasUnpausedPeer(client: SyncthingApi): Boolean = runCatching {
|
||||
val myId = client.myId()
|
||||
val devices = client.devices()
|
||||
(0 until devices.length()).map { devices.getJSONObject(it) }
|
||||
.any { it.getString("deviceID") != myId && !it.optBoolean("paused") }
|
||||
}.getOrDefault(true)
|
||||
|
||||
private fun autoPauseReason(): AutoPause? = when {
|
||||
SyncPrefs.wifiOnly(app) && !onWifi -> AutoPause.WIFI
|
||||
SyncPrefs.pauseInGames(app) && SessionState.running -> AutoPause.GAME
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun changed() { onChange?.invoke() }
|
||||
|
||||
private class SyncthingFailure(message: String) : Exception(message)
|
||||
private class PolicyFailure(cause: Exception) : Exception(cause)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import android.net.LocalSocket
|
||||
import android.net.LocalSocketAddress
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.net.URLEncoder
|
||||
|
||||
class SyncthingApi(val socket: File, private val apiKey: String) {
|
||||
fun ping(): Boolean = runCatching { get("/rest/system/ping").optString("ping") == "pong" }.getOrDefault(false)
|
||||
fun myId(): String = get("/rest/system/status").getString("myID")
|
||||
fun folders(): JSONArray = getArray("/rest/config/folders")
|
||||
fun devices(): JSONArray = getArray("/rest/config/devices")
|
||||
fun folderStatus(id: String): JSONObject = get("/rest/db/status?folder=${enc(id)}")
|
||||
fun connections(): JSONObject = get("/rest/system/connections")
|
||||
fun deviceStats(): JSONObject = get("/rest/stats/device")
|
||||
fun pendingDevices(): JSONObject = get("/rest/cluster/pending/devices")
|
||||
fun pendingFolders(): JSONObject = get("/rest/cluster/pending/folders")
|
||||
|
||||
fun defaultFolder(): JSONObject = get("/rest/config/defaults/folder")
|
||||
fun addFolder(folder: JSONObject) = send("POST", "/rest/config/folders", folder)
|
||||
fun pauseFolder(id: String) = merge("/rest/config/folders/${enc(id)}") { put("paused", true) }
|
||||
fun removeFolder(id: String) { send("DELETE", "/rest/config/folders/${enc(id)}", null) }
|
||||
fun pauseAll() { send("POST", "/rest/system/pause", null) }
|
||||
fun resumeAll() { send("POST", "/rest/system/resume", null) }
|
||||
fun setApiKey(key: String) = merge("/rest/config/gui") { put("apiKey", key) }
|
||||
fun shutdown() { send("POST", "/rest/system/shutdown", null) }
|
||||
|
||||
private fun merge(path: String, change: JSONObject.() -> Unit) = send("PUT", path, get(path).apply(change))
|
||||
|
||||
/** Long-polls for config saves; returns the last event id seen, or [since] on timeout. */
|
||||
fun waitForConfigSaved(since: Long, timeoutSeconds: Int): Pair<Long, Boolean> {
|
||||
val events = JSONArray(request("GET", "/rest/events?events=ConfigSaved&since=$since&timeout=$timeoutSeconds", null, (timeoutSeconds + 10) * 1000))
|
||||
if (events.length() == 0) return since to false
|
||||
return events.getJSONObject(events.length() - 1).getLong("id") to true
|
||||
}
|
||||
|
||||
private fun get(path: String) = JSONObject(request("GET", path, null, TIMEOUT_MS))
|
||||
private fun getArray(path: String) = JSONArray(request("GET", path, null, TIMEOUT_MS))
|
||||
private fun send(method: String, path: String, body: JSONObject?) { request(method, path, body, TIMEOUT_MS) }
|
||||
|
||||
private fun request(method: String, path: String, body: JSONObject?, timeoutMs: Int): String = LocalSocket().use { s ->
|
||||
s.connect(LocalSocketAddress(socket.path, LocalSocketAddress.Namespace.FILESYSTEM))
|
||||
s.soTimeout = timeoutMs
|
||||
val headers = listOf("X-API-Key" to apiKey) + if (body != null) listOf("Content-Type" to "application/json") else emptyList()
|
||||
SyncthingHttp.writeRequest(s.outputStream, method, path, headers, body?.toString()?.toByteArray())
|
||||
val (code, text) = SyncthingHttp.readResponse(s.inputStream.buffered())
|
||||
if (code !in 200..299) throw SyncthingApiException(code, text)
|
||||
text
|
||||
}
|
||||
|
||||
private fun enc(s: String) = URLEncoder.encode(s, "UTF-8")
|
||||
|
||||
companion object { private const val TIMEOUT_MS = 5_000 }
|
||||
}
|
||||
|
||||
class SyncthingApiException(val code: Int, message: String) : Exception("HTTP $code: $message")
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import org.w3c.dom.Document
|
||||
import org.w3c.dom.Element
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.StringReader
|
||||
import java.io.StringWriter
|
||||
import javax.xml.parsers.DocumentBuilderFactory
|
||||
import javax.xml.transform.OutputKeys
|
||||
import javax.xml.transform.TransformerFactory
|
||||
import javax.xml.transform.dom.DOMSource
|
||||
import javax.xml.transform.stream.StreamResult
|
||||
import org.xml.sax.InputSource
|
||||
|
||||
object SyncthingConfig {
|
||||
const val GUI_USER = "droiddeck"
|
||||
private const val RELAYS = "dynamic+https://relays.syncthing.net/endpoint"
|
||||
|
||||
fun apiKey(file: File): String? = runCatching { apiKey(file.readText()) }.getOrNull()
|
||||
|
||||
internal fun apiKey(xml: String): String? =
|
||||
parse(xml).documentElement.child("gui")?.child("apikey")?.textContent?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
fun apply(file: File, ports: SyncthingPorts, guiSocket: File, folderRoot: File, pauseDevices: Boolean, allows: (String) -> Boolean) {
|
||||
val staged = File(file.parentFile, "${file.name}.tmp")
|
||||
try {
|
||||
staged.writeText(apply(file.readText(), ports, guiSocket.path, folderRoot.path, pauseDevices, allows))
|
||||
if (!staged.renameTo(file)) throw IOException("could not replace ${file.name}")
|
||||
} finally {
|
||||
staged.delete()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun apply(xml: String, ports: SyncthingPorts, guiSocket: String, folderRoot: String, pauseDevices: Boolean = false, allows: (String) -> Boolean): String {
|
||||
val doc = parse(xml)
|
||||
val root = doc.documentElement
|
||||
val gui = root.child("gui") ?: doc.createElement("gui").also { root.appendChild(it) }
|
||||
gui.setAttribute("tls", "false")
|
||||
// An absolute path makes Syncthing listen on a Unix socket, which other apps can't reach in our private storage.
|
||||
gui.set("address", guiSocket)
|
||||
gui.set("unixSocketPermissions", "600")
|
||||
val options = root.child("options") ?: doc.createElement("options").also { root.appendChild(it) }
|
||||
options.setList("listenAddress", listOf("tcp://:${ports.sync}", "quic://:${ports.sync}", RELAYS))
|
||||
options.set("localAnnouncePort", ports.discovery.toString())
|
||||
options.set("urAccepted", "-1")
|
||||
options.set("crashReportingEnabled", "false")
|
||||
options.set("autoUpgradeIntervalH", "0")
|
||||
options.set("startBrowser", "false")
|
||||
val defaults = root.child("defaults") ?: doc.createElement("defaults").also { root.appendChild(it) }
|
||||
val folder = defaults.child("folder") ?: doc.createElement("folder").also { defaults.appendChild(it) }
|
||||
folder.setAttribute("path", folderRoot)
|
||||
root.children("folder").filter { !allows(it.getAttribute("path")) }.forEach { it.set("paused", "true") }
|
||||
if (pauseDevices) root.children("device").forEach { it.set("paused", "true") }
|
||||
return write(doc)
|
||||
}
|
||||
|
||||
private fun parse(xml: String): Document =
|
||||
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(InputSource(StringReader(xml)))
|
||||
|
||||
private fun write(doc: Document): String = StringWriter().also {
|
||||
TransformerFactory.newInstance().newTransformer().apply { setOutputProperty(OutputKeys.INDENT, "no") }
|
||||
.transform(DOMSource(doc), StreamResult(it))
|
||||
}.toString()
|
||||
|
||||
private fun Element.children(name: String): List<Element> =
|
||||
(0 until childNodes.length).map { childNodes.item(it) }.filterIsInstance<Element>().filter { it.tagName == name }
|
||||
|
||||
private fun Element.child(name: String): Element? = children(name).firstOrNull()
|
||||
|
||||
private fun Element.set(name: String, value: String) = setList(name, listOf(value))
|
||||
|
||||
private fun Element.setList(name: String, values: List<String>) {
|
||||
val existing = children(name)
|
||||
val anchor = existing.lastOrNull()?.nextSibling
|
||||
existing.forEach { removeChild(it) }
|
||||
values.forEach { value ->
|
||||
val e = ownerDocument.createElement(name).apply { textContent = value }
|
||||
if (anchor != null) insertBefore(e, anchor) else appendChild(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import java.io.File
|
||||
|
||||
/** Decides which Syncthing folder paths stay inside DroidDeck's own storage. */
|
||||
class SyncthingGuard(private val home: File, roots: List<File>, forbidden: List<File>) {
|
||||
private val roots = roots.map { it.canonicalFile }
|
||||
private val forbidden = forbidden.map { it.canonicalFile }
|
||||
|
||||
fun allows(path: String): Boolean {
|
||||
val trimmed = path.trim()
|
||||
if (trimmed.isEmpty()) return false
|
||||
val expanded = when {
|
||||
trimmed == "~" -> home
|
||||
trimmed.startsWith("~/") -> File(home, trimmed.removePrefix("~/"))
|
||||
else -> File(trimmed)
|
||||
}
|
||||
if (!expanded.isAbsolute) return false
|
||||
val target = runCatching { expanded.canonicalFile }.getOrNull() ?: return false
|
||||
return roots.any { within(target, it) } && forbidden.none { within(target, it) || within(it, target) }
|
||||
}
|
||||
|
||||
/** Whether [dir] can be opened while looking for a folder: inside DroidDeck's storage and outside Syncthing's own files. */
|
||||
fun browsable(dir: File): Boolean {
|
||||
val target = runCatching { dir.canonicalFile }.getOrNull() ?: return false
|
||||
return roots.any { within(target, it) } && forbidden.none { within(target, it) }
|
||||
}
|
||||
|
||||
private fun within(target: File, root: File) = target == root || target.path.startsWith(root.path + File.separator)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.io.OutputStream
|
||||
|
||||
/** Just enough HTTP/1.1 to talk to Syncthing over its Unix socket, one request per connection. */
|
||||
internal object SyncthingHttp {
|
||||
private const val LINE_LIMIT = 16 shl 10
|
||||
private const val HEADER_LIMIT = 100
|
||||
|
||||
fun writeRequest(out: OutputStream, method: String, path: String, headers: List<Pair<String, String>>, body: ByteArray?) {
|
||||
val head = StringBuilder("$method $path HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n")
|
||||
headers.forEach { (name, value) -> head.append(name).append(": ").append(value).append("\r\n") }
|
||||
head.append("Content-Length: ").append(body?.size ?: 0).append("\r\n\r\n")
|
||||
out.write(head.toString().toByteArray(Charsets.ISO_8859_1))
|
||||
body?.let(out::write)
|
||||
out.flush()
|
||||
}
|
||||
|
||||
fun readResponse(input: InputStream): Pair<Int, String> {
|
||||
val status = readLine(input) ?: throw IOException("no response")
|
||||
val code = status.split(' ').getOrNull(1)?.toIntOrNull() ?: throw IOException("bad status line: $status")
|
||||
val headers = readHeaders(input)
|
||||
fun header(name: String) = headers.lastOrNull { it.first.equals(name, ignoreCase = true) }?.second
|
||||
val body = when {
|
||||
header("Transfer-Encoding")?.contains("chunked", ignoreCase = true) == true -> chunked(input)
|
||||
header("Content-Length") != null -> exactly(input, header("Content-Length")!!.trim().toInt())
|
||||
else -> input.readBytes()
|
||||
}
|
||||
return code to String(body, Charsets.UTF_8)
|
||||
}
|
||||
|
||||
/** Reads one CRLF-terminated line, or null at end of stream. */
|
||||
fun readLine(input: InputStream): String? {
|
||||
val line = ByteArrayOutputStream()
|
||||
while (true) {
|
||||
val b = input.read()
|
||||
if (b == -1) return if (line.size() == 0) null else throw IOException("truncated line")
|
||||
if (b == '\n'.code) break
|
||||
if (line.size() >= LINE_LIMIT) throw IOException("line too long")
|
||||
line.write(b)
|
||||
}
|
||||
return line.toString("ISO-8859-1").removeSuffix("\r")
|
||||
}
|
||||
|
||||
fun readHeaders(input: InputStream): List<Pair<String, String>> {
|
||||
val headers = mutableListOf<Pair<String, String>>()
|
||||
while (true) {
|
||||
val line = readLine(input) ?: throw IOException("truncated headers")
|
||||
if (line.isEmpty()) return headers
|
||||
if (headers.size >= HEADER_LIMIT) throw IOException("too many headers")
|
||||
val colon = line.indexOf(':')
|
||||
if (colon <= 0) throw IOException("bad header: $line")
|
||||
headers += line.substring(0, colon).trim() to line.substring(colon + 1).trim()
|
||||
}
|
||||
}
|
||||
|
||||
private fun chunked(input: InputStream): ByteArray {
|
||||
val out = ByteArrayOutputStream()
|
||||
while (true) {
|
||||
val size = readLine(input)?.substringBefore(';')?.trim()?.toIntOrNull(16) ?: throw IOException("bad chunk size")
|
||||
if (size == 0) break
|
||||
out.write(exactly(input, size))
|
||||
readLine(input)
|
||||
}
|
||||
while (readLine(input)?.isNotEmpty() == true) Unit
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
private fun exactly(input: InputStream, size: Int): ByteArray {
|
||||
val bytes = ByteArray(size)
|
||||
var read = 0
|
||||
while (read < size) {
|
||||
val n = input.read(bytes, read, size - read)
|
||||
if (n == -1) throw IOException("truncated body")
|
||||
read += n
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import java.net.DatagramSocket
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.ServerSocket
|
||||
|
||||
data class SyncthingPorts(val sync: Int, val discovery: Int)
|
||||
|
||||
object SyncthingPortPicker {
|
||||
// Syncthing's defaults, plus the alternates Syncthing-Fork's debug build uses.
|
||||
internal val RESERVED = setOf(8384, 8385, 22000, 22001, 21027, 21028)
|
||||
internal const val SYNC = 22100
|
||||
internal const val DISCOVERY = 21127
|
||||
private const val SPAN = 50
|
||||
|
||||
fun pick(): SyncthingPorts = pick(::syncFree, ::udpFree)
|
||||
|
||||
internal fun pick(syncFree: (Int) -> Boolean, discoveryFree: (Int) -> Boolean) =
|
||||
SyncthingPorts(first(SYNC, syncFree), first(DISCOVERY, discoveryFree))
|
||||
|
||||
private fun first(base: Int, free: (Int) -> Boolean): Int =
|
||||
(base until base + SPAN).firstOrNull { it !in RESERVED && free(it) } ?: error("no free port in $base..${base + SPAN - 1}")
|
||||
|
||||
private fun tcpFree(port: Int): Boolean = runCatching {
|
||||
ServerSocket().use { it.reuseAddress = false; it.bind(InetSocketAddress(port)) }
|
||||
}.isSuccess
|
||||
|
||||
private fun udpFree(port: Int) = runCatching { DatagramSocket(port).close() }.isSuccess
|
||||
private fun syncFree(port: Int) = tcpFree(port) && udpFree(port)
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import android.net.LocalSocket
|
||||
import android.net.LocalSocketAddress
|
||||
import java.io.Closeable
|
||||
import java.io.File
|
||||
import java.io.FilterInputStream
|
||||
import java.io.InputStream
|
||||
import java.net.InetAddress
|
||||
import java.net.ServerSocket
|
||||
import java.net.Socket
|
||||
import java.net.SocketTimeoutException
|
||||
import java.security.MessageDigest
|
||||
import java.util.Collections
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.Semaphore
|
||||
|
||||
/**
|
||||
* Bridges the in-app WebView to Syncthing's Unix socket while the web UI is open. Any app can connect to a
|
||||
* loopback port, so requests without this session's cookie are refused before they reach Syncthing.
|
||||
*/
|
||||
class SyncthingProxy(private val socket: File, private val auth: String) : Closeable {
|
||||
// Android's getLoopbackAddress() is ::1, but the WebView is pointed at 127.0.0.1.
|
||||
private val server = ServerSocket(0, 16, InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)))
|
||||
private val token = SyncPrefs.randomToken()
|
||||
val url = "http://127.0.0.1:${server.localPort}/"
|
||||
val cookie = "$COOKIE=$token"
|
||||
private val workers = Semaphore(MAX_WORKERS)
|
||||
private val open: MutableSet<Closeable> = Collections.newSetFromMap(ConcurrentHashMap())
|
||||
|
||||
init {
|
||||
Thread(::accept, "syncthing-proxy").apply { isDaemon = true }.start()
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
runCatching { server.close() }
|
||||
open.forEach { runCatching { it.close() } }
|
||||
}
|
||||
|
||||
private fun track(c: Closeable) {
|
||||
open += c
|
||||
if (server.isClosed) runCatching { c.close() }
|
||||
}
|
||||
|
||||
private fun accept() {
|
||||
while (true) {
|
||||
val client = runCatching { server.accept() }.getOrNull() ?: return
|
||||
if (!workers.tryAcquire()) {
|
||||
runCatching { client.close() }
|
||||
continue
|
||||
}
|
||||
val worker = runCatching {
|
||||
track(client)
|
||||
Thread({ try { serve(client) } finally { open -= client; workers.release() } }, "syncthing-proxy-request").apply { isDaemon = true }.start()
|
||||
}
|
||||
if (worker.isFailure) { open -= client; workers.release(); runCatching { client.close() } }
|
||||
}
|
||||
}
|
||||
|
||||
private fun serve(client: Socket) = client.use {
|
||||
runCatching {
|
||||
val deadline = HeadDeadline(client, client.getInputStream(), System.nanoTime() + HEAD_TIMEOUT_MS * 1_000_000L)
|
||||
val input = deadline.buffered()
|
||||
val request = SyncthingHttp.readLine(input) ?: return@runCatching
|
||||
val headers = SyncthingHttp.readHeaders(input)
|
||||
if (!authorized(headers)) {
|
||||
client.getOutputStream().write(FORBIDDEN)
|
||||
return@runCatching
|
||||
}
|
||||
deadline.lift()
|
||||
LocalSocket().use { upstream ->
|
||||
track(upstream)
|
||||
try { relay(client, input, request, headers, upstream) } finally { open -= upstream }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun relay(client: Socket, input: InputStream, request: String, headers: List<Pair<String, String>>, upstream: LocalSocket) {
|
||||
upstream.connect(LocalSocketAddress(socket.path, LocalSocketAddress.Namespace.FILESYSTEM))
|
||||
val head = StringBuilder(request).append("\r\n")
|
||||
headers.filter { it.first.lowercase() !in DROPPED }.forEach { (name, value) ->
|
||||
val kept = if (name.equals("Cookie", ignoreCase = true)) withoutToken(value) else value
|
||||
if (kept.isNotEmpty()) head.append(name).append(": ").append(kept).append("\r\n")
|
||||
}
|
||||
// One request per connection keeps every request behind serve's cookie check.
|
||||
head.append("Authorization: ").append(auth).append("\r\nConnection: close\r\n\r\n")
|
||||
upstream.outputStream.write(head.toString().toByteArray(Charsets.ISO_8859_1))
|
||||
Thread({ runCatching { input.copyTo(upstream.outputStream) } }, "syncthing-proxy-body").apply { isDaemon = true }.start()
|
||||
upstream.inputStream.copyTo(client.getOutputStream())
|
||||
}
|
||||
|
||||
private fun cookies(header: String) = header.split(';').map { it.trim() }
|
||||
|
||||
private fun authorized(headers: List<Pair<String, String>>): Boolean = headers
|
||||
.filter { it.first.equals("Cookie", ignoreCase = true) }
|
||||
.flatMap { cookies(it.second) }
|
||||
.any { MessageDigest.isEqual(it.toByteArray(), cookie.toByteArray()) }
|
||||
|
||||
private fun withoutToken(header: String) = cookies(header).filter { !it.startsWith("$COOKIE=") }.joinToString("; ")
|
||||
|
||||
/** Bounds the whole request line and headers by one deadline, so a slow client can't hold a worker. */
|
||||
private class HeadDeadline(private val client: Socket, input: InputStream, private val until: Long) : FilterInputStream(input) {
|
||||
@Volatile private var lifted = false
|
||||
|
||||
fun lift() {
|
||||
lifted = true
|
||||
client.soTimeout = 0
|
||||
}
|
||||
|
||||
override fun read(): Int { arm(); return super.read() }
|
||||
override fun read(b: ByteArray, off: Int, len: Int): Int { arm(); return super.read(b, off, len) }
|
||||
|
||||
private fun arm() {
|
||||
if (lifted) return
|
||||
val left = (until - System.nanoTime()) / 1_000_000L
|
||||
if (left <= 0) throw SocketTimeoutException("request head took too long")
|
||||
client.soTimeout = left.toInt()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val COOKIE = "droiddeck-proxy"
|
||||
const val HEAD_TIMEOUT_MS = 10_000
|
||||
const val MAX_WORKERS = 16
|
||||
val DROPPED = setOf("authorization", "x-api-key", "connection", "proxy-connection", "keep-alive", "upgrade")
|
||||
val FORBIDDEN = "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".toByteArray()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import com.droiddeck.launcher.FrontEndActivity
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadService
|
||||
|
||||
/** Keeps the app process, and with it Syncthing, alive while "Run in the background" is chosen. */
|
||||
class SyncthingService : Service() {
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_PAUSE -> Syncthing.setPaused(this, !Syncthing.userPaused)
|
||||
ACTION_OFF -> { Syncthing.setEnabled(this, false); return START_NOT_STICKY }
|
||||
}
|
||||
if (!SyncPrefs.enabled(this) || SyncPrefs.runMode(this) != SyncPrefs.RUN_BACKGROUND) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
val n = notification()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) startForeground(ID, n, android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
|
||||
else startForeground(ID, n)
|
||||
Syncthing.onChange = { getSystemService(NotificationManager::class.java)?.notify(ID, notification()) }
|
||||
Syncthing.evaluate()
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
Syncthing.onChange = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun notification(): Notification {
|
||||
channel(this)
|
||||
val snap = Syncthing.snapshot
|
||||
val title = getString(when {
|
||||
Syncthing.phase == Syncthing.Phase.FAILED -> R.string.sync_status_failed
|
||||
Syncthing.phase != Syncthing.Phase.RUNNING -> R.string.sync_status_starting
|
||||
Syncthing.pauseRequested && Syncthing.devicesPaused -> R.string.sync_status_paused
|
||||
Syncthing.pauseRequested -> R.string.sync_status_pausing
|
||||
Syncthing.devicesPaused -> R.string.sync_status_resuming
|
||||
snap?.needsAttention == true -> R.string.sync_status_attention
|
||||
snap?.syncing == true -> R.string.sync_status_syncing
|
||||
else -> R.string.sync_status_up_to_date
|
||||
})
|
||||
val text = snap?.let {
|
||||
getString(R.string.sync_summary, it.folders.size, it.devices.count { d -> d.connected }, it.devices.size)
|
||||
}.orEmpty()
|
||||
val open = PendingIntent.getActivity(this, 0, Intent(this, FrontEndActivity::class.java)
|
||||
.putExtra(StoreDownloadService.EXTRA_NAV, NAV).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) Notification.Builder(this, CHANNEL) else @Suppress("DEPRECATION") Notification.Builder(this)
|
||||
return builder.setSmallIcon(R.drawable.ic_stat_session)
|
||||
.setContentTitle(title)
|
||||
.setContentText(text)
|
||||
.setContentIntent(open)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.addAction(Notification.Action.Builder(null, getString(if (Syncthing.userPaused) R.string.sync_resume else R.string.sync_pause), action(ACTION_PAUSE, 1)).build())
|
||||
.addAction(Notification.Action.Builder(null, getString(R.string.sync_turn_off), action(ACTION_OFF, 2)).build())
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun action(name: String, code: Int) = PendingIntent.getService(this, code,
|
||||
Intent(this, SyncthingService::class.java).setAction(name), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
|
||||
companion object {
|
||||
const val NAV = "setup:sync"
|
||||
private const val CHANNEL = "syncthing"
|
||||
private const val ID = 9203
|
||||
private const val ACTION_PAUSE = "droiddeck.sync.PAUSE"
|
||||
private const val ACTION_OFF = "droiddeck.sync.OFF"
|
||||
@Volatile private var running = false
|
||||
|
||||
private fun channel(context: Context) {
|
||||
val nm = context.getSystemService(NotificationManager::class.java) ?: return
|
||||
if (nm.getNotificationChannel(CHANNEL) == null) {
|
||||
nm.createNotificationChannel(NotificationChannel(CHANNEL, context.getString(R.string.sync_notification_channel), NotificationManager.IMPORTANCE_LOW).apply {
|
||||
setShowBadge(false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fun start(context: Context) {
|
||||
if (running) return
|
||||
running = true
|
||||
runCatching { context.startForegroundService(Intent(context, SyncthingService::class.java)) }.onFailure { running = false }
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
if (!running) return
|
||||
running = false
|
||||
context.stopService(Intent(context, SyncthingService::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
|
||||
data class SyncFolder(
|
||||
val id: String, val label: String, val path: String, val paused: Boolean, val blocked: Boolean,
|
||||
val state: String, val globalBytes: Long, val needBytes: Long, val errors: Int, val sharedWith: List<String>,
|
||||
) {
|
||||
val syncing get() = !paused && !blocked && state in ACTIVE && needBytes > 0
|
||||
val outOfSync get() = !paused && !blocked && (errors > 0 || state == "error" || (state == "idle" && needBytes > 0))
|
||||
|
||||
companion object { private val ACTIVE = setOf("syncing", "sync-preparing", "sync-waiting") }
|
||||
}
|
||||
|
||||
data class SyncDevice(val id: String, val name: String, val connected: Boolean, val address: String?, val lastSeen: Long?)
|
||||
|
||||
data class SyncPendingFolder(val id: String, val label: String, val offeredBy: String, val deviceId: String)
|
||||
|
||||
data class SyncSnapshot(
|
||||
val myId: String,
|
||||
val folders: List<SyncFolder>,
|
||||
val devices: List<SyncDevice>,
|
||||
val pendingFolders: List<SyncPendingFolder>,
|
||||
val pendingDevices: List<String>,
|
||||
val inBytesPerSecond: Long,
|
||||
val outBytesPerSecond: Long,
|
||||
) {
|
||||
val blocked get() = folders.filter { it.blocked }
|
||||
val needsAttention get() = blocked.isNotEmpty() || pendingFolders.isNotEmpty() || pendingDevices.isNotEmpty() || folders.any { it.outOfSync }
|
||||
val syncing get() = folders.any { it.syncing }
|
||||
val needBytes get() = folders.filter { it.syncing }.sumOf { it.needBytes }
|
||||
|
||||
/** Share of the syncing folders' data already in place, 0..100. */
|
||||
val percent: Int get() {
|
||||
val active = folders.filter { it.syncing }
|
||||
val global = active.sumOf { it.globalBytes }
|
||||
if (global <= 0) return 0
|
||||
return (((global - active.sumOf { it.needBytes }).coerceAtLeast(0) * 100) / global).toInt().coerceIn(0, 99)
|
||||
}
|
||||
}
|
||||
|
||||
internal object SyncthingParse {
|
||||
/** Stands in for a folder whose status request failed, so it shows as an error rather than as up to date. */
|
||||
fun unreadableStatus(): JSONObject = JSONObject().put("state", "error").put("errors", 1)
|
||||
|
||||
fun folder(config: JSONObject, status: JSONObject?, blocked: Boolean, names: Map<String, String>): SyncFolder {
|
||||
val id = config.getString("id")
|
||||
val shared = config.optJSONArray("devices")?.let { d -> (0 until d.length()).mapNotNull { names[d.getJSONObject(it).optString("deviceID")] } }.orEmpty()
|
||||
return SyncFolder(
|
||||
id, config.optString("label").ifEmpty { id }, config.optString("path"), blocked || config.optBoolean("paused"), blocked,
|
||||
status?.optString("state").orEmpty(), status?.optLong("globalBytes") ?: 0, status?.optLong("needBytes") ?: 0,
|
||||
(status?.optInt("errors") ?: 0) + (status?.optInt("pullErrors") ?: 0), shared,
|
||||
)
|
||||
}
|
||||
|
||||
fun deviceNames(devices: JSONArray, myId: String): Map<String, String> = (0 until devices.length())
|
||||
.map { devices.getJSONObject(it) }
|
||||
.filter { it.getString("deviceID") != myId }
|
||||
.associate { it.getString("deviceID") to it.optString("name").ifEmpty { it.getString("deviceID").take(7) } }
|
||||
|
||||
fun pendingDevices(json: JSONObject): List<String> =
|
||||
json.keys().asSequence().map { id -> json.optJSONObject(id)?.optString("name").orEmpty().ifEmpty { id.take(7) } }.toList()
|
||||
|
||||
fun pendingFolders(json: JSONObject, names: Map<String, String>): List<SyncPendingFolder> =
|
||||
json.keys().asSequence().flatMap { folderId ->
|
||||
val offeredBy = json.getJSONObject(folderId).optJSONObject("offeredBy") ?: JSONObject()
|
||||
offeredBy.keys().asSequence().map { device ->
|
||||
val label = offeredBy.getJSONObject(device).optString("label").ifEmpty { folderId }
|
||||
SyncPendingFolder(folderId, label, names[device] ?: device.take(7), device)
|
||||
}
|
||||
}.toList()
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.droiddeck.launcher.sync
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.ui.BackLink
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.LocalPalette
|
||||
import com.droiddeck.launcher.ui.SecondaryButton
|
||||
|
||||
/** Syncthing's own web UI, signed in automatically and kept on the loopback address. */
|
||||
class SyncthingWebActivity : ComponentActivity() {
|
||||
private var web: WebView? = null
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent { DroidDeckTheme(appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)) { Screen() } }
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
web?.destroy()
|
||||
web = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Screen() {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val running = Syncthing.phase == Syncthing.Phase.RUNNING
|
||||
val target = remember(running) { if (running) Syncthing.webUiProxy(this) else null }
|
||||
DisposableEffect(target) { onDispose { target?.close() } }
|
||||
LaunchedEffect(Syncthing.phase) { if (Syncthing.phase == Syncthing.Phase.OFF) finish() }
|
||||
BackHandler { web?.takeIf { it.canGoBack() }?.goBack() ?: finish() }
|
||||
Column(Modifier.fillMaxSize().background(colors.background)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.fillMaxWidth().background(colors.surface).padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
) {
|
||||
BackLink(stringResource(R.string.mode_back), compact = true) { finish() }
|
||||
Text(stringResource(R.string.sync_web_title), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Box(Modifier.weight(1f))
|
||||
target?.let { Text(Uri.parse(it.url).authority.orEmpty(), fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant) }
|
||||
SecondaryButton(stringResource(R.string.sync_web_reload), compact = true) { web?.reload() }
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
if (target == null) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Text(stringResource(R.string.sync_not_running), fontSize = 14.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
} else {
|
||||
val view = remember(target) { webView(target.url, target.cookie) }
|
||||
AndroidView({ view }, Modifier.fillMaxSize())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
private fun webView(url: String, cookie: String): WebView = WebView(this).apply {
|
||||
web?.destroy()
|
||||
web = this
|
||||
setBackgroundColor(0xFF0A0B0D.toInt())
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true
|
||||
settings.allowFileAccess = false
|
||||
settings.allowContentAccess = false
|
||||
val cookies = CookieManager.getInstance()
|
||||
cookies.setAcceptCookie(true)
|
||||
val origin = Uri.parse(url).authority
|
||||
webViewClient = object : WebViewClient() {
|
||||
// The proxy cookie isn't port-scoped, so nothing else on loopback may receive it.
|
||||
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? =
|
||||
if (request.url.authority == origin) null else WebResourceResponse("text/plain", "utf-8", 403, "Forbidden", emptyMap(), null)
|
||||
|
||||
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean =
|
||||
request.url.authority != origin
|
||||
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
view.evaluateJavascript(lockFolderPath(getString(R.string.sync_web_path_locked)), null)
|
||||
}
|
||||
}
|
||||
cookies.setCookie(url, "$cookie; HttpOnly; SameSite=Strict") { loadUrl(url) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Keeps Syncthing's folder path field read-only, so new folders get the default path inside DroidDeck's Sync folder. */
|
||||
private fun lockFolderPath(note: String) = """
|
||||
(function (note) {
|
||||
if (window.droiddeckPathLock) return;
|
||||
window.droiddeckPathLock = true;
|
||||
function lock() {
|
||||
var input = document.getElementById('folderPath');
|
||||
if (!input) return;
|
||||
if (!input.readOnly) input.readOnly = true;
|
||||
if (input.hasAttribute('list')) input.removeAttribute('list');
|
||||
if (!document.getElementById('droiddeck-path-note')) {
|
||||
var p = document.createElement('p');
|
||||
p.id = 'droiddeck-path-note';
|
||||
p.className = 'help-block';
|
||||
p.textContent = note;
|
||||
input.parentNode.insertBefore(p, input.nextSibling);
|
||||
}
|
||||
}
|
||||
new MutationObserver(lock).observe(document.documentElement, { subtree: true, childList: true, attributes: true, attributeFilter: ['readonly'] });
|
||||
lock();
|
||||
})(${org.json.JSONObject.quote(note)});
|
||||
""".trimIndent()
|
||||
@@ -203,7 +203,7 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
|
||||
}
|
||||
|
||||
internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) ||
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) || com.droiddeck.launcher.sync.Syncthing.needsAttention
|
||||
|
||||
@Composable
|
||||
private fun NavigationItems(
|
||||
|
||||
@@ -435,6 +435,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
"stores:downloads" -> { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" }
|
||||
"components" -> a.onComponents(true)
|
||||
"setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" }
|
||||
com.droiddeck.launcher.sync.SyncthingService.NAV -> com.droiddeck.launcher.sync.Syncthing.requestOpen()
|
||||
"setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" }
|
||||
else -> selected = target
|
||||
}
|
||||
@@ -554,6 +555,9 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
LaunchedEffect(com.droiddeck.launcher.storage.StorageState.openRequests) {
|
||||
if (com.droiddeck.launcher.storage.StorageState.openPending) showRailPage("setup", true)
|
||||
}
|
||||
LaunchedEffect(com.droiddeck.launcher.sync.Syncthing.openRequests) {
|
||||
if (com.droiddeck.launcher.sync.Syncthing.openPending) showRailPage("setup", true)
|
||||
}
|
||||
val onRailFocus: (String) -> Unit = { key ->
|
||||
if (key != railSelection) showRailPage(key, false)
|
||||
}
|
||||
|
||||
@@ -93,7 +93,8 @@ internal object SetupTabs {
|
||||
var openLauncher = false
|
||||
var openOverview = false
|
||||
}
|
||||
private const val GLASSES_TAB = 5
|
||||
private const val GLASSES_TAB = 6
|
||||
private const val SYNC_TAB = 4
|
||||
|
||||
@Composable
|
||||
private fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) {
|
||||
@@ -190,7 +191,7 @@ internal fun SetupPanel(
|
||||
onDismiss = { editDownloadProxy = false },
|
||||
onSave = { a.onDownloadProxy(it); editDownloadProxy = false },
|
||||
)
|
||||
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
|
||||
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_sync), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses))
|
||||
var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) }
|
||||
SetupTabs.openLauncher = false
|
||||
if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false }
|
||||
@@ -210,6 +211,18 @@ internal fun SetupPanel(
|
||||
a.onRefreshPhantomStatus()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(com.droiddeck.launcher.sync.Syncthing.openRequests) {
|
||||
if (com.droiddeck.launcher.sync.Syncthing.openPending) {
|
||||
com.droiddeck.launcher.sync.Syncthing.openPending = false
|
||||
tab = SYNC_TAB
|
||||
}
|
||||
}
|
||||
var syncAdvanced by rememberSaveable { mutableStateOf(false) }
|
||||
if (syncAdvanced) {
|
||||
androidx.activity.compose.BackHandler { syncAdvanced = false }
|
||||
SyncAdvancedPage(host) { syncAdvanced = false }
|
||||
return
|
||||
}
|
||||
LaunchedEffect(tab) {
|
||||
if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) {
|
||||
androidx.compose.runtime.withFrameNanos { }
|
||||
@@ -492,7 +505,8 @@ internal fun SetupPanel(
|
||||
}
|
||||
}
|
||||
STORAGE_TAB -> StoragePanel(s, a)
|
||||
4 -> {
|
||||
SYNC_TAB -> SyncPanel(host, runtimeOk) { syncAdvanced = true }
|
||||
5 -> {
|
||||
SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) {
|
||||
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
|
||||
ToggleRow(
|
||||
|
||||
@@ -489,10 +489,11 @@ fun <T> ChoiceRow(
|
||||
options: List<Pair<T, String>>, selected: T, enabled: Boolean = true, note: String? = null,
|
||||
chipModifier: Modifier = Modifier,
|
||||
hintLines: Int? = null,
|
||||
stacked: Boolean = false,
|
||||
onPick: (T) -> Unit,
|
||||
) {
|
||||
val open = host.open == key
|
||||
SettingsRow(label, hint, highlighted = open, hintLines = hintLines) {
|
||||
SettingsRow(label, hint, highlighted = open, hintLines = hintLines, stacked = stacked) {
|
||||
Box {
|
||||
ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier.testTag("setting-$key")) { host.open = if (open) null else key }
|
||||
AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus ->
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.content.FileProvider
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.sync.SyncPrefs
|
||||
import com.droiddeck.launcher.sync.Syncthing
|
||||
import java.io.File
|
||||
|
||||
@Composable
|
||||
internal fun SyncAdvancedPage(host: MenuHost, onBack: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
var runMode by remember { mutableStateOf(SyncPrefs.runMode(ctx)) }
|
||||
var wifiOnly by remember { mutableStateOf(SyncPrefs.wifiOnly(ctx)) }
|
||||
var pauseInGames by remember { mutableStateOf(SyncPrefs.pauseInGames(ctx)) }
|
||||
var confirmReset by rememberSaveable { mutableStateOf(false) }
|
||||
if (confirmReset) ResetDialog(onDismiss = { confirmReset = false }) { Syncthing.reset(ctx) }
|
||||
val ports = Syncthing.ports
|
||||
SettingsPage(host, stringResource(R.string.sync_advanced), onBack, eyebrow = stringResource(R.string.setup_tab_sync)) {
|
||||
PairedColumns(
|
||||
{
|
||||
SettingsGroup(stringResource(R.string.sync_ports)) {
|
||||
PortRow(stringResource(R.string.sync_port_sync), ports?.sync?.toString())
|
||||
PortRow(stringResource(R.string.sync_port_discovery), ports?.discovery?.toString())
|
||||
ActionRow(stringResource(R.string.sync_repick), stringResource(R.string.sync_repick_hint), stringResource(R.string.sync_repick_button), onClick = { Syncthing.restart() })
|
||||
}
|
||||
},
|
||||
{
|
||||
SettingsGroup(stringResource(R.string.sync_running_group)) {
|
||||
ChoiceRow(
|
||||
host, "sync-run", stringResource(R.string.sync_run), null,
|
||||
listOf(SyncPrefs.RUN_WHILE_OPEN to stringResource(R.string.sync_run_open), SyncPrefs.RUN_BACKGROUND to stringResource(R.string.sync_run_background)),
|
||||
runMode, stacked = true,
|
||||
) { SyncPrefs.setRunMode(ctx, it); runMode = it; Syncthing.settingsChanged() }
|
||||
ToggleRow(host, "sync-wifi", stringResource(R.string.sync_wifi_only), null, wifiOnly) {
|
||||
SyncPrefs.setWifiOnly(ctx, it); wifiOnly = it; Syncthing.settingsChanged()
|
||||
}
|
||||
ToggleRow(host, "sync-games", stringResource(R.string.sync_pause_games), null, pauseInGames) {
|
||||
SyncPrefs.setPauseInGames(ctx, it); pauseInGames = it; Syncthing.settingsChanged()
|
||||
}
|
||||
ActionRow(stringResource(R.string.sync_logs), stringResource(R.string.sync_logs_hint), stringResource(R.string.sync_logs_share), onClick = { shareLog(ctx) })
|
||||
}
|
||||
},
|
||||
)
|
||||
SettingsGroup(stringResource(R.string.sync_reset_group)) {
|
||||
SettingsRow(stringResource(R.string.sync_api_key), Syncthing.apiKeyTail?.let { "••••••••••••••••••••$it" }) {
|
||||
SecondaryButton(stringResource(R.string.sync_regenerate), enabled = Syncthing.phase == Syncthing.Phase.RUNNING, compact = true) { Syncthing.regenerateApiKey() }
|
||||
}
|
||||
ActionRow(stringResource(R.string.sync_reset), stringResource(R.string.sync_reset_hint), stringResource(R.string.sync_reset_button), onClick = { confirmReset = true })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PortRow(label: String, value: String?) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
SettingsRow(label, null) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(value ?: "—", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
|
||||
Text(stringResource(R.string.common_auto).uppercase(), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ResetDialog(onDismiss: () -> Unit, onReset: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
AppDialog(shown, close, "syncReset", wide = false, maxWidth = 480.dp) {
|
||||
DialogTitleRow(stringResource(R.string.sync_reset_confirm_title), onClose = close)
|
||||
Text(stringResource(R.string.sync_reset_hint), fontSize = 13.5.sp, color = colors.onSurfaceVariant)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = close)
|
||||
PrimaryButton(stringResource(R.string.sync_reset_button), compact = true) { onReset(); close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun shareLog(context: Context) {
|
||||
val log = Syncthing.logFile(context).takeIf { it.isFile } ?: return
|
||||
val out = File(File(context.cacheDir, "share").apply { mkdirs() }, "syncthing-log.txt")
|
||||
log.copyTo(out, overwrite = true)
|
||||
val uri = FileProvider.getUriForFile(context, context.packageName + ".logs", out)
|
||||
val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_STREAM, uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
send.clipData = ClipData.newRawUri(out.name, uri)
|
||||
context.startActivity(Intent.createChooser(send, context.getString(R.string.logshare_chooser)).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION))
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material.icons.outlined.CreateNewFolder
|
||||
import androidx.compose.material.icons.outlined.Folder
|
||||
import androidx.compose.material.icons.outlined.FolderSpecial
|
||||
import androidx.compose.material.icons.outlined.Home
|
||||
import androidx.compose.material.icons.outlined.SdCard
|
||||
import androidx.compose.material.icons.outlined.Smartphone
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.layout.onSizeChanged
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.sync.Syncthing
|
||||
import java.io.File
|
||||
|
||||
internal class SyncLocation(val root: File, val label: String, val icon: ImageVector)
|
||||
|
||||
/** The Linux runtime's /root, which is HOME for everything DroidDeck runs in the container. */
|
||||
internal fun containerHome(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||
|
||||
internal fun syncLocations(context: Context): List<SyncLocation> {
|
||||
val volumes = pickVolumes(context)
|
||||
val roots = Syncthing.storageRoots(context)
|
||||
val shared = roots.drop(1).mapIndexed { i, root ->
|
||||
val volume = volumes.firstOrNull { root.path.startsWith(it.root.path + "/") }
|
||||
if (i == 0) SyncLocation(root, context.getString(R.string.sync_location_shared), Icons.Outlined.Smartphone)
|
||||
else SyncLocation(root, context.getString(R.string.sync_location_card, volume?.label ?: root.path), Icons.Outlined.SdCard)
|
||||
}
|
||||
val home = containerHome(context).takeIf { it.isDirectory }?.let { SyncLocation(it, context.getString(R.string.sync_location_home), Icons.Outlined.Home) }
|
||||
return listOfNotNull(home, SyncLocation(Syncthing.folderRoot(context), context.getString(R.string.sync_location_sync), Icons.Outlined.FolderSpecial)) +
|
||||
shared + SyncLocation(roots.first(), context.getString(R.string.sync_location_app), Icons.Outlined.Folder)
|
||||
}
|
||||
|
||||
/** Browses only DroidDeck's own storage and returns a folder Syncthing is allowed to use. */
|
||||
@Composable
|
||||
internal fun SyncFolderPicker(title: String, suggestedName: String?, onDismiss: () -> Unit, onPick: (File) -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val density = LocalDensity.current
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
val locations = remember { syncLocations(ctx) }
|
||||
val guard = remember { Syncthing.guard(ctx) }
|
||||
fun locationOf(d: File) = locations.filter { d.path == it.root.path || d.path.startsWith(it.root.path + "/") }.maxByOrNull { it.root.path.length }
|
||||
var dir by remember { mutableStateOf<File?>(containerHome(ctx).takeIf { it.isDirectory } ?: Syncthing.folderRoot(ctx).also { it.mkdirs() }) }
|
||||
var refresh by remember { mutableIntStateOf(0) }
|
||||
var naming by remember { mutableStateOf(false) }
|
||||
val location = dir?.let { locationOf(it) }
|
||||
val up = { dir = dir?.let { d -> if (location == null || d.path == location.root.path) null else d.parentFile } }
|
||||
val back = { if (dir == null) close() else up() }
|
||||
val first = remember(dir) { FocusRequester() }
|
||||
LaunchedEffect(dir) { focusWithinFrames({ false }) { first } }
|
||||
val folders = remember(dir, refresh) {
|
||||
dir?.listFiles()?.filter { it.isDirectory && it.canRead() && guard.browsable(it) }
|
||||
?.sortedBy { it.name.lowercase() }.orEmpty()
|
||||
}
|
||||
var locked by remember { mutableStateOf<Dp?>(null) }
|
||||
if (naming) {
|
||||
TextEntryDialog(stringResource(R.string.sync_new_folder), suggestedName.orEmpty(), onDismiss = { naming = false }) { name ->
|
||||
val parent = dir
|
||||
if (parent != null && validName(name)) {
|
||||
val created = File(parent, name)
|
||||
if (created.isDirectory || created.mkdirs()) { dir = created; refresh++ }
|
||||
}
|
||||
}
|
||||
}
|
||||
AppDialog(
|
||||
shown, close, "syncFolderPicker", wide = false, maxWidth = 520.dp, width = locked, fitContent = locked == null, back = back,
|
||||
modifier = Modifier.onSizeChanged { if (locked == null && it.width > 0) locked = with(density) { it.width.toDp() } },
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
DialogTitleRow(title, onClose = close)
|
||||
if (dir != null && location != null) {
|
||||
val crumbs = listOf(location.label) + dir!!.path.removePrefix(location.root.path).split('/').filter { it.isNotEmpty() }
|
||||
Text(crumbs.joinToString(" › "), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
val maxHeight = (LocalConfiguration.current.screenHeightDp * 0.7f).dp
|
||||
Column(
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()).padding(top = 4.dp),
|
||||
) {
|
||||
if (dir == null) {
|
||||
locations.forEachIndexed { i, l ->
|
||||
key(l.root.path) { PickerRow(l.icon, l.label, null, tall = true, focus = if (i == 0) first else null) { dir = l.root.also { it.mkdirs() } } }
|
||||
}
|
||||
} else {
|
||||
PickerRow(Icons.AutoMirrored.Outlined.ArrowBack, "..", null, focus = first, onClick = up)
|
||||
PickerRow(Icons.Filled.Check, stringResource(R.string.sync_use_folder), null, accent = true, enabled = guard.allows(dir!!.path)) {
|
||||
onPick(dir!!); close()
|
||||
}
|
||||
PickerRow(Icons.Outlined.CreateNewFolder, stringResource(R.string.sync_new_folder), null) { naming = true }
|
||||
for (f in folders) key(f.path) {
|
||||
PickerRow(Icons.Outlined.Folder, f.name, null) { dir = f }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun validName(name: String) = name.isNotBlank() && '/' !in name && name != "." && name != ".."
|
||||
@@ -0,0 +1,437 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.text.format.DateUtils
|
||||
import android.text.format.Formatter
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Block
|
||||
import androidx.compose.material.icons.outlined.Sync
|
||||
import androidx.compose.material.icons.outlined.WarningAmber
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.graphics.FilterQuality
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.sync.SyncDevice
|
||||
import com.droiddeck.launcher.sync.SyncFolder
|
||||
import com.droiddeck.launcher.sync.SyncPendingFolder
|
||||
import com.droiddeck.launcher.sync.SyncSnapshot
|
||||
import com.droiddeck.launcher.sync.Syncthing
|
||||
import com.droiddeck.launcher.sync.SyncthingWebActivity
|
||||
import java.io.File
|
||||
|
||||
@Composable
|
||||
internal fun SyncPanel(host: MenuHost, runtimeReady: Boolean, onAdvanced: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
DisposableEffect(Unit) { val release = Syncthing.watch(); onDispose { release() } }
|
||||
var showId by rememberSaveable { mutableStateOf(false) }
|
||||
var confirmOff by rememberSaveable { mutableStateOf(false) }
|
||||
val snap = Syncthing.snapshot
|
||||
if (showId && snap != null) DeviceIdDialog(snap.myId) { showId = false }
|
||||
if (confirmOff) TurnOffDialog(onDismiss = { confirmOff = false }) { forget ->
|
||||
Syncthing.setEnabled(ctx, false, forget)
|
||||
}
|
||||
val phase = Syncthing.phase
|
||||
when {
|
||||
phase == Syncthing.Phase.FAILED -> SyncFailed(
|
||||
if (Syncthing.failure == Syncthing.FAILURE_MISSING) stringResource(R.string.sync_missing) else Syncthing.failure.orEmpty(),
|
||||
onRetry = { Syncthing.restart() }, onAdvanced = onAdvanced, onOff = { confirmOff = true })
|
||||
!Syncthing.enabled -> SyncOff(host, runtimeReady) { Syncthing.setEnabled(ctx, true) }
|
||||
phase != Syncthing.Phase.RUNNING || snap == null -> SyncStarting()
|
||||
else -> SyncRunning(snap, onShowId = { showId = true }, onAdvanced = onAdvanced, onOff = { confirmOff = true })
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncOff(host: MenuHost, runtimeReady: Boolean, onEnable: () -> Unit) {
|
||||
val missing = Syncthing.failure == Syncthing.FAILURE_MISSING
|
||||
val hint = when {
|
||||
missing -> R.string.sync_missing
|
||||
!runtimeReady -> R.string.sync_needs_runtime
|
||||
else -> R.string.sync_enable_hint
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.sync_group)) {
|
||||
ToggleRow(
|
||||
host, "sync-enable", stringResource(R.string.sync_enable), stringResource(hint), false, enabled = !missing && runtimeReady,
|
||||
) { if (it) onEnable() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncStarting() {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 96.dp),
|
||||
) {
|
||||
CircularProgressIndicator(strokeWidth = 3.dp, color = LocalPalette.current.signal, modifier = Modifier.size(40.dp))
|
||||
Text(stringResource(R.string.sync_starting), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncFailed(reason: String, onRetry: () -> Unit, onAdvanced: () -> Unit, onOff: () -> Unit) {
|
||||
SettingsGroup(stringResource(R.string.sync_group)) {
|
||||
SettingsRow(stringResource(R.string.sync_status_failed), reason) {
|
||||
SecondaryButton(stringResource(R.string.sync_failed_retry), compact = true, onClick = onRetry)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.sync_advanced), stringResource(R.string.sync_advanced_hint)) {
|
||||
SecondaryButton(stringResource(R.string.sync_open), compact = true, onClick = onAdvanced)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.sync_running), stringResource(R.string.sync_running_hint)) {
|
||||
ToggleSwitch(true, label = stringResource(R.string.sync_running)) { if (!it) onOff() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SyncRunning(snap: SyncSnapshot, onShowId: () -> Unit, onAdvanced: () -> Unit, onOff: () -> Unit) {
|
||||
PairedColumns(
|
||||
{
|
||||
SettingsGroup(stringResource(R.string.sync_group)) {
|
||||
StatusCard(snap)
|
||||
SettingsRow(stringResource(R.string.sync_running), stringResource(R.string.sync_running_hint)) {
|
||||
ToggleSwitch(true, label = stringResource(R.string.sync_running)) { if (!it) onOff() }
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.sync_this_device)) {
|
||||
SettingsRow(stringResource(R.string.sync_device_id), shortId(snap.myId)) {
|
||||
SecondaryButton(stringResource(R.string.sync_show_qr), compact = true, onClick = onShowId)
|
||||
}
|
||||
SettingsRow(stringResource(R.string.sync_advanced), stringResource(R.string.sync_advanced_hint)) {
|
||||
SecondaryButton(stringResource(R.string.sync_open), compact = true, onClick = onAdvanced)
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
Waiting(snap)
|
||||
SettingsGroup(stringResource(R.string.sync_folders)) {
|
||||
if (snap.folders.isEmpty()) SettingsRow(stringResource(R.string.sync_no_folders), null) {}
|
||||
snap.folders.sortedByDescending { it.blocked }.forEach { FolderRow(it) }
|
||||
AddFolderRow(snap.devices)
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.sync_devices)) {
|
||||
if (snap.devices.isEmpty()) SettingsRow(stringResource(R.string.sync_no_devices), null) {}
|
||||
snap.devices.forEach { DeviceRow(it) }
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/** Two columns of settings groups side by side, stacked on narrow panes. */
|
||||
@Composable
|
||||
internal fun PairedColumns(left: @Composable ColumnScope.() -> Unit, right: @Composable ColumnScope.() -> Unit) {
|
||||
if (LocalNarrowPane.current) {
|
||||
Column { left(); right() }
|
||||
return
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(20.dp), verticalAlignment = Alignment.Top, modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.weight(1f)) { left() }
|
||||
Column(Modifier.weight(1f)) { right() }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusCard(snap: SyncSnapshot) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val paused = Syncthing.pauseRequested || Syncthing.devicesPaused
|
||||
val (headline, tint) = when {
|
||||
Syncthing.pauseRequested && Syncthing.devicesPaused -> stringResource(R.string.sync_status_paused) to colors.onSurfaceVariant
|
||||
Syncthing.pauseRequested -> stringResource(R.string.sync_status_pausing) to colors.onSurfaceVariant
|
||||
Syncthing.devicesPaused -> stringResource(R.string.sync_status_resuming) to colors.onSurfaceVariant
|
||||
snap.needsAttention -> stringResource(R.string.sync_status_attention) to AttentionAmber
|
||||
snap.syncing -> stringResource(R.string.sync_status_syncing) to pal.signal
|
||||
else -> stringResource(R.string.sync_status_up_to_date) to pal.good
|
||||
}
|
||||
val detail = when (Syncthing.autoPause) {
|
||||
Syncthing.AutoPause.WIFI -> stringResource(R.string.sync_paused_wifi)
|
||||
Syncthing.AutoPause.GAME -> stringResource(R.string.sync_paused_game)
|
||||
null -> if (snap.syncing && !paused) stringResource(R.string.sync_left, Formatter.formatShortFileSize(ctx, snap.needBytes))
|
||||
else stringResource(R.string.sync_summary, snap.folders.size, snap.devices.count { it.connected }, snap.devices.size)
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
when {
|
||||
snap.syncing && !paused -> Icon(Icons.Outlined.Sync, null, tint = tint, modifier = Modifier.size(22.dp))
|
||||
snap.needsAttention && !paused -> Icon(Icons.Outlined.WarningAmber, null, tint = tint, modifier = Modifier.size(22.dp))
|
||||
else -> Box(Modifier.size(12.dp).clip(CircleShape).background(tint))
|
||||
}
|
||||
Text(headline, fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
if (snap.syncing && !paused) Text("${snap.percent}%", fontSize = 22.sp, fontWeight = FontWeight.Bold, color = pal.signal)
|
||||
}
|
||||
if (snap.syncing && !paused) LinearProgressIndicator(
|
||||
progress = { snap.percent / 100f }, color = pal.signal, trackColor = pal.line, modifier = Modifier.fillMaxWidth().height(4.dp).clip(CircleShape),
|
||||
)
|
||||
Text(detail, fontSize = 12.5.sp, color = colors.onSurfaceVariant)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
Text("↓ ${rate(ctx, snap.inBytesPerSecond)}", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
Text("↑ ${rate(ctx, snap.outBytesPerSecond)}", fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
PrimaryButton(stringResource(R.string.sync_open_web_ui), compact = true, modifier = Modifier.weight(1f)) { openWebUi(ctx) }
|
||||
SecondaryButton(stringResource(if (Syncthing.userPaused) R.string.sync_resume else R.string.sync_pause), compact = true) {
|
||||
Syncthing.setPaused(ctx, !Syncthing.userPaused)
|
||||
}
|
||||
}
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Waiting(snap: SyncSnapshot) {
|
||||
if (snap.pendingFolders.isEmpty() && snap.pendingDevices.isEmpty()) return
|
||||
val ctx = LocalContext.current
|
||||
var accepting by remember { mutableStateOf<SyncPendingFolder?>(null) }
|
||||
accepting?.let { f ->
|
||||
SyncFolderPicker(stringResource(R.string.sync_accept_title, f.label), f.label, onDismiss = { accepting = null }) { dir ->
|
||||
Syncthing.addFolder(ctx, dir, f.label, listOf(f.deviceId), f.id) { ok -> if (!ok) addFailed(ctx) }
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.sync_waiting)) {
|
||||
snap.pendingDevices.forEach { name ->
|
||||
SettingsRow(stringResource(R.string.sync_pending_device, name), null, highlighted = true) {
|
||||
SecondaryButton(stringResource(R.string.sync_review), compact = true) { openWebUi(ctx) }
|
||||
}
|
||||
}
|
||||
snap.pendingFolders.forEach { f ->
|
||||
SettingsRow(stringResource(R.string.sync_pending_folder, f.offeredBy, f.label), stringResource(R.string.sync_pending_folder_hint), highlighted = true) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
SecondaryButton(stringResource(R.string.sync_review), compact = true) { openWebUi(ctx) }
|
||||
PrimaryButton(stringResource(R.string.sync_accept), compact = true) { accepting = f }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddFolderRow(devices: List<SyncDevice>) {
|
||||
val ctx = LocalContext.current
|
||||
var picking by remember { mutableStateOf(false) }
|
||||
var picked by remember { mutableStateOf<File?>(null) }
|
||||
if (picking) SyncFolderPicker(stringResource(R.string.sync_add_folder), null, onDismiss = { picking = false }) { picked = it }
|
||||
picked?.let { dir ->
|
||||
ShareFolderDialog(dir, devices, onDismiss = { picked = null }) { chosen ->
|
||||
Syncthing.addFolder(ctx, dir, dir.name, chosen) { ok -> if (!ok) addFailed(ctx) }
|
||||
}
|
||||
}
|
||||
SettingsRow(stringResource(R.string.sync_add_folder), stringResource(R.string.sync_add_folder_hint)) {
|
||||
SecondaryButton(stringResource(R.string.sync_choose), compact = true) { picking = true }
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ShareFolderDialog(folder: File, devices: List<SyncDevice>, onDismiss: () -> Unit, onAdd: (List<String>) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
val chosen = remember { mutableStateListOf<String>() }
|
||||
AppDialog(shown, close, "syncShareFolder", wide = false, maxWidth = 520.dp) {
|
||||
DialogTitleRow(folder.name, onClose = close)
|
||||
Text(folder.path, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
if (devices.isEmpty()) {
|
||||
Text(stringResource(R.string.sync_share_none), fontSize = 13.5.sp, color = colors.onSurfaceVariant)
|
||||
} else {
|
||||
Text(stringResource(R.string.sync_share_with), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
devices.forEach { d ->
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape12).border(1.dp, pal.line, Shape12).background(colors.background).padding(end = 12.dp),
|
||||
) {
|
||||
Checkbox(d.id in chosen, { if (it) chosen.add(d.id) else chosen.remove(d.id) })
|
||||
Text(d.name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = close)
|
||||
PrimaryButton(stringResource(R.string.sync_add), compact = true) { onAdd(chosen.toList()); close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun addFailed(context: Context) {
|
||||
android.widget.Toast.makeText(context, R.string.sync_add_failed, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FolderRow(f: SyncFolder) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
if (f.blocked) {
|
||||
Column(Modifier.fillMaxWidth().background(colors.error.copy(alpha = 0.06f)).padding(horizontal = 14.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
Icon(Icons.Outlined.Block, null, tint = colors.error, modifier = Modifier.size(18.dp))
|
||||
Text(f.label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.weight(1f))
|
||||
Text(stringResource(R.string.sync_folder_blocked), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.error)
|
||||
}
|
||||
Text(f.path, fontSize = 12.5.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
|
||||
Text(stringResource(R.string.sync_folder_blocked_hint), fontSize = 12.5.sp, color = colors.onSurfaceVariant)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 4.dp)) {
|
||||
SecondaryButton(stringResource(R.string.sync_remove_folder), compact = true) { Syncthing.removeFolder(f.id) }
|
||||
SecondaryButton(stringResource(R.string.sync_open_web_ui), compact = true) { openWebUi(ctx) }
|
||||
}
|
||||
Text(stringResource(R.string.sync_remove_folder_hint), fontSize = 12.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
return
|
||||
}
|
||||
val (state, tint) = when {
|
||||
f.paused -> stringResource(R.string.sync_folder_paused) to colors.onSurfaceVariant
|
||||
f.syncing -> stringResource(R.string.sync_folder_syncing, percent(f)) to pal.signal
|
||||
f.outOfSync -> stringResource(R.string.sync_folder_out_of_sync) to AttentionAmber
|
||||
f.state == "scanning" || f.state == "scan-waiting" -> stringResource(R.string.sync_folder_scanning) to colors.onSurfaceVariant
|
||||
else -> stringResource(R.string.sync_folder_up_to_date) to pal.good
|
||||
}
|
||||
val detail = when {
|
||||
f.errors > 0 -> stringResource(R.string.sync_folder_errors, f.errors)
|
||||
f.sharedWith.isEmpty() -> Formatter.formatShortFileSize(ctx, f.globalBytes)
|
||||
else -> stringResource(R.string.sync_folder_detail, Formatter.formatShortFileSize(ctx, f.globalBytes), f.sharedWith.joinToString(", "))
|
||||
}
|
||||
SettingsRow(f.label, detail) { StateLabel(state, tint) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DeviceRow(d: SyncDevice) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val detail = when {
|
||||
d.connected -> d.address?.substringAfter("://")
|
||||
d.lastSeen != null -> stringResource(R.string.sync_last_seen, DateUtils.getRelativeTimeSpanString(d.lastSeen).toString())
|
||||
else -> null
|
||||
}
|
||||
SettingsRow(d.name, detail) {
|
||||
if (d.connected) StateLabel(stringResource(R.string.sync_connected), pal.good)
|
||||
else StateLabel(stringResource(R.string.sync_offline), colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StateLabel(text: String, tint: Color) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {
|
||||
Box(Modifier.size(9.dp).clip(CircleShape).background(tint))
|
||||
Text(text, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DeviceIdDialog(id: String, onDismiss: () -> Unit) {
|
||||
val ctx = LocalContext.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
val qr = remember(id) { qrBitmap(id) }
|
||||
AppDialog(shown, close, "syncDeviceId", wide = true, maxWidth = 640.dp) {
|
||||
DialogTitleRow(stringResource(R.string.sync_device_id_title), onClose = close)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(22.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Image(qr, stringResource(R.string.sync_device_id), filterQuality = FilterQuality.None,
|
||||
modifier = Modifier.size(208.dp).clip(Shape14).background(Color.White).padding(10.dp))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.weight(1f)) {
|
||||
Text(id.chunked(32).joinToString("\n"), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, fontFamily = FontFamily.Monospace,
|
||||
color = colors.onBackground, lineHeight = 26.sp)
|
||||
Text(stringResource(R.string.sync_device_id_hint), fontSize = 13.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.sync_copy), compact = true) {
|
||||
ctx.getSystemService(ClipboardManager::class.java)?.setPrimaryClip(ClipData.newPlainText("Syncthing device ID", id))
|
||||
}
|
||||
SecondaryButton(stringResource(R.string.sync_share), compact = true) {
|
||||
ctx.startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, id), null))
|
||||
}
|
||||
PrimaryButton(stringResource(R.string.sync_done), compact = true, onClick = close)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TurnOffDialog(onDismiss: () -> Unit, onTurnOff: (Boolean) -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shown = rememberShown(onDismiss)
|
||||
val close = { shown.targetState = false }
|
||||
var forget by remember { mutableStateOf(false) }
|
||||
AppDialog(shown, close, "syncTurnOff", wide = false, maxWidth = 520.dp) {
|
||||
DialogTitleRow(stringResource(R.string.sync_off_title), onClose = close)
|
||||
Text(stringResource(R.string.sync_off_body), fontSize = 13.5.sp, color = colors.onSurfaceVariant)
|
||||
Row(
|
||||
verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape12).border(1.dp, pal.line, Shape12).background(colors.background).padding(end = 12.dp, top = 2.dp, bottom = 8.dp),
|
||||
) {
|
||||
Checkbox(forget, { forget = it })
|
||||
Column(Modifier.padding(top = 12.dp)) {
|
||||
Text(stringResource(R.string.sync_off_forget), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Text(stringResource(R.string.sync_off_forget_hint), fontSize = 12.5.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.End), modifier = Modifier.fillMaxWidth()) {
|
||||
SecondaryButton(stringResource(R.string.common_cancel), compact = true, onClick = close)
|
||||
PrimaryButton(stringResource(R.string.sync_turn_off), compact = true) { onTurnOff(forget); close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal fun openWebUi(context: Context) {
|
||||
context.startActivity(Intent(context, SyncthingWebActivity::class.java))
|
||||
}
|
||||
|
||||
private fun shortId(id: String) = if (id.length > 16) "${id.take(7)}-…-${id.takeLast(7)}" else id
|
||||
|
||||
private fun rate(context: Context, bytesPerSecond: Long) = Formatter.formatShortFileSize(context, bytesPerSecond) + "/s"
|
||||
|
||||
private fun percent(f: SyncFolder): Int =
|
||||
if (f.globalBytes <= 0) 0 else (((f.globalBytes - f.needBytes).coerceAtLeast(0) * 100) / f.globalBytes).toInt().coerceIn(0, 99)
|
||||
|
||||
private fun qrBitmap(text: String): ImageBitmap {
|
||||
val matrix = com.google.zxing.qrcode.QRCodeWriter().encode(text, com.google.zxing.BarcodeFormat.QR_CODE, 0, 0)
|
||||
val bitmap = android.graphics.Bitmap.createBitmap(matrix.width, matrix.height, android.graphics.Bitmap.Config.ARGB_8888)
|
||||
for (x in 0 until matrix.width) for (y in 0 until matrix.height) {
|
||||
bitmap.setPixel(x, y, if (matrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE)
|
||||
}
|
||||
return bitmap.asImageBitmap()
|
||||
}
|
||||
Reference in new issue
Block a user