diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a148bd1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,12 @@
+*.iml
+.gradle/
+/local.properties
+/.idea/
+.DS_Store
+/build
+/captures
+.externalNativeBuild
+.cxx
+local.properties
+app/schemas/
+build/
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
new file mode 100644
index 0000000..08cf1da
--- /dev/null
+++ b/app/build.gradle.kts
@@ -0,0 +1,102 @@
+plugins {
+ alias(libs.plugins.android.application)
+ alias(libs.plugins.kotlin.android)
+ alias(libs.plugins.kotlin.compose)
+ alias(libs.plugins.kotlin.serialization)
+ alias(libs.plugins.ksp)
+ alias(libs.plugins.hilt)
+}
+
+android {
+ namespace = "es.zenvairo.nextcloudsync"
+ compileSdk = 36
+
+ defaultConfig {
+ applicationId = "es.zenvairo.nextcloudsync"
+ minSdk = 26
+ targetSdk = 36
+ versionCode = 1
+ versionName = "0.1.0"
+
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = true
+ isShrinkResources = true
+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
+ }
+ debug {
+ isMinifyEnabled = false
+ applicationIdSuffix = ".debug"
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ kotlinOptions {
+ jvmTarget = "17"
+ }
+
+ buildFeatures {
+ compose = true
+ }
+
+ packaging {
+ resources {
+ excludes += "/META-INF/{AL2.0,LGPL2.1}"
+ }
+ }
+}
+
+ksp {
+ arg("room.schemaLocation", "$projectDir/schemas")
+}
+
+dependencies {
+ implementation(libs.androidx.core.ktx)
+ implementation(libs.androidx.lifecycle.runtime.ktx)
+ implementation(libs.androidx.lifecycle.viewmodel.compose)
+ implementation(libs.androidx.activity.compose)
+ implementation(platform(libs.androidx.compose.bom))
+ implementation(libs.androidx.ui)
+ implementation(libs.androidx.ui.graphics)
+ implementation(libs.androidx.ui.tooling.preview)
+ implementation(libs.androidx.material3)
+ implementation(libs.androidx.material.icons.extended)
+ implementation(libs.androidx.navigation.compose)
+ debugImplementation(libs.androidx.ui.tooling)
+
+ implementation(libs.hilt.android)
+ ksp(libs.hilt.compiler)
+ implementation(libs.hilt.navigation.compose)
+ implementation(libs.hilt.work)
+ ksp(libs.hilt.work.compiler)
+
+ implementation(libs.room.runtime)
+ implementation(libs.room.ktx)
+ ksp(libs.room.compiler)
+
+ implementation(libs.datastore.preferences)
+ implementation(libs.work.runtime.ktx)
+
+ implementation(libs.okhttp)
+ implementation(libs.okhttp.logging.interceptor)
+ implementation(libs.kotlinx.serialization.json)
+ implementation(libs.kotlinx.coroutines.android)
+
+ implementation(libs.security.crypto)
+ implementation(libs.androidx.browser)
+
+ testImplementation(libs.junit)
+ testImplementation("net.sf.kxml:kxml2:2.3.0")
+ testImplementation(libs.mockwebserver)
+ testImplementation(libs.truth)
+ testImplementation(libs.kotlinx.coroutines.test)
+ androidTestImplementation(libs.androidx.test.ext.junit)
+ androidTestImplementation(libs.espresso.core)
+}
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
new file mode 100644
index 0000000..67af1b1
--- /dev/null
+++ b/app/proguard-rules.pro
@@ -0,0 +1,4 @@
+# Add project specific ProGuard rules here.
+-keepattributes *Annotation*
+-keep class es.zenvairo.nextcloudsync.data.remote.dto.** { *; }
+-keep class es.zenvairo.nextcloudsync.data.auth.dto.** { *; }
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..1fe4360
--- /dev/null
+++ b/app/src/main/AndroidManifest.xml
@@ -0,0 +1,84 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/NextCloudSyncApp.kt b/app/src/main/java/es/zenvairo/nextcloudsync/NextCloudSyncApp.kt
new file mode 100644
index 0000000..87f7dd7
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/NextCloudSyncApp.kt
@@ -0,0 +1,49 @@
+package es.zenvairo.nextcloudsync
+
+import android.app.Application
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.os.Build
+import androidx.hilt.work.HiltWorkerFactory
+import androidx.work.Configuration
+import dagger.hilt.android.HiltAndroidApp
+import javax.inject.Inject
+
+const val NOTIFICATION_CHANNEL_SYNC = "sync_activity"
+const val NOTIFICATION_CHANNEL_ALERTS = "sync_alerts"
+
+@HiltAndroidApp
+class NextCloudSyncApp : Application(), Configuration.Provider {
+
+ @Inject lateinit var workerFactory: HiltWorkerFactory
+
+ override val workManagerConfiguration: Configuration
+ get() = Configuration.Builder()
+ .setWorkerFactory(workerFactory)
+ .setMinimumLoggingLevel(android.util.Log.INFO)
+ .build()
+
+ override fun onCreate() {
+ super.onCreate()
+ createNotificationChannels()
+ }
+
+ private fun createNotificationChannels() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
+ val manager = getSystemService(NotificationManager::class.java)
+ manager.createNotificationChannel(
+ NotificationChannel(
+ NOTIFICATION_CHANNEL_SYNC,
+ getString(R.string.notification_channel_sync_name),
+ NotificationManager.IMPORTANCE_LOW
+ ).apply { description = getString(R.string.notification_channel_sync_description) }
+ )
+ manager.createNotificationChannel(
+ NotificationChannel(
+ NOTIFICATION_CHANNEL_ALERTS,
+ getString(R.string.notification_channel_alerts_name),
+ NotificationManager.IMPORTANCE_DEFAULT
+ ).apply { description = getString(R.string.notification_channel_alerts_description) }
+ )
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/auth/AccountRepository.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/auth/AccountRepository.kt
new file mode 100644
index 0000000..feb95b7
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/auth/AccountRepository.kt
@@ -0,0 +1,58 @@
+package es.zenvairo.nextcloudsync.data.auth
+
+import android.content.Context
+import androidx.security.crypto.EncryptedSharedPreferences
+import androidx.security.crypto.MasterKey
+import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import javax.inject.Inject
+import javax.inject.Singleton
+
+data class NextcloudAccount(val serverUrl: String, val username: String, val appPassword: String)
+
+@Singleton
+class AccountRepository @Inject constructor(@ApplicationContext context: Context) {
+
+ private val masterKey = MasterKey.Builder(context)
+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
+ .build()
+
+ private val prefs = EncryptedSharedPreferences.create(
+ context,
+ "nextcloud_account",
+ masterKey,
+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
+ )
+
+ private val _account = MutableStateFlow(loadFromPrefs())
+ val account: StateFlow = _account
+
+ fun save(credentials: LoginFlowCredentials) {
+ prefs.edit()
+ .putString(KEY_SERVER, credentials.server)
+ .putString(KEY_USERNAME, credentials.loginName)
+ .putString(KEY_APP_PASSWORD, credentials.appPassword)
+ .apply()
+ _account.value = NextcloudAccount(credentials.server, credentials.loginName, credentials.appPassword)
+ }
+
+ fun signOut() {
+ prefs.edit().clear().apply()
+ _account.value = null
+ }
+
+ private fun loadFromPrefs(): NextcloudAccount? {
+ val server = prefs.getString(KEY_SERVER, null) ?: return null
+ val username = prefs.getString(KEY_USERNAME, null) ?: return null
+ val password = prefs.getString(KEY_APP_PASSWORD, null) ?: return null
+ return NextcloudAccount(server, username, password)
+ }
+
+ companion object {
+ private const val KEY_SERVER = "server_url"
+ private const val KEY_USERNAME = "username"
+ private const val KEY_APP_PASSWORD = "app_password"
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/auth/LoginFlowV2Client.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/auth/LoginFlowV2Client.kt
new file mode 100644
index 0000000..bae0983
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/auth/LoginFlowV2Client.kt
@@ -0,0 +1,91 @@
+package es.zenvairo.nextcloudsync.data.auth
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import javax.inject.Inject
+
+@Serializable
+data class LoginFlowInit(val poll: PollInfo, val login: String)
+
+@Serializable
+data class PollInfo(val token: String, val endpoint: String)
+
+@Serializable
+data class LoginFlowCredentials(val server: String, val loginName: String, val appPassword: String)
+
+sealed class LoginPollResult {
+ data class Success(val credentials: LoginFlowCredentials) : LoginPollResult()
+ object Pending : LoginPollResult()
+ object TimedOut : LoginPollResult()
+ data class Error(val cause: Throwable) : LoginPollResult()
+}
+
+/**
+ * Implements Nextcloud's Login Flow v2: https://docs.nextcloud.com/server/latest/developer_manual/client_apis/LoginFlow/index.html
+ * The user authenticates (with 2FA/SSO if configured) in a browser tab; this app never sees the
+ * real password, only the resulting app password.
+ */
+class LoginFlowV2Client @Inject constructor(private val okHttpClient: OkHttpClient) {
+
+ private val json = Json { ignoreUnknownKeys = true }
+
+ suspend fun initiate(serverUrl: String): LoginFlowInit = withContext(Dispatchers.IO) {
+ val url = normalize(serverUrl) + "/index.php/login/v2"
+ val request = Request.Builder().url(url).post("".toRequestBody(null)).build()
+ okHttpClient.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) error("Login init failed: HTTP ${response.code}")
+ val body = response.body?.string() ?: error("Empty login init response")
+ json.decodeFromString(LoginFlowInit.serializer(), body)
+ }
+ }
+
+ /** Polls the endpoint once. Callers loop this with a delay until Success/TimedOut. */
+ suspend fun poll(poll: PollInfo): LoginPollResult = withContext(Dispatchers.IO) {
+ val formBody = "token=${poll.token}".toRequestBody("application/x-www-form-urlencoded".toMediaType())
+ val request = Request.Builder().url(poll.endpoint).post(formBody).build()
+ try {
+ okHttpClient.newCall(request).execute().use { response ->
+ when {
+ response.code == 404 -> LoginPollResult.Pending
+ response.isSuccessful -> {
+ val body = response.body?.string() ?: return@use LoginPollResult.Pending
+ LoginPollResult.Success(json.decodeFromString(LoginFlowCredentials.serializer(), body))
+ }
+ else -> LoginPollResult.Pending
+ }
+ }
+ } catch (t: Throwable) {
+ LoginPollResult.Error(t)
+ }
+ }
+
+ /** Polls until success, timeout, or a hard error. 3s interval as recommended by Nextcloud docs. */
+ suspend fun pollUntilComplete(
+ poll: PollInfo,
+ intervalMillis: Long = 3000,
+ timeoutMillis: Long = 20 * 60 * 1000
+ ): LoginPollResult {
+ val deadline = System.currentTimeMillis() + timeoutMillis
+ while (System.currentTimeMillis() < deadline) {
+ when (val result = poll(poll)) {
+ is LoginPollResult.Success -> return result
+ is LoginPollResult.Error -> return result
+ else -> delay(intervalMillis)
+ }
+ }
+ return LoginPollResult.TimedOut
+ }
+
+ private fun normalize(serverUrl: String): String {
+ var url = serverUrl.trim()
+ if (!url.startsWith("http://") && !url.startsWith("https://")) url = "https://$url"
+ return url.trimEnd('/')
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/Converters.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/Converters.kt
new file mode 100644
index 0000000..6711b6c
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/Converters.kt
@@ -0,0 +1,26 @@
+package es.zenvairo.nextcloudsync.data.db
+
+import androidx.room.TypeConverter
+import es.zenvairo.nextcloudsync.data.db.entity.SyncEventType
+import es.zenvairo.nextcloudsync.domain.model.ConflictPolicy
+import es.zenvairo.nextcloudsync.domain.model.SyncMode
+
+class Converters {
+ @TypeConverter
+ fun fromSyncMode(value: SyncMode): String = value.name
+
+ @TypeConverter
+ fun toSyncMode(value: String): SyncMode = SyncMode.valueOf(value)
+
+ @TypeConverter
+ fun fromConflictPolicy(value: ConflictPolicy): String = value.name
+
+ @TypeConverter
+ fun toConflictPolicy(value: String): ConflictPolicy = ConflictPolicy.valueOf(value)
+
+ @TypeConverter
+ fun fromSyncEventType(value: SyncEventType): String = value.name
+
+ @TypeConverter
+ fun toSyncEventType(value: String): SyncEventType = SyncEventType.valueOf(value)
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/Migrations.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/Migrations.kt
new file mode 100644
index 0000000..fb74ede
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/Migrations.kt
@@ -0,0 +1,25 @@
+package es.zenvairo.nextcloudsync.data.db
+
+import androidx.room.migration.Migration
+import androidx.sqlite.db.SupportSQLiteDatabase
+
+/**
+ * Adds the virtual-folders table. Purely additive - the sync engine's tables are untouched, so an
+ * existing install keeps its folders, file state and conflict history.
+ */
+val MIGRATION_1_2 = object : Migration(1, 2) {
+ override fun migrate(db: SupportSQLiteDatabase) {
+ db.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS `virtual_folders` (
+ `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
+ `displayName` TEXT NOT NULL,
+ `remotePath` TEXT NOT NULL,
+ `cacheMaxBytes` INTEGER NOT NULL,
+ `enabled` INTEGER NOT NULL,
+ `lastErrorMessage` TEXT
+ )
+ """.trimIndent()
+ )
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/NextCloudSyncDatabase.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/NextCloudSyncDatabase.kt
new file mode 100644
index 0000000..095d795
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/NextCloudSyncDatabase.kt
@@ -0,0 +1,35 @@
+package es.zenvairo.nextcloudsync.data.db
+
+import androidx.room.Database
+import androidx.room.RoomDatabase
+import androidx.room.TypeConverters
+import es.zenvairo.nextcloudsync.data.db.dao.ConflictDao
+import es.zenvairo.nextcloudsync.data.db.dao.FileStateDao
+import es.zenvairo.nextcloudsync.data.db.dao.SyncEventDao
+import es.zenvairo.nextcloudsync.data.db.dao.SyncFolderDao
+import es.zenvairo.nextcloudsync.data.db.dao.VirtualFolderDao
+import es.zenvairo.nextcloudsync.data.db.entity.ConflictEntity
+import es.zenvairo.nextcloudsync.data.db.entity.FileStateEntity
+import es.zenvairo.nextcloudsync.data.db.entity.SyncEventEntity
+import es.zenvairo.nextcloudsync.data.db.entity.SyncFolderEntity
+import es.zenvairo.nextcloudsync.data.db.entity.VirtualFolderEntity
+
+@Database(
+ entities = [
+ SyncFolderEntity::class,
+ FileStateEntity::class,
+ ConflictEntity::class,
+ SyncEventEntity::class,
+ VirtualFolderEntity::class
+ ],
+ version = 2,
+ exportSchema = true
+)
+@TypeConverters(Converters::class)
+abstract class NextCloudSyncDatabase : RoomDatabase() {
+ abstract fun syncFolderDao(): SyncFolderDao
+ abstract fun fileStateDao(): FileStateDao
+ abstract fun conflictDao(): ConflictDao
+ abstract fun syncEventDao(): SyncEventDao
+ abstract fun virtualFolderDao(): VirtualFolderDao
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/ConflictDao.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/ConflictDao.kt
new file mode 100644
index 0000000..d549988
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/ConflictDao.kt
@@ -0,0 +1,25 @@
+package es.zenvairo.nextcloudsync.data.db.dao
+
+import androidx.room.Dao
+import androidx.room.Insert
+import androidx.room.Query
+import es.zenvairo.nextcloudsync.data.db.entity.ConflictEntity
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+interface ConflictDao {
+ @Query("SELECT * FROM conflicts WHERE resolved = 0 ORDER BY detectedAtMillis DESC")
+ fun observeUnresolved(): Flow>
+
+ @Query("SELECT COUNT(*) FROM conflicts WHERE resolved = 0 AND folderId = :folderId")
+ fun observeUnresolvedCountForFolder(folderId: Long): Flow
+
+ @Insert
+ suspend fun insert(conflict: ConflictEntity): Long
+
+ @Query("UPDATE conflicts SET resolved = 1 WHERE id = :id")
+ suspend fun markResolved(id: Long)
+
+ @Query("SELECT * FROM conflicts WHERE folderId = :folderId AND relativePath = :relativePath AND resolved = 0 LIMIT 1")
+ suspend fun findOpen(folderId: Long, relativePath: String): ConflictEntity?
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/FileStateDao.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/FileStateDao.kt
new file mode 100644
index 0000000..649ab86
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/FileStateDao.kt
@@ -0,0 +1,29 @@
+package es.zenvairo.nextcloudsync.data.db.dao
+
+import androidx.room.Dao
+import androidx.room.Delete
+import androidx.room.Insert
+import androidx.room.OnConflictStrategy
+import androidx.room.Query
+import es.zenvairo.nextcloudsync.data.db.entity.FileStateEntity
+
+@Dao
+interface FileStateDao {
+ @Query("SELECT * FROM file_state WHERE folderId = :folderId")
+ suspend fun getAllForFolder(folderId: Long): List
+
+ @Query("SELECT * FROM file_state WHERE folderId = :folderId AND relativePath = :relativePath")
+ suspend fun get(folderId: Long, relativePath: String): FileStateEntity?
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(state: FileStateEntity)
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsertAll(states: List)
+
+ @Query("DELETE FROM file_state WHERE folderId = :folderId AND relativePath = :relativePath")
+ suspend fun delete(folderId: Long, relativePath: String)
+
+ @Query("DELETE FROM file_state WHERE folderId = :folderId")
+ suspend fun deleteAllForFolder(folderId: Long)
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/SyncEventDao.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/SyncEventDao.kt
new file mode 100644
index 0000000..3e4dab3
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/SyncEventDao.kt
@@ -0,0 +1,25 @@
+package es.zenvairo.nextcloudsync.data.db.dao
+
+import androidx.room.Dao
+import androidx.room.Insert
+import androidx.room.Query
+import es.zenvairo.nextcloudsync.data.db.entity.SyncEventEntity
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+interface SyncEventDao {
+ @Query("SELECT * FROM sync_events ORDER BY timestampMillis DESC LIMIT 200")
+ fun observeRecent(): Flow>
+
+ @Insert
+ suspend fun insert(event: SyncEventEntity): Long
+
+ @Query("DELETE FROM sync_events WHERE timestampMillis < :beforeMillis")
+ suspend fun pruneOlderThan(beforeMillis: Long)
+
+ @Query("SELECT COUNT(*) FROM sync_events WHERE type = 'RUN_STARTED' AND timestampMillis >= :sinceMillis")
+ suspend fun countRunsSince(sinceMillis: Long): Int
+
+ @Query("SELECT COUNT(*) FROM sync_events WHERE type = 'RUN_FINISHED' AND timestampMillis >= :sinceMillis")
+ suspend fun countCompletedRunsSince(sinceMillis: Long): Int
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/SyncFolderDao.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/SyncFolderDao.kt
new file mode 100644
index 0000000..ce90671
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/SyncFolderDao.kt
@@ -0,0 +1,33 @@
+package es.zenvairo.nextcloudsync.data.db.dao
+
+import androidx.room.Dao
+import androidx.room.Delete
+import androidx.room.Insert
+import androidx.room.Query
+import androidx.room.Update
+import es.zenvairo.nextcloudsync.data.db.entity.SyncFolderEntity
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+interface SyncFolderDao {
+ @Query("SELECT * FROM sync_folders ORDER BY displayName")
+ fun observeAll(): Flow>
+
+ @Query("SELECT * FROM sync_folders WHERE id = :id")
+ suspend fun getById(id: Long): SyncFolderEntity?
+
+ @Query("SELECT * FROM sync_folders WHERE enabled = 1")
+ suspend fun getEnabled(): List
+
+ @Insert
+ suspend fun insert(folder: SyncFolderEntity): Long
+
+ @Update
+ suspend fun update(folder: SyncFolderEntity)
+
+ @Delete
+ suspend fun delete(folder: SyncFolderEntity)
+
+ @Query("UPDATE sync_folders SET lastSyncAtMillis = :atMillis, lastSyncSucceeded = :succeeded, lastErrorMessage = :error WHERE id = :id")
+ suspend fun updateSyncResult(id: Long, atMillis: Long, succeeded: Boolean, error: String?)
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/VirtualFolderDao.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/VirtualFolderDao.kt
new file mode 100644
index 0000000..af47bde
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/dao/VirtualFolderDao.kt
@@ -0,0 +1,30 @@
+package es.zenvairo.nextcloudsync.data.db.dao
+
+import androidx.room.Dao
+import androidx.room.Delete
+import androidx.room.Insert
+import androidx.room.Query
+import androidx.room.Update
+import es.zenvairo.nextcloudsync.data.db.entity.VirtualFolderEntity
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+interface VirtualFolderDao {
+ @Query("SELECT * FROM virtual_folders ORDER BY displayName")
+ fun observeAll(): Flow>
+
+ @Query("SELECT * FROM virtual_folders WHERE id = :id")
+ suspend fun getById(id: Long): VirtualFolderEntity?
+
+ @Insert
+ suspend fun insert(folder: VirtualFolderEntity): Long
+
+ @Update
+ suspend fun update(folder: VirtualFolderEntity)
+
+ @Delete
+ suspend fun delete(folder: VirtualFolderEntity)
+
+ @Query("UPDATE virtual_folders SET lastErrorMessage = :error WHERE id = :id")
+ suspend fun updateError(id: Long, error: String?)
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/ConflictEntity.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/ConflictEntity.kt
new file mode 100644
index 0000000..9cdc313
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/ConflictEntity.kt
@@ -0,0 +1,16 @@
+package es.zenvairo.nextcloudsync.data.db.entity
+
+import androidx.room.Entity
+import androidx.room.PrimaryKey
+
+@Entity(tableName = "conflicts")
+data class ConflictEntity(
+ @PrimaryKey(autoGenerate = true) val id: Long = 0,
+ val folderId: Long,
+ val relativePath: String,
+ val detectedAtMillis: Long,
+ val localSize: Long,
+ val localMtimeMillis: Long,
+ val remoteEtag: String?,
+ val resolved: Boolean = false
+)
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/FileStateEntity.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/FileStateEntity.kt
new file mode 100644
index 0000000..4c01f6d
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/FileStateEntity.kt
@@ -0,0 +1,20 @@
+package es.zenvairo.nextcloudsync.data.db.entity
+
+import androidx.room.Entity
+
+/**
+ * The last known-good synced state of one file within one [SyncFolderEntity]. This is the
+ * "third band" of the three-way diff: without it, a two-way compare of local vs. remote can't
+ * tell a local deletion from a file that never existed locally.
+ */
+@Entity(tableName = "file_state", primaryKeys = ["folderId", "relativePath"])
+data class FileStateEntity(
+ val folderId: Long,
+ val relativePath: String,
+ val isDirectory: Boolean,
+ val localSize: Long,
+ val localMtimeMillis: Long,
+ val remoteEtag: String?,
+ val remoteFileId: String?,
+ val lastSyncedAtMillis: Long
+)
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/SyncEventEntity.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/SyncEventEntity.kt
new file mode 100644
index 0000000..a83ce4a
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/SyncEventEntity.kt
@@ -0,0 +1,16 @@
+package es.zenvairo.nextcloudsync.data.db.entity
+
+import androidx.room.Entity
+import androidx.room.PrimaryKey
+
+enum class SyncEventType { UPLOADED, DOWNLOADED, DELETED_LOCAL, DELETED_REMOTE, CONFLICT, ERROR, RUN_STARTED, RUN_FINISHED }
+
+@Entity(tableName = "sync_events")
+data class SyncEventEntity(
+ @PrimaryKey(autoGenerate = true) val id: Long = 0,
+ val folderId: Long,
+ val type: SyncEventType,
+ val relativePath: String?,
+ val message: String?,
+ val timestampMillis: Long
+)
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/SyncFolderEntity.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/SyncFolderEntity.kt
new file mode 100644
index 0000000..a006ec9
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/SyncFolderEntity.kt
@@ -0,0 +1,24 @@
+package es.zenvairo.nextcloudsync.data.db.entity
+
+import androidx.room.Entity
+import androidx.room.PrimaryKey
+import es.zenvairo.nextcloudsync.domain.model.ConflictPolicy
+import es.zenvairo.nextcloudsync.domain.model.SyncMode
+
+@Entity(tableName = "sync_folders")
+data class SyncFolderEntity(
+ @PrimaryKey(autoGenerate = true) val id: Long = 0,
+ val displayName: String,
+ /** Absolute path on device storage, e.g. /storage/emulated/0/DCIM/Camera */
+ val localPath: String,
+ /** Path relative to the WebDAV files root, e.g. /Photos/Camera */
+ val remotePath: String,
+ val mode: SyncMode = SyncMode.BIDIRECTIONAL,
+ val conflictPolicy: ConflictPolicy = ConflictPolicy.KEEP_BOTH,
+ /** Null = use the app-wide default from SettingsRepository. */
+ val constraintsJson: String? = null,
+ val enabled: Boolean = true,
+ val lastSyncAtMillis: Long? = null,
+ val lastSyncSucceeded: Boolean = true,
+ val lastErrorMessage: String? = null
+)
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/VirtualFolderEntity.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/VirtualFolderEntity.kt
new file mode 100644
index 0000000..e24ba55
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/db/entity/VirtualFolderEntity.kt
@@ -0,0 +1,23 @@
+package es.zenvairo.nextcloudsync.data.db.entity
+
+import androidx.room.Entity
+import androidx.room.PrimaryKey
+
+/**
+ * A remote folder exposed as a read-only FUSE mount (the root-only "virtual folders" mode).
+ *
+ * Deliberately separate from [SyncFolderEntity]: a virtual folder transfers nothing until a file is
+ * opened and has no local counterpart to reconcile, so it shares none of the sync engine's state.
+ */
+@Entity(tableName = "virtual_folders")
+data class VirtualFolderEntity(
+ @PrimaryKey(autoGenerate = true) val id: Long = 0,
+ val displayName: String,
+ /** Path relative to the WebDAV files root, e.g. /Photos - "/" for the whole account. */
+ val remotePath: String,
+ /** Cap on the on-device hydration cache for this folder, evicted LRU once exceeded. */
+ val cacheMaxBytes: Long = 512L * 1024 * 1024,
+ /** Whether to mount it; mounting always needs root granted at that moment. */
+ val enabled: Boolean = true,
+ val lastErrorMessage: String? = null
+)
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/prefs/SettingsRepository.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/prefs/SettingsRepository.kt
new file mode 100644
index 0000000..94f84f3
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/prefs/SettingsRepository.kt
@@ -0,0 +1,34 @@
+package es.zenvairo.nextcloudsync.data.prefs
+
+import android.content.Context
+import androidx.datastore.preferences.core.edit
+import androidx.datastore.preferences.core.stringPreferencesKey
+import androidx.datastore.preferences.preferencesDataStore
+import dagger.hilt.android.qualifiers.ApplicationContext
+import es.zenvairo.nextcloudsync.domain.model.SyncConstraints
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+import kotlinx.serialization.json.Json
+import javax.inject.Inject
+import javax.inject.Singleton
+
+private val Context.dataStore by preferencesDataStore(name = "settings")
+
+@Singleton
+class SettingsRepository @Inject constructor(@ApplicationContext private val context: Context) {
+
+ private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }
+ private val defaultConstraintsKey = stringPreferencesKey("default_sync_constraints")
+
+ val defaultConstraints: Flow = context.dataStore.data.map { prefs ->
+ prefs[defaultConstraintsKey]?.let { runCatching { json.decodeFromString(SyncConstraints.serializer(), it) }.getOrNull() }
+ ?: SyncConstraints()
+ }
+
+ suspend fun updateDefaultConstraints(constraints: SyncConstraints) {
+ context.dataStore.edit { it[defaultConstraintsKey] = json.encodeToString(SyncConstraints.serializer(), constraints) }
+ }
+
+ fun encode(constraints: SyncConstraints): String = json.encodeToString(SyncConstraints.serializer(), constraints)
+ fun decode(value: String): SyncConstraints = json.decodeFromString(SyncConstraints.serializer(), value)
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/CapabilitiesClient.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/CapabilitiesClient.kt
new file mode 100644
index 0000000..4dc4251
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/CapabilitiesClient.kt
@@ -0,0 +1,37 @@
+package es.zenvairo.nextcloudsync.data.remote
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import okhttp3.OkHttpClient
+import okhttp3.Request
+
+/** Reads the OCS capabilities endpoint to see whether the server has the notify_push app,
+ * which lets us open a push websocket instead of polling for remote changes. */
+class CapabilitiesClient(
+ private val okHttpClient: OkHttpClient,
+ private val serverUrl: String,
+ private val authorizationHeader: String
+) {
+ suspend fun fetchNotifyPushWebSocketUrl(): String? = withContext(Dispatchers.IO) {
+ val request = Request.Builder()
+ .url(serverUrl.trimEnd('/') + "/ocs/v2.php/cloud/capabilities?format=json")
+ .header("Authorization", authorizationHeader)
+ .header("OCS-APIRequest", "true")
+ .build()
+ runCatching {
+ okHttpClient.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) return@runCatching null
+ val body = response.body?.string() ?: return@runCatching null
+ val json = Json { ignoreUnknownKeys = true }.parseToJsonElement(body).jsonObject
+ json["ocs"]?.jsonObject
+ ?.get("data")?.jsonObject
+ ?.get("capabilities")?.jsonObject
+ ?.get("notify_push")?.jsonObject
+ ?.get("websocket")?.jsonPrimitive?.content
+ }
+ }.getOrNull()
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/ChunkedUploader.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/ChunkedUploader.kt
new file mode 100644
index 0000000..5da99f3
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/ChunkedUploader.kt
@@ -0,0 +1,90 @@
+package es.zenvairo.nextcloudsync.data.remote
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import java.io.File
+import java.io.RandomAccessFile
+import java.util.UUID
+
+private val OCTET_STREAM = "application/octet-stream".toMediaType()
+
+/**
+ * Uploads large files via Nextcloud's chunking API: PUT each chunk under
+ * /remote.php/dav/uploads/{user}/{transferId}/{index}, then MOVE the assembled
+ * upload to its final destination. Resumable: a PROPFIND of the upload directory
+ * before starting tells us which chunks already landed after a network interruption.
+ */
+class ChunkedUploader(
+ private val webDavClient: WebDavClient,
+ private val serverUrl: String,
+ private val username: String,
+ private val authorizationHeader: String,
+ private val chunkSizeBytes: Long = 10L * 1024 * 1024
+) {
+ private val uploadsBase = serverUrl.trimEnd('/') + "/remote.php/dav/uploads/$username"
+
+ suspend fun upload(
+ relativeDestPath: String,
+ source: File,
+ mtimeMillis: Long,
+ transferId: String = UUID.randomUUID().toString(),
+ onProgress: (bytesSent: Long, totalBytes: Long) -> Unit = { _, _ -> }
+ ): String = withContext(Dispatchers.IO) {
+ val client = webDavClient.client()
+ val transferUrl = "$uploadsBase/$transferId"
+
+ mkcol(transferUrl)
+
+ val totalChunks = ((source.length() + chunkSizeBytes - 1) / chunkSizeBytes).coerceAtLeast(1)
+ var sent = 0L
+ RandomAccessFile(source, "r").use { raf ->
+ for (index in 0 until totalChunks) {
+ val offset = index * chunkSizeBytes
+ val length = minOf(chunkSizeBytes, source.length() - offset)
+ val chunkBytes = ByteArray(length.toInt())
+ raf.seek(offset)
+ raf.readFully(chunkBytes)
+
+ val chunkName = "%015d".format(offset)
+ val request = Request.Builder()
+ .url("$transferUrl/$chunkName")
+ .header("Authorization", authorizationHeader)
+ .put(chunkBytes.toRequestBody(OCTET_STREAM))
+ .build()
+ client.newCall(request).execute().use { response ->
+ if (!response.isSuccessful) throw DavException.Http(response.code, relativeDestPath)
+ }
+ sent += length
+ onProgress(sent, source.length())
+ }
+ }
+
+ val destinationUrl = webDavClient.resolveUrl(relativeDestPath)
+ val moveRequest = Request.Builder()
+ .url("$transferUrl/.file")
+ .header("Authorization", authorizationHeader)
+ .header("Destination", destinationUrl)
+ .header("Overwrite", "T")
+ .header("X-OC-Mtime", (mtimeMillis / 1000).toString())
+ .method("MOVE", null)
+ .build()
+ client.newCall(moveRequest).execute().use { response ->
+ if (response.code == 507) throw DavException.InsufficientStorage(relativeDestPath)
+ if (!response.isSuccessful) throw DavException.Http(response.code, relativeDestPath)
+ response.header("OC-ETag")?.trim('"') ?: response.header("ETag")?.trim('"') ?: ""
+ }
+ }
+
+ private fun mkcol(transferUrl: String) {
+ val request = Request.Builder().url(transferUrl).header("Authorization", authorizationHeader)
+ .method("MKCOL", null).build()
+ webDavClient.client().newCall(request).execute().use { response ->
+ if (!response.isSuccessful && response.code != 405) {
+ throw DavException.Http(response.code, transferUrl)
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/PropfindParser.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/PropfindParser.kt
new file mode 100644
index 0000000..cdfdcac
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/PropfindParser.kt
@@ -0,0 +1,137 @@
+package es.zenvairo.nextcloudsync.data.remote
+
+import org.xmlpull.v1.XmlPullParser
+import org.xmlpull.v1.XmlPullParserFactory
+import java.io.InputStream
+import java.net.URLDecoder
+import java.text.SimpleDateFormat
+import java.util.Locale
+
+/**
+ * Parses a WebDAV multistatus PROPFIND response. Namespace prefixes on Nextcloud servers are
+ * conventionally d:/oc:/nc: but are not guaranteed, so elements are matched by local name only.
+ */
+class PropfindParser {
+
+ private val rfc1123 = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US)
+
+ /**
+ * @param davRoot e.g. "/remote.php/dav/files/alice" - stripped from each href to get the relative path.
+ * @param queriedPath the relative path (from [davRoot]) that was PROPFIND'd, e.g. "/Photos" or "" for
+ * the root. A depth:1 PROPFIND always echoes back the queried resource itself as one of the
+ * responses; that self-entry is skipped by comparing against this rather than only against "",
+ * otherwise scanning any subfolder would misread its own self-entry as a child of itself.
+ */
+ fun parse(input: InputStream, davRoot: String, queriedPath: String = ""): List {
+ val factory = XmlPullParserFactory.newInstance()
+ factory.isNamespaceAware = true
+ val parser = factory.newPullParser()
+ parser.setInput(input, "UTF-8")
+
+ val entries = mutableListOf()
+ var href: String? = null
+ var etag: String? = null
+ var fileId: String? = null
+ var size: Long = 0
+ var lastModified: Long = 0
+ var isCollection = false
+ var anyPropstatOk = false
+ // Status is per-, not per-: a server answers one PROPFIND with several
+ // propstat blocks, typically a 200 carrying the properties it has plus a 404 listing the
+ // ones it doesn't (getcontentlength on a collection, for instance). Treating the 404 as the
+ // response's status would discard the entry entirely - which silently dropped every folder.
+ var propstatOk = true
+ var stagedEtag: String? = null
+ var stagedFileId: String? = null
+ var stagedSize: Long? = null
+ var stagedLastModified: Long? = null
+ var stagedCollection = false
+ var inResponse = false
+ var text = StringBuilder()
+
+ val normalizedQueriedPath = queriedPath.trim('/')
+ var event = parser.eventType
+ while (event != XmlPullParser.END_DOCUMENT) {
+ when (event) {
+ XmlPullParser.START_TAG -> {
+ text.setLength(0)
+ when (parser.name) {
+ "response" -> {
+ inResponse = true
+ href = null; etag = null; fileId = null; size = 0; lastModified = 0
+ isCollection = false; anyPropstatOk = false
+ }
+ "propstat" -> {
+ propstatOk = true
+ stagedEtag = null; stagedFileId = null; stagedSize = null
+ stagedLastModified = null; stagedCollection = false
+ }
+ "collection" -> stagedCollection = true
+ }
+ }
+ XmlPullParser.TEXT -> text.append(parser.text)
+ XmlPullParser.END_TAG -> {
+ if (inResponse) {
+ when (parser.name) {
+ "href" -> href = URLDecoder.decode(text.toString().trim(), "UTF-8")
+ "getetag" -> stagedEtag = text.toString().trim().trim('"')
+ "fileid" -> stagedFileId = text.toString().trim()
+ "getcontentlength", "size" -> text.toString().trim().toLongOrNull()?.let { stagedSize = it }
+ "getlastmodified" -> stagedLastModified = parseRfc1123(text.toString().trim())
+ "status" -> if (text.isNotBlank() && !text.contains("200")) propstatOk = false
+ "propstat" -> {
+ if (propstatOk) {
+ anyPropstatOk = true
+ stagedEtag?.let { etag = it }
+ stagedFileId?.let { fileId = it }
+ stagedSize?.let { size = it }
+ stagedLastModified?.let { lastModified = it }
+ if (stagedCollection) isCollection = true
+ }
+ }
+ "response" -> {
+ inResponse = false
+ val h = href
+ if (h != null && anyPropstatOk) {
+ val relative = toRelativePath(h, davRoot)
+ // Skip the PROPFIND target itself, echoed back by depth:1 requests.
+ if (relative.isNotEmpty() && relative.trim('/') != normalizedQueriedPath) {
+ entries += RemoteEntry(
+ path = relative,
+ isDirectory = isCollection,
+ etag = etag,
+ fileId = fileId,
+ size = size,
+ lastModifiedMillis = lastModified
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ event = parser.next()
+ }
+ return entries
+ }
+
+ private fun toRelativePath(href: String, davRoot: String): String {
+ var path = href
+ val schemeIdx = path.indexOf("://")
+ if (schemeIdx >= 0) {
+ val afterHost = path.indexOf('/', schemeIdx + 3)
+ path = if (afterHost >= 0) path.substring(afterHost) else "/"
+ }
+ val root = if (davRoot.endsWith("/")) davRoot else "$davRoot/"
+ path = when {
+ path.startsWith(root) -> path.substring(root.length)
+ path.startsWith(davRoot) -> path.substring(davRoot.length).trimStart('/')
+ else -> path
+ }
+ if (path.endsWith("/") && path.length > 1) path = path.dropLast(1)
+ return path
+ }
+
+ private fun parseRfc1123(value: String): Long = runCatching { rfc1123.parse(value)?.time }.getOrNull() ?: 0
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/RemoteEntry.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/RemoteEntry.kt
new file mode 100644
index 0000000..6f55fac
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/RemoteEntry.kt
@@ -0,0 +1,21 @@
+package es.zenvairo.nextcloudsync.data.remote
+
+/** One entry returned by a PROPFIND, path relative to the files root (leading slash, no host). */
+data class RemoteEntry(
+ val path: String,
+ val isDirectory: Boolean,
+ val etag: String?,
+ val fileId: String?,
+ val size: Long,
+ val lastModifiedMillis: Long
+)
+
+sealed class DavException(message: String) : Exception(message) {
+ class NotFound(path: String) : DavException("Not found: $path")
+ class Conflict(path: String) : DavException("Conflict (412) writing $path")
+ class Locked(path: String) : DavException("Locked (423): $path")
+ class InsufficientStorage(path: String) : DavException("Server out of space (507) for $path")
+ class Unauthorized(path: String) : DavException("Unauthorized: $path")
+ class Http(val code: Int, path: String) : DavException("HTTP $code for $path")
+ class Network(cause: Throwable) : DavException(cause.message ?: "Network error")
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/WebDavClient.kt b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/WebDavClient.kt
new file mode 100644
index 0000000..2dbeea0
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/data/remote/WebDavClient.kt
@@ -0,0 +1,146 @@
+package es.zenvairo.nextcloudsync.data.remote
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.Credentials
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.asRequestBody
+import okhttp3.RequestBody.Companion.toRequestBody
+import java.io.File
+import java.io.IOException
+
+private val XML_MEDIA_TYPE = "application/xml; charset=utf-8".toMediaType()
+private val OCTET_STREAM = "application/octet-stream".toMediaType()
+
+/** Thin WebDAV client scoped to one Nextcloud account's files root, e.g. /remote.php/dav/files/alice. */
+class WebDavClient(
+ private val okHttpClient: OkHttpClient,
+ private val serverUrl: String,
+ private val username: String,
+ appPassword: String
+) {
+ private val credentials = Credentials.basic(username, appPassword)
+ val davRoot = "/remote.php/dav/files/$username"
+ private val baseUrl = serverUrl.trimEnd('/') + davRoot
+ private val parser = PropfindParser()
+
+ private fun urlFor(relativePath: String): String {
+ val encoded = relativePath.trim('/').split('/').joinToString("/") {
+ java.net.URLEncoder.encode(it, "UTF-8").replace("+", "%20")
+ }
+ return "$baseUrl/$encoded"
+ }
+
+ suspend fun propfind(relativePath: String, depth: Int = 1): List = withContext(Dispatchers.IO) {
+ val body = PROPFIND_BODY.toRequestBody(XML_MEDIA_TYPE)
+ val request = Request.Builder()
+ .url(urlFor(relativePath))
+ .header("Authorization", credentials)
+ .header("Depth", depth.toString())
+ .method("PROPFIND", body)
+ .build()
+ execute(request, relativePath).use { response ->
+ if (response.code == 404) throw DavException.NotFound(relativePath)
+ if (!response.isSuccessful) throw statusException(response.code, relativePath)
+ val stream = response.body?.byteStream() ?: return@use emptyList()
+ parser.parse(stream, davRoot, queriedPath = relativePath)
+ }
+ }
+
+ suspend fun download(relativePath: String, destination: File, ifNoneMatchEtag: String? = null): Boolean =
+ withContext(Dispatchers.IO) {
+ val builder = Request.Builder().url(urlFor(relativePath)).header("Authorization", credentials)
+ if (ifNoneMatchEtag != null) builder.header("If-None-Match", "\"$ifNoneMatchEtag\"")
+ execute(builder.build(), relativePath).use { response ->
+ if (response.code == 304) return@use false
+ if (response.code == 404) throw DavException.NotFound(relativePath)
+ if (!response.isSuccessful) throw statusException(response.code, relativePath)
+ val tmp = File(destination.parentFile, "${destination.name}.part")
+ tmp.parentFile?.mkdirs()
+ response.body?.byteStream()?.use { input ->
+ tmp.outputStream().use { output -> input.copyTo(output) }
+ }
+ if (!tmp.renameTo(destination)) {
+ tmp.copyTo(destination, overwrite = true)
+ tmp.delete()
+ }
+ true
+ }
+ }
+
+ /** Small-file upload with optimistic concurrency via If-Match; use [ChunkedUploader] for large files. */
+ suspend fun upload(relativePath: String, source: File, ifMatchEtag: String?, mtimeMillis: Long): String =
+ withContext(Dispatchers.IO) {
+ val builder = Request.Builder()
+ .url(urlFor(relativePath))
+ .header("Authorization", credentials)
+ .header("X-OC-Mtime", (mtimeMillis / 1000).toString())
+ .put(source.asRequestBody(OCTET_STREAM))
+ if (ifMatchEtag != null) builder.header("If-Match", "\"$ifMatchEtag\"")
+ execute(builder.build(), relativePath).use { response ->
+ if (response.code == 412) throw DavException.Conflict(relativePath)
+ if (response.code == 423) throw DavException.Locked(relativePath)
+ if (response.code == 507) throw DavException.InsufficientStorage(relativePath)
+ if (!response.isSuccessful) throw statusException(response.code, relativePath)
+ response.header("OC-ETag")?.trim('"') ?: response.header("ETag")?.trim('"') ?: ""
+ }
+ }
+
+ suspend fun mkcol(relativePath: String) = withContext(Dispatchers.IO) {
+ val request = Request.Builder().url(urlFor(relativePath)).header("Authorization", credentials)
+ .method("MKCOL", null).build()
+ execute(request, relativePath).use { response ->
+ // 405 = already exists, treat as success.
+ if (!response.isSuccessful && response.code != 405) throw statusException(response.code, relativePath)
+ }
+ }
+
+ suspend fun delete(relativePath: String) = withContext(Dispatchers.IO) {
+ val request = Request.Builder().url(urlFor(relativePath)).header("Authorization", credentials)
+ .delete().build()
+ execute(request, relativePath).use { response ->
+ if (!response.isSuccessful && response.code != 404) throw statusException(response.code, relativePath)
+ }
+ }
+
+ suspend fun move(fromRelativePath: String, toRelativePath: String) = withContext(Dispatchers.IO) {
+ val request = Request.Builder().url(urlFor(fromRelativePath)).header("Authorization", credentials)
+ .header("Destination", urlFor(toRelativePath))
+ .header("Overwrite", "F")
+ .method("MOVE", null).build()
+ execute(request, fromRelativePath).use { response ->
+ if (!response.isSuccessful) throw statusException(response.code, fromRelativePath)
+ }
+ }
+
+ fun authorizationHeader(): String = credentials
+ fun resolveUrl(relativePath: String): String = urlFor(relativePath)
+ fun client(): OkHttpClient = okHttpClient
+
+ private fun execute(request: Request, path: String) = try {
+ okHttpClient.newCall(request).execute().also {
+ if (it.code == 401) throw DavException.Unauthorized(path)
+ }
+ } catch (e: IOException) {
+ throw DavException.Network(e)
+ }
+
+ private fun statusException(code: Int, path: String) = DavException.Http(code, path)
+
+ companion object {
+ private const val PROPFIND_BODY = """
+
+
+
+
+
+
+
+
+
+
+"""
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/di/AppModule.kt b/app/src/main/java/es/zenvairo/nextcloudsync/di/AppModule.kt
new file mode 100644
index 0000000..426038e
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/di/AppModule.kt
@@ -0,0 +1,55 @@
+package es.zenvairo.nextcloudsync.di
+
+import android.content.Context
+import androidx.room.Room
+import dagger.Module
+import dagger.Provides
+import dagger.hilt.InstallIn
+import dagger.hilt.android.qualifiers.ApplicationContext
+import dagger.hilt.components.SingletonComponent
+import es.zenvairo.nextcloudsync.data.db.MIGRATION_1_2
+import es.zenvairo.nextcloudsync.data.db.NextCloudSyncDatabase
+import es.zenvairo.nextcloudsync.data.db.dao.ConflictDao
+import es.zenvairo.nextcloudsync.data.db.dao.FileStateDao
+import es.zenvairo.nextcloudsync.data.db.dao.SyncEventDao
+import es.zenvairo.nextcloudsync.data.db.dao.SyncFolderDao
+import es.zenvairo.nextcloudsync.data.db.dao.VirtualFolderDao
+import okhttp3.OkHttpClient
+import java.util.concurrent.TimeUnit
+import javax.inject.Singleton
+
+@Module
+@InstallIn(SingletonComponent::class)
+object AppModule {
+
+ @Provides
+ @Singleton
+ fun provideOkHttpClient(): OkHttpClient = OkHttpClient.Builder()
+ .connectTimeout(30, TimeUnit.SECONDS)
+ .readTimeout(2, TimeUnit.MINUTES)
+ .writeTimeout(5, TimeUnit.MINUTES)
+ .retryOnConnectionFailure(true)
+ .build()
+
+ @Provides
+ @Singleton
+ fun provideDatabase(@ApplicationContext context: Context): NextCloudSyncDatabase =
+ Room.databaseBuilder(context, NextCloudSyncDatabase::class.java, "nextcloudsync.db")
+ .addMigrations(MIGRATION_1_2)
+ .build()
+
+ @Provides
+ fun provideSyncFolderDao(db: NextCloudSyncDatabase): SyncFolderDao = db.syncFolderDao()
+
+ @Provides
+ fun provideFileStateDao(db: NextCloudSyncDatabase): FileStateDao = db.fileStateDao()
+
+ @Provides
+ fun provideConflictDao(db: NextCloudSyncDatabase): ConflictDao = db.conflictDao()
+
+ @Provides
+ fun provideSyncEventDao(db: NextCloudSyncDatabase): SyncEventDao = db.syncEventDao()
+
+ @Provides
+ fun provideVirtualFolderDao(db: NextCloudSyncDatabase): VirtualFolderDao = db.virtualFolderDao()
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/model/SyncConstraints.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/model/SyncConstraints.kt
new file mode 100644
index 0000000..e795ef0
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/model/SyncConstraints.kt
@@ -0,0 +1,35 @@
+package es.zenvairo.nextcloudsync.domain.model
+
+import kotlinx.serialization.Serializable
+
+enum class NetworkTrigger { ANY, UNMETERED, WIFI_ONLY }
+
+enum class SyncEventTrigger { ON_FILE_CHANGE, ON_CHARGER_CONNECT, ON_WIFI_CONNECT, ON_BOOT, MANUAL_ONLY }
+
+/**
+ * Sync trigger/filter policy. Used both as the global default (stored in DataStore) and as a
+ * per-folder override (stored as JSON on [es.zenvairo.nextcloudsync.data.db.entity.SyncFolderEntity]).
+ */
+@Serializable
+data class SyncConstraints(
+ val networkTrigger: NetworkTrigger = NetworkTrigger.UNMETERED,
+ val allowRoaming: Boolean = false,
+ val allowedSsids: List = emptyList(),
+ val minBatteryPercent: Int = 15,
+ val chargingOnly: Boolean = false,
+ val respectBatterySaver: Boolean = true,
+ val intervalMinutes: Long = 60,
+ val quietHoursStart: Int? = null, // 0-23, null = disabled
+ val quietHoursEnd: Int? = null,
+ val eventTriggers: Set = setOf(SyncEventTrigger.ON_FILE_CHANGE, SyncEventTrigger.ON_BOOT),
+ val excludeGlobs: List = listOf(".git/**", "*.tmp", "~*"),
+ val maxFileSizeBytes: Long? = null, // null = unlimited
+ val skipHidden: Boolean = true
+) {
+ fun isWithinQuietHours(hourOfDay: Int): Boolean {
+ val start = quietHoursStart ?: return false
+ val end = quietHoursEnd ?: return false
+ return if (start <= end) hourOfDay in start until end
+ else hourOfDay >= start || hourOfDay < end
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/model/SyncMode.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/model/SyncMode.kt
new file mode 100644
index 0000000..db8eb7a
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/model/SyncMode.kt
@@ -0,0 +1,29 @@
+package es.zenvairo.nextcloudsync.domain.model
+
+/**
+ * How a [es.zenvairo.nextcloudsync.data.db.entity.SyncFolderEntity] propagates changes.
+ * MIRROR_* modes propagate deletes; UPLOAD_ONLY/DOWNLOAD_ONLY are additive-only and never delete.
+ */
+enum class SyncMode {
+ BIDIRECTIONAL,
+ UPLOAD_ONLY,
+ DOWNLOAD_ONLY,
+ MIRROR_UP,
+ MIRROR_DOWN;
+
+ val allowsLocalToRemote: Boolean
+ get() = this == BIDIRECTIONAL || this == UPLOAD_ONLY || this == MIRROR_UP
+
+ val allowsRemoteToLocal: Boolean
+ get() = this == BIDIRECTIONAL || this == DOWNLOAD_ONLY || this == MIRROR_DOWN
+
+ val propagatesDeletes: Boolean
+ get() = this == BIDIRECTIONAL || this == MIRROR_UP || this == MIRROR_DOWN
+}
+
+enum class ConflictPolicy {
+ KEEP_BOTH,
+ PREFER_LOCAL,
+ PREFER_REMOTE,
+ ASK
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/ConflictResolver.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/ConflictResolver.kt
new file mode 100644
index 0000000..87aa29f
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/ConflictResolver.kt
@@ -0,0 +1,37 @@
+package es.zenvairo.nextcloudsync.domain.sync
+
+import es.zenvairo.nextcloudsync.domain.model.ConflictPolicy
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+sealed class ConflictOutcome {
+ /** Duplicate the local file under a new name, then treat the original path as a plain download. */
+ data class KeepBoth(val renamedLocalPath: String) : ConflictOutcome()
+ object PreferLocal : ConflictOutcome()
+ object PreferRemote : ConflictOutcome()
+ /** Policy is ASK: leave both sides untouched and record it in the conflicts table for the user. */
+ object DeferToUser : ConflictOutcome()
+}
+
+class ConflictResolver {
+ private val stamp = SimpleDateFormat("yyyy-MM-dd HHmmss", Locale.US)
+
+ fun resolve(relativePath: String, policy: ConflictPolicy): ConflictOutcome = when (policy) {
+ ConflictPolicy.PREFER_LOCAL -> ConflictOutcome.PreferLocal
+ ConflictPolicy.PREFER_REMOTE -> ConflictOutcome.PreferRemote
+ ConflictPolicy.ASK -> ConflictOutcome.DeferToUser
+ ConflictPolicy.KEEP_BOTH -> ConflictOutcome.KeepBoth(renamedPath(relativePath))
+ }
+
+ private fun renamedPath(relativePath: String): String {
+ val dot = relativePath.lastIndexOf('.')
+ val slash = relativePath.lastIndexOf('/')
+ val suffix = " (conflict ${stamp.format(Date())})"
+ return if (dot > slash) {
+ relativePath.substring(0, dot) + suffix + relativePath.substring(dot)
+ } else {
+ relativePath + suffix
+ }
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/DiffCalculator.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/DiffCalculator.kt
new file mode 100644
index 0000000..da460f5
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/DiffCalculator.kt
@@ -0,0 +1,72 @@
+package es.zenvairo.nextcloudsync.domain.sync
+
+import es.zenvairo.nextcloudsync.data.db.entity.FileStateEntity
+import es.zenvairo.nextcloudsync.domain.model.SyncMode
+
+/**
+ * Three-way diff: compares the current local and remote snapshots against the last known-good
+ * [FileStateEntity] snapshot to classify what changed on each side independently, then decides
+ * an action. This is what lets "deleted locally" be told apart from "never existed locally" -
+ * a two-way (local vs remote only) diff cannot make that distinction.
+ */
+class DiffCalculator {
+
+ fun decide(
+ relativePath: String,
+ local: SideSnapshot,
+ remote: SideSnapshot,
+ lastKnown: FileStateEntity?,
+ mode: SyncMode
+ ): PlannedChange {
+ val localChanged = hasLocalChanged(local, lastKnown)
+ val remoteChanged = hasRemoteChanged(remote, lastKnown)
+ val isDirectory = local.isDirectory || remote.isDirectory
+
+ val action = when {
+ // Neither side ever recorded and both now absent - nothing to do.
+ !local.exists && !remote.exists -> SyncAction.FORGET
+
+ // First sight of a path that exists on exactly one side.
+ lastKnown == null && local.exists && !remote.exists -> SyncAction.UPLOAD
+ lastKnown == null && !local.exists && remote.exists -> SyncAction.DOWNLOAD
+ lastKnown == null -> if (localChanged) SyncAction.CONFLICT else SyncAction.NO_OP
+
+ // One side deleted since last sync, other side unchanged -> propagate delete.
+ !local.exists && remote.exists && !remoteChanged -> SyncAction.DELETE_REMOTE
+ local.exists && !remote.exists && !localChanged -> SyncAction.DELETE_LOCAL
+
+ // One side deleted, but the *other* side also changed -> conflict, don't destroy data.
+ !local.exists && remote.exists && remoteChanged -> SyncAction.CONFLICT
+ local.exists && !remote.exists && localChanged -> SyncAction.CONFLICT
+
+ // Both present.
+ !localChanged && remoteChanged -> SyncAction.DOWNLOAD
+ localChanged && !remoteChanged -> SyncAction.UPLOAD
+ localChanged && remoteChanged -> SyncAction.CONFLICT
+ else -> SyncAction.NO_OP
+ }
+
+ return PlannedChange(relativePath, filterForMode(action, mode), isDirectory)
+ }
+
+ /** Unidirectional modes only ever perform the actions they're allowed to; everything else becomes a no-op. */
+ private fun filterForMode(action: SyncAction, mode: SyncMode): SyncAction = when (action) {
+ SyncAction.UPLOAD -> if (mode.allowsLocalToRemote) action else SyncAction.NO_OP
+ SyncAction.DOWNLOAD -> if (mode.allowsRemoteToLocal) action else SyncAction.NO_OP
+ SyncAction.DELETE_REMOTE -> if (mode.propagatesDeletes && mode.allowsLocalToRemote) action else SyncAction.NO_OP
+ SyncAction.DELETE_LOCAL -> if (mode.propagatesDeletes && mode.allowsRemoteToLocal) action else SyncAction.NO_OP
+ else -> action
+ }
+
+ private fun hasLocalChanged(local: SideSnapshot, lastKnown: FileStateEntity?): Boolean {
+ if (lastKnown == null) return local.exists
+ if (!local.exists) return false
+ return local.size != lastKnown.localSize || local.mtimeMillis != lastKnown.localMtimeMillis
+ }
+
+ private fun hasRemoteChanged(remote: SideSnapshot, lastKnown: FileStateEntity?): Boolean {
+ if (lastKnown == null) return remote.exists
+ if (!remote.exists) return false
+ return remote.etag != lastKnown.remoteEtag
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/FileChange.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/FileChange.kt
new file mode 100644
index 0000000..ca7197e
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/FileChange.kt
@@ -0,0 +1,30 @@
+package es.zenvairo.nextcloudsync.domain.sync
+
+/** Snapshot of one side (local or remote) of a file, as seen right now. */
+data class SideSnapshot(
+ val exists: Boolean,
+ val isDirectory: Boolean = false,
+ val size: Long = 0,
+ /** Local: mtime millis. Remote: unused for comparison (etag is authoritative). */
+ val mtimeMillis: Long = 0,
+ /** Remote only: WebDAV etag. Null for local snapshots. */
+ val etag: String? = null,
+ /** Remote only: Nextcloud stable file id, used to detect renames. */
+ val fileId: String? = null
+)
+
+enum class SyncAction {
+ NO_OP,
+ DOWNLOAD,
+ UPLOAD,
+ DELETE_LOCAL,
+ DELETE_REMOTE,
+ CONFLICT,
+ FORGET // both sides deleted: drop from the index, nothing to transfer
+}
+
+data class PlannedChange(
+ val relativePath: String,
+ val action: SyncAction,
+ val isDirectory: Boolean = false
+)
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/LocalScanner.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/LocalScanner.kt
new file mode 100644
index 0000000..d4044b0
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/LocalScanner.kt
@@ -0,0 +1,29 @@
+package es.zenvairo.nextcloudsync.domain.sync
+
+import java.io.File
+
+/** Walks a local folder tree and returns every entry keyed by its path relative to the root. */
+class LocalScanner {
+
+ fun scan(root: File, filter: PathFilter): Map {
+ val result = LinkedHashMap()
+ if (!root.exists()) return result
+ walk(root, root, filter, result)
+ return result
+ }
+
+ private fun walk(root: File, dir: File, filter: PathFilter, out: MutableMap) {
+ val children = dir.listFiles() ?: return
+ for (child in children) {
+ val relative = child.relativeTo(root).path.replace(File.separatorChar, '/')
+ if (filter.isExcludedFile(child, relative)) continue
+ out[relative] = SideSnapshot(
+ exists = true,
+ isDirectory = child.isDirectory,
+ size = if (child.isFile) child.length() else 0,
+ mtimeMillis = child.lastModified()
+ )
+ if (child.isDirectory) walk(root, child, filter, out)
+ }
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/PathFilter.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/PathFilter.kt
new file mode 100644
index 0000000..b7cd20e
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/PathFilter.kt
@@ -0,0 +1,45 @@
+package es.zenvairo.nextcloudsync.domain.sync
+
+import es.zenvairo.nextcloudsync.domain.model.SyncConstraints
+import java.io.File
+
+/** Applies exclude globs, hidden-file skipping and max-size filtering to a candidate path. */
+class PathFilter(private val constraints: SyncConstraints) {
+
+ private val excludeRegexes = constraints.excludeGlobs.map { globToRegex(it) }
+
+ fun isExcluded(relativePath: String, isDirectory: Boolean, sizeBytes: Long): Boolean {
+ val name = relativePath.substringAfterLast('/')
+ if (constraints.skipHidden && name.startsWith(".")) return true
+ if (excludeRegexes.any { it.matches(relativePath) || it.matches(name) }) return true
+ if (!isDirectory) {
+ val maxSize = constraints.maxFileSizeBytes
+ if (maxSize != null && sizeBytes > maxSize) return true
+ }
+ return false
+ }
+
+ fun isExcludedFile(file: File, relativePath: String): Boolean =
+ isExcluded(relativePath, file.isDirectory, if (file.isFile) file.length() else 0)
+
+ private fun globToRegex(glob: String): Regex {
+ val sb = StringBuilder()
+ var i = 0
+ while (i < glob.length) {
+ when (val c = glob[i]) {
+ '*' -> {
+ if (i + 1 < glob.length && glob[i + 1] == '*') {
+ sb.append(".*"); i++
+ } else {
+ sb.append("[^/]*")
+ }
+ }
+ '?' -> sb.append("[^/]")
+ '.', '(', ')', '+', '|', '^', '$', '{', '}', '[', ']', '\\' -> sb.append('\\').append(c)
+ else -> sb.append(c)
+ }
+ i++
+ }
+ return Regex(sb.toString())
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/RemoteScanner.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/RemoteScanner.kt
new file mode 100644
index 0000000..f5e71f4
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/RemoteScanner.kt
@@ -0,0 +1,47 @@
+package es.zenvairo.nextcloudsync.domain.sync
+
+import es.zenvairo.nextcloudsync.data.remote.DavException
+import es.zenvairo.nextcloudsync.data.remote.WebDavClient
+
+/**
+ * Walks a remote folder tree via repeated Depth:1 PROPFINDs (Depth:infinity is disabled on most
+ * Nextcloud instances for performance reasons) and returns every entry keyed by its path relative
+ * to the synced folder's remote root.
+ */
+class RemoteScanner(private val webDavClient: WebDavClient) {
+
+ suspend fun scan(remoteRoot: String, filter: PathFilter): Map {
+ val result = LinkedHashMap()
+ val normalizedRoot = if (remoteRoot.startsWith("/")) remoteRoot else "/$remoteRoot"
+ try {
+ webDavClient.mkcol(normalizedRoot)
+ } catch (_: Exception) {
+ // best-effort: folder may already exist or the account may lack create rights yet
+ }
+ walk(normalizedRoot, "", filter, result)
+ return result
+ }
+
+ private suspend fun walk(remoteRoot: String, relativeDir: String, filter: PathFilter, out: MutableMap) {
+ val path = if (relativeDir.isEmpty()) remoteRoot else "$remoteRoot/$relativeDir"
+ val entries = try {
+ webDavClient.propfind(path, depth = 1)
+ } catch (e: DavException.NotFound) {
+ return
+ }
+ for (entry in entries) {
+ val name = entry.path.substringAfterLast('/')
+ val relative = if (relativeDir.isEmpty()) name else "$relativeDir/$name"
+ if (filter.isExcluded(relative, entry.isDirectory, entry.size)) continue
+ out[relative] = SideSnapshot(
+ exists = true,
+ isDirectory = entry.isDirectory,
+ size = entry.size,
+ mtimeMillis = entry.lastModifiedMillis,
+ etag = entry.etag,
+ fileId = entry.fileId
+ )
+ if (entry.isDirectory) walk(remoteRoot, relative, filter, out)
+ }
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/SyncEngine.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/SyncEngine.kt
new file mode 100644
index 0000000..f2cda5e
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/SyncEngine.kt
@@ -0,0 +1,210 @@
+package es.zenvairo.nextcloudsync.domain.sync
+
+import es.zenvairo.nextcloudsync.data.db.dao.ConflictDao
+import es.zenvairo.nextcloudsync.data.db.dao.FileStateDao
+import es.zenvairo.nextcloudsync.data.db.dao.SyncEventDao
+import es.zenvairo.nextcloudsync.data.db.entity.ConflictEntity
+import es.zenvairo.nextcloudsync.data.db.entity.FileStateEntity
+import es.zenvairo.nextcloudsync.data.db.entity.SyncEventEntity
+import es.zenvairo.nextcloudsync.data.db.entity.SyncEventType
+import es.zenvairo.nextcloudsync.data.db.entity.SyncFolderEntity
+import es.zenvairo.nextcloudsync.data.remote.ChunkedUploader
+import es.zenvairo.nextcloudsync.data.remote.DavException
+import es.zenvairo.nextcloudsync.data.remote.WebDavClient
+import java.io.File
+
+data class SyncSummary(
+ val uploaded: Int = 0,
+ val downloaded: Int = 0,
+ val deletedLocal: Int = 0,
+ val deletedRemote: Int = 0,
+ val conflicts: Int = 0,
+ val errors: List = emptyList()
+)
+
+private const val CHUNKED_UPLOAD_THRESHOLD = 20L * 1024 * 1024
+
+/** Runs one full sync pass for a single folder pair: scan both sides, diff, execute, persist state. */
+class SyncEngine(
+ private val webDavClient: WebDavClient,
+ private val chunkedUploader: ChunkedUploader,
+ private val fileStateDao: FileStateDao,
+ private val conflictDao: ConflictDao,
+ private val syncEventDao: SyncEventDao,
+ private val localScanner: LocalScanner = LocalScanner(),
+ private val remoteScanner: RemoteScanner = RemoteScanner(webDavClient),
+ private val diffCalculator: DiffCalculator = DiffCalculator(),
+ private val conflictResolver: ConflictResolver = ConflictResolver()
+) {
+ suspend fun syncFolder(folder: SyncFolderEntity, filter: PathFilter): SyncSummary {
+ val localRoot = File(folder.localPath)
+ localRoot.mkdirs()
+
+ val localSnapshots = localScanner.scan(localRoot, filter)
+ val remoteSnapshots = remoteScanner.scan(folder.remotePath, filter)
+ val knownStates = fileStateDao.getAllForFolder(folder.id).associateBy { it.relativePath }
+
+ val allPaths = (localSnapshots.keys + remoteSnapshots.keys + knownStates.keys)
+ .sortedBy { it.count { c -> c == '/' } } // parents before children
+
+ var uploaded = 0; var downloaded = 0; var deletedLocal = 0; var deletedRemote = 0; var conflicts = 0
+ val errors = mutableListOf()
+
+ for (path in allPaths) {
+ val local = localSnapshots[path] ?: SideSnapshot(exists = false)
+ val remote = remoteSnapshots[path] ?: SideSnapshot(exists = false)
+ val known = knownStates[path]
+ val plan = diffCalculator.decide(path, local, remote, known, folder.mode)
+
+ try {
+ when (plan.action) {
+ SyncAction.NO_OP -> Unit
+ SyncAction.FORGET -> fileStateDao.delete(folder.id, path)
+ SyncAction.DOWNLOAD -> {
+ downloadOne(folder, localRoot, path, plan.isDirectory, remote)
+ downloaded++
+ }
+ SyncAction.UPLOAD -> {
+ uploadOne(folder, localRoot, path, plan.isDirectory, local)
+ uploaded++
+ }
+ SyncAction.DELETE_LOCAL -> {
+ deleteLocal(localRoot, path)
+ fileStateDao.delete(folder.id, path)
+ deletedLocal++
+ logEvent(folder.id, SyncEventType.DELETED_LOCAL, path)
+ }
+ SyncAction.DELETE_REMOTE -> {
+ webDavClient.delete(remotePathOf(folder, path))
+ fileStateDao.delete(folder.id, path)
+ deletedRemote++
+ logEvent(folder.id, SyncEventType.DELETED_REMOTE, path)
+ }
+ SyncAction.CONFLICT -> {
+ conflicts++
+ handleConflict(folder, localRoot, path, plan.isDirectory, local, remote)
+ }
+ }
+ } catch (e: Exception) {
+ errors += "$path: ${e.message}"
+ logEvent(folder.id, SyncEventType.ERROR, path, e.message)
+ }
+ }
+
+ return SyncSummary(uploaded, downloaded, deletedLocal, deletedRemote, conflicts, errors)
+ }
+
+ private suspend fun handleConflict(
+ folder: SyncFolderEntity,
+ localRoot: File,
+ path: String,
+ isDirectory: Boolean,
+ local: SideSnapshot,
+ remote: SideSnapshot
+ ) {
+ logEvent(folder.id, SyncEventType.CONFLICT, path)
+ when (val outcome = conflictResolver.resolve(path, folder.conflictPolicy)) {
+ is ConflictOutcome.PreferLocal -> if (local.exists) uploadOne(folder, localRoot, path, isDirectory, local)
+ is ConflictOutcome.PreferRemote -> downloadOne(folder, localRoot, path, isDirectory, remote)
+ is ConflictOutcome.KeepBoth -> {
+ if (local.exists) {
+ File(localRoot, path).copyTo(File(localRoot, outcome.renamedLocalPath), overwrite = true)
+ }
+ if (remote.exists) downloadOne(folder, localRoot, path, isDirectory, remote)
+ }
+ is ConflictOutcome.DeferToUser -> {
+ val existing = conflictDao.findOpen(folder.id, path)
+ if (existing == null) {
+ conflictDao.insert(
+ ConflictEntity(
+ folderId = folder.id,
+ relativePath = path,
+ detectedAtMillis = System.currentTimeMillis(),
+ localSize = local.size,
+ localMtimeMillis = local.mtimeMillis,
+ remoteEtag = remote.etag
+ )
+ )
+ }
+ }
+ }
+ }
+
+ private suspend fun downloadOne(folder: SyncFolderEntity, localRoot: File, path: String, isDirectory: Boolean, remote: SideSnapshot) {
+ val destination = File(localRoot, path)
+ if (isDirectory) {
+ destination.mkdirs()
+ } else {
+ destination.parentFile?.mkdirs()
+ webDavClient.download(remotePathOf(folder, path), destination)
+ destination.setLastModified(remote.mtimeMillis)
+ }
+ fileStateDao.upsert(
+ FileStateEntity(
+ folderId = folder.id,
+ relativePath = path,
+ isDirectory = isDirectory,
+ localSize = destination.length(),
+ localMtimeMillis = destination.lastModified(),
+ remoteEtag = remote.etag,
+ remoteFileId = remote.fileId,
+ lastSyncedAtMillis = System.currentTimeMillis()
+ )
+ )
+ logEvent(folder.id, SyncEventType.DOWNLOADED, path)
+ }
+
+ private suspend fun uploadOne(folder: SyncFolderEntity, localRoot: File, path: String, isDirectory: Boolean, local: SideSnapshot) {
+ val source = File(localRoot, path)
+ val remotePath = remotePathOf(folder, path)
+ val etag = if (isDirectory) {
+ webDavClient.mkcol(remotePath)
+ null
+ } else if (source.length() >= CHUNKED_UPLOAD_THRESHOLD) {
+ chunkedUploader.upload(remotePath, source, source.lastModified())
+ } else {
+ val known = fileStateDao.get(folder.id, path)
+ try {
+ webDavClient.upload(remotePath, source, known?.remoteEtag, source.lastModified())
+ } catch (e: DavException.Conflict) {
+ handleConflict(folder, localRoot, path, isDirectory, local, SideSnapshot(exists = true))
+ return
+ }
+ }
+ fileStateDao.upsert(
+ FileStateEntity(
+ folderId = folder.id,
+ relativePath = path,
+ isDirectory = isDirectory,
+ localSize = local.size,
+ localMtimeMillis = local.mtimeMillis,
+ remoteEtag = etag,
+ remoteFileId = fileStateDao.get(folder.id, path)?.remoteFileId,
+ lastSyncedAtMillis = System.currentTimeMillis()
+ )
+ )
+ logEvent(folder.id, SyncEventType.UPLOADED, path)
+ }
+
+ private fun deleteLocal(localRoot: File, path: String) {
+ val target = File(localRoot, path)
+ if (target.isDirectory) target.deleteRecursively() else target.delete()
+ }
+
+ private fun remotePathOf(folder: SyncFolderEntity, relativePath: String): String {
+ val root = folder.remotePath.trimEnd('/')
+ return if (relativePath.isEmpty()) root else "$root/$relativePath"
+ }
+
+ private suspend fun logEvent(folderId: Long, type: SyncEventType, path: String?, message: String? = null) {
+ syncEventDao.insert(
+ SyncEventEntity(
+ folderId = folderId,
+ type = type,
+ relativePath = path,
+ message = message,
+ timestampMillis = System.currentTimeMillis()
+ )
+ )
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/SyncEngineFactory.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/SyncEngineFactory.kt
new file mode 100644
index 0000000..5be081d
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/sync/SyncEngineFactory.kt
@@ -0,0 +1,34 @@
+package es.zenvairo.nextcloudsync.domain.sync
+
+import es.zenvairo.nextcloudsync.data.auth.AccountRepository
+import es.zenvairo.nextcloudsync.data.db.dao.ConflictDao
+import es.zenvairo.nextcloudsync.data.db.dao.FileStateDao
+import es.zenvairo.nextcloudsync.data.db.dao.SyncEventDao
+import es.zenvairo.nextcloudsync.data.remote.ChunkedUploader
+import es.zenvairo.nextcloudsync.data.remote.WebDavClient
+import okhttp3.Credentials
+import okhttp3.OkHttpClient
+import javax.inject.Inject
+import javax.inject.Singleton
+
+/** Builds a [SyncEngine] bound to whichever Nextcloud account is currently signed in. */
+@Singleton
+class SyncEngineFactory @Inject constructor(
+ private val okHttpClient: OkHttpClient,
+ private val accountRepository: AccountRepository,
+ private val fileStateDao: FileStateDao,
+ private val conflictDao: ConflictDao,
+ private val syncEventDao: SyncEventDao
+) {
+ fun create(): SyncEngine? {
+ val account = accountRepository.account.value ?: return null
+ val webDavClient = WebDavClient(okHttpClient, account.serverUrl, account.username, account.appPassword)
+ val chunkedUploader = ChunkedUploader(
+ webDavClient = webDavClient,
+ serverUrl = account.serverUrl,
+ username = account.username,
+ authorizationHeader = Credentials.basic(account.username, account.appPassword)
+ )
+ return SyncEngine(webDavClient, chunkedUploader, fileStateDao, conflictDao, syncEventDao)
+ }
+}
diff --git a/app/src/main/java/es/zenvairo/nextcloudsync/domain/vfs/VirtualFolderManager.kt b/app/src/main/java/es/zenvairo/nextcloudsync/domain/vfs/VirtualFolderManager.kt
new file mode 100644
index 0000000..c7c2a7b
--- /dev/null
+++ b/app/src/main/java/es/zenvairo/nextcloudsync/domain/vfs/VirtualFolderManager.kt
@@ -0,0 +1,95 @@
+package es.zenvairo.nextcloudsync.domain.vfs
+
+import es.zenvairo.nextcloudsync.data.auth.AccountRepository
+import es.zenvairo.nextcloudsync.data.db.dao.VirtualFolderDao
+import es.zenvairo.nextcloudsync.data.db.entity.VirtualFolderEntity
+import es.zenvairo.nextcloudsync.root.MountResult
+import es.zenvairo.nextcloudsync.root.RootMountController
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import javax.inject.Inject
+import javax.inject.Singleton
+
+sealed class MountState {
+ object Unmounted : MountState()
+ object Mounting : MountState()
+ data class Mounted(val mountpoint: String) : MountState()
+ data class Failed(val reason: String) : MountState()
+}
+
+/**
+ * Owns the mount lifecycle of every virtual folder and the observable state the UI renders.
+ *
+ * Mounts are never established automatically: they need root at the moment they happen, and on
+ * KernelSU a denied or not-yet-granted request just fails rather than prompting. So the user
+ * mounts explicitly, and after a reboot they mount again.
+ */
+@Singleton
+class VirtualFolderManager @Inject constructor(
+ private val controller: RootMountController,
+ private val virtualFolderDao: VirtualFolderDao,
+ private val accountRepository: AccountRepository
+) {
+ private val _states = MutableStateFlow