Add SFTP backups and remote playback for Wear OS
Add server settings, transfer status, and automatic backups Support Ed25519 keys and one-time server trust approval Resume uploads, verify checksums, and preserve local recordings Add cached remote playback, tests, and setup documentation
This commit is contained in:
31 files changed
+1800
-10
No files matched your search
@@ -35,7 +35,9 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.jsch)
|
||||
implementation(libs.bcprov)
|
||||
testImplementation(libs.junit)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package meghdad.remember
|
||||
|
||||
import android.app.job.JobScheduler
|
||||
import android.Manifest
|
||||
import android.media.MediaRecorder
|
||||
import android.media.MediaPlayer
|
||||
import android.content.Intent
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.Button
|
||||
import android.widget.EditText
|
||||
import androidx.test.espresso.Espresso.onView
|
||||
import androidx.test.espresso.action.ViewActions.click
|
||||
import androidx.test.espresso.matcher.ViewMatchers.withText
|
||||
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
|
||||
import androidx.test.espresso.assertion.ViewAssertions.matches
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Assume.assumeTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class BackupTest {
|
||||
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
private val context = instrumentation.targetContext
|
||||
private val settings get() = BackupSettings(context)
|
||||
private fun restorePreferences(previous: Map<String, *>) {
|
||||
val editor = settings.preferences.edit().clear()
|
||||
previous.forEach { (key, value) -> when (value) {
|
||||
is String -> editor.putString(key, value)
|
||||
is Boolean -> editor.putBoolean(key, value)
|
||||
is Int -> editor.putInt(key, value)
|
||||
is Long -> editor.putLong(key, value)
|
||||
} }
|
||||
editor.commit()
|
||||
}
|
||||
@Test fun backupPagesAreReachableAndAutomaticUploadsDefaultOff() {
|
||||
val activity = instrumentation.startActivitySync(Intent(context, BackupActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
try {
|
||||
instrumentation.runOnMainSync {
|
||||
fun descendants(view: View): List<View> = listOf(view) + if (view is ViewGroup)
|
||||
(0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
|
||||
fun button(label: String) = descendants(activity.window.decorView).filterIsInstance<Button>().first { it.text == label }
|
||||
listOf("Server", "Transfers", "Server recordings", "Automatic backup", "Advanced").forEach {
|
||||
button(it).performClick(); button("Back").performClick()
|
||||
}
|
||||
}
|
||||
assertFalse(settings.automatic)
|
||||
} finally { instrumentation.runOnMainSync { activity.finish() } }
|
||||
}
|
||||
@Test fun encryptedWatchKeyPersistsWithoutPlaintextPrivateKeyInPreferences() {
|
||||
val public = settings.generateKey()
|
||||
assertTrue(public.startsWith("ssh-ed25519 "))
|
||||
assertEquals(public, BackupSettings(context).generateKey())
|
||||
val privateKey = settings.privateKey()
|
||||
try {
|
||||
assertTrue(privateKey.toString(Charsets.UTF_8).contains("OPENSSH PRIVATE KEY"))
|
||||
assertFalse(settings.preferences.getString("key", "")!!.contains("PRIVATE KEY"))
|
||||
} finally { privateKey.fill(0) }
|
||||
}
|
||||
@Test fun manifestsPreserveTitlesAndBookmarksAndRejectTraversal() {
|
||||
val clip = Clip(UUID.randomUUID().toString(), "A thought", 1000, 20000, listOf(1000, 12000))
|
||||
assertEquals(clip, parseRemoteClip(clipManifest(clip, 4096, "a".repeat(64))).clip)
|
||||
assertThrows(IllegalArgumentException::class.java) {
|
||||
parseRemoteClip(clipManifest(clip.copy(id = "../../private"), 4096, "a".repeat(64)))
|
||||
}
|
||||
}
|
||||
@Test fun discoveryDoesNotSaveTrustOrRequireAWatchKey() {
|
||||
val args = InstrumentationRegistry.getArguments()
|
||||
val expected = args.getString("sftpFingerprint")
|
||||
assumeTrue("Disposable SFTP fixture not configured", expected != null)
|
||||
val previous = settings.preferences.all
|
||||
val pending = BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", "")
|
||||
try {
|
||||
settings.save(pending)
|
||||
settings.preferences.edit().remove("key").remove("public_key").commit()
|
||||
val found = ServerTrustProbe(pending, 20).use { it.fetch() }
|
||||
assertEquals(expected, found)
|
||||
assertEquals("", settings.server().fingerprint)
|
||||
assertNull(settings.publicKey())
|
||||
assertThrows(IllegalArgumentException::class.java) { BackupTransport(context).use { it.connect() } }
|
||||
} finally { restorePreferences(previous) }
|
||||
}
|
||||
@Test fun connectAndTrustRequiresApprovalAndBlocksChangedIdentity() {
|
||||
val args = InstrumentationRegistry.getArguments()
|
||||
val expected = args.getString("sftpFingerprint")
|
||||
assumeTrue("Disposable SFTP fixture not configured", expected != null)
|
||||
val previous = settings.preferences.all
|
||||
val pending = BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", "")
|
||||
var activity: android.app.Activity? = null
|
||||
fun descendants(view: View): List<View> = listOf(view) + if (view is ViewGroup)
|
||||
(0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
|
||||
fun press(label: String) = instrumentation.runOnMainSync {
|
||||
descendants(activity!!.window.decorView).filterIsInstance<Button>().first { it.text == label }.performClick()
|
||||
}
|
||||
fun await(condition: () -> Boolean) {
|
||||
val end = android.os.SystemClock.elapsedRealtime() + 10000
|
||||
while (!condition() && android.os.SystemClock.elapsedRealtime() < end) android.os.SystemClock.sleep(50)
|
||||
assertTrue("Trust flow did not reach expected state", condition())
|
||||
}
|
||||
fun dialogVisible() = instrumentation.uiAutomation.rootInActiveWindow
|
||||
?.findAccessibilityNodeInfosByText("Trust this server?")?.any { it.text?.toString() == "Trust this server?" } == true
|
||||
try {
|
||||
settings.save(pending)
|
||||
settings.preferences.edit().remove("key").remove("public_key").commit()
|
||||
activity = instrumentation.startActivitySync(Intent(context, BackupActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
press("Server")
|
||||
instrumentation.runOnMainSync {
|
||||
assertEquals("Fingerprint must not require typing", 4, descendants(activity!!.window.decorView).filterIsInstance<EditText>().size)
|
||||
}
|
||||
press("Connect & trust"); await { dialogVisible() }
|
||||
assertEquals("", settings.server().fingerprint)
|
||||
if (args.getString("saveTrustScreenshot") == "true") {
|
||||
instrumentation.uiAutomation.waitForIdle(200, 3000)
|
||||
instrumentation.uiAutomation.takeScreenshot()?.let { bitmap ->
|
||||
File(context.cacheDir, "trust-dialog.png").outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
onView(withText(android.R.string.cancel)).perform(click())
|
||||
assertEquals("", settings.server().fingerprint)
|
||||
press("Connect & trust"); await { dialogVisible() }
|
||||
press("View fingerprint")
|
||||
onView(withText(expected)).check(matches(isDisplayed()))
|
||||
assertEquals("Viewing the fingerprint must not approve it", "", settings.server().fingerprint)
|
||||
press("Back"); await { dialogVisible() }
|
||||
if (args.getString("saveTrustScreenshot") == "true") {
|
||||
instrumentation.uiAutomation.waitForIdle(200, 3000)
|
||||
instrumentation.uiAutomation.takeScreenshot()?.let { bitmap ->
|
||||
File(context.cacheDir, "trust-dialog.png").outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }
|
||||
bitmap.recycle()
|
||||
}
|
||||
}
|
||||
onView(withText("Trust server")).perform(click())
|
||||
await { settings.server().fingerprint == expected }
|
||||
val wrong = "SHA256:" + "A".repeat(43)
|
||||
settings.save(settings.server().copy(fingerprint = wrong))
|
||||
press("Connect & trust")
|
||||
val busyField = BackupActivity::class.java.getDeclaredField("busy").apply { isAccessible = true }
|
||||
await { var busy = true; instrumentation.runOnMainSync { busy = busyField.getBoolean(activity) }; !busy }
|
||||
assertEquals("Changed identity must retain the existing pin", wrong, settings.server().fingerprint)
|
||||
assertFalse(dialogVisible())
|
||||
} finally {
|
||||
instrumentation.runOnMainSync { activity?.finish() }
|
||||
restorePreferences(previous)
|
||||
}
|
||||
}
|
||||
@Test fun rsaIdentityIsRetainedUntilExplicitEd25519Replacement() {
|
||||
val previous = settings.preferences.all
|
||||
val rsa = com.jcraft.jsch.KeyPair.genKeyPair(SshCrypto.client(), com.jcraft.jsch.KeyPair.RSA, 2048)
|
||||
val privateBytes = java.io.ByteArrayOutputStream().also { rsa.writePrivateKey(it) }.toByteArray()
|
||||
try {
|
||||
val public = java.io.ByteArrayOutputStream().also { rsa.writePublicKey(it, "migration-fixture") }.toString("UTF-8")
|
||||
val encrypt = BackupSettings::class.java.getDeclaredMethod("encrypt", ByteArray::class.java).apply { isAccessible = true }
|
||||
settings.preferences.edit().putString("key", encrypt.invoke(settings, privateBytes) as String).putString("public_key", public).commit()
|
||||
assertEquals(public, settings.generateKey())
|
||||
val retained = settings.privateKey()
|
||||
try { assertArrayEquals(privateBytes, retained) } finally { retained.fill(0) }
|
||||
val replaced = settings.generateKey(replace = true)
|
||||
assertTrue(replaced.startsWith("ssh-ed25519 "))
|
||||
assertEquals(replaced, BackupSettings(context).generateKey())
|
||||
val key = settings.privateKey()
|
||||
try { assertTrue(key.toString(Charsets.UTF_8).contains("OPENSSH PRIVATE KEY")) }
|
||||
finally { key.fill(0) }
|
||||
} finally { privateBytes.fill(0); rsa.dispose(); restorePreferences(previous) }
|
||||
}
|
||||
@Test fun manualJobBacksUpSavedAudioAndAutomaticJobsKeepConstraints() {
|
||||
val args = InstrumentationRegistry.getArguments()
|
||||
val fingerprint = args.getString("sftpFingerprint")
|
||||
assumeTrue("Disposable SFTP fixture not configured", fingerprint != null)
|
||||
assumeTrue("Do not test during recording", RecordingService.activeId == null)
|
||||
val previous = settings.preferences.all
|
||||
val store = Recordings(context)
|
||||
val clip = Clip(UUID.randomUUID().toString(), "Scheduled fixture", 1000, 10000, listOf(1000))
|
||||
val scheduler = context.getSystemService(JobScheduler::class.java)
|
||||
settings.save(BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", fingerprint!!))
|
||||
settings.generateKey()
|
||||
store.audio(clip.id).writeBytes(ByteArray(65536) { (it % 251).toByte() }); store.save(clip)
|
||||
try {
|
||||
BackupWork.start(context)
|
||||
val end = android.os.SystemClock.elapsedRealtime() + 60_000
|
||||
while (settings.receipt(clip.id) == null && android.os.SystemClock.elapsedRealtime() < end) android.os.SystemClock.sleep(100)
|
||||
assertEquals(backupVersion(clip, store.audio(clip.id)), settings.receipt(clip.id))
|
||||
settings.preferences.edit().putBoolean("automatic", true).putBoolean("charging", true).putBoolean("unmetered", true).putInt("hours", 24).commit()
|
||||
BackupWork.schedule(context)
|
||||
val job = scheduler.getPendingJob(72)!!
|
||||
assertTrue(job.isRequireCharging)
|
||||
assertTrue(job.isPersisted)
|
||||
assertTrue(job.requiredNetwork!!.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED))
|
||||
assertEquals(24 * 60 * 60_000L, job.intervalMillis)
|
||||
BackupWork.cancel(context)
|
||||
assertNull(scheduler.getPendingJob(72))
|
||||
assertFalse(settings.automatic)
|
||||
assertTrue("Backup must retain local audio", store.audio(clip.id).exists())
|
||||
} finally {
|
||||
BackupWork.cancel(context); store.delete(clip)
|
||||
restorePreferences(previous)
|
||||
}
|
||||
}
|
||||
@Test fun remoteAudioPlaysFromVerifiedCacheAndPausesInBackground() {
|
||||
val args = InstrumentationRegistry.getArguments()
|
||||
val fingerprint = args.getString("sftpFingerprint")
|
||||
assumeTrue("Disposable SFTP fixture not configured", fingerprint != null)
|
||||
assumeTrue("Do not test during recording", RecordingService.activeId == null)
|
||||
val previous = settings.preferences.all
|
||||
val audio = File(context.cacheDir, "remote-playback-fixture.m4a")
|
||||
var activity: android.app.Activity? = null
|
||||
var foreground: android.app.Activity? = null
|
||||
settings.save(BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", fingerprint!!))
|
||||
settings.generateKey()
|
||||
instrumentation.uiAutomation.grantRuntimePermission(context.packageName, Manifest.permission.RECORD_AUDIO)
|
||||
try {
|
||||
activity = instrumentation.startActivitySync(Intent(context, BackupActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
val recorder = MediaRecorder(context)
|
||||
try {
|
||||
recorder.setAudioSource(MediaRecorder.AudioSource.MIC)
|
||||
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
|
||||
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
|
||||
recorder.setOutputFile(audio.absolutePath)
|
||||
recorder.prepare(); recorder.start(); android.os.SystemClock.sleep(3000); recorder.stop()
|
||||
} finally { recorder.release() }
|
||||
val id = UUID.randomUUID().toString()
|
||||
val clip = Clip(id, "Playback fixture ${id.take(8)}", 1000, 3000, listOf(1000))
|
||||
BackupTransport(context).use { client -> client.connect(); client.upload(audio, clip) { _, _ -> } }
|
||||
fun descendants(view: View): List<View> = listOf(view) + if (view is ViewGroup)
|
||||
(0 until view.childCount).flatMap { descendants(view.getChildAt(it)) } else emptyList()
|
||||
fun click(prefix: String) = instrumentation.runOnMainSync {
|
||||
descendants(activity!!.window.decorView).filterIsInstance<Button>().first { it.text.startsWith(prefix) }.performClick()
|
||||
}
|
||||
fun await(timeout: Long = 10000, condition: () -> Boolean) {
|
||||
val end = android.os.SystemClock.elapsedRealtime() + timeout
|
||||
var ready = false
|
||||
while (!ready && android.os.SystemClock.elapsedRealtime() < end) {
|
||||
instrumentation.runOnMainSync { ready = condition() }; if (!ready) android.os.SystemClock.sleep(50)
|
||||
}
|
||||
assertTrue("Remote playback did not reach expected state", ready)
|
||||
}
|
||||
click("Server recordings"); click("Refresh")
|
||||
await { descendants(activity!!.window.decorView).filterIsInstance<Button>().any { it.text.startsWith(clip.title) } }
|
||||
click(clip.title); click("Download & play")
|
||||
val playerField = BackupActivity::class.java.getDeclaredField("player").apply { isAccessible = true }
|
||||
val readyField = BackupActivity::class.java.getDeclaredField("playbackReady").apply { isAccessible = true }
|
||||
await { readyField.getBoolean(activity) && (playerField.get(activity) as? MediaPlayer)?.isPlaying == true }
|
||||
foreground = instrumentation.startActivitySync(Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
instrumentation.runOnMainSync { assertFalse((playerField.get(activity) as MediaPlayer).isPlaying) }
|
||||
assertEquals(audio.inputStream().use { digestStream(it) }, File(context.cacheDir, "server-playback.m4a").inputStream().use { digestStream(it) })
|
||||
} finally {
|
||||
instrumentation.runOnMainSync { foreground?.finish(); activity?.finish() }
|
||||
audio.delete(); File(context.cacheDir, "server-playback.m4a").delete()
|
||||
restorePreferences(previous)
|
||||
}
|
||||
}
|
||||
/** Opt-in: point ONLY at a disposable SFTP fixture, never at a personal backup folder. */
|
||||
@Test fun sftpResumesVerifiesAndRejectsChangedHostKey() {
|
||||
val args = InstrumentationRegistry.getArguments()
|
||||
val fingerprint = args.getString("sftpFingerprint")
|
||||
assumeTrue("Disposable SFTP fixture not configured", fingerprint != null)
|
||||
val previous = settings.preferences.all
|
||||
val fixture = BackupServer("127.0.0.1", args.getString("sftpPort", "2222").toInt(), "backup-test", "/remember", fingerprint!!)
|
||||
val file = File(context.cacheDir, "backup-fixture.bin")
|
||||
val downloaded = File(context.cacheDir, "backup-downloaded.bin")
|
||||
val clip = Clip(UUID.randomUUID().toString(), "Disposable test", 1000, 20000, listOf(1000, 5000))
|
||||
file.outputStream().use { output -> repeat(64) { output.write(ByteArray(32768) { (it % 251).toByte() }) } }
|
||||
settings.save(fixture); settings.generateKey()
|
||||
try {
|
||||
var interrupted = false
|
||||
BackupTransport(context).use { client ->
|
||||
client.connect()
|
||||
try { client.upload(file, clip) { sent, _ -> if (sent > 32768) error("Simulated interruption") } }
|
||||
catch (_: Exception) { interrupted = true }
|
||||
}
|
||||
assertTrue(interrupted)
|
||||
var firstProgress = 0L
|
||||
BackupTransport(context).use { client ->
|
||||
client.connect()
|
||||
client.upload(file, clip) { sent, total ->
|
||||
if (firstProgress == 0L) firstProgress = sent
|
||||
assertTrue(sent <= total)
|
||||
}
|
||||
assertTrue("Expected resumed transfer", firstProgress > 32768)
|
||||
val remote = client.list().single { it.clip.id == clip.id }
|
||||
assertEquals(clip, remote.clip)
|
||||
client.download(remote, downloaded) { _, _ -> }
|
||||
assertEquals(file.inputStream().use { digestStream(it) }, downloaded.inputStream().use { digestStream(it) })
|
||||
assertThrows(IllegalArgumentException::class.java) { client.download(remote.copy(digest = "0".repeat(64)), downloaded) { _, _ -> } }
|
||||
assertEquals("Failed verification must preserve the previous cached file", file.length(), downloaded.length())
|
||||
client.upload(file, clip.copy(title = "Renamed")) { _, _ -> }
|
||||
assertEquals("Renamed", client.list().single { it.clip.id == clip.id }.clip.title)
|
||||
}
|
||||
settings.save(fixture.copy(fingerprint = "SHA256:" + "A".repeat(43)))
|
||||
assertThrows(Exception::class.java) { BackupTransport(context).use { it.connect() } }
|
||||
} finally {
|
||||
file.delete(); downloaded.delete()
|
||||
// Previous settings may be incomplete, so restore their fields without validating them.
|
||||
restorePreferences(previous)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,9 @@
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||
<application android:allowBackup="false" android:dataExtractionRules="@xml/data_extraction_rules" android:icon="@drawable/ic_remember"
|
||||
android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.Remember">
|
||||
<meta-data android:name="com.google.android.wearable.standalone" android:value="true" />
|
||||
@@ -17,5 +20,7 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<service android:name=".RecordingService" android:exported="false" android:foregroundServiceType="microphone" />
|
||||
<activity android:name=".BackupActivity" android:exported="false" android:taskAffinity="" />
|
||||
<service android:name=".BackupWorker" android:permission="android.permission.BIND_JOB_SERVICE" android:exported="true" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,15 @@
|
||||
MIT License (https://opensource.org/licenses/MIT)
|
||||
|
||||
Copyright (c) 2000-2026 The Legion of the Bouncy Castle Inc. (https://www.bouncycastle.org).
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the "Software"), to deal in the Software without restriction,
|
||||
including without limitation the rights to use, copy, modify, merge, publish, distribute,
|
||||
sub license, and/or sell copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions: The above copyright notice and this
|
||||
permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
|
||||
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.**
|
||||
@@ -0,0 +1,30 @@
|
||||
JSch 0.0.* was released under the GNU LGPL license. Later, we have switched
|
||||
over to a BSD-style license.
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
Copyright (c) 2002-2015 Atsuhiko Yamanaka, JCraft,Inc.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in
|
||||
the documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. The names of the authors may not be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
|
||||
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
|
||||
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
|
||||
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
|
||||
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1,462 @@
|
||||
package meghdad.remember
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Intent
|
||||
import android.graphics.Color
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.media.MediaPlayer
|
||||
import android.os.*
|
||||
import android.text.InputType
|
||||
import android.view.Gravity
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import java.io.File
|
||||
import java.text.DateFormat
|
||||
import java.util.Date
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** Backup navigation is independent of capture; opening it never stops RecordingService. */
|
||||
class BackupActivity : Activity() {
|
||||
private val lime = Color.rgb(199, 234, 24)
|
||||
private val muted = Color.rgb(164, 175, 143)
|
||||
private lateinit var settings: BackupSettings
|
||||
private lateinit var body: LinearLayout
|
||||
private lateinit var scroll: ScrollView
|
||||
private var page = "overview"
|
||||
private var busy = false
|
||||
private val executor = Executors.newSingleThreadExecutor()
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
@Volatile private var client: BackupTransport? = null
|
||||
@Volatile private var trustProbe: ServerTrustProbe? = null
|
||||
private var player: MediaPlayer? = null
|
||||
private var playbackReady = false
|
||||
private var resumed = false
|
||||
private var selected: RemoteClip? = null
|
||||
private var remoteClips: List<RemoteClip> = emptyList()
|
||||
private var serverDraft: BackupServer? = null
|
||||
private var pendingTrust: BackupServer? = null
|
||||
private var summary: TextView? = null
|
||||
private var progress: TextView? = null
|
||||
private var playbackButton: Button? = null
|
||||
private var seek: SeekBar? = null
|
||||
private val rows = mutableMapOf<String, TextView>()
|
||||
private var localClips: List<Clip> = emptyList()
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (page == "overview") summary?.text = settings.preferences.getString("summary", "Ready when you are")
|
||||
if (page == "transfers") rows.forEach { (id, view) ->
|
||||
val clip = localClips.find { it.id == id }
|
||||
if (clip != null) view.text = transferState(clip)
|
||||
}
|
||||
player?.takeIf { playbackReady }?.let { p -> runCatching {
|
||||
seek?.progress = p.currentPosition
|
||||
playbackButton?.text = if (p.isPlaying) "Pause" else "Play"
|
||||
progress?.text = timeLabel(p.currentPosition.toLong())
|
||||
} }
|
||||
handler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
settings = BackupSettings(this)
|
||||
if (Build.VERSION.SDK_INT >= 33) onBackInvokedDispatcher.registerOnBackInvokedCallback(0) { back() }
|
||||
render()
|
||||
}
|
||||
override fun onResume() { super.onResume(); resumed = true; handler.post(tick) }
|
||||
override fun onPause() { resumed = false; handler.removeCallbacks(tick); if (playbackReady) player?.pause(); super.onPause() }
|
||||
override fun onDestroy() { trustProbe?.close(); client?.close(); executor.shutdownNow(); player?.release(); super.onDestroy() }
|
||||
private fun dp(value: Int) = (value * resources.displayMetrics.density).roundToInt()
|
||||
private fun text(value: String, size: Float = 12f, color: Int = Color.WHITE): TextView = TextView(this).apply {
|
||||
text = value; textSize = size; setTextColor(color); gravity = Gravity.CENTER
|
||||
setPadding(dp(3), dp(5), dp(3), dp(5)); body.addView(this, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
private fun button(label: String, action: () -> Unit): Button = Button(this).apply {
|
||||
text = label; textSize = 12f; isAllCaps = false; setTextColor(Color.WHITE)
|
||||
background = GradientDrawable().apply { setColor(Color.rgb(43, 52, 32)); cornerRadius = dp(24).toFloat() }
|
||||
stateListAnimator = null
|
||||
setOnClickListener { action() }
|
||||
body.addView(this, LinearLayout.LayoutParams(-1, dp(48)).apply { setMargins(0, dp(4), 0, dp(4)) })
|
||||
}
|
||||
private fun navigate(target: String) {
|
||||
if (busy) { toast(getString(R.string.backup_wait_for_the_current_action_or_cancel_it)); return }
|
||||
player?.release(); player = null
|
||||
playbackReady = false
|
||||
page = target; render()
|
||||
}
|
||||
private fun render() {
|
||||
rows.clear(); summary = null; progress = null; playbackButton = null; seek = null
|
||||
scroll = ScrollView(this).apply { isFillViewport = true; isVerticalScrollBarEnabled = false; setBackgroundColor(Color.rgb(13, 17, 11)) }
|
||||
body = LinearLayout(this).apply {
|
||||
orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL
|
||||
// Keep controls inside a round watch's usable area even on emulator images
|
||||
// that omit the round configuration qualifier.
|
||||
setPadding(dp(28), dp(28), dp(28), dp(36))
|
||||
}
|
||||
scroll.addView(body); setContentView(scroll)
|
||||
scroll.setOnGenericMotionListener { _, event ->
|
||||
if (event.action == MotionEvent.ACTION_SCROLL) {
|
||||
scroll.smoothScrollBy(0, (-event.getAxisValue(MotionEvent.AXIS_SCROLL) * dp(35)).toInt()); true
|
||||
} else false
|
||||
}
|
||||
when (page) {
|
||||
"server" -> serverPage()
|
||||
"trust" -> trustPage()
|
||||
"trust_fingerprint" -> {
|
||||
title(getString(R.string.backup_server_identity))
|
||||
text(pendingTrust?.fingerprint.orEmpty(), 12f, muted)
|
||||
button(getString(R.string.backup_back)) { navigate("trust") }
|
||||
}
|
||||
"transfers" -> transfersPage()
|
||||
"remote" -> remotePage()
|
||||
"playback" -> playbackPage()
|
||||
"automatic" -> automaticPage()
|
||||
"advanced" -> advancedPage()
|
||||
"licenses" -> { title(getString(R.string.backup_open_source_licenses)); text(listOf("JSch.txt", "Bouncy-Castle.txt").joinToString("\n\n") { name -> assets.open("licenses/$name").bufferedReader().use { it.readText() } }, 10f, muted); button(getString(R.string.backup_back)) { navigate("advanced") } }
|
||||
else -> overview()
|
||||
}
|
||||
}
|
||||
private fun title(value: String) { text(value.uppercase(), 10f, lime) }
|
||||
private fun overview() {
|
||||
title(getString(R.string.backup_backup))
|
||||
text(getString(R.string.backup_keep_your_moments), 16f)
|
||||
val clips = Recordings(this).list()
|
||||
val backed = clips.count { settings.receipt(it.id) == backupVersion(it, Recordings(this).audio(it.id)) }
|
||||
text("$backed backed up\n${clips.size - backed} waiting", 16f, lime)
|
||||
button(getString(R.string.backup_back_up_now)) { startBackup() }.apply {
|
||||
background = GradientDrawable().apply {
|
||||
setColor(Color.rgb(35, 44, 20)); cornerRadius = dp(24).toFloat(); setStroke(dp(1), lime)
|
||||
}
|
||||
}
|
||||
val time = settings.preferences.getLong("last_success", 0)
|
||||
text(if (time == 0L) "No completed backup yet" else "Last backup\n${DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date(time))}", 10f, muted)
|
||||
summary = text(settings.preferences.getString("summary", "Ready when you are")!!, 11f, muted)
|
||||
button(getString(R.string.backup_server)) { navigate("server") }
|
||||
button(getString(R.string.backup_transfers)) { navigate("transfers") }
|
||||
button(getString(R.string.backup_server_recordings)) { navigate("remote") }
|
||||
button(getString(R.string.backup_automatic_backup)) { navigate("automatic") }
|
||||
button(getString(R.string.backup_advanced)) { navigate("advanced") }
|
||||
button(getString(R.string.backup_back)) { finish() }
|
||||
}
|
||||
private fun field(label: String, value: String, type: Int = InputType.TYPE_CLASS_TEXT): EditText {
|
||||
text(label, 11f, muted)
|
||||
return EditText(this).apply {
|
||||
setText(value); setTextColor(Color.WHITE); textSize = 12f; inputType = type
|
||||
contentDescription = label; setSelectAllOnFocus(true)
|
||||
body.addView(this, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
}
|
||||
private fun serverPage() {
|
||||
title(getString(R.string.backup_server))
|
||||
val server = serverDraft?.withRememberedTrust(settings.server()) ?: settings.server()
|
||||
val host = field(getString(R.string.backup_address), server.host, InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
|
||||
val port = field(getString(R.string.backup_port), server.port.toString(), InputType.TYPE_CLASS_NUMBER)
|
||||
val user = field(getString(R.string.backup_username), server.user)
|
||||
val folder = field(getString(R.string.backup_backup_folder), server.folder, InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI)
|
||||
fun draft(): BackupServer = BackupServer(host.text.toString().trim(), port.text.toString().toIntOrNull() ?: 0,
|
||||
user.text.toString().trim(), folder.text.toString().trim(), "").withRememberedTrust(settings.server())
|
||||
val trustStatus = text(getString(if (server.fingerprint.isEmpty()) R.string.backup_server_untrusted else R.string.backup_server_trusted), 11f, lime)
|
||||
fun updateTrustStatus() { trustStatus.text = getString(if (draft().fingerprint.isEmpty()) R.string.backup_server_untrusted else R.string.backup_server_trusted) }
|
||||
val endpointWatcher = object : android.text.TextWatcher {
|
||||
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
|
||||
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { updateTrustStatus() }
|
||||
override fun afterTextChanged(s: android.text.Editable?) = Unit
|
||||
}
|
||||
host.addTextChangedListener(endpointWatcher); port.addTextChangedListener(endpointWatcher)
|
||||
fun save(candidate: BackupServer): Boolean = persistServer(candidate).also { if (it) updateTrustStatus() }
|
||||
fun testConnection() { runRemote("Connecting…") { it.test(); "Connected. Backup folder is accessible." } }
|
||||
button(getString(R.string.backup_connect_trust)) {
|
||||
val candidate = draft()
|
||||
runCatching { candidate.validateConfiguration() }.onSuccess {
|
||||
serverDraft = candidate
|
||||
runTask(getString(R.string.backup_reading_server_identity), {
|
||||
check(BackupGate.lock.tryLock()) { "A backup is running. Pause transfers first." }
|
||||
try {
|
||||
ServerTrustProbe(candidate, settings.timeout).use { probe ->
|
||||
trustProbe = probe; probe.fetch()
|
||||
}
|
||||
} finally { trustProbe = null; BackupGate.lock.unlock() }
|
||||
}) { found ->
|
||||
if (draft().copy(fingerprint = "") != candidate.copy(fingerprint = "")) {
|
||||
toast(getString(R.string.backup_server_details_changed))
|
||||
} else if (candidate.fingerprint.isNotEmpty() && candidate.fingerprint != found) {
|
||||
toast(getString(R.string.backup_server_key_changed))
|
||||
} else if (candidate.fingerprint == found) {
|
||||
if (save(candidate)) testConnection()
|
||||
} else {
|
||||
pendingTrust = candidate.copy(fingerprint = found)
|
||||
page = "trust"; render()
|
||||
}
|
||||
}
|
||||
}.onFailure { toast(it.message ?: "Check server settings") }
|
||||
}
|
||||
button(getString(R.string.backup_save_server)) {
|
||||
if (save(draft())) {
|
||||
if (settings.server().fingerprint.isNotEmpty()) BackupWork.schedule(this)
|
||||
navigate("overview")
|
||||
}
|
||||
}
|
||||
button(getString(R.string.backup_test_connection)) {
|
||||
val candidate = draft()
|
||||
runCatching { candidate.validate() }.onSuccess { if (save(candidate)) testConnection() }
|
||||
.onFailure { toast(it.message ?: "Use Connect & trust first") }
|
||||
}
|
||||
button(if (settings.publicKey() == null) "Create watch key" else "Show watch key") {
|
||||
runTask("Preparing key…", { settings.generateKey() }) { key ->
|
||||
showPublicKey(key)
|
||||
}
|
||||
}
|
||||
if (settings.publicKey()?.startsWith("ssh-rsa ") == true) {
|
||||
button(getString(R.string.backup_replace_ed25519)) {
|
||||
AlertDialog.Builder(this).setTitle(R.string.backup_replace_ed25519)
|
||||
.setMessage(R.string.backup_replace_key_message)
|
||||
.setPositiveButton(R.string.backup_replace_key_confirm) { _, _ ->
|
||||
runTask("Preparing key…", {
|
||||
BackupWork.cancel(this)
|
||||
settings.generateKey(replace = true)
|
||||
}) { key -> render(); showPublicKey(key) }
|
||||
}.setNegativeButton(android.R.string.cancel, null).show()
|
||||
}
|
||||
}
|
||||
progress = text("", 10f, muted)
|
||||
button(getString(R.string.backup_back)) { navigate("overview") }
|
||||
}
|
||||
private fun persistServer(candidate: BackupServer): Boolean = try {
|
||||
candidate.validateConfiguration()
|
||||
check(!busy) { "Wait for the current action" }
|
||||
check(BackupGate.lock.tryLock()) { "Pause transfers before changing the server" }
|
||||
try {
|
||||
if (candidate.fingerprint.isEmpty()) BackupWork.cancel(this)
|
||||
settings.save(candidate)
|
||||
} finally { BackupGate.lock.unlock() }
|
||||
serverDraft = null; remoteClips = emptyList(); selected = null
|
||||
true
|
||||
} catch (error: Exception) { toast(error.message ?: "Check server settings"); false }
|
||||
private fun cancelTrust() { pendingTrust = null; page = "server"; render() }
|
||||
private fun trustPage() {
|
||||
val candidate = pendingTrust ?: run { page = "server"; serverPage(); return }
|
||||
text(getString(R.string.backup_trust_server_title), 17f, lime)
|
||||
text(getString(R.string.backup_trust_server_address, candidate.host, candidate.port), 14f)
|
||||
text(getString(R.string.backup_remember_server), 11f, muted)
|
||||
button(getString(R.string.backup_trust_server_confirm)) {
|
||||
if (persistServer(candidate)) {
|
||||
pendingTrust = null; page = "server"; render()
|
||||
if (settings.publicKey() != null) runRemote("Connecting…") { it.test(); "Connected. Backup folder is accessible." }
|
||||
else toast(getString(R.string.backup_server_trusted_create_key))
|
||||
}
|
||||
}.setTextColor(lime)
|
||||
button(getString(android.R.string.cancel)) { cancelTrust() }
|
||||
button(getString(R.string.backup_view_fingerprint)) { navigate("trust_fingerprint") }
|
||||
}
|
||||
private fun showPublicKey(key: String) {
|
||||
AlertDialog.Builder(this).setTitle("Watch public key").setMessage("Add this public key to the backup account's authorized_keys:\n\n$key")
|
||||
.setPositiveButton("Export") { _, _ ->
|
||||
runCatching {
|
||||
startActivityForResult(Intent(Intent.ACTION_CREATE_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE)
|
||||
.setType("text/plain").putExtra(Intent.EXTRA_TITLE, "remember-watch.pub"), 20)
|
||||
}.onFailure { toast("No file picker available. Copy the public key instead.") }
|
||||
}.setNeutralButton("Copy") { _, _ ->
|
||||
getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("Watch public key", key)); toast(getString(R.string.backup_public_key_copied))
|
||||
}.setNegativeButton("Close", null).show()
|
||||
}
|
||||
@Deprecated("Framework document picker result")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (requestCode == 20 && resultCode == RESULT_OK) runCatching {
|
||||
contentResolver.openOutputStream(data?.data ?: error("No file selected"))!!.use { it.write(settings.publicKey()!!.toByteArray()) }
|
||||
}.onSuccess { toast(getString(R.string.backup_public_key_exported)) }.onFailure { toast(getString(R.string.backup_could_not_export_key)) }
|
||||
}
|
||||
private fun transferState(clip: Clip): String = if (settings.receipt(clip.id) == backupVersion(clip, Recordings(this).audio(clip.id))) "Backed up" else settings.status(clip.id).let {
|
||||
if (it == "Backed up") "Waiting · changed" else it
|
||||
}
|
||||
private fun transfersPage() {
|
||||
title(getString(R.string.backup_transfers))
|
||||
val clips = Recordings(this).list()
|
||||
localClips = clips
|
||||
if (clips.isEmpty()) text(getString(R.string.backup_save_a_recording_to_begin), 14f)
|
||||
clips.forEach { clip ->
|
||||
text(clip.title, 14f)
|
||||
rows[clip.id] = text(transferState(clip), 11f, lime)
|
||||
}
|
||||
button(getString(R.string.backup_back_up_retry)) { startBackup() }
|
||||
button(getString(R.string.backup_pause_all_backups)) {
|
||||
BackupWork.cancel(this)
|
||||
clips.forEach { if (transferState(it) != "Backed up") settings.status(it.id, "Waiting") }
|
||||
toast(getString(R.string.backup_backups_paused_automatic_backup_is_off))
|
||||
}
|
||||
text(getString(R.string.backup_copies_stay_on_the_server_when_you_delete_local_recordings), 10f, muted)
|
||||
button(getString(R.string.backup_back)) { navigate("overview") }
|
||||
}
|
||||
private fun startBackup() {
|
||||
runCatching { BackupWork.start(this) }.onSuccess { toast(getString(R.string.backup_backup_queued_opens_when_connected)) }
|
||||
.onFailure { toast(it.message ?: "Configure the server first") }
|
||||
}
|
||||
private fun remotePage() {
|
||||
title(getString(R.string.backup_server_recordings))
|
||||
button(getString(R.string.backup_refresh)) {
|
||||
runTask("Loading recordings…", { withRemote { it.list() } }) { remoteClips = it; render() }
|
||||
}
|
||||
if (remoteClips.isEmpty()) text(getString(R.string.backup_tap_refresh_to_browse_your_backups), 12f, muted)
|
||||
remoteClips.forEach { remote ->
|
||||
val date = DateFormat.getDateInstance(DateFormat.SHORT).format(Date(remote.clip.created))
|
||||
button("${remote.clip.title}\n$date · ${timeLabel(remote.clip.duration)}") { selected = remote; navigate("playback") }.apply {
|
||||
maxLines = 2; ellipsize = android.text.TextUtils.TruncateAt.END
|
||||
}
|
||||
}
|
||||
progress = text("", 10f, muted)
|
||||
button(getString(R.string.backup_back)) { navigate("overview") }
|
||||
}
|
||||
private fun playbackPage() {
|
||||
val remote = selected ?: return
|
||||
title(getString(R.string.backup_server_playback))
|
||||
text(remote.clip.title, 17f)
|
||||
text("${timeLabel(remote.clip.duration)} · ${remote.clip.marks.size} bookmarks", 11f, muted)
|
||||
text(getString(R.string.backup_audio_downloads_to_a_temporary_watch_cache_before_playing), 10f, muted)
|
||||
progress = text(getString(R.string.backup_ready_to_download), 11f, lime)
|
||||
playbackButton = button(getString(R.string.backup_download_play)) {
|
||||
if (player != null) { if (playbackReady) player!!.let { if (it.isPlaying) it.pause() else it.start() }; return@button }
|
||||
val file = File(cacheDir, "server-playback.m4a")
|
||||
runTask("Preparing audio…", {
|
||||
require(StatFs(cacheDir.absolutePath).availableBytes > remote.bytes + 16 * 1024 * 1024) { "Not enough free space for playback" }
|
||||
var lastProgress = 0L
|
||||
withRemote { client -> client.download(remote, file) { sent, total ->
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
if (now - lastProgress > 500) {
|
||||
lastProgress = now
|
||||
handler.post { if (!isDestroyed && page == "playback") progress?.text = getString(R.string.backup_download_progress, sent * 100 / total) }
|
||||
}
|
||||
} }
|
||||
file
|
||||
}) { downloaded ->
|
||||
runCatching {
|
||||
player = MediaPlayer().apply {
|
||||
setDataSource(downloaded.absolutePath)
|
||||
setOnPreparedListener { p -> playbackReady = true; seek?.max = p.duration; if (resumed) p.start() }
|
||||
setOnErrorListener { _, _, _ -> player?.release(); player = null; playbackReady = false; toast(getString(R.string.backup_could_not_play_audio)); true }
|
||||
prepareAsync()
|
||||
}
|
||||
}.onFailure { toast(getString(R.string.backup_could_not_play_audio)) }
|
||||
}
|
||||
}
|
||||
seek = SeekBar(this).apply {
|
||||
contentDescription = "Playback position"
|
||||
setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
|
||||
override fun onProgressChanged(bar: SeekBar?, value: Int, fromUser: Boolean) { if (fromUser && playbackReady) runCatching { player?.seekTo(value) } }
|
||||
override fun onStartTrackingTouch(bar: SeekBar?) = Unit
|
||||
override fun onStopTrackingTouch(bar: SeekBar?) = Unit
|
||||
}); body.addView(this, LinearLayout.LayoutParams(-1, dp(40)))
|
||||
}
|
||||
remote.clip.marks.forEach { mark -> button("Bookmark · ${timeLabel(mark)}") { runCatching { player?.seekTo(mark.coerceAtMost(Int.MAX_VALUE.toLong()).toInt()) } } }
|
||||
button(getString(R.string.backup_cancel_download)) { client?.close() }
|
||||
button(getString(R.string.backup_back)) { navigate("remote") }
|
||||
}
|
||||
private fun toggle(label: String, value: Boolean, change: (Boolean) -> Unit) {
|
||||
Switch(this).apply {
|
||||
text = label; textSize = 12f; setTextColor(Color.WHITE); isChecked = value
|
||||
setOnCheckedChangeListener { _, checked -> change(checked) }
|
||||
body.addView(this, LinearLayout.LayoutParams(-1, dp(52)))
|
||||
}
|
||||
}
|
||||
private fun automaticPage() {
|
||||
title(getString(R.string.backup_automatic_backup))
|
||||
toggle("Enable", settings.automatic) {
|
||||
settings.preferences.edit().putBoolean("automatic", it).apply()
|
||||
runCatching { BackupWork.schedule(this) }.onFailure { error ->
|
||||
settings.preferences.edit().putBoolean("automatic", false).apply(); toast(error.message ?: "Configure server first"); render()
|
||||
}
|
||||
}
|
||||
toggle("While charging", settings.charging) { updateOption("charging", it) }
|
||||
toggle("Unmetered only", settings.unmetered) { updateOption("unmetered", it) }
|
||||
button("Check every ${settings.hours} hours") {
|
||||
choose("Backup interval", arrayOf("Every hour", "Every 6 hours", "Daily")) { index ->
|
||||
settings.preferences.edit().putInt("hours", intArrayOf(1, 6, 24)[index]).apply(); BackupWork.schedule(this); render()
|
||||
}
|
||||
}
|
||||
text(getString(R.string.backup_runs_when_conditions_allow_the_watch_may_delay_background), 10f, muted)
|
||||
button(getString(R.string.backup_back)) { navigate("overview") }
|
||||
}
|
||||
private fun updateOption(key: String, value: Boolean) { settings.preferences.edit().putBoolean(key, value).apply(); BackupWork.schedule(this) }
|
||||
private fun advancedPage() {
|
||||
title(getString(R.string.backup_advanced))
|
||||
button("Retry attempts · ${settings.attempts}") { choose("Retry attempts", arrayOf("1", "3", "5")) { index ->
|
||||
settings.preferences.edit().putInt("attempts", intArrayOf(1, 3, 5)[index]).apply(); render()
|
||||
} }
|
||||
button("Connection timeout · ${settings.timeout}s") { choose("Connection timeout", arrayOf("20 seconds", "40 seconds", "60 seconds")) { index ->
|
||||
settings.preferences.edit().putInt("timeout", intArrayOf(20, 40, 60)[index]).apply(); render()
|
||||
} }
|
||||
button(getString(R.string.backup_clear_playback_cache)) {
|
||||
player?.release(); player = null; playbackReady = false
|
||||
File(cacheDir, "server-playback.m4a").delete(); File(cacheDir, "server-playback.m4a.download").delete()
|
||||
toast(getString(R.string.backup_playback_cache_cleared))
|
||||
}
|
||||
text(getString(R.string.backup_one_transfer_at_a_time_interrupted_uploads_resume_and_are), 10f, muted)
|
||||
if (settings.server().fingerprint.isNotEmpty()) button(getString(R.string.backup_server_identity)) {
|
||||
val trusted = settings.server()
|
||||
AlertDialog.Builder(this).setTitle(R.string.backup_server_identity)
|
||||
.setMessage("${trusted.host}:${trusted.port}\n\n${trusted.fingerprint}")
|
||||
.setPositiveButton(R.string.backup_forget_trust) { _, _ ->
|
||||
AlertDialog.Builder(this).setTitle(R.string.backup_forget_trust)
|
||||
.setMessage(R.string.backup_forget_trust_message)
|
||||
.setPositiveButton(R.string.backup_forget_trust) { _, _ ->
|
||||
runTask("Pausing backups…", {
|
||||
BackupWork.cancel(this)
|
||||
check(BackupGate.lock.tryLock(5, java.util.concurrent.TimeUnit.SECONDS)) { "Wait for transfers to stop" }
|
||||
try { settings.save(trusted.copy(fingerprint = "")) } finally { BackupGate.lock.unlock() }
|
||||
}) { remoteClips = emptyList(); selected = null; render(); toast(getString(R.string.backup_trust_forgotten)) }
|
||||
}.setNegativeButton(android.R.string.cancel, null).show()
|
||||
}.setNegativeButton(android.R.string.cancel, null).show()
|
||||
}
|
||||
button(getString(R.string.backup_open_source_licenses)) { navigate("licenses") }
|
||||
button(getString(R.string.backup_back)) { navigate("overview") }
|
||||
}
|
||||
private fun choose(title: String, values: Array<String>, action: (Int) -> Unit) { AlertDialog.Builder(this).setTitle(title).setItems(values) { _, index -> action(index) }.show() }
|
||||
private fun <T> runTask(message: String, task: () -> T, done: (T) -> Unit) {
|
||||
if (busy) { toast(getString(R.string.backup_an_action_is_already_running)); return }
|
||||
busy = true; progress?.text = message
|
||||
executor.execute {
|
||||
val result = runCatching { task() }
|
||||
handler.post {
|
||||
busy = false
|
||||
if (isDestroyed) return@post
|
||||
result.onSuccess { progress?.text = ""; done(it) }.onFailure {
|
||||
val message = friendlyError(it)
|
||||
progress?.text = message; toast(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private fun <T> withRemote(action: (BackupTransport) -> T): T {
|
||||
check(BackupGate.lock.tryLock()) { "A backup is running. Pause transfers first." }
|
||||
try {
|
||||
return BackupTransport(this) { check(!isDestroyed && !Thread.currentThread().isInterrupted) { "Cancelled" } }.use {
|
||||
client = it; it.connect(); action(it)
|
||||
}
|
||||
} finally { client = null; BackupGate.lock.unlock() }
|
||||
}
|
||||
private fun runRemote(message: String, action: (BackupTransport) -> String) { runTask(message, { withRemote(action) }) { toast(it); progress?.text = it } }
|
||||
private fun friendlyError(error: Throwable): String {
|
||||
val message = error.message.orEmpty()
|
||||
return when {
|
||||
error is IllegalArgumentException || error is IllegalStateException -> message
|
||||
message.contains("HostKey", true) || message.contains("host key", true) -> "Server fingerprint does not match. Check it with your administrator."
|
||||
message.contains("Auth fail", true) -> "Key rejected. Authorize the watch public key on the server."
|
||||
else -> "Connection failed. Check address, connection, permissions, and backup folder."
|
||||
}
|
||||
}
|
||||
private fun toast(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() }
|
||||
private fun back() {
|
||||
when (page) {
|
||||
"overview" -> finish()
|
||||
"trust" -> cancelTrust()
|
||||
"trust_fingerprint" -> navigate("trust")
|
||||
else -> navigate(when (page) { "playback" -> "remote"; "licenses" -> "advanced"; else -> "overview" })
|
||||
}
|
||||
}
|
||||
@android.annotation.SuppressLint("GestureBackNavigation")
|
||||
@Deprecated("Framework back navigation")
|
||||
override fun onBackPressed() { back() }
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package meghdad.remember
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import com.jcraft.jsch.KeyPair
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.security.KeyStore
|
||||
import java.security.MessageDigest
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
data class BackupServer(val host: String, val port: Int, val user: String, val folder: String, val fingerprint: String) {
|
||||
fun validateConfiguration() {
|
||||
require(host.isNotBlank() && host.none { it.isWhitespace() || it == '/' }) { "Enter a server address without ssh://" }
|
||||
require(port in 1..65535) { "Port must be 1–65535" }
|
||||
require(user.isNotBlank()) { "Enter a username" }
|
||||
require(folder.startsWith('/') && folder != "/" && folder.none { it == '\u0000' || it == '*' || it == '?' || it == '[' || it == '\\' } && folder.split('/').none { it == ".." }) { "Use an absolute backup folder without wildcards or .." }
|
||||
require(fingerprint.isEmpty() || fingerprint.matches(Regex("SHA256:[A-Za-z0-9+/]{43}"))) { "Invalid server fingerprint" }
|
||||
}
|
||||
fun validate() {
|
||||
validateConfiguration()
|
||||
require(fingerprint.isNotEmpty()) { "Use Connect & trust on the Server page first" }
|
||||
}
|
||||
fun withRememberedTrust(previous: BackupServer): BackupServer = copy(
|
||||
fingerprint = if (host == previous.host && port == previous.port) previous.fingerprint else "")
|
||||
val identity: String get() = sha256("$host:$port\n$user\n$folder\n$fingerprint".toByteArray())
|
||||
}
|
||||
|
||||
fun sha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
|
||||
|
||||
/** Secrets are encrypted with a non-exportable Android Keystore wrapping key. */
|
||||
class BackupSettings(context: Context) {
|
||||
val preferences = context.getSharedPreferences("backup", Context.MODE_PRIVATE)
|
||||
fun server() = BackupServer(preferences.getString("host", "")!!, preferences.getInt("port", 22),
|
||||
preferences.getString("user", "")!!, preferences.getString("folder", "/remember")!!,
|
||||
preferences.getString("fingerprint", "")!!)
|
||||
fun save(server: BackupServer) {
|
||||
server.validateConfiguration()
|
||||
val changed = server.identity != server().identity
|
||||
val editor = preferences.edit().putString("host", server.host).putInt("port", server.port).putString("user", server.user)
|
||||
.putString("folder", server.folder.trimEnd('/')).putString("fingerprint", server.fingerprint)
|
||||
if (changed) editor.putString("summary", "Ready when you are").putLong("last_success", 0)
|
||||
editor.apply()
|
||||
}
|
||||
private fun wrappingKey(): SecretKey {
|
||||
val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
return (store.getKey("remember-backup", null) as? SecretKey) ?: KeyGenerator.getInstance("AES", "AndroidKeyStore").apply {
|
||||
init(KeyGenParameterSpec.Builder("remember-backup", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build())
|
||||
}.generateKey()
|
||||
}
|
||||
private fun encrypt(bytes: ByteArray): String {
|
||||
val cipher = Cipher.getInstance("AES/GCM/NoPadding").apply { init(Cipher.ENCRYPT_MODE, wrappingKey()) }
|
||||
return Base64.encodeToString(cipher.iv + cipher.doFinal(bytes), Base64.NO_WRAP)
|
||||
}
|
||||
fun privateKey(): ByteArray {
|
||||
val data = Base64.decode(preferences.getString("key", null) ?: error("Generate a watch key first"), Base64.NO_WRAP)
|
||||
return Cipher.getInstance("AES/GCM/NoPadding").run {
|
||||
init(Cipher.DECRYPT_MODE, wrappingKey(), GCMParameterSpec(128, data.copyOfRange(0, 12)))
|
||||
doFinal(data.copyOfRange(12, data.size))
|
||||
}
|
||||
}
|
||||
fun publicKey(): String? = preferences.getString("public_key", null)
|
||||
fun generateKey(replace: Boolean = false): String {
|
||||
// Showing an existing public key must not pause an active transfer.
|
||||
if (!replace) publicKey()?.let { return it }
|
||||
check(BackupGate.lock.tryLock(5, java.util.concurrent.TimeUnit.SECONDS)) { "Pause transfers before changing the watch key" }
|
||||
try {
|
||||
if (!replace) publicKey()?.let { return it }
|
||||
val pair = KeyPair.genKeyPair(SshCrypto.client(), KeyPair.ED25519)
|
||||
try {
|
||||
val privateBytes = ByteArrayOutputStream().also { pair.writeOpenSSHv1PrivateKey(it, null as ByteArray?) }.toByteArray()
|
||||
val public = ByteArrayOutputStream().also { pair.writePublicKey(it, "remember-watch") }.toString("UTF-8")
|
||||
try { check(preferences.edit().putString("key", encrypt(privateBytes)).putString("public_key", public).commit()) }
|
||||
finally { privateBytes.fill(0) }
|
||||
return public
|
||||
} finally { pair.dispose() }
|
||||
} finally { BackupGate.lock.unlock() }
|
||||
}
|
||||
val automatic get() = preferences.getBoolean("automatic", false)
|
||||
val charging get() = preferences.getBoolean("charging", true)
|
||||
val unmetered get() = preferences.getBoolean("unmetered", true)
|
||||
val hours get() = preferences.getInt("hours", 24)
|
||||
val attempts get() = preferences.getInt("attempts", 3)
|
||||
val timeout get() = preferences.getInt("timeout", 20)
|
||||
fun receipt(id: String): String? = preferences.getString("receipt_${server().identity}_$id", null)
|
||||
fun receipt(id: String, version: String) {
|
||||
check(preferences.edit().putString("receipt_${server().identity}_$id", version).commit()) { "Could not save backup status" }
|
||||
}
|
||||
fun status(id: String): String = preferences.getString("status_${server().identity}_$id", "Waiting")!!
|
||||
fun status(id: String, text: String) { preferences.edit().putString("status_${server().identity}_$id", text).apply() }
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package meghdad.remember
|
||||
|
||||
import android.content.Context
|
||||
import com.jcraft.jsch.*
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.security.MessageDigest
|
||||
|
||||
data class RemoteClip(val clip: Clip, val bytes: Long, val digest: String)
|
||||
|
||||
fun clipManifest(clip: Clip, bytes: Long, digest: String): String = JSONObject()
|
||||
.put("version", 1).put("id", clip.id).put("title", clip.title).put("created", clip.created)
|
||||
.put("duration", clip.duration).put("marks", JSONArray(clip.marks)).put("bytes", bytes).put("sha256", digest).toString()
|
||||
|
||||
fun parseRemoteClip(text: String): RemoteClip {
|
||||
val json = JSONObject(text)
|
||||
require(json.getInt("version") == 1)
|
||||
val id = json.getString("id")
|
||||
require(id.matches(Regex("[a-fA-F0-9-]{36}")))
|
||||
val bytes = json.getLong("bytes")
|
||||
require(bytes in 1..500L * 1024 * 1024)
|
||||
val digest = json.getString("sha256")
|
||||
require(digest.matches(Regex("[a-f0-9]{64}")))
|
||||
val duration = json.getLong("duration")
|
||||
require(duration >= 0)
|
||||
val marks = json.optJSONArray("marks") ?: JSONArray()
|
||||
require(marks.length() <= 10000)
|
||||
return RemoteClip(Clip(id, json.getString("title").take(200), json.getLong("created"), duration,
|
||||
(0 until marks.length()).map { marks.getLong(it).coerceIn(0, duration) }), bytes, digest)
|
||||
}
|
||||
|
||||
fun digestStream(input: InputStream, check: () -> Unit = {}, maximumBytes: Long = Long.MAX_VALUE): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
val buffer = ByteArray(32 * 1024)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
check()
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
total += count
|
||||
require(total <= maximumBytes) { "Audio exceeds its expected size" }
|
||||
digest.update(buffer, 0, count)
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
|
||||
/** One authenticated session, bounded buffers, and no remote shell commands. */
|
||||
class BackupTransport(context: Context, private val check: () -> Unit = {}) : AutoCloseable {
|
||||
private val settings = BackupSettings(context)
|
||||
private val server = settings.server().also { it.validate() }
|
||||
private var session: Session? = null
|
||||
private var channel: ChannelSftp? = null
|
||||
@Volatile private var closed = false
|
||||
private val sftp get() = channel ?: error("Not connected")
|
||||
fun connect() {
|
||||
check()
|
||||
check(!closed) { "Connection cancelled" }
|
||||
val ssh = SshCrypto.client()
|
||||
ssh.hostKeyRepository = SshHostTrust.repository(server.fingerprint)
|
||||
val key = settings.privateKey()
|
||||
try { ssh.addIdentity("remember-watch", key, null, null) } finally { key.fill(0) }
|
||||
val connection = ssh.getSession(server.user, server.host, server.port)
|
||||
session = connection
|
||||
connection.apply {
|
||||
setConfig("StrictHostKeyChecking", "yes")
|
||||
// Keep the previous RSA/ECDSA host-key preference for existing fingerprint pins.
|
||||
// Ed25519 remains available for servers offering only that host-key type.
|
||||
setConfig("server_host_key", SshHostTrust.ALGORITHMS)
|
||||
setConfig("PreferredAuthentications", "publickey")
|
||||
setConfig("compression.s2c", "none"); setConfig("compression.c2s", "none")
|
||||
timeout = settings.timeout * 1000
|
||||
connect(settings.timeout * 1000)
|
||||
}
|
||||
check()
|
||||
check(!closed) { "Connection cancelled" }
|
||||
val files = connection.openChannel("sftp") as ChannelSftp
|
||||
channel = files
|
||||
files.apply {
|
||||
setBulkRequests(4)
|
||||
connect(settings.timeout * 1000)
|
||||
cd(server.folder)
|
||||
}
|
||||
check()
|
||||
check(!closed) { "Connection cancelled" }
|
||||
}
|
||||
fun test(): String { check(); return sftp.pwd() }
|
||||
private fun size(path: String): Long? = try { sftp.lstat(path).size } catch (e: SftpException) {
|
||||
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) null else throw e
|
||||
}
|
||||
fun upload(file: File, clip: Clip, stage: (String) -> Unit = {}, progress: (Long, Long) -> Unit): String {
|
||||
check()
|
||||
stage("Checking audio")
|
||||
val digest = file.inputStream().use { digestStream(it, check) }
|
||||
val manifest = clipManifest(clip, file.length(), digest)
|
||||
val remote = "${clip.id}.m4a"
|
||||
val partial = "$remote.upload"
|
||||
stage("Checking server copy")
|
||||
// Verify existing final audio too: metadata may have changed after an earlier backup.
|
||||
val finalMatches = size(remote) == file.length() && sftp.get(remote).use { digestStream(it, check, file.length()) } == digest
|
||||
if (!finalMatches) {
|
||||
var offset = size(partial) ?: 0L
|
||||
if (offset > file.length()) { sftp.rm(partial); offset = 0 }
|
||||
var transferred = offset
|
||||
val monitor = object : SftpProgressMonitor {
|
||||
override fun init(op: Int, src: String?, dest: String?, max: Long) = Unit
|
||||
override fun count(count: Long): Boolean {
|
||||
check(); transferred += count; progress(transferred, file.length()); return true
|
||||
}
|
||||
override fun end() = Unit
|
||||
}
|
||||
file.inputStream().use { input ->
|
||||
// JSch's InputStream RESUME overload skips the remote size itself.
|
||||
sftp.put(input, partial, monitor, ChannelSftp.RESUME)
|
||||
}
|
||||
check()
|
||||
stage("Verifying backup")
|
||||
if (sftp.get(partial).use { digestStream(it, check, file.length()) } != digest) {
|
||||
sftp.rm(partial)
|
||||
error("Upload verification failed. Retry the recording.")
|
||||
}
|
||||
if (size(remote) != null) sftp.rm(remote)
|
||||
sftp.rename(partial, remote)
|
||||
}
|
||||
check()
|
||||
stage("Updating details")
|
||||
manifest.byteInputStream().use { sftp.put(it, "${clip.id}.json.upload", ChannelSftp.OVERWRITE) }
|
||||
if (size("${clip.id}.json") != null) sftp.rm("${clip.id}.json")
|
||||
// Metadata is the commit marker; remote browsers ignore unfinished uploads.
|
||||
sftp.rename("${clip.id}.json.upload", "${clip.id}.json")
|
||||
return sha256(manifest.toByteArray())
|
||||
}
|
||||
fun list(): List<RemoteClip> {
|
||||
val entries = mutableListOf<ChannelSftp.LsEntry>()
|
||||
try {
|
||||
sftp.ls("*.json", ChannelSftp.LsEntrySelector { entry ->
|
||||
entries.add(entry)
|
||||
if (entries.size >= 1000) ChannelSftp.LsEntrySelector.BREAK else ChannelSftp.LsEntrySelector.CONTINUE
|
||||
})
|
||||
} catch (e: SftpException) { if (e.id != ChannelSftp.SSH_FX_NO_SUCH_FILE) throw e }
|
||||
return entries.mapNotNull { item ->
|
||||
check()
|
||||
if (!item.filename.matches(Regex("[a-fA-F0-9-]{36}\\.json")) || item.attrs.size > 128 * 1024) return@mapNotNull null
|
||||
runCatching {
|
||||
val remote = parseRemoteClip(sftp.get(item.filename).use { it.readBytesLimited(128 * 1024).toString(Charsets.UTF_8) })
|
||||
require(item.filename == "${remote.clip.id}.json")
|
||||
require(size("${remote.clip.id}.m4a") == remote.bytes)
|
||||
remote
|
||||
}.getOrNull()
|
||||
}.sortedByDescending { it.clip.created }
|
||||
}
|
||||
fun download(remote: RemoteClip, destination: File, progress: (Long, Long) -> Unit) {
|
||||
val temporary = File(destination.parentFile, "${destination.name}.download")
|
||||
try {
|
||||
sftp.get("${remote.clip.id}.m4a").use { input -> temporary.outputStream().use { output ->
|
||||
val buffer = ByteArray(32 * 1024)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
check()
|
||||
val count = input.read(buffer)
|
||||
if (count < 0) break
|
||||
total += count
|
||||
require(total <= remote.bytes) { "Remote audio size changed" }
|
||||
output.write(buffer, 0, count); progress(total, remote.bytes)
|
||||
}
|
||||
require(total == remote.bytes) { "Incomplete download" }
|
||||
} }
|
||||
require(temporary.inputStream().use { digestStream(it, check) } == remote.digest) { "Audio verification failed" }
|
||||
check(destination.exists().not() || destination.delete())
|
||||
check(temporary.renameTo(destination))
|
||||
} finally { temporary.delete() }
|
||||
}
|
||||
override fun close() { closed = true; channel?.disconnect(); session?.disconnect(); channel = null; session = null }
|
||||
}
|
||||
|
||||
private fun InputStream.readBytesLimited(limit: Int): ByteArray {
|
||||
val output = java.io.ByteArrayOutputStream()
|
||||
val buffer = ByteArray(4096)
|
||||
while (true) {
|
||||
val count = read(buffer)
|
||||
if (count < 0) break
|
||||
require(output.size() + count <= limit) { "Metadata is too large" }
|
||||
output.write(buffer, 0, count)
|
||||
}
|
||||
return output.toByteArray()
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package meghdad.remember
|
||||
|
||||
import android.content.Context
|
||||
import android.app.job.JobInfo
|
||||
import android.app.job.JobParameters
|
||||
import android.app.job.JobScheduler
|
||||
import android.app.job.JobService
|
||||
import android.content.ComponentName
|
||||
import java.io.File
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
|
||||
object BackupGate { val lock = ReentrantLock() }
|
||||
|
||||
fun backupVersion(clip: Clip, file: File): String = sha256(
|
||||
"${clip.id}\n${clip.title}\n${clip.created}\n${clip.duration}\n${clip.marks}\n${file.length()}\n${file.lastModified()}".toByteArray())
|
||||
|
||||
object BackupWork {
|
||||
private const val MANUAL = 71
|
||||
private const val AUTOMATIC = 72
|
||||
fun start(context: Context) {
|
||||
val settings = BackupSettings(context)
|
||||
settings.server().validate()
|
||||
require(settings.publicKey() != null) { "Generate and authorize the watch key first" }
|
||||
val scheduler = context.getSystemService(JobScheduler::class.java)
|
||||
if (scheduler.getPendingJob(MANUAL) != null) return
|
||||
settings.preferences.edit().putInt("attempt_71", 0).putString("summary", "Waiting for connection").apply()
|
||||
check(scheduler.schedule(JobInfo.Builder(MANUAL, ComponentName(context, BackupWorker::class.java))
|
||||
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).setPersisted(true)
|
||||
.setBackoffCriteria(30_000, JobInfo.BACKOFF_POLICY_EXPONENTIAL).build()) == JobScheduler.RESULT_SUCCESS) { "Could not queue backup" }
|
||||
}
|
||||
fun cancel(context: Context) {
|
||||
val scheduler = context.getSystemService(JobScheduler::class.java)
|
||||
scheduler.cancel(MANUAL); scheduler.cancel(AUTOMATIC)
|
||||
BackupSettings(context).preferences.edit().putBoolean("automatic", false).putString("summary", "Backups paused").apply()
|
||||
}
|
||||
fun schedule(context: Context) {
|
||||
val settings = BackupSettings(context)
|
||||
val scheduler = context.getSystemService(JobScheduler::class.java)
|
||||
if (!settings.automatic) { scheduler.cancel(AUTOMATIC); return }
|
||||
settings.server().validate()
|
||||
require(settings.publicKey() != null) { "Generate and authorize the watch key first" }
|
||||
check(scheduler.schedule(JobInfo.Builder(AUTOMATIC, ComponentName(context, BackupWorker::class.java))
|
||||
.setPeriodic(TimeUnit.HOURS.toMillis(settings.hours.toLong()))
|
||||
.setRequiresCharging(settings.charging).setPersisted(true)
|
||||
.setRequiredNetworkType(if (settings.unmetered) JobInfo.NETWORK_TYPE_UNMETERED else JobInfo.NETWORK_TYPE_ANY)
|
||||
.setBackoffCriteria(30_000, JobInfo.BACKOFF_POLICY_EXPONENTIAL).build()) == JobScheduler.RESULT_SUCCESS) { "Could not schedule backups" }
|
||||
}
|
||||
}
|
||||
|
||||
class BackupWorker : JobService() {
|
||||
private data class Running(val runner: BackupRunner, val thread: Thread)
|
||||
private val running = mutableMapOf<Int, Running>()
|
||||
override fun onStartJob(params: JobParameters): Boolean {
|
||||
val runner = BackupRunner(applicationContext)
|
||||
val thread = Thread {
|
||||
val retry = runner.performBackup(params.jobId)
|
||||
android.os.Handler(mainLooper).post {
|
||||
if (running[params.jobId]?.runner === runner) {
|
||||
running.remove(params.jobId)
|
||||
if (!runner.stopped) jobFinished(params, retry)
|
||||
}
|
||||
}
|
||||
}
|
||||
running[params.jobId] = Running(runner, thread)
|
||||
thread.start()
|
||||
return true
|
||||
}
|
||||
override fun onStopJob(params: JobParameters): Boolean {
|
||||
running.remove(params.jobId)?.let { it.runner.stop(); it.thread.interrupt() }
|
||||
return params.stopReason != JobParameters.STOP_REASON_CANCELLED_BY_APP
|
||||
}
|
||||
override fun onDestroy() {
|
||||
running.values.forEach { it.runner.stop(); it.thread.interrupt() }; running.clear()
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
|
||||
private class BackupRunner(private val applicationContext: Context) {
|
||||
@Volatile var stopped = false
|
||||
private set
|
||||
fun stop() { stopped = true; transport?.close() }
|
||||
@Volatile private var transport: BackupTransport? = null
|
||||
private fun ensureRunning() {
|
||||
check(!stopped && !Thread.currentThread().isInterrupted) { "Backup paused" }
|
||||
}
|
||||
fun performBackup(jobId: Int): Boolean {
|
||||
if (!BackupGate.lock.tryLock()) return true
|
||||
val settings = BackupSettings(applicationContext)
|
||||
var current: String? = null
|
||||
val start = android.os.SystemClock.elapsedRealtime()
|
||||
try {
|
||||
settings.server().validate()
|
||||
val store = Recordings(applicationContext)
|
||||
val clips = store.list().filter { settings.receipt(it.id) != backupVersion(it, store.audio(it.id)) }
|
||||
if (clips.isEmpty()) {
|
||||
settings.preferences.edit().putInt("attempt_$jobId", 0).putString("summary", "Everything is backed up").apply()
|
||||
return false
|
||||
}
|
||||
settings.preferences.edit().putString("summary", "Connecting…").apply()
|
||||
BackupTransport(applicationContext) {
|
||||
ensureRunning()
|
||||
check(android.os.SystemClock.elapsedRealtime() - start < 8 * 60_000) { "Backup will continue in another attempt" }
|
||||
}.use { client ->
|
||||
transport = client
|
||||
client.connect()
|
||||
for (clip in clips) {
|
||||
ensureRunning()
|
||||
current = clip.id
|
||||
val file = store.audio(clip.id)
|
||||
if (!file.exists()) continue
|
||||
val version = backupVersion(clip, file)
|
||||
settings.status(clip.id, "Uploading")
|
||||
var lastProgress = 0L
|
||||
client.upload(file, clip, stage = { stage ->
|
||||
settings.status(clip.id, stage)
|
||||
settings.preferences.edit().putString("summary", stage).apply()
|
||||
}) { sent, total ->
|
||||
val now = android.os.SystemClock.elapsedRealtime()
|
||||
if (now - lastProgress > 500) {
|
||||
val percentage = (sent * 100 / total.coerceAtLeast(1)).coerceIn(0, 100)
|
||||
settings.status(clip.id, "Uploading · $percentage%")
|
||||
settings.preferences.edit().putString("summary", "Uploading · $percentage%").apply()
|
||||
lastProgress = now
|
||||
}
|
||||
}
|
||||
// A simultaneous rename should be uploaded again, not silently acknowledged.
|
||||
settings.receipt(clip.id, version)
|
||||
settings.status(clip.id, "Backed up")
|
||||
}
|
||||
}
|
||||
settings.preferences.edit().putInt("attempt_$jobId", 0).putLong("last_success", System.currentTimeMillis()).putString("summary", "Backup complete").apply()
|
||||
return false
|
||||
} catch (_: Exception) {
|
||||
val message = if (stopped) "Waiting" else "Failed · check connection and server settings"
|
||||
current?.let { settings.status(it, message) }
|
||||
settings.preferences.edit().putString("summary", if (stopped) "Backup paused" else message).apply()
|
||||
val attempts = settings.preferences.getInt("attempt_$jobId", 0) + 1
|
||||
val retry = !stopped && attempts < settings.attempts
|
||||
settings.preferences.edit().putInt("attempt_$jobId", if (retry) attempts else 0).apply()
|
||||
return retry
|
||||
} finally { transport?.close(); transport = null; BackupGate.lock.unlock() }
|
||||
}
|
||||
}
|
||||
@@ -243,6 +243,7 @@ class MainActivity : Activity() {
|
||||
text("Make it yours.", 17f)
|
||||
button("Storage") { screen = "storage"; render() }.apply { layoutParams.height = dp(56) }
|
||||
button("Recording limit") { screen = "limits"; render() }.apply { layoutParams.height = dp(56) }
|
||||
button("Backup") { startActivity(Intent(this, BackupActivity::class.java)) }.apply { layoutParams.height = dp(56) }
|
||||
button(if (active) "Back to recording" else "Back") { screen = "home"; render() }
|
||||
}
|
||||
private fun storage() {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package meghdad.remember
|
||||
|
||||
import com.jcraft.jsch.JSch
|
||||
|
||||
/** Use the lightweight BC primitives directly, without replacing Android's JCA providers. */
|
||||
object SshCrypto {
|
||||
init {
|
||||
JSch.setConfig("keypairgen.eddsa", "com.jcraft.jsch.bc.KeyPairGenEdDSA")
|
||||
JSch.setConfig("keypairgen_fromprivate.eddsa", "com.jcraft.jsch.bc.KeyPairGenEdDSA")
|
||||
JSch.setConfig("ssh-ed25519", "com.jcraft.jsch.bc.SignatureEd25519")
|
||||
}
|
||||
fun client(): JSch = JSch()
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package meghdad.remember
|
||||
|
||||
import com.jcraft.jsch.*
|
||||
import java.security.MessageDigest
|
||||
import java.util.Base64
|
||||
|
||||
object SshHostTrust {
|
||||
const val ALGORITHMS = "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256,ssh-ed25519"
|
||||
fun fingerprint(key: ByteArray): String = "SHA256:" + Base64.getEncoder().withoutPadding()
|
||||
.encodeToString(MessageDigest.getInstance("SHA-256").digest(key))
|
||||
|
||||
/** An unapproved discovery key is always rejected before authentication. */
|
||||
fun repository(expected: String?, observed: (String) -> Unit = {}): HostKeyRepository = object : HostKeyRepository {
|
||||
override fun check(host: String?, key: ByteArray): Int {
|
||||
val actual = fingerprint(key)
|
||||
observed(actual)
|
||||
return when {
|
||||
expected == null -> HostKeyRepository.NOT_INCLUDED
|
||||
actual == expected -> HostKeyRepository.OK
|
||||
else -> HostKeyRepository.CHANGED
|
||||
}
|
||||
}
|
||||
override fun add(key: HostKey?, ui: UserInfo?) = Unit
|
||||
override fun remove(host: String?, type: String?) = Unit
|
||||
override fun remove(host: String?, type: String?, key: ByteArray?) = Unit
|
||||
override fun getKnownHostsRepositoryID() = "Remember approved server"
|
||||
override fun getHostKey(): Array<HostKey> = emptyArray()
|
||||
override fun getHostKey(host: String?, type: String?): Array<HostKey> = emptyArray()
|
||||
}
|
||||
}
|
||||
|
||||
class ServerTrustProbe(private val server: BackupServer, private val timeout: Int) : AutoCloseable {
|
||||
@Volatile private var connection: Session? = null
|
||||
@Volatile private var closed = false
|
||||
fun fetch(): String {
|
||||
server.validateConfiguration()
|
||||
check(!closed) { "Connection cancelled" }
|
||||
var discovered: String? = null
|
||||
val ssh = SshCrypto.client()
|
||||
ssh.hostKeyRepository = SshHostTrust.repository(null) { discovered = it }
|
||||
val session = ssh.getSession(server.user, server.host, server.port)
|
||||
connection = session
|
||||
try {
|
||||
session.setConfig("StrictHostKeyChecking", "yes")
|
||||
session.setConfig("server_host_key", SshHostTrust.ALGORITHMS)
|
||||
session.timeout = timeout * 1000
|
||||
try { session.connect(timeout * 1000) }
|
||||
catch (error: JSchException) { if (discovered == null) throw error }
|
||||
check(!closed) { "Connection cancelled" }
|
||||
return discovered ?: error("Could not read the server identity")
|
||||
} finally { session.disconnect(); connection = null }
|
||||
}
|
||||
override fun close() { closed = true; connection?.disconnect() }
|
||||
}
|
||||
@@ -1 +1,62 @@
|
||||
<resources><string name="app_name">Remember</string></resources>
|
||||
<resources>
|
||||
<string name="app_name">Remember</string>
|
||||
<string name="backup_download_progress">Downloading · %1$d%%</string>
|
||||
<string name="backup_address">Address</string>
|
||||
<string name="backup_advanced">Advanced</string>
|
||||
<string name="backup_an_action_is_already_running">An action is already running</string>
|
||||
<string name="backup_audio_downloads_to_a_temporary_watch_cache_before_playing">Audio downloads to a temporary watch cache before playing.</string>
|
||||
<string name="backup_automatic_backup">Automatic backup</string>
|
||||
<string name="backup_back">Back</string>
|
||||
<string name="backup_back_up_now">Back up now</string>
|
||||
<string name="backup_back_up_retry">Back up / Retry</string>
|
||||
<string name="backup_backup">Backup</string>
|
||||
<string name="backup_backup_folder">Backup folder</string>
|
||||
<string name="backup_backup_queued_opens_when_connected">Backup queued. Opens when connected.</string>
|
||||
<string name="backup_backups_paused_automatic_backup_is_off">Backups paused. Automatic backup is off.</string>
|
||||
<string name="backup_cancel_download">Cancel download</string>
|
||||
<string name="backup_clear_playback_cache">Clear playback cache</string>
|
||||
<string name="backup_copies_stay_on_the_server_when_you_delete_local_recordings">Copies stay on the server when you delete local recordings.</string>
|
||||
<string name="backup_could_not_export_key">Could not export key</string>
|
||||
<string name="backup_could_not_play_audio">Could not play audio</string>
|
||||
<string name="backup_download_play">Download & play</string>
|
||||
<string name="backup_keep_your_moments">Keep your moments.</string>
|
||||
<string name="backup_one_transfer_at_a_time_interrupted_uploads_resume_and_are">One transfer at a time. Interrupted uploads resume and are verified before completion. Local files are retained. SSH protects transfers; server files are not encrypted at rest.</string>
|
||||
<string name="backup_open_source_licenses">Open-source licenses</string>
|
||||
<string name="backup_pause_all_backups">Pause all backups</string>
|
||||
<string name="backup_playback_cache_cleared">Playback cache cleared</string>
|
||||
<string name="backup_port">Port</string>
|
||||
<string name="backup_public_key_copied">Public key copied</string>
|
||||
<string name="backup_public_key_exported">Public key exported</string>
|
||||
<string name="backup_ready_to_download">Ready to download</string>
|
||||
<string name="backup_refresh">Refresh</string>
|
||||
<string name="backup_runs_when_conditions_allow_the_watch_may_delay_background">Runs when conditions allow. The watch may delay background work to save battery. Unmetered does not guarantee Wi-Fi.</string>
|
||||
<string name="backup_save_a_recording_to_begin">Save a recording to begin.</string>
|
||||
<string name="backup_save_server">Save server</string>
|
||||
<string name="backup_server">Server</string>
|
||||
<string name="backup_server_playback">Server playback</string>
|
||||
<string name="backup_server_recordings">Server recordings</string>
|
||||
<string name="backup_tap_refresh_to_browse_your_backups">Tap Refresh to browse your backups.</string>
|
||||
<string name="backup_test_connection">Test connection</string>
|
||||
<string name="backup_transfers">Transfers</string>
|
||||
<string name="backup_username">Username</string>
|
||||
<string name="backup_wait_for_the_current_action_or_cancel_it">Wait for the current action, or cancel it</string>
|
||||
<string name="backup_replace_ed25519">Replace with Ed25519</string>
|
||||
<string name="backup_replace_key_message">This pauses backups and replaces the watch key. Add the new public key to your server before starting backups again.</string>
|
||||
<string name="backup_replace_key_confirm">Replace key</string>
|
||||
<string name="backup_connect_trust">Connect & trust</string>
|
||||
<string name="backup_reading_server_identity">Reading server identity…</string>
|
||||
<string name="backup_server_untrusted">Trust this server to connect</string>
|
||||
<string name="backup_server_trusted">Server trusted</string>
|
||||
<string name="backup_server_details_changed">Server details changed. Connect again.</string>
|
||||
<string name="backup_server_key_changed">Server identity changed. Connection blocked. Check with your administrator before forgetting its old identity.</string>
|
||||
<string name="backup_trust_server_title">Trust this server?</string>
|
||||
<string name="backup_trust_server_confirm">Trust server</string>
|
||||
<string name="backup_server_trusted_create_key">Server trusted. Create and authorize the watch key, then test the connection.</string>
|
||||
<string name="backup_server_identity">Server identity</string>
|
||||
<string name="backup_forget_trust">Forget trust</string>
|
||||
<string name="backup_forget_trust_message">This pauses backups and removes the remembered server identity. Only approve a replacement identity after checking a legitimate server change.</string>
|
||||
<string name="backup_trust_forgotten">Trust forgotten. Use Connect & trust on the Server page.</string>
|
||||
<string name="backup_trust_server_address">%1$s:%2$d</string>
|
||||
<string name="backup_remember_server">Remember this server.</string>
|
||||
<string name="backup_view_fingerprint">View fingerprint</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,35 @@
|
||||
package meghdad.remember
|
||||
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class BackupServerTest {
|
||||
private fun server() = BackupServer("example.test", 22, "backup", "/remember", "SHA256:" + "A".repeat(43))
|
||||
@Test fun rejectsUnsafeOrIncompleteServerDetails() {
|
||||
val invalid = listOf(server().copy(host = "ssh://example.test"), server().copy(port = 0),
|
||||
server().copy(user = ""), server().copy(folder = "/"), server().copy(folder = "/remember/../other"),
|
||||
server().copy(folder = "/remember/*"), server().copy(fingerprint = ""))
|
||||
invalid.forEach { candidate ->
|
||||
assertThrows(IllegalArgumentException::class.java) { candidate.validate() }
|
||||
}
|
||||
server().validate()
|
||||
}
|
||||
@Test fun backupReceiptsAreScopedToTheDestinationAndHostKey() {
|
||||
val original = server()
|
||||
assertNotEquals(original.identity, original.copy(folder = "/other").identity)
|
||||
assertNotEquals(original.identity, original.copy(user = "other").identity)
|
||||
assertNotEquals(original.identity, original.copy(fingerprint = "SHA256:" + "B".repeat(43)).identity)
|
||||
assertEquals(original.identity, original.copy().identity)
|
||||
}
|
||||
@Test fun savedConfigurationCanBeUntrustedButTransfersRequireApproval() {
|
||||
val pending = server().copy(fingerprint = "")
|
||||
pending.validateConfiguration()
|
||||
assertThrows(IllegalArgumentException::class.java) { pending.validate() }
|
||||
}
|
||||
@Test fun changingTheEndpointClearsTrustButChangingTheAccountDoesNot() {
|
||||
val trusted = server()
|
||||
assertEquals("", trusted.copy(host = "other.test").withRememberedTrust(trusted).fingerprint)
|
||||
assertEquals("", trusted.copy(port = 2222).withRememberedTrust(trusted).fingerprint)
|
||||
assertEquals(trusted.fingerprint, trusted.copy(user = "other", folder = "/other").withRememberedTrust(trusted).fingerprint)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package meghdad.remember
|
||||
|
||||
import com.jcraft.jsch.KeyPair
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
import java.io.ByteArrayOutputStream
|
||||
|
||||
class SshCryptoTest {
|
||||
@Test fun ed25519OpenSshIdentityReloadsAndSignsWithTheAndroidCompatibleBackend() {
|
||||
val client = SshCrypto.client()
|
||||
val pair = KeyPair.genKeyPair(client, KeyPair.ED25519)
|
||||
val bytes = ByteArrayOutputStream().also { pair.writeOpenSSHv1PrivateKey(it, null as ByteArray?) }.toByteArray()
|
||||
try {
|
||||
assertTrue(bytes.toString(Charsets.UTF_8).startsWith("-----BEGIN OPENSSH PRIVATE KEY-----"))
|
||||
val restored = KeyPair.load(client, bytes, null)
|
||||
try {
|
||||
assertEquals(KeyPair.ED25519, restored.keyType)
|
||||
assertArrayEquals(pair.publicKeyBlob, restored.publicKeyBlob)
|
||||
val message = "backup authentication".toByteArray()
|
||||
val verifier = pair.verifier
|
||||
verifier.update(message)
|
||||
assertTrue(verifier.verify(restored.getSignature(message)))
|
||||
} finally { restored.dispose() }
|
||||
} finally { bytes.fill(0); pair.dispose() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package meghdad.remember
|
||||
|
||||
import com.jcraft.jsch.HostKeyRepository
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SshHostTrustTest {
|
||||
@Test fun discoveryReportsTheFingerprintButNeverApprovesTheKey() {
|
||||
val key = byteArrayOf(1, 2, 3)
|
||||
var observed: String? = null
|
||||
val repository = SshHostTrust.repository(null) { observed = it }
|
||||
assertEquals(HostKeyRepository.NOT_INCLUDED, repository.check("server.test", key))
|
||||
assertEquals(SshHostTrust.fingerprint(key), observed)
|
||||
assertEquals(HostKeyRepository.NOT_INCLUDED, repository.check("server.test", key))
|
||||
}
|
||||
@Test fun authenticationAcceptsOnlyThePreviouslyApprovedKey() {
|
||||
val original = byteArrayOf(1, 2, 3)
|
||||
val repository = SshHostTrust.repository(SshHostTrust.fingerprint(original))
|
||||
assertEquals(HostKeyRepository.OK, repository.check("server.test", original))
|
||||
assertEquals(HostKeyRepository.CHANGED, repository.check("server.test", byteArrayOf(4, 5, 6)))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user