Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5f45a344b7 | |||
| e237555222 | |||
| d6220b7bd7 | |||
| c8e50ac17e |
@@ -7,17 +7,28 @@ import androidx.activity.enableEdgeToEdge
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.biometric.BiometricManager
|
||||
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
|
||||
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_WEAK
|
||||
import androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL
|
||||
import androidx.biometric.BiometricPrompt
|
||||
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.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Lock
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
@@ -36,6 +47,7 @@ class MainActivity : AppCompatActivity() {
|
||||
@Inject lateinit var appPreferences: AppPreferences
|
||||
|
||||
private var isLocked by mutableStateOf(false)
|
||||
private var showRetry by mutableStateOf(false)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
installSplashScreen()
|
||||
@@ -47,66 +59,106 @@ class MainActivity : AppCompatActivity() {
|
||||
SyncFlowNavGraph(rememberNavController())
|
||||
}
|
||||
if (isLocked) {
|
||||
LockOverlay()
|
||||
LaunchedEffect(Unit) {
|
||||
showBiometricPrompt(onSuccess = { isLocked = false })
|
||||
}
|
||||
LockOverlay(
|
||||
showRetry = showRetry,
|
||||
onRetry = { triggerBiometric() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (isLocked) triggerBiometric()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
super.onStop()
|
||||
if (isChangingConfigurations) return
|
||||
lifecycleScope.launch {
|
||||
if (appPreferences.biometricLockEnabled.first() && canAuthenticate()) {
|
||||
isLocked = true
|
||||
showRetry = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun canAuthenticate(): Boolean {
|
||||
val authenticators = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
|
||||
BIOMETRIC_STRONG or DEVICE_CREDENTIAL
|
||||
else
|
||||
BIOMETRIC_STRONG
|
||||
return BiometricManager.from(this).canAuthenticate(authenticators) ==
|
||||
BiometricManager.BIOMETRIC_SUCCESS
|
||||
}
|
||||
|
||||
private fun showBiometricPrompt(onSuccess: () -> Unit) {
|
||||
private fun triggerBiometric() {
|
||||
showRetry = false
|
||||
val authenticators = bestAuthenticators()
|
||||
val executor = ContextCompat.getMainExecutor(this)
|
||||
val prompt = BiometricPrompt(this, executor, object : BiometricPrompt.AuthenticationCallback() {
|
||||
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
|
||||
onSuccess()
|
||||
isLocked = false
|
||||
showRetry = false
|
||||
}
|
||||
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
|
||||
// Show the Unlock button so the user can tap to retry manually
|
||||
showRetry = true
|
||||
}
|
||||
override fun onAuthenticationFailed() {
|
||||
// Wrong biometric — BiometricPrompt retries automatically
|
||||
}
|
||||
})
|
||||
val promptInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
BiometricPrompt.PromptInfo.Builder()
|
||||
.setTitle("Unlock SyncFlow")
|
||||
.setSubtitle("Confirm your identity to continue")
|
||||
.setAllowedAuthenticators(BIOMETRIC_STRONG or DEVICE_CREDENTIAL)
|
||||
.setSubtitle("Use fingerprint or PIN")
|
||||
.setAllowedAuthenticators(authenticators)
|
||||
.build()
|
||||
} else {
|
||||
BiometricPrompt.PromptInfo.Builder()
|
||||
.setTitle("Unlock SyncFlow")
|
||||
.setSubtitle("Confirm your identity to continue")
|
||||
.setSubtitle("Use fingerprint")
|
||||
.setNegativeButtonText("Cancel")
|
||||
.build()
|
||||
}
|
||||
prompt.authenticate(promptInfo)
|
||||
}
|
||||
|
||||
private fun bestAuthenticators(): Int {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return BIOMETRIC_STRONG
|
||||
val bm = BiometricManager.from(this)
|
||||
// Prefer strong+credential; fall back to weak+credential so side-sensor phones work
|
||||
return if (bm.canAuthenticate(BIOMETRIC_STRONG or DEVICE_CREDENTIAL) == BiometricManager.BIOMETRIC_SUCCESS)
|
||||
BIOMETRIC_STRONG or DEVICE_CREDENTIAL
|
||||
else
|
||||
BIOMETRIC_WEAK or DEVICE_CREDENTIAL
|
||||
}
|
||||
|
||||
private fun canAuthenticate(): Boolean {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R)
|
||||
return BiometricManager.from(this).canAuthenticate(BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS
|
||||
val bm = BiometricManager.from(this)
|
||||
return bm.canAuthenticate(BIOMETRIC_STRONG or DEVICE_CREDENTIAL) == BiometricManager.BIOMETRIC_SUCCESS ||
|
||||
bm.canAuthenticate(BIOMETRIC_WEAK or DEVICE_CREDENTIAL) == BiometricManager.BIOMETRIC_SUCCESS
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LockOverlay() {
|
||||
private fun LockOverlay(showRetry: Boolean, onRetry: () -> Unit) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(MaterialTheme.colorScheme.background),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Icon(Icons.Default.Lock, null, modifier = Modifier.size(56.dp), tint = MaterialTheme.colorScheme.primary)
|
||||
Text("SyncFlow is locked", style = MaterialTheme.typography.titleMedium)
|
||||
if (showRetry) {
|
||||
Button(onClick = onRetry) { Text("Unlock") }
|
||||
} else {
|
||||
Text(
|
||||
"Use fingerprint or PIN to unlock",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,6 @@ import androidx.room.TypeConverter
|
||||
import java.time.Instant
|
||||
|
||||
class DbConverters {
|
||||
@TypeConverter fun fromInstant(v: Instant?): Long? = v?.epochSecond
|
||||
@TypeConverter fun toInstant(v: Long?): Instant? = v?.let { Instant.ofEpochSecond(it) }
|
||||
@TypeConverter fun fromInstant(v: Instant?): Long? = v?.toEpochMilli()
|
||||
@TypeConverter fun toInstant(v: Long?): Instant? = v?.let { Instant.ofEpochMilli(it) }
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package com.syncflow.data.db
|
||||
import androidx.room.Database
|
||||
import androidx.room.RoomDatabase
|
||||
import androidx.room.TypeConverters
|
||||
import androidx.room.migration.Migration
|
||||
import androidx.sqlite.db.SupportSQLiteDatabase
|
||||
import com.syncflow.data.db.entities.*
|
||||
|
||||
@Database(
|
||||
@@ -13,11 +15,21 @@ import com.syncflow.data.db.entities.*
|
||||
SyncConflictEntity::class,
|
||||
SyncEventEntity::class,
|
||||
],
|
||||
version = 2,
|
||||
version = 3,
|
||||
exportSchema = true,
|
||||
)
|
||||
@TypeConverters(DbConverters::class)
|
||||
abstract class SyncDatabase : RoomDatabase() {
|
||||
|
||||
companion object {
|
||||
// Wipe file states: timestamps were stored as epoch-seconds, now epoch-millis.
|
||||
// All previously saved states are wrong so we drop and re-learn on next sync.
|
||||
val MIGRATION_2_3 = object : Migration(2, 3) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("DELETE FROM sync_file_states")
|
||||
}
|
||||
}
|
||||
}
|
||||
abstract fun cloudAccountDao(): CloudAccountDao
|
||||
abstract fun syncPairDao(): SyncPairDao
|
||||
abstract fun syncFileStateDao(): SyncFileStateDao
|
||||
|
||||
@@ -21,9 +21,8 @@ object AppModule {
|
||||
@Provides @Singleton
|
||||
fun provideDatabase(@ApplicationContext ctx: Context): SyncDatabase =
|
||||
Room.databaseBuilder(ctx, SyncDatabase::class.java, "syncflow.db")
|
||||
// Only fall back to destructive migration for very old dev builds (v1).
|
||||
// All future version bumps must include a proper Migration object.
|
||||
.fallbackToDestructiveMigrationFrom(1)
|
||||
.addMigrations(SyncDatabase.MIGRATION_2_3)
|
||||
.build()
|
||||
|
||||
@Provides fun provideCloudAccountDao(db: SyncDatabase): CloudAccountDao = db.cloudAccountDao()
|
||||
|
||||
@@ -68,14 +68,18 @@ class SyncEngine @Inject constructor(
|
||||
.associateBy { it.path.removePrefix(pair.remotePath).trimStart('/') }
|
||||
val localFiles = accessor.walkFiles(pair)
|
||||
|
||||
var uploaded = 0; var downloaded = 0; var deleted = 0; var skipped = 0; var failed = 0; var conflicts = 0
|
||||
var bytesTransferred = 0L
|
||||
val newStates = mutableListOf<com.syncflow.data.db.entities.SyncFileStateEntity>()
|
||||
|
||||
val allPaths = (localFiles.keys + remoteFiles.keys + knownStates.keys).toSet()
|
||||
val semaphore = Semaphore(4)
|
||||
|
||||
coroutineScope {
|
||||
// Each async block returns its outcome; no shared mutable state across coroutines.
|
||||
data class FileOutcome(
|
||||
val uploaded: Int = 0, val downloaded: Int = 0, val deleted: Int = 0,
|
||||
val skipped: Int = 0, val failed: Int = 0, val conflicts: Int = 0,
|
||||
val bytesTransferred: Long = 0L,
|
||||
val newState: com.syncflow.data.db.entities.SyncFileStateEntity? = null,
|
||||
)
|
||||
|
||||
val outcomes: List<FileOutcome> = coroutineScope {
|
||||
allPaths.map { rel ->
|
||||
async {
|
||||
semaphore.withPermit {
|
||||
@@ -93,14 +97,11 @@ class SyncEngine @Inject constructor(
|
||||
local!!.sizeBytes
|
||||
}.getOrElse { e ->
|
||||
Timber.e(e, "Upload failed: $rel")
|
||||
failed++
|
||||
logEvent(pair.id, SyncEventType.FILE_SKIPPED, rel, e.message, 0)
|
||||
return@withPermit
|
||||
return@withPermit FileOutcome(failed = 1)
|
||||
}
|
||||
uploaded++
|
||||
bytesTransferred += bytes
|
||||
newStates += buildState(pair.id, rel, local!!, remote)
|
||||
logEvent(pair.id, SyncEventType.FILE_UPLOADED, rel, null, bytes)
|
||||
FileOutcome(uploaded = 1, bytesTransferred = bytes, newState = buildState(pair.id, rel, local!!, remote))
|
||||
}
|
||||
SyncDecision.DOWNLOAD -> {
|
||||
val bytes = runCatching {
|
||||
@@ -110,29 +111,25 @@ class SyncEngine @Inject constructor(
|
||||
remote!!.sizeBytes
|
||||
}.getOrElse { e ->
|
||||
Timber.e(e, "Download failed: $rel")
|
||||
failed++
|
||||
logEvent(pair.id, SyncEventType.FILE_SKIPPED, rel, e.message, 0)
|
||||
return@withPermit
|
||||
return@withPermit FileOutcome(failed = 1)
|
||||
}
|
||||
downloaded++
|
||||
bytesTransferred += bytes
|
||||
newStates += buildState(pair.id, rel, null, remote)
|
||||
logEvent(pair.id, SyncEventType.FILE_DOWNLOADED, rel, null, bytes)
|
||||
FileOutcome(downloaded = 1, bytesTransferred = bytes, newState = buildState(pair.id, rel, null, remote))
|
||||
}
|
||||
SyncDecision.DELETE_LOCAL -> {
|
||||
accessor.delete(rel)
|
||||
fileStateDao.delete(pair.id, rel)
|
||||
deleted++
|
||||
logEvent(pair.id, SyncEventType.FILE_DELETED, rel, "local", 0)
|
||||
FileOutcome(deleted = 1)
|
||||
}
|
||||
SyncDecision.DELETE_REMOTE -> {
|
||||
provider.deleteFile("${pair.remotePath}/$rel")
|
||||
fileStateDao.delete(pair.id, rel)
|
||||
deleted++
|
||||
logEvent(pair.id, SyncEventType.FILE_DELETED, rel, "remote", 0)
|
||||
FileOutcome(deleted = 1)
|
||||
}
|
||||
SyncDecision.CONFLICT -> {
|
||||
conflicts++
|
||||
conflictDao.insert(SyncConflictEntity(
|
||||
syncPairId = pair.id,
|
||||
relativePath = rel,
|
||||
@@ -144,16 +141,25 @@ class SyncEngine @Inject constructor(
|
||||
detectedAt = Instant.now(),
|
||||
))
|
||||
logEvent(pair.id, SyncEventType.CONFLICT_DETECTED, rel, null, 0)
|
||||
FileOutcome(conflicts = 1)
|
||||
}
|
||||
SyncDecision.SKIP -> skipped++
|
||||
SyncDecision.SKIP -> FileOutcome(skipped = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}.awaitAll()
|
||||
}
|
||||
|
||||
fileStateDao.upsertAll(newStates)
|
||||
return SyncResult(uploaded, downloaded, deleted, skipped, failed, conflicts, bytesTransferred)
|
||||
fileStateDao.upsertAll(outcomes.mapNotNull { it.newState })
|
||||
return SyncResult(
|
||||
uploaded = outcomes.sumOf { it.uploaded },
|
||||
downloaded = outcomes.sumOf { it.downloaded },
|
||||
deleted = outcomes.sumOf { it.deleted },
|
||||
skipped = outcomes.sumOf { it.skipped },
|
||||
failedFiles = outcomes.sumOf { it.failed },
|
||||
conflicts = outcomes.sumOf { it.conflicts },
|
||||
bytesTransferred = outcomes.sumOf { it.bytesTransferred },
|
||||
)
|
||||
}
|
||||
|
||||
private fun decide(
|
||||
@@ -168,7 +174,7 @@ class SyncEngine @Inject constructor(
|
||||
val remoteExists = remote != null
|
||||
|
||||
val localChanged = known == null || (localExists && local!!.lastModifiedMs != known.localModifiedAt?.toEpochMilli())
|
||||
val remoteChanged = known == null || (remoteExists && remote!!.etag != known.remoteEtag && remote.modifiedAt != known.remoteModifiedAt)
|
||||
val remoteChanged = known == null || (remoteExists && (remote!!.etag != known.remoteEtag || remote.modifiedAt != known.remoteModifiedAt))
|
||||
|
||||
return when {
|
||||
!localExists && !remoteExists -> SyncDecision.SKIP
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.syncflow.ui.addpair
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
@@ -14,6 +15,7 @@ import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
@@ -29,10 +31,17 @@ fun AddPairScreen(onDone: () -> Unit, vm: AddPairViewModel = hiltViewModel()) {
|
||||
val s by vm.state.collectAsState()
|
||||
LaunchedEffect(s.done) { if (s.done) onDone() }
|
||||
|
||||
val context = LocalContext.current
|
||||
var showRemoteBrowser by remember { mutableStateOf(false) }
|
||||
|
||||
val dirPicker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri: Uri? ->
|
||||
uri?.let { vm.update { copy(localPath = it.toString()) } }
|
||||
uri?.let {
|
||||
context.contentResolver.takePersistableUriPermission(
|
||||
it,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
|
||||
)
|
||||
vm.update { copy(localPath = it.toString()) }
|
||||
}
|
||||
}
|
||||
|
||||
if (showRemoteBrowser && s.selectedAccountId != -1L) {
|
||||
|
||||
@@ -23,7 +23,7 @@ class HomeViewModel @Inject constructor(
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||
|
||||
fun triggerSync(pair: SyncPairEntity) {
|
||||
val req = SyncWorker.buildOneTimeRequest(pair.id, pair.wifiOnly, pair.chargingOnly)
|
||||
val req = SyncWorker.buildOneTimeRequest(pair.id, wifiOnly = false, chargingOnly = false)
|
||||
workManager.enqueue(req)
|
||||
}
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ fun SyncFlowNavGraph(navController: NavHostController) {
|
||||
) {
|
||||
PairDetailScreen(
|
||||
onBack = { navController.popBackStack() },
|
||||
onEdit = { id -> navController.navigate(Screen.AddPair.route(id)) },
|
||||
onConflicts = { id -> navController.navigate(Screen.Conflicts.route(id)) },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import java.time.format.FormatStyle
|
||||
@Composable
|
||||
fun PairDetailScreen(
|
||||
onBack: () -> Unit,
|
||||
onEdit: (Long) -> Unit,
|
||||
onConflicts: (Long) -> Unit,
|
||||
vm: PairDetailViewModel = hiltViewModel(),
|
||||
) {
|
||||
@@ -49,6 +50,7 @@ fun PairDetailScreen(
|
||||
title = { Text(pair?.name ?: "…") },
|
||||
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.Default.ArrowBack, "Back") } },
|
||||
actions = {
|
||||
IconButton(onClick = { pair?.let { onEdit(it.id) } }) { Icon(Icons.Default.Edit, "Edit") }
|
||||
IconButton(onClick = { vm.syncNow() }) { Icon(Icons.Default.Sync, "Sync now") }
|
||||
IconButton(onClick = { showDelete = true }) { Icon(Icons.Default.Delete, "Delete") }
|
||||
},
|
||||
|
||||
@@ -36,7 +36,7 @@ class PairDetailViewModel @Inject constructor(
|
||||
|
||||
fun syncNow() {
|
||||
val p = pair.value ?: return
|
||||
workManager.enqueue(SyncWorker.buildOneTimeRequest(p.id, p.wifiOnly, p.chargingOnly))
|
||||
workManager.enqueue(SyncWorker.buildOneTimeRequest(p.id, wifiOnly = false, chargingOnly = false))
|
||||
}
|
||||
|
||||
fun delete() {
|
||||
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
VERSION_NAME=1.0.1
|
||||
VERSION_CODE=2
|
||||
VERSION_NAME=1.0.5
|
||||
VERSION_CODE=6
|
||||
|
||||
Reference in New Issue
Block a user