Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c60eb8d27b | |||
| 21b7ffc7b3 | |||
| cb9fa1d3db | |||
| e59564ac07 | |||
| 0ba4fd7eb9 | |||
| 69d4257a18 | |||
| 683169e8b7 |
@@ -1,5 +1,6 @@
|
||||
*.iml
|
||||
.gradle/
|
||||
.kotlin/
|
||||
local.properties
|
||||
.idea/
|
||||
.DS_Store
|
||||
|
||||
@@ -15,20 +15,27 @@ import com.syncflow.data.db.entities.*
|
||||
SyncConflictEntity::class,
|
||||
SyncEventEntity::class,
|
||||
],
|
||||
version = 3,
|
||||
version = 4,
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
val MIGRATION_3_4 = object : Migration(3, 4) {
|
||||
override fun migrate(db: SupportSQLiteDatabase) {
|
||||
db.execSQL("ALTER TABLE sync_pairs ADD COLUMN lastSyncUploaded INTEGER NOT NULL DEFAULT 0")
|
||||
db.execSQL("ALTER TABLE sync_pairs ADD COLUMN lastSyncDownloaded INTEGER NOT NULL DEFAULT 0")
|
||||
db.execSQL("ALTER TABLE sync_pairs ADD COLUMN lastSyncDeleted INTEGER NOT NULL DEFAULT 0")
|
||||
db.execSQL("ALTER TABLE sync_pairs ADD COLUMN lastSyncBytesTransferred INTEGER NOT NULL DEFAULT 0")
|
||||
}
|
||||
}
|
||||
}
|
||||
abstract fun cloudAccountDao(): CloudAccountDao
|
||||
abstract fun syncPairDao(): SyncPairDao
|
||||
|
||||
@@ -29,8 +29,8 @@ interface SyncPairDao {
|
||||
@Delete
|
||||
suspend fun delete(entity: SyncPairEntity)
|
||||
|
||||
@Query("UPDATE sync_pairs SET lastSyncAt = :at, lastSyncResult = :result, pendingConflicts = :conflicts WHERE id = :id")
|
||||
suspend fun updateSyncResult(id: Long, at: Instant, result: SyncStatus, conflicts: Int)
|
||||
@Query("UPDATE sync_pairs SET lastSyncAt = :at, lastSyncResult = :result, pendingConflicts = :conflicts, lastSyncUploaded = :uploaded, lastSyncDownloaded = :downloaded, lastSyncDeleted = :deleted, lastSyncBytesTransferred = :bytes WHERE id = :id")
|
||||
suspend fun updateSyncResult(id: Long, at: Instant, result: SyncStatus, conflicts: Int, uploaded: Int, downloaded: Int, deleted: Int, bytes: Long)
|
||||
|
||||
@Query("UPDATE sync_pairs SET lastSyncResult = :status WHERE id = :id")
|
||||
suspend fun updateStatus(id: Long, status: SyncStatus)
|
||||
|
||||
@@ -53,6 +53,11 @@ data class SyncPairEntity(
|
||||
val lastSyncAt: Instant?,
|
||||
val lastSyncResult: SyncStatus,
|
||||
val pendingConflicts: Int,
|
||||
// Last sync outcome counters (persist across pause/resume)
|
||||
val lastSyncUploaded: Int = 0,
|
||||
val lastSyncDownloaded: Int = 0,
|
||||
val lastSyncDeleted: Int = 0,
|
||||
val lastSyncBytesTransferred: Long = 0L,
|
||||
)
|
||||
|
||||
fun SyncPairEntity.toDomain() = SyncPair(
|
||||
|
||||
@@ -22,7 +22,7 @@ object AppModule {
|
||||
fun provideDatabase(@ApplicationContext ctx: Context): SyncDatabase =
|
||||
Room.databaseBuilder(ctx, SyncDatabase::class.java, "syncflow.db")
|
||||
.fallbackToDestructiveMigrationFrom(1)
|
||||
.addMigrations(SyncDatabase.MIGRATION_2_3)
|
||||
.addMigrations(SyncDatabase.MIGRATION_2_3, SyncDatabase.MIGRATION_3_4)
|
||||
.build()
|
||||
|
||||
@Provides fun provideCloudAccountDao(db: SyncDatabase): CloudAccountDao = db.cloudAccountDao()
|
||||
|
||||
@@ -58,6 +58,7 @@ enum class ConflictStrategy(val label: String) {
|
||||
enum class DeleteBehavior(val label: String, val description: String) {
|
||||
MIRROR("Mirror deletions", "Delete on target when deleted on source"),
|
||||
KEEP("Keep deleted files", "Never delete — only add/update"),
|
||||
ARCHIVE("Archive deleted", "Move files deleted from phone to _Deleted/ folder on remote"),
|
||||
}
|
||||
|
||||
enum class ScheduleType(val label: String) {
|
||||
@@ -69,5 +70,5 @@ enum class ScheduleType(val label: String) {
|
||||
}
|
||||
|
||||
enum class SyncStatus {
|
||||
IDLE, SYNCING, SUCCESS, PARTIAL, FAILED, CONFLICT,
|
||||
IDLE, SYNCING, PAUSED, SUCCESS, PARTIAL, FAILED, CONFLICT,
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ import kotlinx.coroutines.sync.withPermit
|
||||
import timber.log.Timber
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
import javax.inject.Inject
|
||||
|
||||
class SyncEngine @Inject constructor(
|
||||
@@ -33,34 +35,28 @@ class SyncEngine @Inject constructor(
|
||||
private val eventDao: SyncEventDao,
|
||||
@ApplicationContext private val context: Context,
|
||||
) {
|
||||
suspend fun sync(pair: SyncPair, provider: CloudProvider): SyncResult {
|
||||
if (!pair.localPath.startsWith("content://")) {
|
||||
val canonical = runCatching { File(pair.localPath).canonicalPath }.getOrElse { pair.localPath }
|
||||
if (canonical == "/storage/emulated/0") {
|
||||
val msg = "Local folder is the storage root — Android blocks writes here. Edit the pair and select a subfolder."
|
||||
syncPairDao.updateSyncResult(pair.id, Instant.now(), SyncStatus.FAILED, 0)
|
||||
logEvent(pair.id, SyncEventType.SYNC_FAILED, null, msg, 0)
|
||||
return SyncResult(failedFiles = 1, error = Exception(msg))
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun sync(
|
||||
pair: SyncPair,
|
||||
provider: CloudProvider,
|
||||
onProgress: (suspend (uploaded: Int, downloaded: Int, deleted: Int, bytesTransferred: Long) -> Unit)? = null,
|
||||
): SyncResult {
|
||||
syncPairDao.updateStatus(pair.id, SyncStatus.SYNCING)
|
||||
logEvent(pair.id, SyncEventType.SYNC_STARTED, null, null, 0)
|
||||
|
||||
return try {
|
||||
val result = performSync(pair, provider)
|
||||
val result = performSync(pair, provider, onProgress = onProgress)
|
||||
val finalStatus = when {
|
||||
result.failedFiles > 0 && result.conflicts > 0 -> SyncStatus.CONFLICT
|
||||
result.failedFiles > 0 -> SyncStatus.PARTIAL
|
||||
result.conflicts > 0 -> SyncStatus.CONFLICT
|
||||
else -> SyncStatus.SUCCESS
|
||||
}
|
||||
syncPairDao.updateSyncResult(pair.id, Instant.now(), finalStatus, result.conflicts)
|
||||
syncPairDao.updateSyncResult(pair.id, Instant.now(), finalStatus, result.conflicts, result.uploaded, result.downloaded, result.deleted, result.bytesTransferred)
|
||||
logEvent(pair.id, SyncEventType.SYNC_COMPLETED, null, "↑${result.uploaded} ↓${result.downloaded} ✕${result.deleted} ✗${result.failedFiles}", result.bytesTransferred)
|
||||
result
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e, "Sync failed for pair ${pair.id}")
|
||||
syncPairDao.updateSyncResult(pair.id, Instant.now(), SyncStatus.FAILED, 0)
|
||||
syncPairDao.updateSyncResult(pair.id, Instant.now(), SyncStatus.FAILED, 0, 0, 0, 0, 0L)
|
||||
logEvent(pair.id, SyncEventType.SYNC_FAILED, null, e.message, 0)
|
||||
SyncResult(failedFiles = 1, error = e)
|
||||
}
|
||||
@@ -76,6 +72,7 @@ class SyncEngine @Inject constructor(
|
||||
pair: SyncPair,
|
||||
provider: CloudProvider,
|
||||
isRetry: Boolean = false,
|
||||
onProgress: (suspend (Int, Int, Int, Long) -> Unit)? = null,
|
||||
): SyncResult {
|
||||
val accessor = makeAccessor(pair.localPath)
|
||||
var knownStates = fileStateDao.getForPair(pair.id).associateBy { it.relativePath }
|
||||
@@ -91,12 +88,16 @@ class SyncEngine @Inject constructor(
|
||||
knownStates.keys.none { it in localFiles }) {
|
||||
Timber.w("SyncEngine: stale folder states detected for pair ${pair.id} — resetting")
|
||||
fileStateDao.deleteForPair(pair.id)
|
||||
return performSync(pair, provider, isRetry = true)
|
||||
return performSync(pair, provider, isRetry = true, onProgress = onProgress)
|
||||
}
|
||||
|
||||
val allPaths = (localFiles.keys + remoteFiles.keys + knownStates.keys).toSet()
|
||||
val hasPriorSyncState = knownStates.isNotEmpty()
|
||||
val semaphore = Semaphore(4)
|
||||
val uploadedAtomic = AtomicInteger(0)
|
||||
val downloadedAtomic = AtomicInteger(0)
|
||||
val deletedAtomic = AtomicInteger(0)
|
||||
val bytesAtomic = AtomicLong(0L)
|
||||
|
||||
// Each async block returns its outcome; no shared mutable state across coroutines.
|
||||
data class FileOutcome(
|
||||
@@ -129,6 +130,9 @@ class SyncEngine @Inject constructor(
|
||||
return@withPermit FileOutcome(failed = 1)
|
||||
}
|
||||
logEvent(pair.id, SyncEventType.FILE_UPLOADED, rel, null, bytes)
|
||||
val up = uploadedAtomic.incrementAndGet()
|
||||
bytesAtomic.addAndGet(bytes)
|
||||
onProgress?.invoke(up, downloadedAtomic.get(), deletedAtomic.get(), bytesAtomic.get())
|
||||
// Don't store remote metadata from upload response — the server (Nextcloud etc.)
|
||||
// may change mtime/etag during post-upload processing. Leaving remoteModifiedAt
|
||||
// null forces the SKIP reconciliation on the next sync to fill it in from the
|
||||
@@ -152,6 +156,9 @@ class SyncEngine @Inject constructor(
|
||||
.getOrDefault(System.currentTimeMillis()).takeIf { it > 0L }
|
||||
?: System.currentTimeMillis()
|
||||
logEvent(pair.id, SyncEventType.FILE_DOWNLOADED, rel, null, bytes)
|
||||
val down = downloadedAtomic.incrementAndGet()
|
||||
bytesAtomic.addAndGet(bytes)
|
||||
onProgress?.invoke(uploadedAtomic.get(), down, deletedAtomic.get(), bytesAtomic.get())
|
||||
FileOutcome(downloaded = 1, bytesTransferred = bytes,
|
||||
newState = buildState(pair.id, rel,
|
||||
LocalFileInfo(rel, remote!!.sizeBytes, localMtime),
|
||||
@@ -163,13 +170,27 @@ class SyncEngine @Inject constructor(
|
||||
if (!deleted) Timber.w("SyncEngine: DELETE_LOCAL failed (silent) for $rel")
|
||||
fileStateDao.delete(pair.id, rel)
|
||||
logEvent(pair.id, SyncEventType.FILE_DELETED, rel, "local", 0)
|
||||
val del = deletedAtomic.incrementAndGet()
|
||||
onProgress?.invoke(uploadedAtomic.get(), downloadedAtomic.get(), del, bytesAtomic.get())
|
||||
FileOutcome(deleted = 1)
|
||||
}
|
||||
SyncDecision.DELETE_REMOTE -> {
|
||||
runCatching { provider.deleteFile("${pair.remotePath}/$rel") }
|
||||
.onFailure { e -> Timber.e(e, "SyncEngine: DELETE_REMOTE failed for $rel") }
|
||||
fileStateDao.delete(pair.id, rel)
|
||||
logEvent(pair.id, SyncEventType.FILE_DELETED, rel, "remote", 0)
|
||||
if (pair.deleteBehavior == DeleteBehavior.ARCHIVE) {
|
||||
val archivePath = "${pair.remotePath}/_Deleted/$rel"
|
||||
runCatching {
|
||||
ensureRemoteDirs(provider, "${pair.remotePath}/_Deleted", rel)
|
||||
provider.moveFile("${pair.remotePath}/$rel", archivePath).getOrThrow()
|
||||
}.onFailure { e -> Timber.e(e, "SyncEngine: ARCHIVE failed for $rel") }
|
||||
fileStateDao.delete(pair.id, rel)
|
||||
logEvent(pair.id, SyncEventType.FILE_DELETED, rel, "archived", 0)
|
||||
} else {
|
||||
runCatching { provider.deleteFile("${pair.remotePath}/$rel") }
|
||||
.onFailure { e -> Timber.e(e, "SyncEngine: DELETE_REMOTE failed for $rel") }
|
||||
fileStateDao.delete(pair.id, rel)
|
||||
logEvent(pair.id, SyncEventType.FILE_DELETED, rel, "remote", 0)
|
||||
}
|
||||
val del = deletedAtomic.incrementAndGet()
|
||||
onProgress?.invoke(uploadedAtomic.get(), downloadedAtomic.get(), del, bytesAtomic.get())
|
||||
FileOutcome(deleted = 1)
|
||||
}
|
||||
SyncDecision.CONFLICT -> {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.syncflow.ui.addpair
|
||||
|
||||
import android.content.Intent
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.*
|
||||
@@ -12,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
|
||||
@@ -28,9 +32,20 @@ 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) }
|
||||
var showLocalBrowser by remember { mutableStateOf(false) }
|
||||
|
||||
val safLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->
|
||||
if (uri != null) {
|
||||
context.contentResolver.takePersistableUriPermission(
|
||||
uri,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
|
||||
)
|
||||
vm.update { copy(localPath = uri.toString()) }
|
||||
}
|
||||
}
|
||||
|
||||
if (showLocalBrowser) {
|
||||
LocalBrowserDialog(
|
||||
initialPath = s.localPath.ifBlank { "" },
|
||||
|
||||
@@ -34,6 +34,12 @@ import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.Settings
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -131,6 +137,10 @@ fun LocalBrowserDialog(
|
||||
else entries.filter { it.file.name.contains(searchQuery, ignoreCase = true) }
|
||||
|
||||
val currentFolderName = currentPath.name.ifBlank { "Internal Storage" }
|
||||
val context = LocalContext.current
|
||||
val hasAllFilesAccess = remember {
|
||||
Build.VERSION.SDK_INT < Build.VERSION_CODES.R || Environment.isExternalStorageManager()
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -192,6 +202,35 @@ fun LocalBrowserDialog(
|
||||
colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.surface),
|
||||
)
|
||||
|
||||
// ── All-files-access banner ──────────────────────────────────
|
||||
if (!hasAllFilesAccess) {
|
||||
Surface(color = MaterialTheme.colorScheme.errorContainer) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Icon(Icons.Default.Warning, null, Modifier.size(18.dp), tint = MaterialTheme.colorScheme.onErrorContainer)
|
||||
Text(
|
||||
"Grant \"All files access\" to browse and sync all folders",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(
|
||||
onClick = {
|
||||
val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
|
||||
Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,
|
||||
Uri.fromParts("package", context.packageName, null))
|
||||
else Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
|
||||
context.startActivity(intent)
|
||||
},
|
||||
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp),
|
||||
) { Text("Grant", style = MaterialTheme.typography.labelSmall) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Breadcrumbs ──────────────────────────────────────────────
|
||||
Surface(tonalElevation = 1.dp) {
|
||||
LazyRow(
|
||||
@@ -263,23 +302,13 @@ fun LocalBrowserDialog(
|
||||
}
|
||||
|
||||
// ── Select button ────────────────────────────────────────────
|
||||
val isStorageRoot = currentPath.absolutePath == STORAGE_ROOT.absolutePath
|
||||
Surface(tonalElevation = 4.dp, modifier = Modifier.fillMaxWidth()) {
|
||||
Column {
|
||||
if (isStorageRoot) {
|
||||
Text(
|
||||
"Android blocks writes to the storage root — please open a subfolder first",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = 20.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
Button(
|
||||
onClick = { onSelect(currentPath.absolutePath) },
|
||||
enabled = !isStorageRoot,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 16.dp, top = 4.dp, end = 16.dp, bottom = 12.dp)
|
||||
.padding(start = 16.dp, top = 12.dp, end = 16.dp, bottom = 12.dp)
|
||||
.height(52.dp),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -40,6 +40,9 @@ class FilesViewModel @Inject constructor(
|
||||
val pairs: StateFlow<List<SyncPairEntity>> = syncPairDao.observeAll()
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
|
||||
|
||||
val accounts = accountRepository.observeAll()
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
|
||||
|
||||
private val _selectedPairId = MutableStateFlow<Long?>(null)
|
||||
|
||||
val selectedPair: StateFlow<SyncPairEntity?> = combine(_selectedPairId, pairs) { id, list ->
|
||||
@@ -158,6 +161,31 @@ class FilesViewModel @Inject constructor(
|
||||
|
||||
fun fileKey(file: SyncFileStateEntity) = "${file.syncPairId}:${file.relativePath}"
|
||||
|
||||
fun openCloudFile(accountId: Long, remotePath: String) {
|
||||
viewModelScope.launch {
|
||||
val account = accountRepository.getAccount(accountId) ?: run {
|
||||
_fileAction.emit(FileAction.Error("Account not found"))
|
||||
return@launch
|
||||
}
|
||||
val provider = providerFactory.create(account)
|
||||
val fileName = remotePath.substringAfterLast('/')
|
||||
val cacheFile = File(context.cacheDir, "syncflow_open/$fileName")
|
||||
cacheFile.parentFile?.mkdirs()
|
||||
_isDownloading.value = true
|
||||
try {
|
||||
cacheFile.outputStream().use { out ->
|
||||
provider.downloadFile(remotePath, out) { }.getOrThrow()
|
||||
}
|
||||
_fileAction.emit(FileAction.Open(cacheFile))
|
||||
} catch (e: Exception) {
|
||||
Timber.e(e, "Cloud open failed: $remotePath")
|
||||
_fileAction.emit(FileAction.Error("Cannot open: ${e.message}"))
|
||||
} finally {
|
||||
_isDownloading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Download-then-open/share ──────────────────────────────────────────────
|
||||
|
||||
private fun downloadAndOpen(file: SyncFileStateEntity) {
|
||||
|
||||
@@ -24,6 +24,7 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.syncflow.data.db.entities.SyncPairEntity
|
||||
import com.syncflow.domain.model.SyncStatus
|
||||
import com.syncflow.ui.shared.SyncProgress
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
import java.time.ZoneId
|
||||
@@ -38,6 +39,7 @@ fun HomeScreen(
|
||||
vm: HomeViewModel = hiltViewModel(),
|
||||
) {
|
||||
val pairs by vm.syncPairs.collectAsState()
|
||||
val progressMap by vm.syncProgressMap.collectAsState()
|
||||
|
||||
if (pairs.isEmpty()) {
|
||||
EmptyState(modifier = modifier.fillMaxSize(), onAdd = onAddPair)
|
||||
@@ -50,9 +52,11 @@ fun HomeScreen(
|
||||
items(pairs, key = { it.id }) { pair ->
|
||||
SyncPairCard(
|
||||
pair = pair,
|
||||
progress = progressMap[pair.id],
|
||||
onClick = { onPairClick(pair.id) },
|
||||
onSync = { vm.triggerSync(pair) },
|
||||
onToggle = { vm.toggleEnabled(pair) },
|
||||
onPause = { vm.pauseSync(pair) },
|
||||
)
|
||||
}
|
||||
item { Spacer(Modifier.height(80.dp)) }
|
||||
@@ -63,9 +67,11 @@ fun HomeScreen(
|
||||
@Composable
|
||||
private fun SyncPairCard(
|
||||
pair: SyncPairEntity,
|
||||
progress: SyncProgress? = null,
|
||||
onClick: () -> Unit,
|
||||
onSync: () -> Unit,
|
||||
onToggle: () -> Unit,
|
||||
onPause: () -> Unit = {},
|
||||
) {
|
||||
val accentColor = pair.lastSyncResult.accentColor
|
||||
|
||||
@@ -170,13 +176,57 @@ private fun SyncPairCard(
|
||||
animationSpec = infiniteRepeatable(tween(900, easing = LinearEasing)),
|
||||
label = "cardRotation",
|
||||
)
|
||||
FilledTonalIconButton(onClick = onSync, modifier = Modifier.size(36.dp)) {
|
||||
Icon(
|
||||
Icons.Default.Sync, "Sync now",
|
||||
modifier = Modifier.size(18.dp).graphicsLayer {
|
||||
if (pair.lastSyncResult == SyncStatus.SYNCING) rotationZ = syncRotation
|
||||
},
|
||||
)
|
||||
when (pair.lastSyncResult) {
|
||||
SyncStatus.SYNCING -> FilledTonalIconButton(onClick = onPause, modifier = Modifier.size(36.dp)) {
|
||||
Icon(Icons.Default.Pause, "Pause sync", modifier = Modifier.size(18.dp))
|
||||
}
|
||||
SyncStatus.PAUSED -> FilledTonalIconButton(onClick = onSync, modifier = Modifier.size(36.dp), enabled = pair.isEnabled) {
|
||||
Icon(Icons.Default.PlayArrow, "Resume sync", modifier = Modifier.size(18.dp))
|
||||
}
|
||||
else -> FilledTonalIconButton(onClick = onSync, modifier = Modifier.size(36.dp)) {
|
||||
Icon(Icons.Default.Sync, "Sync now", modifier = Modifier.size(18.dp).graphicsLayer { rotationZ = syncRotation * 0f })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val displayProgress = when {
|
||||
pair.lastSyncResult == SyncStatus.SYNCING -> progress
|
||||
pair.lastSyncUploaded > 0 || pair.lastSyncDownloaded > 0 || pair.lastSyncDeleted > 0 ->
|
||||
SyncProgress(pair.lastSyncUploaded, pair.lastSyncDownloaded, pair.lastSyncDeleted, pair.lastSyncBytesTransferred)
|
||||
else -> null
|
||||
}
|
||||
if (pair.lastSyncResult == SyncStatus.SYNCING && displayProgress == null) {
|
||||
Text(
|
||||
"Starting…",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
} else if (displayProgress != null) {
|
||||
Row(
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
if (displayProgress.uploaded > 0) {
|
||||
Icon(Icons.Default.ArrowUpward, null, Modifier.size(11.dp), tint = MaterialTheme.colorScheme.primary)
|
||||
Text("${displayProgress.uploaded}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
if (displayProgress.downloaded > 0) {
|
||||
Icon(Icons.Default.ArrowDownward, null, Modifier.size(11.dp), tint = MaterialTheme.colorScheme.secondary)
|
||||
Text("${displayProgress.downloaded}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.secondary)
|
||||
}
|
||||
if (displayProgress.deleted > 0) {
|
||||
Icon(Icons.Default.DeleteOutline, null, Modifier.size(11.dp), tint = MaterialTheme.colorScheme.error)
|
||||
Text("${displayProgress.deleted}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
if (displayProgress.bytesTransferred > 0) {
|
||||
Text(
|
||||
"· ${displayProgress.bytesTransferred.toDisplaySize()}",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -189,6 +239,7 @@ private fun StatusPill(status: SyncStatus) {
|
||||
val (icon, label) = when (status) {
|
||||
SyncStatus.SUCCESS -> Pair(Icons.Default.CheckCircle, "Synced")
|
||||
SyncStatus.SYNCING -> Pair(Icons.Default.Sync, "Syncing…")
|
||||
SyncStatus.PAUSED -> Pair(Icons.Default.Pause, "Paused")
|
||||
SyncStatus.FAILED -> Pair(Icons.Default.Error, "Failed")
|
||||
SyncStatus.CONFLICT -> Pair(Icons.Default.Warning, "Conflict")
|
||||
SyncStatus.PARTIAL -> Pair(Icons.Default.WarningAmber, "Partial")
|
||||
@@ -245,13 +296,21 @@ private fun EmptyState(modifier: Modifier = Modifier, onAdd: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
private fun Long.toDisplaySize(): String = when {
|
||||
this < 1_024 -> "$this B"
|
||||
this < 1_048_576 -> "${"%.1f".format(this / 1_024.0)} KB"
|
||||
this < 1_073_741_824 -> "${"%.1f".format(this / 1_048_576.0)} MB"
|
||||
else -> "${"%.1f".format(this / 1_073_741_824.0)} GB"
|
||||
}
|
||||
|
||||
private val SyncStatus.accentColor: Color
|
||||
@Composable get() = when (this) {
|
||||
SyncStatus.SUCCESS -> Color(0xFF2E7D32) // green — done, healthy
|
||||
SyncStatus.SYNCING -> Color(0xFF1565C0) // blue — in progress
|
||||
SyncStatus.FAILED -> Color(0xFFC62828) // red — error
|
||||
SyncStatus.PARTIAL -> Color(0xFFE65100) // orange — some files failed
|
||||
SyncStatus.CONFLICT -> Color(0xFFF9A825) // amber — needs resolution
|
||||
SyncStatus.SUCCESS -> Color(0xFF2E7D32)
|
||||
SyncStatus.SYNCING -> Color(0xFF1565C0)
|
||||
SyncStatus.PAUSED -> Color(0xFF6A1B9A)
|
||||
SyncStatus.FAILED -> Color(0xFFC62828)
|
||||
SyncStatus.PARTIAL -> Color(0xFFE65100)
|
||||
SyncStatus.CONFLICT -> Color(0xFFF9A825)
|
||||
SyncStatus.IDLE -> MaterialTheme.colorScheme.outline
|
||||
}
|
||||
|
||||
|
||||
@@ -4,15 +4,20 @@ import android.content.Context
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.work.ExistingPeriodicWorkPolicy
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkQuery
|
||||
import com.syncflow.data.db.SyncPairDao
|
||||
import com.syncflow.data.db.entities.SyncPairEntity
|
||||
import com.syncflow.domain.model.ScheduleType
|
||||
import com.syncflow.domain.model.SyncStatus
|
||||
import com.syncflow.ui.shared.SyncProgress
|
||||
import com.syncflow.worker.FileWatchService
|
||||
import com.syncflow.worker.SyncWorker
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
@@ -27,11 +32,33 @@ class HomeViewModel @Inject constructor(
|
||||
val syncPairs = syncPairDao.observeAll()
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
|
||||
|
||||
val syncProgressMap: kotlinx.coroutines.flow.StateFlow<Map<Long, SyncProgress>> =
|
||||
workManager.getWorkInfosFlow(WorkQuery.fromStates(WorkInfo.State.RUNNING))
|
||||
.map { infos ->
|
||||
infos
|
||||
.mapNotNull { info ->
|
||||
val tag = info.tags.firstOrNull { it.startsWith("sync_") } ?: return@mapNotNull null
|
||||
val pairId = tag.removePrefix("sync_").toLongOrNull() ?: return@mapNotNull null
|
||||
val up = info.progress.getInt(SyncWorker.KEY_PROGRESS_UPLOADED, 0)
|
||||
val down = info.progress.getInt(SyncWorker.KEY_PROGRESS_DOWNLOADED, 0)
|
||||
val del = info.progress.getInt(SyncWorker.KEY_PROGRESS_DELETED, 0)
|
||||
val bytes = info.progress.getLong(SyncWorker.KEY_PROGRESS_BYTES, 0L)
|
||||
if (up > 0 || down > 0 || del > 0) pairId to SyncProgress(up, down, del, bytes) else null
|
||||
}
|
||||
.toMap()
|
||||
}
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyMap())
|
||||
|
||||
fun triggerSync(pair: SyncPairEntity) {
|
||||
val req = SyncWorker.buildOneTimeRequest(pair.id, wifiOnly = false, chargingOnly = false)
|
||||
workManager.enqueue(req)
|
||||
}
|
||||
|
||||
fun pauseSync(pair: SyncPairEntity) {
|
||||
workManager.cancelAllWorkByTag("sync_${pair.id}")
|
||||
viewModelScope.launch { syncPairDao.updateStatus(pair.id, SyncStatus.PAUSED) }
|
||||
}
|
||||
|
||||
fun toggleEnabled(pair: SyncPairEntity) {
|
||||
viewModelScope.launch {
|
||||
val nowEnabled = !pair.isEnabled
|
||||
|
||||
@@ -22,6 +22,7 @@ import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import com.syncflow.data.db.entities.SyncPairEntity
|
||||
import com.syncflow.domain.model.SyncStatus
|
||||
import com.syncflow.ui.shared.SyncProgress
|
||||
import com.syncflow.ui.shared.SyncEventRow
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
@@ -40,6 +41,7 @@ fun PairDetailScreen(
|
||||
val pair by vm.pair.collectAsState()
|
||||
val events by vm.events.collectAsState()
|
||||
val conflictCount by vm.unresolvedConflicts.collectAsState()
|
||||
val syncProgress by vm.syncProgress.collectAsState()
|
||||
var showDelete by remember { mutableStateOf(false) }
|
||||
|
||||
if (showDelete) {
|
||||
@@ -66,7 +68,17 @@ fun PairDetailScreen(
|
||||
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") }
|
||||
when (pair?.lastSyncResult) {
|
||||
SyncStatus.SYNCING -> IconButton(onClick = { vm.pauseSync() }) {
|
||||
Icon(Icons.Default.Pause, "Pause sync")
|
||||
}
|
||||
SyncStatus.PAUSED -> IconButton(onClick = { vm.syncNow() }, enabled = pair?.isEnabled == true) {
|
||||
Icon(Icons.Default.PlayArrow, "Resume sync")
|
||||
}
|
||||
else -> IconButton(onClick = { vm.syncNow() }) {
|
||||
Icon(Icons.Default.Sync, "Sync now")
|
||||
}
|
||||
}
|
||||
IconButton(onClick = { showDelete = true }) { Icon(Icons.Default.Delete, "Delete") }
|
||||
},
|
||||
)
|
||||
@@ -78,7 +90,7 @@ fun PairDetailScreen(
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
item {
|
||||
pair?.let { p -> StatusBanner(p) }
|
||||
pair?.let { p -> StatusBanner(p, syncProgress) }
|
||||
}
|
||||
|
||||
item {
|
||||
@@ -138,10 +150,11 @@ fun PairDetailScreen(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusBanner(pair: SyncPairEntity) {
|
||||
private fun StatusBanner(pair: SyncPairEntity, progress: SyncProgress? = null) {
|
||||
val (icon, label, containerColor) = when (pair.lastSyncResult) {
|
||||
SyncStatus.SUCCESS -> Triple(Icons.Default.CheckCircle, "Synced", MaterialTheme.colorScheme.primaryContainer)
|
||||
SyncStatus.SYNCING -> Triple(Icons.Default.Sync, "Syncing…", MaterialTheme.colorScheme.secondaryContainer)
|
||||
SyncStatus.PAUSED -> Triple(Icons.Default.Pause, "Paused — tap ▶ to resume", MaterialTheme.colorScheme.surfaceVariant)
|
||||
SyncStatus.FAILED -> Triple(Icons.Default.Error, "Failed", MaterialTheme.colorScheme.errorContainer)
|
||||
SyncStatus.CONFLICT -> Triple(Icons.Default.Warning, "Conflict", MaterialTheme.colorScheme.tertiaryContainer)
|
||||
SyncStatus.PARTIAL -> Triple(Icons.Default.WarningAmber,"Partial", MaterialTheme.colorScheme.tertiaryContainer)
|
||||
@@ -170,8 +183,39 @@ private fun StatusBanner(pair: SyncPairEntity) {
|
||||
Spacer(Modifier.width(16.dp))
|
||||
Column {
|
||||
Text(label, style = MaterialTheme.typography.titleMedium)
|
||||
pair.lastSyncAt?.let {
|
||||
Text(it.toRelativeString(), style = MaterialTheme.typography.bodySmall)
|
||||
val displayProgress = when {
|
||||
pair.lastSyncResult == SyncStatus.SYNCING -> progress
|
||||
pair.lastSyncUploaded > 0 || pair.lastSyncDownloaded > 0 || pair.lastSyncDeleted > 0 ->
|
||||
SyncProgress(pair.lastSyncUploaded, pair.lastSyncDownloaded, pair.lastSyncDeleted, pair.lastSyncBytesTransferred)
|
||||
else -> null
|
||||
}
|
||||
if (pair.lastSyncResult == SyncStatus.SYNCING && displayProgress == null) {
|
||||
Text("Starting…", style = MaterialTheme.typography.bodySmall)
|
||||
} else if (displayProgress != null) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
if (displayProgress.uploaded > 0) {
|
||||
Icon(Icons.Default.ArrowUpward, null, Modifier.size(12.dp))
|
||||
Text("${displayProgress.uploaded} up", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
if (displayProgress.downloaded > 0) {
|
||||
Icon(Icons.Default.ArrowDownward, null, Modifier.size(12.dp))
|
||||
Text("${displayProgress.downloaded} down", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
if (displayProgress.deleted > 0) {
|
||||
Icon(Icons.Default.DeleteOutline, null, Modifier.size(12.dp))
|
||||
Text("${displayProgress.deleted} del", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
if (displayProgress.bytesTransferred > 0) {
|
||||
Text("· ${displayProgress.bytesTransferred.toDisplaySize()}", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pair.lastSyncAt?.let {
|
||||
Text(it.toRelativeString(), style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,6 +273,13 @@ private fun InfoRow(
|
||||
}
|
||||
}
|
||||
|
||||
private fun Long.toDisplaySize(): String = when {
|
||||
this < 1_024 -> "$this B"
|
||||
this < 1_048_576 -> "${"%.1f".format(this / 1_024.0)} KB"
|
||||
this < 1_073_741_824 -> "${"%.1f".format(this / 1_048_576.0)} MB"
|
||||
else -> "${"%.1f".format(this / 1_073_741_824.0)} GB"
|
||||
}
|
||||
|
||||
private fun String.toDisplayPath(): String {
|
||||
val decoded = java.net.URLDecoder.decode(this, "UTF-8")
|
||||
return decoded.trimEnd('/').substringAfterLast('/').substringAfterLast(':').ifEmpty { decoded }
|
||||
|
||||
@@ -3,13 +3,17 @@ package com.syncflow.ui.pairdetail
|
||||
import androidx.lifecycle.SavedStateHandle
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import androidx.work.WorkInfo
|
||||
import androidx.work.WorkManager
|
||||
import com.syncflow.data.db.SyncConflictDao
|
||||
import com.syncflow.data.db.SyncEventDao
|
||||
import com.syncflow.data.db.SyncPairDao
|
||||
import com.syncflow.domain.model.SyncStatus
|
||||
import com.syncflow.worker.SyncWorker
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import com.syncflow.ui.shared.SyncProgress
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import javax.inject.Inject
|
||||
@@ -34,11 +38,30 @@ class PairDetailViewModel @Inject constructor(
|
||||
val unresolvedConflicts = conflictDao.observeUnresolvedCount(pairId)
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), 0)
|
||||
|
||||
val syncProgress = workManager.getWorkInfosByTagFlow("sync_$pairId")
|
||||
.map { infos ->
|
||||
infos.firstOrNull { it.state == WorkInfo.State.RUNNING }?.progress?.let { data ->
|
||||
SyncProgress(
|
||||
uploaded = data.getInt(SyncWorker.KEY_PROGRESS_UPLOADED, 0),
|
||||
downloaded = data.getInt(SyncWorker.KEY_PROGRESS_DOWNLOADED, 0),
|
||||
deleted = data.getInt(SyncWorker.KEY_PROGRESS_DELETED, 0),
|
||||
bytesTransferred = data.getLong(SyncWorker.KEY_PROGRESS_BYTES, 0L),
|
||||
).takeIf { it.uploaded > 0 || it.downloaded > 0 || it.deleted > 0 }
|
||||
}
|
||||
}
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), null)
|
||||
|
||||
fun syncNow() {
|
||||
val p = pair.value ?: return
|
||||
workManager.enqueue(SyncWorker.buildOneTimeRequest(p.id, wifiOnly = false, chargingOnly = false))
|
||||
}
|
||||
|
||||
fun pauseSync() {
|
||||
val p = pair.value ?: return
|
||||
workManager.cancelAllWorkByTag("sync_${p.id}")
|
||||
viewModelScope.launch { syncPairDao.updateStatus(p.id, SyncStatus.PAUSED) }
|
||||
}
|
||||
|
||||
fun delete() {
|
||||
viewModelScope.launch {
|
||||
pair.value?.let { syncPairDao.delete(it) }
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.syncflow.ui.shared
|
||||
|
||||
data class SyncProgress(val uploaded: Int, val downloaded: Int, val deleted: Int, val bytesTransferred: Long)
|
||||
@@ -47,7 +47,14 @@ class SyncWorker @AssistedInject constructor(
|
||||
return try {
|
||||
val domainPair = pair.toDomain()
|
||||
val provider = providerFactory.create(account)
|
||||
val result = syncEngine.sync(domainPair, provider)
|
||||
val result = syncEngine.sync(domainPair, provider) { up, down, del, bytes ->
|
||||
setProgress(workDataOf(
|
||||
KEY_PROGRESS_UPLOADED to up,
|
||||
KEY_PROGRESS_DOWNLOADED to down,
|
||||
KEY_PROGRESS_DELETED to del,
|
||||
KEY_PROGRESS_BYTES to bytes,
|
||||
))
|
||||
}
|
||||
|
||||
val lines = buildList {
|
||||
if (result.uploaded > 0) add("↑${result.uploaded}")
|
||||
@@ -158,6 +165,10 @@ class SyncWorker @AssistedInject constructor(
|
||||
const val KEY_PAIR_ID = "pair_id"
|
||||
const val KEY_SILENT = "silent"
|
||||
const val KEY_RESULT_SUMMARY = "result_summary"
|
||||
const val KEY_PROGRESS_UPLOADED = "prog_up"
|
||||
const val KEY_PROGRESS_DOWNLOADED = "prog_down"
|
||||
const val KEY_PROGRESS_DELETED = "prog_del"
|
||||
const val KEY_PROGRESS_BYTES = "prog_bytes"
|
||||
private const val NOTIFICATION_ID = 1001
|
||||
private const val RESULT_ID_OFFSET = 2000
|
||||
private const val CHANNEL_PROGRESS = "sync_progress"
|
||||
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
VERSION_NAME=1.0.53
|
||||
VERSION_CODE=54
|
||||
VERSION_NAME=1.0.63
|
||||
VERSION_CODE=64
|
||||
|
||||
Reference in New Issue
Block a user