Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a7c5ed713a | |||
| 739e6ece46 | |||
| d70defe3e1 | |||
| a4aca43fa7 | |||
| cfac742856 | |||
| be3f46287a | |||
| 894c2ffe78 | |||
| 59335dab13 | |||
| b15637132c | |||
| bcfecbb867 | |||
| f751b26a9e |
@@ -0,0 +1,52 @@
|
|||||||
|
name: Build & Release APK
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
java-version: '17'
|
||||||
|
distribution: 'temurin'
|
||||||
|
cache: gradle
|
||||||
|
|
||||||
|
- uses: android-actions/setup-android@v3
|
||||||
|
|
||||||
|
- name: Build debug APK
|
||||||
|
run: |
|
||||||
|
chmod +x gradlew
|
||||||
|
./gradlew assembleDebug --no-daemon
|
||||||
|
|
||||||
|
- name: Get version name
|
||||||
|
id: ver
|
||||||
|
run: echo "name=$(grep VERSION_NAME version.properties | cut -d= -f2)" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Rename APK
|
||||||
|
run: |
|
||||||
|
mkdir dist
|
||||||
|
cp app/build/outputs/apk/debug/app-debug.apk \
|
||||||
|
dist/SyncFlow-v${{ steps.ver.outputs.name }}.apk
|
||||||
|
|
||||||
|
- name: Attach APK to release
|
||||||
|
env:
|
||||||
|
TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
TAG: ${{ github.ref_name }}
|
||||||
|
VERSION: ${{ steps.ver.outputs.name }}
|
||||||
|
run: |
|
||||||
|
RELEASE_ID=$(curl -sf \
|
||||||
|
"https://gitea.khodak.me/api/v1/repos/amir/SyncFlow/releases/tags/$TAG" \
|
||||||
|
-H "Authorization: token $TOKEN" \
|
||||||
|
| python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
|
||||||
|
curl -sf -X POST \
|
||||||
|
"https://gitea.khodak.me/api/v1/repos/amir/SyncFlow/releases/$RELEASE_ID/assets" \
|
||||||
|
-H "Authorization: token $TOKEN" \
|
||||||
|
-F "attachment=@dist/SyncFlow-v${VERSION}.apk"
|
||||||
|
echo "APK uploaded to release $TAG"
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
|
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SHORT_SERVICE" />
|
||||||
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
@@ -68,10 +69,16 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</receiver>
|
</receiver>
|
||||||
|
|
||||||
|
<!-- File watcher for ON_CHANGE sync pairs -->
|
||||||
|
<service
|
||||||
|
android:name=".worker.FileWatchService"
|
||||||
|
android:foregroundServiceType="dataSync|shortService"
|
||||||
|
android:exported="false" />
|
||||||
|
|
||||||
<!-- Required on API 29+ so WorkManager can start a typed foreground service -->
|
<!-- Required on API 29+ so WorkManager can start a typed foreground service -->
|
||||||
<service
|
<service
|
||||||
android:name="androidx.work.impl.foreground.SystemForegroundService"
|
android:name="androidx.work.impl.foreground.SystemForegroundService"
|
||||||
android:foregroundServiceType="dataSync"
|
android:foregroundServiceType="dataSync|shortService"
|
||||||
tools:node="merge" />
|
tools:node="merge" />
|
||||||
|
|
||||||
<!-- Remove WorkManager's default initializer — app uses on-demand init via Configuration.Provider -->
|
<!-- Remove WorkManager's default initializer — app uses on-demand init via Configuration.Provider -->
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
package com.syncflow
|
package com.syncflow
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.pm.PackageManager
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.enableEdgeToEdge
|
import androidx.activity.enableEdgeToEdge
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
import androidx.biometric.BiometricManager
|
import androidx.biometric.BiometricManager
|
||||||
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
|
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
|
||||||
@@ -49,10 +52,14 @@ class MainActivity : AppCompatActivity() {
|
|||||||
private var isLocked by mutableStateOf(false)
|
private var isLocked by mutableStateOf(false)
|
||||||
private var showRetry by mutableStateOf(false)
|
private var showRetry by mutableStateOf(false)
|
||||||
|
|
||||||
|
private val requestNotificationPermission =
|
||||||
|
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* proceed regardless */ }
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
installSplashScreen()
|
installSplashScreen()
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
enableEdgeToEdge()
|
enableEdgeToEdge()
|
||||||
|
requestNotificationPermissionIfNeeded()
|
||||||
setContent {
|
setContent {
|
||||||
SyncFlowTheme {
|
SyncFlowTheme {
|
||||||
Surface(modifier = Modifier.fillMaxSize()) {
|
Surface(modifier = Modifier.fillMaxSize()) {
|
||||||
@@ -127,6 +134,16 @@ class MainActivity : AppCompatActivity() {
|
|||||||
BIOMETRIC_WEAK or DEVICE_CREDENTIAL
|
BIOMETRIC_WEAK or DEVICE_CREDENTIAL
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun requestNotificationPermissionIfNeeded() {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
!= PackageManager.PERMISSION_GRANTED
|
||||||
|
) {
|
||||||
|
requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun canAuthenticate(): Boolean {
|
private fun canAuthenticate(): Boolean {
|
||||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R)
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R)
|
||||||
return BiometricManager.from(this).canAuthenticate(BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS
|
return BiometricManager.from(this).canAuthenticate(BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS
|
||||||
|
|||||||
@@ -1,9 +1,18 @@
|
|||||||
package com.syncflow
|
package com.syncflow
|
||||||
|
|
||||||
import android.app.Application
|
import android.app.Application
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.content.Context
|
||||||
import androidx.hilt.work.HiltWorkerFactory
|
import androidx.hilt.work.HiltWorkerFactory
|
||||||
import androidx.work.Configuration
|
import androidx.work.Configuration
|
||||||
|
import com.syncflow.data.db.SyncPairDao
|
||||||
|
import com.syncflow.domain.model.ScheduleType
|
||||||
|
import com.syncflow.worker.FileWatchService
|
||||||
import dagger.hilt.android.HiltAndroidApp
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
@@ -11,10 +20,38 @@ import javax.inject.Inject
|
|||||||
class SyncFlowApp : Application(), Configuration.Provider {
|
class SyncFlowApp : Application(), Configuration.Provider {
|
||||||
|
|
||||||
@Inject lateinit var workerFactory: HiltWorkerFactory
|
@Inject lateinit var workerFactory: HiltWorkerFactory
|
||||||
|
@Inject lateinit var syncPairDao: SyncPairDao
|
||||||
|
|
||||||
override fun onCreate() {
|
override fun onCreate() {
|
||||||
super.onCreate()
|
super.onCreate()
|
||||||
if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree())
|
if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree())
|
||||||
|
createNotificationChannels()
|
||||||
|
// Start file watcher on every app launch for any existing ON_CHANGE pairs
|
||||||
|
CoroutineScope(Dispatchers.IO).launch {
|
||||||
|
val hasOnChange = syncPairDao.getEnabled().any { it.scheduleType == ScheduleType.ON_CHANGE }
|
||||||
|
if (hasOnChange) FileWatchService.start(this@SyncFlowApp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createNotificationChannels() {
|
||||||
|
val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
listOf(
|
||||||
|
NotificationChannel("sync_progress", "Sync progress", NotificationManager.IMPORTANCE_LOW).apply {
|
||||||
|
description = "Shown while a sync is running"
|
||||||
|
},
|
||||||
|
NotificationChannel("sync_complete", "Sync complete", NotificationManager.IMPORTANCE_LOW).apply {
|
||||||
|
description = "Summary after each successful sync"
|
||||||
|
},
|
||||||
|
NotificationChannel("sync_alerts", "Sync errors", NotificationManager.IMPORTANCE_DEFAULT).apply {
|
||||||
|
description = "Alerts for sync failures and conflicts"
|
||||||
|
},
|
||||||
|
NotificationChannel("sync_watching", "File watching", NotificationManager.IMPORTANCE_MIN).apply {
|
||||||
|
description = "Background service watching folders for changes"
|
||||||
|
setShowBadge(false)
|
||||||
|
},
|
||||||
|
).forEach { channel ->
|
||||||
|
if (nm.getNotificationChannel(channel.id) == null) nm.createNotificationChannel(channel)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override val workManagerConfiguration: Configuration
|
override val workManagerConfiguration: Configuration
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ interface SyncEventDao {
|
|||||||
@Query("SELECT * FROM sync_events WHERE syncPairId = :pairId ORDER BY timestamp DESC LIMIT :limit")
|
@Query("SELECT * FROM sync_events WHERE syncPairId = :pairId ORDER BY timestamp DESC LIMIT :limit")
|
||||||
fun observeRecent(pairId: Long, limit: Int = 200): Flow<List<SyncEventEntity>>
|
fun observeRecent(pairId: Long, limit: Int = 200): Flow<List<SyncEventEntity>>
|
||||||
|
|
||||||
|
@Query("SELECT * FROM sync_events ORDER BY timestamp DESC LIMIT :limit")
|
||||||
|
fun observeAll(limit: Int = 500): Flow<List<SyncEventEntity>>
|
||||||
|
|
||||||
@Insert
|
@Insert
|
||||||
suspend fun insert(entity: SyncEventEntity): Long
|
suspend fun insert(entity: SyncEventEntity): Long
|
||||||
|
|
||||||
|
|||||||
@@ -7,19 +7,20 @@ import com.syncflow.data.providers.owncloud.OwnCloudProvider
|
|||||||
import com.syncflow.data.providers.onedrive.OneDriveProvider
|
import com.syncflow.data.providers.onedrive.OneDriveProvider
|
||||||
import com.syncflow.data.providers.sftp.SftpProvider
|
import com.syncflow.data.providers.sftp.SftpProvider
|
||||||
import com.syncflow.data.providers.webdav.WebDavProvider
|
import com.syncflow.data.providers.webdav.WebDavProvider
|
||||||
|
import com.syncflow.data.security.CredentialStore
|
||||||
import com.syncflow.domain.model.CloudAccount
|
import com.syncflow.domain.model.CloudAccount
|
||||||
import com.syncflow.domain.model.ProviderType
|
import com.syncflow.domain.model.ProviderType
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
class ProviderFactory @Inject constructor() {
|
class ProviderFactory @Inject constructor(private val credentialStore: CredentialStore) {
|
||||||
fun create(account: CloudAccount): CloudProvider = when (account.providerType) {
|
fun create(account: CloudAccount): CloudProvider = when (account.providerType) {
|
||||||
ProviderType.GOOGLE_DRIVE -> GoogleDriveProvider(account)
|
ProviderType.GOOGLE_DRIVE -> GoogleDriveProvider(account)
|
||||||
ProviderType.DROPBOX -> DropboxProvider(account)
|
ProviderType.DROPBOX -> DropboxProvider(account)
|
||||||
ProviderType.ONEDRIVE -> OneDriveProvider(account)
|
ProviderType.ONEDRIVE -> OneDriveProvider(account)
|
||||||
ProviderType.WEBDAV -> WebDavProvider(account)
|
ProviderType.WEBDAV -> WebDavProvider(account)
|
||||||
ProviderType.SFTP -> SftpProvider(account)
|
ProviderType.SFTP -> SftpProvider(account, credentialStore)
|
||||||
ProviderType.NEXTCLOUD -> NextcloudProvider(account)
|
ProviderType.NEXTCLOUD -> NextcloudProvider(account)
|
||||||
ProviderType.OWNCLOUD -> OwnCloudProvider(account)
|
ProviderType.OWNCLOUD -> OwnCloudProvider(account)
|
||||||
ProviderType.SFTPGO -> WebDavProvider(account) // SFTPGo exposes WebDAV
|
ProviderType.SFTPGO -> WebDavProvider(account) // SFTPGo exposes WebDAV
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ class DropboxProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
}
|
}
|
||||||
private val client = OkHttpClient()
|
private val client = OkHttpClient()
|
||||||
|
|
||||||
private fun apiReq(url: String, bodyJson: String): Request =
|
private fun apiReq(url: String, argJson: JsonObject): Request =
|
||||||
Request.Builder().url(url)
|
Request.Builder().url(url)
|
||||||
.post(bodyJson.toRequestBody("application/json".toMediaType()))
|
.post(argJson.toString().toRequestBody("application/json".toMediaType()))
|
||||||
.header("Authorization", "Bearer $token")
|
.header("Authorization", "Bearer $token")
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
@@ -33,7 +33,8 @@ class DropboxProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
|
|
||||||
override suspend fun listFiles(remotePath: String): Result<List<RemoteFile>> = runCatching {
|
override suspend fun listFiles(remotePath: String): Result<List<RemoteFile>> = runCatching {
|
||||||
val path = if (remotePath == "/" || remotePath.isBlank()) "" else remotePath
|
val path = if (remotePath == "/" || remotePath.isBlank()) "" else remotePath
|
||||||
val req = apiReq("https://api.dropboxapi.com/2/files/list_folder", """{"path":"$path","recursive":false}""")
|
val arg = buildJsonObject { put("path", path); put("recursive", false) }
|
||||||
|
val req = apiReq("https://api.dropboxapi.com/2/files/list_folder", arg)
|
||||||
client.newCall(req).execute().use { resp ->
|
client.newCall(req).execute().use { resp ->
|
||||||
val body = resp.body?.string() ?: throw Exception("HTTP ${resp.code}")
|
val body = resp.body?.string() ?: throw Exception("HTTP ${resp.code}")
|
||||||
if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}: $body")
|
if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}: $body")
|
||||||
@@ -44,11 +45,15 @@ class DropboxProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
|
|
||||||
override suspend fun uploadFile(localStream: InputStream, remotePath: String, sizeBytes: Long, onProgress: (Long) -> Unit): Result<RemoteFile> = runCatching {
|
override suspend fun uploadFile(localStream: InputStream, remotePath: String, sizeBytes: Long, onProgress: (Long) -> Unit): Result<RemoteFile> = runCatching {
|
||||||
val bytes = localStream.readBytes()
|
val bytes = localStream.readBytes()
|
||||||
val argHeader = """{"path":"${remotePath.normalizeDropbox()}","mode":"overwrite","autorename":false}"""
|
val arg = buildJsonObject {
|
||||||
|
put("path", remotePath.normalizeDropbox())
|
||||||
|
put("mode", "overwrite")
|
||||||
|
put("autorename", false)
|
||||||
|
}
|
||||||
val req = Request.Builder().url("https://content.dropboxapi.com/2/files/upload")
|
val req = Request.Builder().url("https://content.dropboxapi.com/2/files/upload")
|
||||||
.post(bytes.toRequestBody("application/octet-stream".toMediaType()))
|
.post(bytes.toRequestBody("application/octet-stream".toMediaType()))
|
||||||
.header("Authorization", "Bearer $token")
|
.header("Authorization", "Bearer $token")
|
||||||
.header("Dropbox-API-Arg", argHeader).build()
|
.header("Dropbox-API-Arg", arg.toString()).build()
|
||||||
client.newCall(req).execute().use { resp ->
|
client.newCall(req).execute().use { resp ->
|
||||||
val body = resp.body?.string() ?: throw Exception("HTTP ${resp.code}")
|
val body = resp.body?.string() ?: throw Exception("HTTP ${resp.code}")
|
||||||
if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}: $body")
|
if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}: $body")
|
||||||
@@ -58,11 +63,11 @@ class DropboxProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun downloadFile(remotePath: String, destination: OutputStream, onProgress: (Long) -> Unit): Result<Unit> = runCatching {
|
override suspend fun downloadFile(remotePath: String, destination: OutputStream, onProgress: (Long) -> Unit): Result<Unit> = runCatching {
|
||||||
val argHeader = """{"path":"${remotePath.normalizeDropbox()}"}"""
|
val arg = buildJsonObject { put("path", remotePath.normalizeDropbox()) }
|
||||||
val req = Request.Builder().url("https://content.dropboxapi.com/2/files/download")
|
val req = Request.Builder().url("https://content.dropboxapi.com/2/files/download")
|
||||||
.post("".toRequestBody())
|
.post("".toRequestBody())
|
||||||
.header("Authorization", "Bearer $token")
|
.header("Authorization", "Bearer $token")
|
||||||
.header("Dropbox-API-Arg", argHeader).build()
|
.header("Dropbox-API-Arg", arg.toString()).build()
|
||||||
client.newCall(req).execute().use { resp ->
|
client.newCall(req).execute().use { resp ->
|
||||||
if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}")
|
if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}")
|
||||||
var total = 0L
|
var total = 0L
|
||||||
@@ -75,17 +80,20 @@ class DropboxProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun deleteFile(remotePath: String): Result<Unit> = runCatching {
|
override suspend fun deleteFile(remotePath: String): Result<Unit> = runCatching {
|
||||||
val req = apiReq("https://api.dropboxapi.com/2/files/delete_v2", """{"path":"${remotePath.normalizeDropbox()}"}""")
|
val arg = buildJsonObject { put("path", remotePath.normalizeDropbox()) }
|
||||||
|
val req = apiReq("https://api.dropboxapi.com/2/files/delete_v2", arg)
|
||||||
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}") }
|
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}") }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun createDirectory(remotePath: String): Result<Unit> = runCatching {
|
override suspend fun createDirectory(remotePath: String): Result<Unit> = runCatching {
|
||||||
val req = apiReq("https://api.dropboxapi.com/2/files/create_folder_v2", """{"path":"${remotePath.normalizeDropbox()}"}""")
|
val arg = buildJsonObject { put("path", remotePath.normalizeDropbox()) }
|
||||||
|
val req = apiReq("https://api.dropboxapi.com/2/files/create_folder_v2", arg)
|
||||||
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful && resp.code != 409) throw Exception("HTTP ${resp.code}") }
|
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful && resp.code != 409) throw Exception("HTTP ${resp.code}") }
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getFileMetadata(remotePath: String): Result<RemoteFile> = runCatching {
|
override suspend fun getFileMetadata(remotePath: String): Result<RemoteFile> = runCatching {
|
||||||
val req = apiReq("https://api.dropboxapi.com/2/files/get_metadata", """{"path":"${remotePath.normalizeDropbox()}"}""")
|
val arg = buildJsonObject { put("path", remotePath.normalizeDropbox()) }
|
||||||
|
val req = apiReq("https://api.dropboxapi.com/2/files/get_metadata", arg)
|
||||||
client.newCall(req).execute().use { resp ->
|
client.newCall(req).execute().use { resp ->
|
||||||
val body = resp.body?.string() ?: throw Exception("HTTP ${resp.code}")
|
val body = resp.body?.string() ?: throw Exception("HTTP ${resp.code}")
|
||||||
Json.parseToJsonElement(body).jsonObject.toRemoteFile()
|
Json.parseToJsonElement(body).jsonObject.toRemoteFile()
|
||||||
@@ -93,8 +101,11 @@ class DropboxProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun moveFile(fromPath: String, toPath: String): Result<Unit> = runCatching {
|
override suspend fun moveFile(fromPath: String, toPath: String): Result<Unit> = runCatching {
|
||||||
val req = apiReq("https://api.dropboxapi.com/2/files/move_v2",
|
val arg = buildJsonObject {
|
||||||
"""{"from_path":"${fromPath.normalizeDropbox()}","to_path":"${toPath.normalizeDropbox()}"}""")
|
put("from_path", fromPath.normalizeDropbox())
|
||||||
|
put("to_path", toPath.normalizeDropbox())
|
||||||
|
}
|
||||||
|
val req = apiReq("https://api.dropboxapi.com/2/files/move_v2", arg)
|
||||||
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}") }
|
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}") }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -44,9 +44,11 @@ class GoogleDriveProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
val name = remotePath.substringAfterLast('/')
|
val name = remotePath.substringAfterLast('/')
|
||||||
val parentId = if ('/' in remotePath.dropLast(1)) remotePath.substringBeforeLast('/') else "root"
|
val parentId = if ('/' in remotePath.dropLast(1)) remotePath.substringBeforeLast('/') else "root"
|
||||||
|
|
||||||
// Multipart upload
|
// Multipart upload — use JSON builder to avoid injection via filenames with special chars
|
||||||
val metaPart = """{"name":"$name","parents":["$parentId"]}"""
|
val metaPart = buildJsonObject {
|
||||||
.toRequestBody("application/json".toMediaType())
|
put("name", name)
|
||||||
|
put("parents", buildJsonArray { add(parentId) })
|
||||||
|
}.toString().toRequestBody("application/json".toMediaType())
|
||||||
val dataPart = bytes.toRequestBody("application/octet-stream".toMediaType())
|
val dataPart = bytes.toRequestBody("application/octet-stream".toMediaType())
|
||||||
val multipart = MultipartBody.Builder()
|
val multipart = MultipartBody.Builder()
|
||||||
.setType(MultipartBody.FORM)
|
.setType(MultipartBody.FORM)
|
||||||
@@ -86,8 +88,11 @@ class GoogleDriveProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
override suspend fun createDirectory(remotePath: String): Result<Unit> = runCatching {
|
override suspend fun createDirectory(remotePath: String): Result<Unit> = runCatching {
|
||||||
val name = remotePath.substringAfterLast('/')
|
val name = remotePath.substringAfterLast('/')
|
||||||
val parentId = if ('/' in remotePath.dropLast(1)) remotePath.substringBeforeLast('/') else "root"
|
val parentId = if ('/' in remotePath.dropLast(1)) remotePath.substringBeforeLast('/') else "root"
|
||||||
val body = """{"name":"$name","mimeType":"application/vnd.google-apps.folder","parents":["$parentId"]}"""
|
val body = buildJsonObject {
|
||||||
.toRequestBody("application/json".toMediaType())
|
put("name", name)
|
||||||
|
put("mimeType", "application/vnd.google-apps.folder")
|
||||||
|
put("parents", buildJsonArray { add(parentId) })
|
||||||
|
}.toString().toRequestBody("application/json".toMediaType())
|
||||||
val req = auth(Request.Builder().url("https://www.googleapis.com/drive/v3/files").post(body)).build()
|
val req = auth(Request.Builder().url("https://www.googleapis.com/drive/v3/files").post(body)).build()
|
||||||
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}") }
|
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}") }
|
||||||
}
|
}
|
||||||
@@ -102,7 +107,8 @@ class GoogleDriveProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
|
|
||||||
override suspend fun moveFile(fromPath: String, toPath: String): Result<Unit> = runCatching {
|
override suspend fun moveFile(fromPath: String, toPath: String): Result<Unit> = runCatching {
|
||||||
val newName = toPath.substringAfterLast('/')
|
val newName = toPath.substringAfterLast('/')
|
||||||
val body = """{"name":"$newName"}""".toRequestBody("application/json".toMediaType())
|
val body = buildJsonObject { put("name", newName) }.toString()
|
||||||
|
.toRequestBody("application/json".toMediaType())
|
||||||
val req = auth(Request.Builder().url("https://www.googleapis.com/drive/v3/files/$fromPath").patch(body)).build()
|
val req = auth(Request.Builder().url("https://www.googleapis.com/drive/v3/files/$fromPath").patch(body)).build()
|
||||||
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}") }
|
client.newCall(req).execute().use { resp -> if (!resp.isSuccessful) throw Exception("HTTP ${resp.code}") }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.syncflow.data.providers.sftp
|
package com.syncflow.data.providers.sftp
|
||||||
|
|
||||||
import com.syncflow.data.providers.CloudProvider
|
import com.syncflow.data.providers.CloudProvider
|
||||||
|
import com.syncflow.data.security.CredentialStore
|
||||||
import com.syncflow.domain.model.CloudAccount
|
import com.syncflow.domain.model.CloudAccount
|
||||||
import com.syncflow.domain.model.RemoteFile
|
import com.syncflow.domain.model.RemoteFile
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
@@ -8,13 +9,12 @@ import kotlinx.serialization.json.jsonObject
|
|||||||
import kotlinx.serialization.json.jsonPrimitive
|
import kotlinx.serialization.json.jsonPrimitive
|
||||||
import net.schmizz.sshj.SSHClient
|
import net.schmizz.sshj.SSHClient
|
||||||
import net.schmizz.sshj.sftp.SFTPClient
|
import net.schmizz.sshj.sftp.SFTPClient
|
||||||
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
|
|
||||||
import net.schmizz.sshj.xfer.InMemorySourceFile
|
import net.schmizz.sshj.xfer.InMemorySourceFile
|
||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
import java.io.OutputStream
|
import java.io.OutputStream
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
|
|
||||||
class SftpProvider(private val account: CloudAccount) : CloudProvider {
|
class SftpProvider(private val account: CloudAccount, private val credentialStore: CredentialStore) : CloudProvider {
|
||||||
|
|
||||||
private val creds = Json.parseToJsonElement(account.credentialJson).jsonObject
|
private val creds = Json.parseToJsonElement(account.credentialJson).jsonObject
|
||||||
private val host = account.serverUrl ?: "localhost"
|
private val host = account.serverUrl ?: "localhost"
|
||||||
@@ -25,7 +25,7 @@ class SftpProvider(private val account: CloudAccount) : CloudProvider {
|
|||||||
|
|
||||||
private fun <T> withSftp(block: (SFTPClient) -> T): T {
|
private fun <T> withSftp(block: (SFTPClient) -> T): T {
|
||||||
val ssh = SSHClient()
|
val ssh = SSHClient()
|
||||||
ssh.addHostKeyVerifier(PromiscuousVerifier()) // TODO: replace with proper key pinning
|
ssh.addHostKeyVerifier(TofuHostKeyVerifier(credentialStore))
|
||||||
ssh.connect(host, port)
|
ssh.connect(host, port)
|
||||||
try {
|
try {
|
||||||
if (!privateKey.isNullOrBlank()) {
|
if (!privateKey.isNullOrBlank()) {
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package com.syncflow.data.providers.sftp
|
||||||
|
|
||||||
|
import com.syncflow.data.security.CredentialStore
|
||||||
|
import net.schmizz.sshj.transport.verification.HostKeyVerifier
|
||||||
|
import java.security.MessageDigest
|
||||||
|
import java.security.PublicKey
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trust-On-First-Use SSH host key verifier.
|
||||||
|
*
|
||||||
|
* First connection to a host: fingerprint is stored in EncryptedSharedPreferences and accepted.
|
||||||
|
* Subsequent connections: stored fingerprint must match — mismatch aborts (possible MITM).
|
||||||
|
*/
|
||||||
|
class TofuHostKeyVerifier(private val credentialStore: CredentialStore) : HostKeyVerifier {
|
||||||
|
|
||||||
|
override fun verify(hostname: String, port: Int, key: PublicKey): Boolean {
|
||||||
|
val fingerprint = sha256Fingerprint(key)
|
||||||
|
val stored = credentialStore.getHostFingerprint(hostname, port)
|
||||||
|
return if (stored == null) {
|
||||||
|
credentialStore.saveHostKey(hostname, port, fingerprint)
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
stored == fingerprint
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return empty list so sshj uses server preference order for key exchange.
|
||||||
|
// Our verify() will accept or reject whatever algorithm is negotiated.
|
||||||
|
override fun findExistingAlgorithms(hostname: String, port: Int): List<String> = emptyList()
|
||||||
|
|
||||||
|
private fun sha256Fingerprint(key: PublicKey): String {
|
||||||
|
val digest = MessageDigest.getInstance("SHA-256").digest(key.encoded)
|
||||||
|
return digest.joinToString(":") { "%02x".format(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import kotlinx.serialization.json.Json
|
|||||||
import kotlinx.serialization.json.jsonObject
|
import kotlinx.serialization.json.jsonObject
|
||||||
import kotlinx.serialization.json.jsonPrimitive
|
import kotlinx.serialization.json.jsonPrimitive
|
||||||
import okhttp3.*
|
import okhttp3.*
|
||||||
|
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||||
import okhttp3.MediaType.Companion.toMediaType
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import org.xmlpull.v1.XmlPullParser
|
import org.xmlpull.v1.XmlPullParser
|
||||||
@@ -38,9 +39,14 @@ open class WebDavProvider(protected val account: CloudAccount) : CloudProvider {
|
|||||||
.header("Authorization", Credentials.basic(user, pass))
|
.header("Authorization", Credentials.basic(user, pass))
|
||||||
.build()
|
.build()
|
||||||
val resp = chain.proceed(req)
|
val resp = chain.proceed(req)
|
||||||
// follow redirect manually for WebDAV methods (OkHttp skips non-GET/HEAD redirects)
|
// Follow redirects for WebDAV methods (OkHttp skips non-GET/HEAD redirects).
|
||||||
|
// Only follow same-host redirects to prevent credential leakage to a different server.
|
||||||
if (resp.code in 301..308) {
|
if (resp.code in 301..308) {
|
||||||
val location = resp.header("Location") ?: return@addInterceptor resp
|
val location = resp.header("Location") ?: return@addInterceptor resp
|
||||||
|
val redirectHost = location.toHttpUrlOrNull()?.host
|
||||||
|
if (redirectHost == null || redirectHost != req.url.host) {
|
||||||
|
return@addInterceptor resp
|
||||||
|
}
|
||||||
resp.close()
|
resp.close()
|
||||||
val redirectReq = req.newBuilder().url(location).build()
|
val redirectReq = req.newBuilder().url(location).build()
|
||||||
chain.proceed(redirectReq)
|
chain.proceed(redirectReq)
|
||||||
@@ -158,43 +164,42 @@ open class WebDavProvider(protected val account: CloudAccount) : CloudProvider {
|
|||||||
|
|
||||||
private fun parsePropfind(xml: String, parentPath: String, dropFirst: Boolean = true): List<RemoteFile> {
|
private fun parsePropfind(xml: String, parentPath: String, dropFirst: Boolean = true): List<RemoteFile> {
|
||||||
val results = mutableListOf<RemoteFile>()
|
val results = mutableListOf<RemoteFile>()
|
||||||
try {
|
val factory = XmlPullParserFactory.newInstance()
|
||||||
val factory = XmlPullParserFactory.newInstance()
|
factory.isNamespaceAware = true
|
||||||
factory.isNamespaceAware = true
|
val parser = factory.newPullParser()
|
||||||
val parser = factory.newPullParser()
|
parser.setInput(xml.reader())
|
||||||
parser.setInput(xml.reader())
|
|
||||||
|
|
||||||
var href = ""; var isCollection = false; var contentLength = 0L
|
var href = ""; var isCollection = false; var contentLength = 0L
|
||||||
var lastModified: Instant = Instant.EPOCH; var etag: String? = null; var contentType: String? = null
|
var lastModified: Instant = Instant.EPOCH; var etag: String? = null; var contentType: String? = null
|
||||||
var inResponse = false; var inProp = false
|
var inResponse = false; var inProp = false
|
||||||
|
|
||||||
var eventType = parser.eventType
|
var eventType = parser.eventType
|
||||||
while (eventType != XmlPullParser.END_DOCUMENT) {
|
while (eventType != XmlPullParser.END_DOCUMENT) {
|
||||||
val tag = parser.name?.substringAfterLast(':')?.lowercase()
|
val tag = parser.name?.substringAfterLast(':')?.lowercase()
|
||||||
when (eventType) {
|
when (eventType) {
|
||||||
XmlPullParser.START_TAG -> when (tag) {
|
XmlPullParser.START_TAG -> when (tag) {
|
||||||
"response" -> { inResponse = true; href = ""; isCollection = false; contentLength = 0L; lastModified = Instant.EPOCH; etag = null; contentType = null }
|
"response" -> { inResponse = true; href = ""; isCollection = false; contentLength = 0L; lastModified = Instant.EPOCH; etag = null; contentType = null }
|
||||||
"prop" -> inProp = true
|
"prop" -> inProp = true
|
||||||
"href" -> if (!inProp) href = parser.nextText().trim()
|
"href" -> if (!inProp) href = parser.nextText().trim()
|
||||||
"collection" -> if (inProp) isCollection = true
|
"collection" -> if (inProp) isCollection = true
|
||||||
"getcontentlength" -> if (inProp) contentLength = parser.nextText().trim().toLongOrNull() ?: 0L
|
"getcontentlength" -> if (inProp) contentLength = parser.nextText().trim().toLongOrNull() ?: 0L
|
||||||
"getlastmodified" -> if (inProp) lastModified = parseHttpDate(parser.nextText().trim())
|
"getlastmodified" -> if (inProp) lastModified = parseHttpDate(parser.nextText().trim())
|
||||||
"getetag" -> if (inProp) etag = parser.nextText().trim().trim('"')
|
"getetag" -> if (inProp) etag = parser.nextText().trim().trim('"')
|
||||||
"getcontenttype" -> if (inProp) contentType = parser.nextText().trim()
|
"getcontenttype" -> if (inProp) contentType = parser.nextText().trim()
|
||||||
}
|
}
|
||||||
XmlPullParser.END_TAG -> when (tag) {
|
XmlPullParser.END_TAG -> when (tag) {
|
||||||
"prop" -> inProp = false
|
"prop" -> inProp = false
|
||||||
"response" -> if (inResponse && href.isNotBlank()) {
|
"response" -> if (inResponse && href.isNotBlank()) {
|
||||||
val name = href.trimEnd('/').substringAfterLast('/')
|
val rawName = href.trimEnd('/').substringAfterLast('/')
|
||||||
val relPath = "$parentPath/$name".replace("//", "/")
|
val name = try { java.net.URLDecoder.decode(rawName, "UTF-8") } catch (_: Exception) { rawName }
|
||||||
results.add(RemoteFile(relPath, name, isCollection, contentLength, lastModified, etag, contentType))
|
val relPath = "$parentPath/$name".replace("//", "/")
|
||||||
inResponse = false
|
results.add(RemoteFile(relPath, name, isCollection, contentLength, lastModified, etag, contentType))
|
||||||
}
|
inResponse = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
eventType = parser.next()
|
|
||||||
}
|
}
|
||||||
} catch (_: Exception) {}
|
eventType = parser.next()
|
||||||
|
}
|
||||||
return if (dropFirst) results.drop(1) else results
|
return if (dropFirst) results.drop(1) else results
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package com.syncflow.data.security
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.SharedPreferences
|
import android.content.SharedPreferences
|
||||||
import androidx.security.crypto.EncryptedSharedPreferences
|
import androidx.security.crypto.EncryptedSharedPreferences
|
||||||
import androidx.security.crypto.MasterKey
|
import androidx.security.crypto.MasterKeys
|
||||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
@@ -12,13 +12,11 @@ import javax.inject.Singleton
|
|||||||
class CredentialStore @Inject constructor(@ApplicationContext private val context: Context) {
|
class CredentialStore @Inject constructor(@ApplicationContext private val context: Context) {
|
||||||
|
|
||||||
private val prefs: SharedPreferences by lazy {
|
private val prefs: SharedPreferences by lazy {
|
||||||
val masterKey = MasterKey.Builder(context)
|
val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
|
||||||
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
|
|
||||||
.build()
|
|
||||||
EncryptedSharedPreferences.create(
|
EncryptedSharedPreferences.create(
|
||||||
context,
|
|
||||||
"syncflow_credentials",
|
"syncflow_credentials",
|
||||||
masterKey,
|
masterKeyAlias,
|
||||||
|
context,
|
||||||
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
|
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
|
||||||
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
|
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,
|
||||||
)
|
)
|
||||||
@@ -37,7 +35,7 @@ class CredentialStore @Inject constructor(@ApplicationContext private val contex
|
|||||||
prefs.edit().remove(credKey(accountId)).apply()
|
prefs.edit().remove(credKey(accountId)).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── PKCE verifiers (OAuth flow) ───────────────────────────────────────────
|
// ── PKCE verifiers and OAuth state (OAuth flow) ───────────────────────────
|
||||||
|
|
||||||
fun savePkceVerifier(provider: String, verifier: String) {
|
fun savePkceVerifier(provider: String, verifier: String) {
|
||||||
prefs.edit().putString(pkceKey(provider), verifier).apply()
|
prefs.edit().putString(pkceKey(provider), verifier).apply()
|
||||||
@@ -49,8 +47,18 @@ class CredentialStore @Inject constructor(@ApplicationContext private val contex
|
|||||||
prefs.edit().remove(pkceKey(provider)).apply()
|
prefs.edit().remove(pkceKey(provider)).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── SFTP host key fingerprints (TOFU) ─────────────────────────────────────
|
||||||
|
|
||||||
|
fun saveHostKey(host: String, port: Int, fingerprint: String) {
|
||||||
|
prefs.edit().putString(hostKey(host, port), fingerprint).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getHostFingerprint(host: String, port: Int): String? =
|
||||||
|
prefs.getString(hostKey(host, port), null)
|
||||||
|
|
||||||
// ── Key helpers ───────────────────────────────────────────────────────────
|
// ── Key helpers ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
private fun credKey(accountId: Long) = "cred_$accountId"
|
private fun credKey(accountId: Long) = "cred_$accountId"
|
||||||
private fun pkceKey(provider: String) = "pkce_$provider"
|
private fun pkceKey(provider: String) = "pkce_$provider"
|
||||||
|
private fun hostKey(host: String, port: Int) = "sshhost_${host}_$port"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.syncflow.ui.addpair
|
package com.syncflow.ui.addpair
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
import androidx.lifecycle.SavedStateHandle
|
import androidx.lifecycle.SavedStateHandle
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
@@ -7,9 +8,10 @@ import com.syncflow.data.db.CloudAccountDao
|
|||||||
import com.syncflow.data.db.SyncPairDao
|
import com.syncflow.data.db.SyncPairDao
|
||||||
import com.syncflow.data.db.entities.CloudAccountEntity
|
import com.syncflow.data.db.entities.CloudAccountEntity
|
||||||
import com.syncflow.data.db.entities.SyncPairEntity
|
import com.syncflow.data.db.entities.SyncPairEntity
|
||||||
import com.syncflow.data.db.entities.toDomain
|
|
||||||
import com.syncflow.domain.model.*
|
import com.syncflow.domain.model.*
|
||||||
|
import com.syncflow.worker.FileWatchService
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import kotlinx.coroutines.flow.*
|
import kotlinx.coroutines.flow.*
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@@ -31,7 +33,7 @@ data class AddPairUiState(
|
|||||||
val scheduleType: ScheduleType = ScheduleType.INTERVAL,
|
val scheduleType: ScheduleType = ScheduleType.INTERVAL,
|
||||||
val intervalMinutes: Int = 30,
|
val intervalMinutes: Int = 30,
|
||||||
val dailyTime: String = "02:00",
|
val dailyTime: String = "02:00",
|
||||||
val weekdays: Int = 0b1111111, // all 7 days by default
|
val weekdays: Int = 0b1111111,
|
||||||
// ── Constraints ──────────────────────────────────────────────────────────
|
// ── Constraints ──────────────────────────────────────────────────────────
|
||||||
val wifiOnly: Boolean = true,
|
val wifiOnly: Boolean = true,
|
||||||
val wifiSsid: String = "",
|
val wifiSsid: String = "",
|
||||||
@@ -57,6 +59,7 @@ data class AddPairUiState(
|
|||||||
class AddPairViewModel @Inject constructor(
|
class AddPairViewModel @Inject constructor(
|
||||||
private val syncPairDao: SyncPairDao,
|
private val syncPairDao: SyncPairDao,
|
||||||
private val accountDao: CloudAccountDao,
|
private val accountDao: CloudAccountDao,
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
savedState: SavedStateHandle,
|
savedState: SavedStateHandle,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
@@ -147,7 +150,10 @@ class AddPairViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
if (editPairId == null) syncPairDao.insert(entity) else syncPairDao.update(entity)
|
if (editPairId == null) syncPairDao.insert(entity) else syncPairDao.update(entity)
|
||||||
}
|
}
|
||||||
.onSuccess { _state.update { it.copy(done = true) } }
|
.onSuccess {
|
||||||
|
if (s.scheduleType == ScheduleType.ON_CHANGE) FileWatchService.start(context)
|
||||||
|
_state.update { it.copy(done = true) }
|
||||||
|
}
|
||||||
.onFailure { e -> _state.update { it.copy(isSaving = false, error = e.message) } }
|
.onFailure { e -> _state.update { it.copy(isSaving = false, error = e.message) } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package com.syncflow.ui.auth
|
|||||||
|
|
||||||
import android.accounts.AccountManager
|
import android.accounts.AccountManager
|
||||||
import android.app.Activity
|
import android.app.Activity
|
||||||
|
import android.view.WindowManager
|
||||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.compose.foundation.Image
|
import androidx.compose.foundation.Image
|
||||||
@@ -201,6 +202,15 @@ private fun CredentialContent(
|
|||||||
) {
|
) {
|
||||||
val provider = state.providerType ?: return
|
val provider = state.providerType ?: return
|
||||||
|
|
||||||
|
// Prevent screenshots and screen recording while credentials are visible
|
||||||
|
val activity = LocalContext.current as? Activity
|
||||||
|
DisposableEffect(Unit) {
|
||||||
|
activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
|
||||||
|
onDispose {
|
||||||
|
activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
modifier = modifier
|
modifier = modifier
|
||||||
.padding(horizontal = 20.dp)
|
.padding(horizontal = 20.dp)
|
||||||
|
|||||||
@@ -38,7 +38,9 @@ private fun generateChallenge(verifier: String): String {
|
|||||||
|
|
||||||
fun launchDropboxOAuth(context: Context, credentialStore: CredentialStore, appKey: String) {
|
fun launchDropboxOAuth(context: Context, credentialStore: CredentialStore, appKey: String) {
|
||||||
val verifier = generateVerifier()
|
val verifier = generateVerifier()
|
||||||
|
val state = generateVerifier()
|
||||||
credentialStore.savePkceVerifier("dropbox", verifier)
|
credentialStore.savePkceVerifier("dropbox", verifier)
|
||||||
|
credentialStore.savePkceVerifier("dropbox_state", state)
|
||||||
val challenge = generateChallenge(verifier)
|
val challenge = generateChallenge(verifier)
|
||||||
val url = "https://www.dropbox.com/oauth2/authorize" +
|
val url = "https://www.dropbox.com/oauth2/authorize" +
|
||||||
"?client_id=$appKey" +
|
"?client_id=$appKey" +
|
||||||
@@ -46,13 +48,16 @@ fun launchDropboxOAuth(context: Context, credentialStore: CredentialStore, appKe
|
|||||||
"&redirect_uri=syncflow%3A%2F%2Foauth%2Fdropbox" +
|
"&redirect_uri=syncflow%3A%2F%2Foauth%2Fdropbox" +
|
||||||
"&code_challenge=$challenge" +
|
"&code_challenge=$challenge" +
|
||||||
"&code_challenge_method=S256" +
|
"&code_challenge_method=S256" +
|
||||||
"&token_access_type=offline"
|
"&token_access_type=offline" +
|
||||||
|
"&state=$state"
|
||||||
openCustomTab(context, url)
|
openCustomTab(context, url)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun launchOneDriveOAuth(context: Context, credentialStore: CredentialStore, clientId: String) {
|
fun launchOneDriveOAuth(context: Context, credentialStore: CredentialStore, clientId: String) {
|
||||||
val verifier = generateVerifier()
|
val verifier = generateVerifier()
|
||||||
|
val state = generateVerifier()
|
||||||
credentialStore.savePkceVerifier("onedrive", verifier)
|
credentialStore.savePkceVerifier("onedrive", verifier)
|
||||||
|
credentialStore.savePkceVerifier("onedrive_state", state)
|
||||||
val challenge = generateChallenge(verifier)
|
val challenge = generateChallenge(verifier)
|
||||||
val scopes = "Files.ReadWrite+User.Read+offline_access"
|
val scopes = "Files.ReadWrite+User.Read+offline_access"
|
||||||
val url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize" +
|
val url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize" +
|
||||||
@@ -61,7 +66,8 @@ fun launchOneDriveOAuth(context: Context, credentialStore: CredentialStore, clie
|
|||||||
"&redirect_uri=syncflow%3A%2F%2Foauth%2Fonedrive" +
|
"&redirect_uri=syncflow%3A%2F%2Foauth%2Fonedrive" +
|
||||||
"&scope=$scopes" +
|
"&scope=$scopes" +
|
||||||
"&code_challenge=$challenge" +
|
"&code_challenge=$challenge" +
|
||||||
"&code_challenge_method=S256"
|
"&code_challenge_method=S256" +
|
||||||
|
"&state=$state"
|
||||||
openCustomTab(context, url)
|
openCustomTab(context, url)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,11 +28,22 @@ class OAuthRedirectActivity : ComponentActivity() {
|
|||||||
private fun handleIntent(intent: Intent) {
|
private fun handleIntent(intent: Intent) {
|
||||||
val uri = intent.data ?: run { finish(); return }
|
val uri = intent.data ?: run { finish(); return }
|
||||||
val code = uri.getQueryParameter("code") ?: run { finish(); return }
|
val code = uri.getQueryParameter("code") ?: run { finish(); return }
|
||||||
|
val returnedState = uri.getQueryParameter("state") ?: run { finish(); return }
|
||||||
|
|
||||||
val provider = when {
|
val provider = when {
|
||||||
uri.host == "oauth" && uri.path?.contains("dropbox") == true -> "dropbox"
|
uri.host == "oauth" && uri.path?.contains("dropbox") == true -> "dropbox"
|
||||||
uri.host == "oauth" && uri.path?.contains("onedrive") == true -> "onedrive"
|
uri.host == "oauth" && uri.path?.contains("onedrive") == true -> "onedrive"
|
||||||
else -> run { finish(); return }
|
else -> run { finish(); return }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate state before doing anything with the code (CSRF protection)
|
||||||
|
val storedState = credentialStore.getPkceVerifier("${provider}_state")
|
||||||
|
if (storedState == null || returnedState != storedState) {
|
||||||
|
finish()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
credentialStore.removePkceVerifier("${provider}_state")
|
||||||
|
|
||||||
val appKey = getString(com.syncflow.R.string.dropbox_app_key)
|
val appKey = getString(com.syncflow.R.string.dropbox_app_key)
|
||||||
val odClientId = getString(com.syncflow.R.string.onedrive_client_id)
|
val odClientId = getString(com.syncflow.R.string.onedrive_client_id)
|
||||||
lifecycleScope.launch {
|
lifecycleScope.launch {
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ fun RemoteBrowserDialog(
|
|||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
vm: RemoteBrowserViewModel = hiltViewModel(),
|
vm: RemoteBrowserViewModel = hiltViewModel(),
|
||||||
) {
|
) {
|
||||||
LaunchedEffect(accountId) { vm.init(accountId, initialPath) }
|
LaunchedEffect(accountId, initialPath) { vm.init(accountId, initialPath) }
|
||||||
|
|
||||||
val state by vm.state.collectAsState()
|
val state by vm.state.collectAsState()
|
||||||
|
|
||||||
@@ -81,6 +81,7 @@ fun RemoteBrowserDialog(
|
|||||||
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Icon(Icons.Default.ErrorOutline, null, Modifier.size(48.dp), tint = MaterialTheme.colorScheme.error)
|
Icon(Icons.Default.ErrorOutline, null, Modifier.size(48.dp), tint = MaterialTheme.colorScheme.error)
|
||||||
Text(state.error!!, color = MaterialTheme.colorScheme.error)
|
Text(state.error!!, color = MaterialTheme.colorScheme.error)
|
||||||
|
FilledTonalButton(onClick = { vm.retry() }) { Text("Retry") }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
state.entries.isEmpty() -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
state.entries.isEmpty() -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import com.syncflow.data.providers.ProviderFactory
|
|||||||
import com.syncflow.data.repository.AccountRepository
|
import com.syncflow.data.repository.AccountRepository
|
||||||
import com.syncflow.domain.model.RemoteFile
|
import com.syncflow.domain.model.RemoteFile
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.flow.asStateFlow
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
@@ -30,15 +31,19 @@ class RemoteBrowserViewModel @Inject constructor(
|
|||||||
private val _state = MutableStateFlow(BrowserState())
|
private val _state = MutableStateFlow(BrowserState())
|
||||||
val state = _state.asStateFlow()
|
val state = _state.asStateFlow()
|
||||||
|
|
||||||
|
private var loadJob: Job? = null
|
||||||
|
|
||||||
fun init(accountId: Long, startPath: String = "/") {
|
fun init(accountId: Long, startPath: String = "/") {
|
||||||
_state.update { it.copy(accountId = accountId, currentPath = startPath, pathStack = listOf(startPath)) }
|
loadJob?.cancel()
|
||||||
loadPath(accountId, startPath)
|
_state.value = BrowserState(accountId = accountId, currentPath = startPath, pathStack = listOf(startPath), isLoading = true)
|
||||||
|
loadJob = loadPath(accountId, startPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun navigateTo(path: String) {
|
fun navigateTo(path: String) {
|
||||||
val accountId = _state.value.accountId
|
val accountId = _state.value.accountId
|
||||||
_state.update { s -> s.copy(currentPath = path, pathStack = s.pathStack + path) }
|
loadJob?.cancel()
|
||||||
loadPath(accountId, path)
|
_state.update { s -> s.copy(currentPath = path, pathStack = s.pathStack + path, isLoading = true, entries = emptyList(), error = null) }
|
||||||
|
loadJob = loadPath(accountId, path)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun navigateUp(): Boolean {
|
fun navigateUp(): Boolean {
|
||||||
@@ -46,30 +51,36 @@ class RemoteBrowserViewModel @Inject constructor(
|
|||||||
if (stack.size <= 1) return false
|
if (stack.size <= 1) return false
|
||||||
val newStack = stack.dropLast(1)
|
val newStack = stack.dropLast(1)
|
||||||
val parent = newStack.last()
|
val parent = newStack.last()
|
||||||
_state.update { it.copy(currentPath = parent, pathStack = newStack) }
|
loadJob?.cancel()
|
||||||
loadPath(_state.value.accountId, parent)
|
_state.update { it.copy(currentPath = parent, pathStack = newStack, isLoading = true, entries = emptyList(), error = null) }
|
||||||
|
loadJob = loadPath(_state.value.accountId, parent)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun loadPath(accountId: Long, path: String) {
|
fun retry() {
|
||||||
viewModelScope.launch {
|
val s = _state.value
|
||||||
_state.update { it.copy(isLoading = true, error = null) }
|
if (s.accountId == -1L) return
|
||||||
val account = accountRepository.getAccount(accountId)
|
loadJob?.cancel()
|
||||||
if (account == null) {
|
_state.update { it.copy(isLoading = true, error = null) }
|
||||||
_state.update { it.copy(isLoading = false, error = "Account not found") }
|
loadJob = loadPath(s.accountId, s.currentPath)
|
||||||
return@launch
|
}
|
||||||
}
|
|
||||||
val provider = runCatching { providerFactory.create(account) }.getOrElse { e ->
|
private fun loadPath(accountId: Long, path: String): Job = viewModelScope.launch {
|
||||||
_state.update { it.copy(isLoading = false, error = e.message) }
|
val account = accountRepository.getAccount(accountId)
|
||||||
return@launch
|
if (account == null) {
|
||||||
}
|
_state.update { it.copy(isLoading = false, error = "Account not found") }
|
||||||
provider.listFiles(path)
|
return@launch
|
||||||
.onSuccess { files ->
|
|
||||||
_state.update { it.copy(isLoading = false, entries = files.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() }))) }
|
|
||||||
}
|
|
||||||
.onFailure { e ->
|
|
||||||
_state.update { it.copy(isLoading = false, error = e.message ?: "Failed to list files") }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
val provider = runCatching { providerFactory.create(account) }.getOrElse { e ->
|
||||||
|
_state.update { it.copy(isLoading = false, error = e.message ?: "Failed to create provider") }
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
provider.listFiles(path)
|
||||||
|
.onSuccess { files ->
|
||||||
|
_state.update { it.copy(isLoading = false, entries = files.sortedWith(compareBy({ !it.isDirectory }, { it.name.lowercase() }))) }
|
||||||
|
}
|
||||||
|
.onFailure { e ->
|
||||||
|
_state.update { it.copy(isLoading = false, error = e.message ?: "Failed to list files") }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
package com.syncflow.ui.home
|
package com.syncflow.ui.home
|
||||||
|
|
||||||
|
import androidx.compose.animation.core.LinearEasing
|
||||||
|
import androidx.compose.animation.core.animateFloat
|
||||||
|
import androidx.compose.animation.core.infiniteRepeatable
|
||||||
|
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
import androidx.compose.foundation.BorderStroke
|
import androidx.compose.foundation.BorderStroke
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
@@ -14,6 +19,7 @@ import androidx.compose.runtime.*
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import com.syncflow.data.db.entities.SyncPairEntity
|
import com.syncflow.data.db.entities.SyncPairEntity
|
||||||
@@ -159,8 +165,18 @@ private fun SyncPairCard(
|
|||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
val syncRotation by rememberInfiniteTransition(label = "cardSyncSpin").animateFloat(
|
||||||
|
initialValue = 0f, targetValue = 360f,
|
||||||
|
animationSpec = infiniteRepeatable(tween(900, easing = LinearEasing)),
|
||||||
|
label = "cardRotation",
|
||||||
|
)
|
||||||
FilledTonalIconButton(onClick = onSync, modifier = Modifier.size(36.dp)) {
|
FilledTonalIconButton(onClick = onSync, modifier = Modifier.size(36.dp)) {
|
||||||
Icon(Icons.Default.Sync, "Sync now", modifier = Modifier.size(18.dp))
|
Icon(
|
||||||
|
Icons.Default.Sync, "Sync now",
|
||||||
|
modifier = Modifier.size(18.dp).graphicsLayer {
|
||||||
|
if (pair.lastSyncResult == SyncStatus.SYNCING) rotationZ = syncRotation
|
||||||
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -179,10 +195,11 @@ private fun StatusPill(status: SyncStatus) {
|
|||||||
SyncStatus.IDLE -> Pair(Icons.Outlined.Circle, "Idle")
|
SyncStatus.IDLE -> Pair(Icons.Outlined.Circle, "Idle")
|
||||||
}
|
}
|
||||||
val containerColor = status.accentColor
|
val containerColor = status.accentColor
|
||||||
val contentColor = when (status) {
|
val rotation by rememberInfiniteTransition(label = "syncSpin").animateFloat(
|
||||||
SyncStatus.IDLE -> MaterialTheme.colorScheme.onSurfaceVariant
|
initialValue = 0f, targetValue = 360f,
|
||||||
else -> MaterialTheme.colorScheme.surface
|
animationSpec = infiniteRepeatable(tween(1000, easing = LinearEasing)),
|
||||||
}
|
label = "rotation",
|
||||||
|
)
|
||||||
Surface(
|
Surface(
|
||||||
shape = RoundedCornerShape(50),
|
shape = RoundedCornerShape(50),
|
||||||
color = containerColor.copy(alpha = 0.15f),
|
color = containerColor.copy(alpha = 0.15f),
|
||||||
@@ -192,7 +209,11 @@ private fun StatusPill(status: SyncStatus) {
|
|||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
) {
|
) {
|
||||||
Icon(icon, null, Modifier.size(12.dp), tint = containerColor)
|
Icon(
|
||||||
|
icon, null,
|
||||||
|
Modifier.size(12.dp).graphicsLayer { if (status == SyncStatus.SYNCING) rotationZ = rotation },
|
||||||
|
tint = containerColor,
|
||||||
|
)
|
||||||
Text(label, style = MaterialTheme.typography.labelSmall, color = containerColor)
|
Text(label, style = MaterialTheme.typography.labelSmall, color = containerColor)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
package com.syncflow.ui.home
|
package com.syncflow.ui.home
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
import androidx.lifecycle.ViewModel
|
import androidx.lifecycle.ViewModel
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import androidx.work.ExistingPeriodicWorkPolicy
|
||||||
import androidx.work.WorkManager
|
import androidx.work.WorkManager
|
||||||
import com.syncflow.data.db.SyncPairDao
|
import com.syncflow.data.db.SyncPairDao
|
||||||
import com.syncflow.data.db.entities.SyncPairEntity
|
import com.syncflow.data.db.entities.SyncPairEntity
|
||||||
import com.syncflow.domain.model.ScheduleType
|
import com.syncflow.domain.model.ScheduleType
|
||||||
|
import com.syncflow.worker.FileWatchService
|
||||||
import com.syncflow.worker.SyncWorker
|
import com.syncflow.worker.SyncWorker
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
@@ -17,6 +21,7 @@ import javax.inject.Inject
|
|||||||
class HomeViewModel @Inject constructor(
|
class HomeViewModel @Inject constructor(
|
||||||
private val syncPairDao: SyncPairDao,
|
private val syncPairDao: SyncPairDao,
|
||||||
private val workManager: WorkManager,
|
private val workManager: WorkManager,
|
||||||
|
@ApplicationContext private val context: Context,
|
||||||
) : ViewModel() {
|
) : ViewModel() {
|
||||||
|
|
||||||
val syncPairs = syncPairDao.observeAll()
|
val syncPairs = syncPairDao.observeAll()
|
||||||
@@ -29,21 +34,28 @@ class HomeViewModel @Inject constructor(
|
|||||||
|
|
||||||
fun toggleEnabled(pair: SyncPairEntity) {
|
fun toggleEnabled(pair: SyncPairEntity) {
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
syncPairDao.update(pair.copy(isEnabled = !pair.isEnabled))
|
val nowEnabled = !pair.isEnabled
|
||||||
if (!pair.isEnabled && pair.scheduleType != ScheduleType.MANUAL) {
|
syncPairDao.update(pair.copy(isEnabled = nowEnabled))
|
||||||
val req = SyncWorker.buildPeriodicRequest(
|
if (nowEnabled) {
|
||||||
pair.id,
|
when (pair.scheduleType) {
|
||||||
pair.scheduleIntervalMinutes.toLong().coerceAtLeast(15),
|
ScheduleType.ON_CHANGE -> FileWatchService.start(context)
|
||||||
pair.wifiOnly,
|
ScheduleType.MANUAL -> { /* nothing */ }
|
||||||
pair.chargingOnly,
|
else -> {
|
||||||
)
|
val req = SyncWorker.buildPeriodicRequest(
|
||||||
workManager.enqueueUniquePeriodicWork(
|
pair.id,
|
||||||
"periodic_${pair.id}",
|
pair.scheduleIntervalMinutes.toLong().coerceAtLeast(15),
|
||||||
androidx.work.ExistingPeriodicWorkPolicy.UPDATE,
|
pair.wifiOnly,
|
||||||
req,
|
pair.chargingOnly,
|
||||||
)
|
)
|
||||||
|
workManager.enqueueUniquePeriodicWork("periodic_${pair.id}", ExistingPeriodicWorkPolicy.UPDATE, req)
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
workManager.cancelAllWorkByTag("sync_${pair.id}")
|
workManager.cancelAllWorkByTag("sync_${pair.id}")
|
||||||
|
// Refresh watcher (it will stop itself if no ON_CHANGE pairs remain)
|
||||||
|
if (pair.scheduleType == ScheduleType.ON_CHANGE) {
|
||||||
|
FileWatchService.start(context)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,178 @@
|
|||||||
|
package com.syncflow.ui.log
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.*
|
||||||
|
import androidx.compose.material.icons.outlined.Circle
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.vector.ImageVector
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
|
import com.syncflow.domain.model.SyncEventType
|
||||||
|
import java.time.Duration
|
||||||
|
import java.time.Instant
|
||||||
|
import java.time.ZoneId
|
||||||
|
import java.time.format.DateTimeFormatter
|
||||||
|
import java.time.format.FormatStyle
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun LogScreen(
|
||||||
|
modifier: Modifier = Modifier,
|
||||||
|
vm: LogViewModel = hiltViewModel(),
|
||||||
|
) {
|
||||||
|
val entries by vm.entries.collectAsState()
|
||||||
|
|
||||||
|
if (entries.isEmpty()) {
|
||||||
|
Box(
|
||||||
|
modifier = modifier.fillMaxSize(),
|
||||||
|
contentAlignment = Alignment.Center,
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||||
|
) {
|
||||||
|
Icon(
|
||||||
|
Icons.Default.Notifications,
|
||||||
|
contentDescription = null,
|
||||||
|
modifier = Modifier.size(72.dp),
|
||||||
|
tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.35f),
|
||||||
|
)
|
||||||
|
Text("No activity yet", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text(
|
||||||
|
"Sync events will appear here",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
LazyColumn(
|
||||||
|
modifier = modifier.fillMaxSize(),
|
||||||
|
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(0.dp),
|
||||||
|
) {
|
||||||
|
// Group entries by calendar date
|
||||||
|
val grouped = entries.groupBy { entry ->
|
||||||
|
entry.event.timestamp.atZone(ZoneId.systemDefault()).toLocalDate()
|
||||||
|
}
|
||||||
|
grouped.forEach { (date, dayEntries) ->
|
||||||
|
item(key = date.toString()) {
|
||||||
|
Text(
|
||||||
|
text = date.toRelativeLabel(),
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.padding(top = 16.dp, bottom = 4.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
items(dayEntries, key = { it.event.id }) { entry ->
|
||||||
|
LogEntryRow(entry)
|
||||||
|
HorizontalDivider(
|
||||||
|
color = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
|
||||||
|
modifier = Modifier.padding(start = 52.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
item { Spacer(Modifier.height(80.dp)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LogEntryRow(entry: LogEntry) {
|
||||||
|
val (icon, tint) = entry.event.eventType.iconAndTint()
|
||||||
|
val timeFmt = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
|
||||||
|
val timeStr = entry.event.timestamp.atZone(ZoneId.systemDefault()).let { timeFmt.format(it) }
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(vertical = 10.dp),
|
||||||
|
verticalAlignment = Alignment.Top,
|
||||||
|
) {
|
||||||
|
// Icon bubble
|
||||||
|
Surface(
|
||||||
|
shape = RoundedCornerShape(10.dp),
|
||||||
|
color = tint.copy(alpha = 0.12f),
|
||||||
|
modifier = Modifier.size(36.dp),
|
||||||
|
) {
|
||||||
|
Box(contentAlignment = Alignment.Center) {
|
||||||
|
Icon(icon, contentDescription = null, Modifier.size(18.dp), tint = tint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(Modifier.width(12.dp))
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
entry.pairName,
|
||||||
|
style = MaterialTheme.typography.labelMedium,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.weight(1f, fill = false),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
timeStr,
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(Modifier.height(2.dp))
|
||||||
|
Text(
|
||||||
|
text = entry.event.eventType.label(),
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
)
|
||||||
|
val detail = entry.event.filePath ?: entry.event.message
|
||||||
|
if (detail != null) {
|
||||||
|
Text(
|
||||||
|
text = detail,
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
maxLines = 1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun SyncEventType.iconAndTint(): Pair<ImageVector, Color> = when (this) {
|
||||||
|
SyncEventType.SYNC_STARTED -> Icons.Default.Sync to MaterialTheme.colorScheme.secondary
|
||||||
|
SyncEventType.SYNC_COMPLETED -> Icons.Default.CheckCircle to MaterialTheme.colorScheme.primary
|
||||||
|
SyncEventType.SYNC_FAILED -> Icons.Default.Error to MaterialTheme.colorScheme.error
|
||||||
|
SyncEventType.FILE_UPLOADED -> Icons.Default.CloudUpload to MaterialTheme.colorScheme.secondary
|
||||||
|
SyncEventType.FILE_DOWNLOADED -> Icons.Default.CloudDownload to MaterialTheme.colorScheme.secondary
|
||||||
|
SyncEventType.FILE_DELETED -> Icons.Default.DeleteForever to MaterialTheme.colorScheme.tertiary
|
||||||
|
SyncEventType.FILE_SKIPPED -> Icons.Outlined.Circle to MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
SyncEventType.CONFLICT_DETECTED -> Icons.Default.Warning to MaterialTheme.colorScheme.tertiary
|
||||||
|
SyncEventType.CONFLICT_RESOLVED -> Icons.Default.CheckCircle to MaterialTheme.colorScheme.primary
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun SyncEventType.label(): String = when (this) {
|
||||||
|
SyncEventType.SYNC_STARTED -> "Sync started"
|
||||||
|
SyncEventType.SYNC_COMPLETED -> "Sync completed"
|
||||||
|
SyncEventType.SYNC_FAILED -> "Sync failed"
|
||||||
|
SyncEventType.FILE_UPLOADED -> "File uploaded"
|
||||||
|
SyncEventType.FILE_DOWNLOADED -> "File downloaded"
|
||||||
|
SyncEventType.FILE_DELETED -> "File deleted"
|
||||||
|
SyncEventType.FILE_SKIPPED -> "File skipped"
|
||||||
|
SyncEventType.CONFLICT_DETECTED -> "Conflict detected"
|
||||||
|
SyncEventType.CONFLICT_RESOLVED -> "Conflict resolved"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun java.time.LocalDate.toRelativeLabel(): String {
|
||||||
|
val today = java.time.LocalDate.now()
|
||||||
|
return when {
|
||||||
|
this == today -> "Today"
|
||||||
|
this == today.minusDays(1) -> "Yesterday"
|
||||||
|
else -> DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.syncflow.ui.log
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import com.syncflow.data.db.SyncEventDao
|
||||||
|
import com.syncflow.data.db.SyncPairDao
|
||||||
|
import com.syncflow.data.db.entities.SyncEventEntity
|
||||||
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
data class LogEntry(val event: SyncEventEntity, val pairName: String)
|
||||||
|
|
||||||
|
@HiltViewModel
|
||||||
|
class LogViewModel @Inject constructor(
|
||||||
|
syncEventDao: SyncEventDao,
|
||||||
|
syncPairDao: SyncPairDao,
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
|
val entries = combine(
|
||||||
|
syncEventDao.observeAll(500),
|
||||||
|
syncPairDao.observeAll(),
|
||||||
|
) { events, pairs ->
|
||||||
|
val pairNames = pairs.associateBy({ it.id }, { it.name })
|
||||||
|
events.map { LogEntry(it, pairNames[it.syncPairId] ?: "Unknown") }
|
||||||
|
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
|
||||||
|
}
|
||||||
@@ -20,8 +20,10 @@ import androidx.compose.foundation.pager.rememberPagerState
|
|||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.filled.Add
|
import androidx.compose.material.icons.filled.Add
|
||||||
import androidx.compose.material.icons.filled.ManageAccounts
|
import androidx.compose.material.icons.filled.ManageAccounts
|
||||||
|
import androidx.compose.material.icons.filled.Notifications
|
||||||
import androidx.compose.material.icons.filled.Sync
|
import androidx.compose.material.icons.filled.Sync
|
||||||
import androidx.compose.material.icons.outlined.ManageAccounts
|
import androidx.compose.material.icons.outlined.ManageAccounts
|
||||||
|
import androidx.compose.material.icons.outlined.NotificationsNone
|
||||||
import androidx.compose.material.icons.outlined.Sync
|
import androidx.compose.material.icons.outlined.Sync
|
||||||
import androidx.compose.material3.*
|
import androidx.compose.material3.*
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
@@ -32,6 +34,7 @@ import androidx.compose.ui.res.painterResource
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import com.syncflow.R
|
import com.syncflow.R
|
||||||
import com.syncflow.ui.home.HomeScreen
|
import com.syncflow.ui.home.HomeScreen
|
||||||
|
import com.syncflow.ui.log.LogScreen
|
||||||
import com.syncflow.ui.settings.SettingsScreen
|
import com.syncflow.ui.settings.SettingsScreen
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
@@ -42,7 +45,7 @@ fun MainShell(
|
|||||||
onPairClick: (Long) -> Unit,
|
onPairClick: (Long) -> Unit,
|
||||||
onAddAccount: () -> Unit,
|
onAddAccount: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val pagerState = rememberPagerState(pageCount = { 2 })
|
val pagerState = rememberPagerState(pageCount = { 3 })
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val currentPage = pagerState.currentPage
|
val currentPage = pagerState.currentPage
|
||||||
|
|
||||||
@@ -88,7 +91,18 @@ fun MainShell(
|
|||||||
onClick = { scope.launch { pagerState.animateScrollToPage(1) } },
|
onClick = { scope.launch { pagerState.animateScrollToPage(1) } },
|
||||||
icon = {
|
icon = {
|
||||||
Icon(
|
Icon(
|
||||||
if (currentPage == 1) Icons.Filled.ManageAccounts else Icons.Outlined.ManageAccounts,
|
if (currentPage == 1) Icons.Filled.Notifications else Icons.Outlined.NotificationsNone,
|
||||||
|
contentDescription = null,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
label = { Text("Log") },
|
||||||
|
)
|
||||||
|
NavigationBarItem(
|
||||||
|
selected = currentPage == 2,
|
||||||
|
onClick = { scope.launch { pagerState.animateScrollToPage(2) } },
|
||||||
|
icon = {
|
||||||
|
Icon(
|
||||||
|
if (currentPage == 2) Icons.Filled.ManageAccounts else Icons.Outlined.ManageAccounts,
|
||||||
contentDescription = null,
|
contentDescription = null,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
@@ -120,7 +134,8 @@ fun MainShell(
|
|||||||
) { page ->
|
) { page ->
|
||||||
when (page) {
|
when (page) {
|
||||||
0 -> HomeScreen(onAddPair = onAddPair, onPairClick = onPairClick)
|
0 -> HomeScreen(onAddPair = onAddPair, onPairClick = onPairClick)
|
||||||
1 -> SettingsScreen(onAddAccount = onAddAccount)
|
1 -> LogScreen()
|
||||||
|
2 -> SettingsScreen(onAddAccount = onAddAccount)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
package com.syncflow.ui.pairdetail
|
package com.syncflow.ui.pairdetail
|
||||||
|
|
||||||
|
import androidx.compose.animation.core.LinearEasing
|
||||||
|
import androidx.compose.animation.core.animateFloat
|
||||||
|
import androidx.compose.animation.core.infiniteRepeatable
|
||||||
|
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
import androidx.compose.foundation.lazy.items
|
import androidx.compose.foundation.lazy.items
|
||||||
@@ -13,6 +18,7 @@ import androidx.compose.ui.Alignment
|
|||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
import androidx.compose.ui.draw.clip
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.hilt.navigation.compose.hiltViewModel
|
import androidx.hilt.navigation.compose.hiltViewModel
|
||||||
import com.syncflow.data.db.entities.SyncEventEntity
|
import com.syncflow.data.db.entities.SyncEventEntity
|
||||||
@@ -143,6 +149,11 @@ private fun StatusBanner(pair: SyncPairEntity) {
|
|||||||
SyncStatus.PARTIAL -> Triple(Icons.Default.WarningAmber,"Partial", MaterialTheme.colorScheme.tertiaryContainer)
|
SyncStatus.PARTIAL -> Triple(Icons.Default.WarningAmber,"Partial", MaterialTheme.colorScheme.tertiaryContainer)
|
||||||
SyncStatus.IDLE -> Triple(Icons.Outlined.Circle, "Idle", MaterialTheme.colorScheme.surfaceVariant)
|
SyncStatus.IDLE -> Triple(Icons.Outlined.Circle, "Idle", MaterialTheme.colorScheme.surfaceVariant)
|
||||||
}
|
}
|
||||||
|
val rotation by rememberInfiniteTransition(label = "bannerSpin").animateFloat(
|
||||||
|
initialValue = 0f, targetValue = 360f,
|
||||||
|
animationSpec = infiniteRepeatable(tween(1000, easing = LinearEasing)),
|
||||||
|
label = "bannerRotation",
|
||||||
|
)
|
||||||
Surface(
|
Surface(
|
||||||
color = containerColor,
|
color = containerColor,
|
||||||
shape = RoundedCornerShape(16.dp),
|
shape = RoundedCornerShape(16.dp),
|
||||||
@@ -152,7 +163,12 @@ private fun StatusBanner(pair: SyncPairEntity) {
|
|||||||
modifier = Modifier.padding(16.dp),
|
modifier = Modifier.padding(16.dp),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
) {
|
) {
|
||||||
Icon(icon, null, modifier = Modifier.size(40.dp))
|
Icon(
|
||||||
|
icon, null,
|
||||||
|
modifier = Modifier.size(40.dp).graphicsLayer {
|
||||||
|
if (pair.lastSyncResult == SyncStatus.SYNCING) rotationZ = rotation
|
||||||
|
},
|
||||||
|
)
|
||||||
Spacer(Modifier.width(16.dp))
|
Spacer(Modifier.width(16.dp))
|
||||||
Column {
|
Column {
|
||||||
Text(label, style = MaterialTheme.typography.titleMedium)
|
Text(label, style = MaterialTheme.typography.titleMedium)
|
||||||
|
|||||||
@@ -137,11 +137,17 @@ fun SettingsScreen(
|
|||||||
) {
|
) {
|
||||||
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
|
||||||
Text(
|
Text(
|
||||||
"SyncFlow v${com.syncflow.BuildConfig.VERSION_NAME} — Free, no subscription.",
|
"SyncFlow",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.titleSmall,
|
||||||
)
|
)
|
||||||
Text(
|
Text(
|
||||||
"Open source. No ads. No tracking.",
|
"Version ${com.syncflow.BuildConfig.VERSION_NAME} (build ${com.syncflow.BuildConfig.VERSION_CODE})",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(2.dp))
|
||||||
|
Text(
|
||||||
|
"Free, no subscription. No ads. No tracking.",
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.syncflow.worker
|
|||||||
import android.content.BroadcastReceiver
|
import android.content.BroadcastReceiver
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import androidx.work.ExistingPeriodicWorkPolicy
|
||||||
import androidx.work.WorkManager
|
import androidx.work.WorkManager
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
@@ -22,17 +23,24 @@ class BootReceiver : BroadcastReceiver() {
|
|||||||
val pending = goAsync()
|
val pending = goAsync()
|
||||||
CoroutineScope(Dispatchers.IO).launch {
|
CoroutineScope(Dispatchers.IO).launch {
|
||||||
try {
|
try {
|
||||||
syncPairDao.getEnabled()
|
val pairs = syncPairDao.getEnabled()
|
||||||
.filter { it.scheduleType != ScheduleType.MANUAL && it.scheduleType != ScheduleType.ON_CHANGE }
|
var hasOnChange = false
|
||||||
.forEach { pair ->
|
pairs.forEach { pair ->
|
||||||
val req = SyncWorker.buildPeriodicRequest(
|
when (pair.scheduleType) {
|
||||||
pair.id,
|
ScheduleType.ON_CHANGE -> hasOnChange = true
|
||||||
pair.scheduleIntervalMinutes.toLong().coerceAtLeast(15),
|
ScheduleType.MANUAL -> { /* nothing */ }
|
||||||
pair.wifiOnly,
|
else -> {
|
||||||
pair.chargingOnly,
|
val req = SyncWorker.buildPeriodicRequest(
|
||||||
)
|
pair.id,
|
||||||
wm.enqueueUniquePeriodicWork("periodic_${pair.id}", androidx.work.ExistingPeriodicWorkPolicy.UPDATE, req)
|
pair.scheduleIntervalMinutes.toLong().coerceAtLeast(15),
|
||||||
|
pair.wifiOnly,
|
||||||
|
pair.chargingOnly,
|
||||||
|
)
|
||||||
|
wm.enqueueUniquePeriodicWork("periodic_${pair.id}", ExistingPeriodicWorkPolicy.UPDATE, req)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
if (hasOnChange) FileWatchService.start(context)
|
||||||
} finally {
|
} finally {
|
||||||
pending.finish()
|
pending.finish()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,213 @@
|
|||||||
|
package com.syncflow.worker
|
||||||
|
|
||||||
|
import android.app.*
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.database.ContentObserver
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.FileObserver
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.IBinder
|
||||||
|
import android.os.Looper
|
||||||
|
import android.provider.DocumentsContract
|
||||||
|
import androidx.core.app.NotificationCompat
|
||||||
|
import androidx.work.ExistingWorkPolicy
|
||||||
|
import androidx.work.WorkManager
|
||||||
|
import com.syncflow.MainActivity
|
||||||
|
import com.syncflow.R
|
||||||
|
import com.syncflow.data.db.SyncPairDao
|
||||||
|
import com.syncflow.domain.model.ScheduleType
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import timber.log.Timber
|
||||||
|
import java.io.File
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class FileWatchService : Service() {
|
||||||
|
|
||||||
|
@Inject lateinit var syncPairDao: SyncPairDao
|
||||||
|
|
||||||
|
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||||
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
|
private val fileObservers = mutableMapOf<Long, FileObserver>()
|
||||||
|
private val contentObservers = mutableMapOf<Long, ContentObserver>()
|
||||||
|
private val debounceJobs = mutableMapOf<Long, Job>()
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val CHANNEL_WATCH = "sync_watching"
|
||||||
|
private const val NOTIFICATION_ID = 1002
|
||||||
|
|
||||||
|
fun start(context: Context) {
|
||||||
|
val intent = Intent(context, FileWatchService::class.java)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
context.startForegroundService(intent)
|
||||||
|
} else {
|
||||||
|
context.startService(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop(context: Context) {
|
||||||
|
context.stopService(Intent(context, FileWatchService::class.java))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
ensureChannel()
|
||||||
|
startForeground(NOTIFICATION_ID, buildNotification(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
|
scope.launch { refresh() }
|
||||||
|
return START_STICKY
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
clearWatchers()
|
||||||
|
scope.cancel()
|
||||||
|
super.onDestroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
|
private suspend fun refresh() {
|
||||||
|
clearWatchers()
|
||||||
|
val pairs = syncPairDao.getEnabled().filter { it.scheduleType == ScheduleType.ON_CHANGE }
|
||||||
|
|
||||||
|
pairs.forEach { pair ->
|
||||||
|
val pairId = pair.id
|
||||||
|
val localPath = pair.localPath
|
||||||
|
|
||||||
|
if (localPath.startsWith("content://")) {
|
||||||
|
// Try to resolve the SAF tree URI to a real filesystem path so we can use
|
||||||
|
// FileObserver. ContentObserver on a DocumentsProvider tree URI only fires
|
||||||
|
// when changes come through the SAF API, not for raw filesystem writes.
|
||||||
|
val realPath = safTreeUriToRealPath(localPath)
|
||||||
|
if (realPath != null) {
|
||||||
|
watchPath(realPath, pairId, pair.wifiOnly, pair.chargingOnly)
|
||||||
|
} else {
|
||||||
|
// Fallback: register a ContentObserver for SAF paths that can't be resolved
|
||||||
|
val treeUri = Uri.parse(localPath)
|
||||||
|
val observer = object : ContentObserver(mainHandler) {
|
||||||
|
override fun onChange(selfChange: Boolean) = onChangeDetected(pairId, pair.wifiOnly, pair.chargingOnly)
|
||||||
|
override fun onChange(selfChange: Boolean, uri: Uri?) = onChangeDetected(pairId, pair.wifiOnly, pair.chargingOnly)
|
||||||
|
}
|
||||||
|
contentResolver.registerContentObserver(treeUri, true, observer)
|
||||||
|
contentObservers[pairId] = observer
|
||||||
|
Timber.d("FileWatchService: watching SAF URI (ContentObserver fallback) for pair $pairId")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
watchPath(localPath, pairId, pair.wifiOnly, pair.chargingOnly)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val count = fileObservers.size + contentObservers.size
|
||||||
|
updateNotification(count)
|
||||||
|
|
||||||
|
if (count == 0) {
|
||||||
|
Timber.d("FileWatchService: no ON_CHANGE pairs, stopping")
|
||||||
|
stopSelf()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun safTreeUriToRealPath(uriString: String): String? {
|
||||||
|
return try {
|
||||||
|
val treeUri = Uri.parse(uriString)
|
||||||
|
val docId = DocumentsContract.getTreeDocumentId(treeUri)
|
||||||
|
// docId format is "primary:RelativePath" for primary internal storage
|
||||||
|
if (docId.startsWith("primary:")) {
|
||||||
|
val relative = docId.removePrefix("primary:")
|
||||||
|
"/storage/emulated/0/$relative"
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Timber.w("FileWatchService: could not resolve SAF URI to real path: $e")
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun watchPath(path: String, pairId: Long, wifiOnly: Boolean, chargingOnly: Boolean) {
|
||||||
|
val dir = File(path)
|
||||||
|
if (!dir.exists()) {
|
||||||
|
Timber.w("FileWatchService: path does not exist for pair $pairId: $path")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val mask = FileObserver.CREATE or FileObserver.DELETE or FileObserver.MODIFY or
|
||||||
|
FileObserver.MOVED_FROM or FileObserver.MOVED_TO
|
||||||
|
val observer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
|
object : FileObserver(dir, mask) {
|
||||||
|
override fun onEvent(event: Int, p: String?) = onChangeDetected(pairId, wifiOnly, chargingOnly)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
object : FileObserver(path, mask) {
|
||||||
|
override fun onEvent(event: Int, p: String?) = onChangeDetected(pairId, wifiOnly, chargingOnly)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
observer.startWatching()
|
||||||
|
fileObservers[pairId] = observer
|
||||||
|
Timber.d("FileWatchService: watching filesystem path for pair $pairId: $path")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onChangeDetected(pairId: Long, wifiOnly: Boolean, chargingOnly: Boolean) {
|
||||||
|
debounceJobs[pairId]?.cancel()
|
||||||
|
debounceJobs[pairId] = scope.launch {
|
||||||
|
delay(5_000)
|
||||||
|
val pair = syncPairDao.getById(pairId)
|
||||||
|
if (pair == null || !pair.isEnabled) return@launch
|
||||||
|
Timber.d("FileWatchService: triggering sync for pair $pairId after debounce")
|
||||||
|
val req = SyncWorker.buildOneTimeRequest(pairId, wifiOnly, chargingOnly)
|
||||||
|
WorkManager.getInstance(applicationContext)
|
||||||
|
.enqueueUniqueWork("onchange_$pairId", ExistingWorkPolicy.KEEP, req)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clearWatchers() {
|
||||||
|
fileObservers.values.forEach { it.stopWatching() }
|
||||||
|
fileObservers.clear()
|
||||||
|
contentObservers.values.forEach { contentResolver.unregisterContentObserver(it) }
|
||||||
|
contentObservers.clear()
|
||||||
|
debounceJobs.values.forEach { it.cancel() }
|
||||||
|
debounceJobs.clear()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ensureChannel() {
|
||||||
|
val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
if (nm.getNotificationChannel(CHANNEL_WATCH) == null) {
|
||||||
|
nm.createNotificationChannel(
|
||||||
|
NotificationChannel(CHANNEL_WATCH, "File watching", NotificationManager.IMPORTANCE_LOW).apply {
|
||||||
|
description = "Background service watching folders for changes"
|
||||||
|
setShowBadge(false)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildNotification(count: Int): Notification {
|
||||||
|
val tapIntent = PendingIntent.getActivity(
|
||||||
|
this, 0,
|
||||||
|
Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_SINGLE_TOP },
|
||||||
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
|
)
|
||||||
|
return NotificationCompat.Builder(this, CHANNEL_WATCH)
|
||||||
|
.setContentTitle("SyncFlow")
|
||||||
|
.setContentText(
|
||||||
|
if (count > 0) "Watching $count folder${if (count != 1) "s" else ""} for changes"
|
||||||
|
else "Starting file watcher…"
|
||||||
|
)
|
||||||
|
.setSmallIcon(R.drawable.ic_sync)
|
||||||
|
.setContentIntent(tapIntent)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setPriority(NotificationCompat.PRIORITY_MIN)
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateNotification(count: Int) {
|
||||||
|
val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
|
nm.notify(NOTIFICATION_ID, buildNotification(count))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -56,17 +56,19 @@ class SyncWorker @AssistedInject constructor(
|
|||||||
priority = NotificationCompat.PRIORITY_DEFAULT,
|
priority = NotificationCompat.PRIORITY_DEFAULT,
|
||||||
)
|
)
|
||||||
} else if (pair.notifyOnComplete && result.error == null) {
|
} else if (pair.notifyOnComplete && result.error == null) {
|
||||||
val summary = buildString {
|
val lines = buildList {
|
||||||
if (result.uploaded > 0) append("↑${result.uploaded} ")
|
if (result.uploaded > 0) add("↑ Uploaded: ${result.uploaded} file${if (result.uploaded != 1) "s" else ""}")
|
||||||
if (result.downloaded > 0) append("↓${result.downloaded} ")
|
if (result.downloaded > 0) add("↓ Downloaded: ${result.downloaded} file${if (result.downloaded != 1) "s" else ""}")
|
||||||
if (result.deleted > 0) append("🗑${result.deleted} ")
|
if (result.deleted > 0) add("🗑 Deleted: ${result.deleted} file${if (result.deleted != 1) "s" else ""}")
|
||||||
if (result.conflicts > 0) append("⚠${result.conflicts} conflict${if (result.conflicts != 1) "s" else ""}")
|
if (result.conflicts > 0) add("⚠ ${result.conflicts} conflict${if (result.conflicts != 1) "s" else ""}")
|
||||||
}.trim().ifEmpty { "Up to date" }
|
}
|
||||||
|
val summary = if (lines.isEmpty()) "Up to date — nothing to sync" else lines.joinToString("\n")
|
||||||
notify(
|
notify(
|
||||||
id = pairId.toInt() + RESULT_ID_OFFSET,
|
id = pairId.toInt() + RESULT_ID_OFFSET,
|
||||||
channelId = CHANNEL_COMPLETE,
|
channelId = CHANNEL_COMPLETE,
|
||||||
title = "${pair.name} — Synced",
|
title = "${pair.name} — Changes synced",
|
||||||
text = summary,
|
text = if (lines.isEmpty()) summary else lines.first(),
|
||||||
|
bigText = summary,
|
||||||
priority = NotificationCompat.PRIORITY_LOW,
|
priority = NotificationCompat.PRIORITY_LOW,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -122,21 +124,24 @@ class SyncWorker @AssistedInject constructor(
|
|||||||
ForegroundInfo(NOTIFICATION_ID, notification)
|
ForegroundInfo(NOTIFICATION_ID, notification)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun notify(id: Int, channelId: String, title: String, text: String, priority: Int) {
|
private fun notify(id: Int, channelId: String, title: String, text: String, priority: Int, bigText: String? = null) {
|
||||||
val tapIntent = PendingIntent.getActivity(
|
val tapIntent = PendingIntent.getActivity(
|
||||||
applicationContext, id,
|
applicationContext, id,
|
||||||
Intent(applicationContext, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_SINGLE_TOP },
|
Intent(applicationContext, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_SINGLE_TOP },
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
|
||||||
)
|
)
|
||||||
val nm = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
val nm = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||||
nm.notify(id, NotificationCompat.Builder(applicationContext, channelId)
|
val builder = NotificationCompat.Builder(applicationContext, channelId)
|
||||||
.setContentTitle(title)
|
.setContentTitle(title)
|
||||||
.setContentText(text)
|
.setContentText(text)
|
||||||
.setSmallIcon(R.drawable.ic_sync)
|
.setSmallIcon(R.drawable.ic_sync)
|
||||||
.setPriority(priority)
|
.setPriority(priority)
|
||||||
.setContentIntent(tapIntent)
|
.setContentIntent(tapIntent)
|
||||||
.setAutoCancel(true)
|
.setAutoCancel(true)
|
||||||
.build())
|
if (bigText != null) {
|
||||||
|
builder.setStyle(NotificationCompat.BigTextStyle().bigText(bigText))
|
||||||
|
}
|
||||||
|
nm.notify(id, builder.build())
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
<gradient
|
<gradient
|
||||||
android:type="linear"
|
android:type="linear"
|
||||||
android:angle="135"
|
android:angle="135"
|
||||||
android:startColor="#312E81"
|
android:startColor="#2E1065"
|
||||||
android:endColor="#6366F1"/>
|
android:centerColor="#6D28D9"
|
||||||
|
android:endColor="#1E40AF"/>
|
||||||
</shape>
|
</shape>
|
||||||
|
|||||||
@@ -1,13 +1,70 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
xmlns:aapt="http://schemas.android.com/aapt"
|
||||||
android:width="108dp"
|
android:width="108dp"
|
||||||
android:height="108dp"
|
android:height="108dp"
|
||||||
android:viewportWidth="24"
|
android:viewportWidth="108"
|
||||||
android:viewportHeight="24">
|
android:viewportHeight="108">
|
||||||
|
|
||||||
|
<!-- Outer soft glow ring -->
|
||||||
<path
|
<path
|
||||||
android:fillColor="#FFFFFF"
|
android:pathData="M54,54m-44,0a44,44 0 1,0 88,0a44,44 0 1,0 -88,0"
|
||||||
android:pathData="M12,4V1L8,5l4,4V6c3.31,0 6,2.69 6,6 0,1.01-0.25,1.97-0.7,2.8l1.46,1.46C19.54,15.03 20,13.57 20,12c0-4.42-3.58-8-8-8z"/>
|
android:fillColor="#12FFFFFF"/>
|
||||||
|
|
||||||
|
<!-- Mid glow ring -->
|
||||||
<path
|
<path
|
||||||
android:fillColor="#FFFFFF"
|
android:pathData="M54,54m-33,0a33,33 0 1,0 66,0a33,33 0 1,0 -66,0"
|
||||||
android:pathData="M12,18c-3.31,0-6,-2.69-6,-6 0,-1.01 0.25,-1.97 0.7,-2.8L5.24,7.74C4.46,8.97 4,10.43 4,12c0,4.42 3.58,8 8,8v3l4,-4-4,-4v3z"/>
|
android:fillColor="#18FFFFFF"/>
|
||||||
|
|
||||||
|
<!-- Inner glow ring -->
|
||||||
|
<path
|
||||||
|
android:pathData="M54,54m-21,0a21,21 0 1,0 42,0a21,21 0 1,0 -42,0"
|
||||||
|
android:fillColor="#10FFFFFF"/>
|
||||||
|
|
||||||
|
<!-- Upload arrow (top-right) — neon cyan → sky blue -->
|
||||||
|
<path android:pathData="M54,18V4.5L36,22.5l18,18V27c14.895,0 27,12.105 27,27 0,4.545-1.125,8.865-3.15,12.6l6.57,6.57C87.93,67.635 90,61.065 90,54c0-19.89-16.11-36-36-36z">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient android:type="linear"
|
||||||
|
android:startX="36" android:startY="4"
|
||||||
|
android:endX="90" android:endY="70"
|
||||||
|
android:startColor="#67E8F9"
|
||||||
|
android:endColor="#38BDF8"/>
|
||||||
|
</aapt:attr>
|
||||||
|
</path>
|
||||||
|
|
||||||
|
<!-- Download arrow (bottom-left) — hot pink → coral -->
|
||||||
|
<path android:pathData="M54,81c-14.895,0-27,-12.105-27,-27 0,-4.545 1.125,-8.865 3.15,-12.6L23.58,34.83C20.07,40.365 18,46.935 18,54c0,19.89 16.11,36 36,36v13.5l18,-18-18,-18v13.5z">
|
||||||
|
<aapt:attr name="android:fillColor">
|
||||||
|
<gradient android:type="linear"
|
||||||
|
android:startX="18" android:startY="35"
|
||||||
|
android:endX="72" android:endY="103"
|
||||||
|
android:startColor="#F472B6"
|
||||||
|
android:endColor="#FB923C"/>
|
||||||
|
</aapt:attr>
|
||||||
|
</path>
|
||||||
|
|
||||||
|
<!-- Center glowing orb -->
|
||||||
|
<path
|
||||||
|
android:pathData="M54,54m-7,0a7,7 0 1,0 14,0a7,7 0 1,0 -14,0"
|
||||||
|
android:fillColor="#60FFFFFF"/>
|
||||||
|
<path
|
||||||
|
android:pathData="M54,54m-4,0a4,4 0 1,0 8,0a4,4 0 1,0 -8,0"
|
||||||
|
android:fillColor="#FFFFFF"/>
|
||||||
|
|
||||||
|
<!-- Cardinal accent sparks -->
|
||||||
|
<!-- Top — cyan -->
|
||||||
|
<path android:pathData="M54,13m-3,0a3,3 0 1,0 6,0a3,3 0 1,0 -6,0" android:fillColor="#22D3EE"/>
|
||||||
|
<!-- Right — indigo -->
|
||||||
|
<path android:pathData="M95,54m-3,0a3,3 0 1,0 6,0a3,3 0 1,0 -6,0" android:fillColor="#818CF8"/>
|
||||||
|
<!-- Bottom — pink -->
|
||||||
|
<path android:pathData="M54,95m-3,0a3,3 0 1,0 6,0a3,3 0 1,0 -6,0" android:fillColor="#F9A8D4"/>
|
||||||
|
<!-- Left — emerald -->
|
||||||
|
<path android:pathData="M13,54m-3,0a3,3 0 1,0 6,0a3,3 0 1,0 -6,0" android:fillColor="#6EE7B7"/>
|
||||||
|
|
||||||
|
<!-- Diagonal mini sparks (45°) -->
|
||||||
|
<path android:pathData="M85,23m-2,0a2,2 0 1,0 4,0a2,2 0 1,0 -4,0" android:fillColor="#A5F3FC"/>
|
||||||
|
<path android:pathData="M85,85m-2,0a2,2 0 1,0 4,0a2,2 0 1,0 -4,0" android:fillColor="#FDBA74"/>
|
||||||
|
<path android:pathData="M23,85m-2,0a2,2 0 1,0 4,0a2,2 0 1,0 -4,0" android:fillColor="#C084FC"/>
|
||||||
|
<path android:pathData="M23,23m-2,0a2,2 0 1,0 4,0a2,2 0 1,0 -4,0" android:fillColor="#86EFAC"/>
|
||||||
|
|
||||||
</vector>
|
</vector>
|
||||||
|
|||||||
@@ -28,8 +28,8 @@ localbroadcastmanager = "1.1.0"
|
|||||||
coil = "2.7.0"
|
coil = "2.7.0"
|
||||||
splashscreen = "1.0.1"
|
splashscreen = "1.0.1"
|
||||||
timber = "5.0.1"
|
timber = "5.0.1"
|
||||||
securityCrypto = "1.1.0-alpha06"
|
securityCrypto = "1.0.0"
|
||||||
biometric = "1.2.0-alpha05"
|
biometric = "1.1.0"
|
||||||
junit = "4.13.2"
|
junit = "4.13.2"
|
||||||
androidxTestExt = "1.2.1"
|
androidxTestExt = "1.2.1"
|
||||||
espresso = "3.6.1"
|
espresso = "3.6.1"
|
||||||
@@ -106,7 +106,7 @@ coil-compose = { group = "io.coil-kt", name = "coil-compose", version.ref = "coi
|
|||||||
|
|
||||||
# Security
|
# Security
|
||||||
security-crypto = { group = "androidx.security", name = "security-crypto", version.ref = "securityCrypto" }
|
security-crypto = { group = "androidx.security", name = "security-crypto", version.ref = "securityCrypto" }
|
||||||
biometric = { group = "androidx.biometric", name = "biometric-ktx", version.ref = "biometric" }
|
biometric = { group = "androidx.biometric", name = "biometric", version.ref = "biometric" }
|
||||||
|
|
||||||
# Logging
|
# Logging
|
||||||
timber = { group = "com.jakewharton.timber", name = "timber", version.ref = "timber" }
|
timber = { group = "com.jakewharton.timber", name = "timber", version.ref = "timber" }
|
||||||
|
|||||||
Vendored
BIN
Binary file not shown.
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=file\:///home/amir/gradle/gradle-8.6/gradle-8.6-bin.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
zipStorePath=wrapper/dists
|
zipStorePath=wrapper/dists
|
||||||
|
|||||||
@@ -1,2 +1,39 @@
|
|||||||
#!/bin/bash
|
#!/bin/sh
|
||||||
exec /home/amir/gradle/gradle-8.6/bin/gradle "$@"
|
##############################################################################
|
||||||
|
# Gradle wrapper — standard portable launcher
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
app_path=$0
|
||||||
|
while [ -h "$app_path" ]; do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in
|
||||||
|
/*) app_path=$link ;;
|
||||||
|
*) app_path=${app_path%"${app_path##*/}"}$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
APP_HOME=$( cd "${app_path%"${app_path##*/}"}." && pwd -P ) || exit
|
||||||
|
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
if [ -n "$JAVA_HOME" ]; then
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
fi
|
||||||
|
|
||||||
|
MAX_FD=maximum
|
||||||
|
case "$( uname )" in
|
||||||
|
Darwin*) ;;
|
||||||
|
*)
|
||||||
|
MAX_FD=$( ulimit -H -n 2>/dev/null ) && ulimit -n "$MAX_FD" 2>/dev/null ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS \
|
||||||
|
"\"-Dorg.gradle.appname=$APP_BASE_NAME\"" \
|
||||||
|
-classpath "\"$CLASSPATH\"" \
|
||||||
|
org.gradle.wrapper.GradleWrapperMain '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
|
|||||||
Binary file not shown.
+2
-2
@@ -1,2 +1,2 @@
|
|||||||
VERSION_NAME=1.0.14
|
VERSION_NAME=1.0.21
|
||||||
VERSION_CODE=15
|
VERSION_CODE=22
|
||||||
|
|||||||
Reference in New Issue
Block a user