everysync: new app
- Commit
1a8784999f91f8e8c8b52faa7e2a920d2751c764- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-16 19:03 UTC (4 months ago)
- Parents
f6dee6f
Diff
everysync/build.gradle.kts
diff --git a/everysync/build.gradle.kts b/everysync/build.gradle.ktsnew file mode 100644index 0000000000..5a54d4e12b--- /dev/null+++ b/everysync/build.gradle.kts@@ -0,0 +1,51 @@+plugins {+ id("common-conventions-app")+ id("common-conventions-metadata")+ alias(libs.plugins.ksp)+}++android {+ defaultConfig {+ applicationId = "com.vayunmathur.everysync"++ // OAuth2 public-client IDs (PKCE, no secret shipped). Registered clients+ // must use the redirect scheme "com.vayunmathur.everysync:/oauth". Empty+ // placeholders let the module compile; provide real IDs to test Google /+ // Withings integrations.+ buildConfigField("String", "GOOGLE_OAUTH_CLIENT_ID", "\"${project.findProperty("EVERYSYNC_GOOGLE_CLIENT_ID") ?: ""}\"")+ buildConfigField("String", "WITHINGS_OAUTH_CLIENT_ID", "\"${project.findProperty("EVERYSYNC_WITHINGS_CLIENT_ID") ?: ""}\"")+ buildConfigField("String", "WITHINGS_OAUTH_CLIENT_SECRET", "\"${project.findProperty("EVERYSYNC_WITHINGS_CLIENT_SECRET") ?: ""}\"")+ }+ buildFeatures {+ buildConfig = true+ }+}++metadataScreenshots {+ permissions.addAll(+ "android.permission.READ_CONTACTS",+ "android.permission.WRITE_CONTACTS",+ "android.permission.READ_CALENDAR",+ "android.permission.WRITE_CALENDAR",+ "android.permission.GET_ACCOUNTS",+ )+}++dependencies {+ // Custom Tabs for OAuth PKCE flow+ implementation(libs.androidx.browser)++ // Health Connect (Withings + Samsung/Google Health bridge)+ implementation(libs.androidx.connect.client)++ // Background sync+ implementation(libs.androidx.work.runtime.ktx)++ // ktor client (custom WebDAV methods + JSON)+ implementation(project(":library:network"))++ // Material icons (Default.* + AutoMirrored)+ implementation("androidx.compose.material:material-icons-extended")++ testImplementation(libs.junit)+}
everysync/src/androidTest/java/com/vayunmathur/everysync/MetadataScreenshots.kt
diff --git a/everysync/src/androidTest/java/com/vayunmathur/everysync/MetadataScreenshots.kt b/everysync/src/androidTest/java/com/vayunmathur/everysync/MetadataScreenshots.ktnew file mode 100644index 0000000000..fb71031396--- /dev/null+++ b/everysync/src/androidTest/java/com/vayunmathur/everysync/MetadataScreenshots.kt@@ -0,0 +1,85 @@+package com.vayunmathur.everysync++import androidx.compose.ui.graphics.asAndroidBitmap+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.junit4.createEmptyComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onRoot+import androidx.test.core.app.ActivityScenario+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.AccountStore+import com.vayunmathur.everysync.provider.DataType+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File++/**+ * Screenshot generator driven by `:everysync:metadata`. Seeds a couple of+ * accounts so the home screen renders a populated list, then captures it.+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++ @get:Rule+ val composeRule = createEmptyComposeRule()++ private val ctx = InstrumentationRegistry.getInstrumentation().targetContext++ private val outDir: File by lazy {+ File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+ deleteRecursively()+ mkdirs()+ }+ }++ private fun snap(index: Int) {+ val image = composeRule.onRoot().captureToImage()+ File(outDir, "$index.png").outputStream().use { out ->+ image.asAndroidBitmap().compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out)+ }+ }++ @Test+ fun generateStoreScreenshots() {+ val store = AccountStore.getInstance(ctx)+ runBlocking {+ store.upsert(+ AccountConfig(+ accountName = "[email protected] (Google)",+ providerId = "google",+ enabledTypes = setOf(DataType.CONTACTS, DataType.CALENDAR),+ lastSyncEpochMs = System.currentTimeMillis(),+ ),+ )+ store.upsert(+ AccountConfig(+ accountName = "[email protected] (Apple / iCloud)",+ providerId = "icloud",+ enabledTypes = setOf(DataType.CONTACTS, DataType.CALENDAR),+ lastSyncEpochMs = System.currentTimeMillis(),+ ),+ )+ store.upsert(+ AccountConfig(+ accountName = "Withings",+ providerId = "withings",+ enabledTypes = setOf(DataType.HEALTH),+ lastSyncEpochMs = System.currentTimeMillis(),+ ),+ )+ }++ ActivityScenario.launch(MainActivity::class.java).use {+ composeRule.waitUntil(timeoutMillis = 20_000) {+ composeRule.onAllNodesWithText("Google", substring = true)+ .fetchSemanticsNodes().isNotEmpty()+ }+ Thread.sleep(500)+ snap(1)+ }+ }+}
everysync/src/main/AndroidManifest.xml
diff --git a/everysync/src/main/AndroidManifest.xml b/everysync/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..53753ff607--- /dev/null+++ b/everysync/src/main/AndroidManifest.xml@@ -0,0 +1,142 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />++ <!-- Contacts -->+ <uses-permission android:name="android.permission.READ_CONTACTS" />+ <uses-permission android:name="android.permission.WRITE_CONTACTS" />++ <!-- Calendar -->+ <uses-permission android:name="android.permission.READ_CALENDAR" />+ <uses-permission android:name="android.permission.WRITE_CALENDAR" />++ <!-- Accounts + sync framework -->+ <uses-permission android:name="android.permission.GET_ACCOUNTS" />+ <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />+ <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />+ <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />+ <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />++ <!-- Health Connect: body composition + vitals we bridge from Withings /+ Samsung Health / Google Health. -->+ <uses-permission android:name="android.permission.health.READ_WEIGHT" />+ <uses-permission android:name="android.permission.health.WRITE_WEIGHT" />+ <uses-permission android:name="android.permission.health.READ_HEIGHT" />+ <uses-permission android:name="android.permission.health.WRITE_HEIGHT" />+ <uses-permission android:name="android.permission.health.READ_BODY_FAT" />+ <uses-permission android:name="android.permission.health.WRITE_BODY_FAT" />+ <uses-permission android:name="android.permission.health.READ_LEAN_BODY_MASS" />+ <uses-permission android:name="android.permission.health.WRITE_LEAN_BODY_MASS" />+ <uses-permission android:name="android.permission.health.READ_BONE_MASS" />+ <uses-permission android:name="android.permission.health.WRITE_BONE_MASS" />+ <uses-permission android:name="android.permission.health.READ_BODY_WATER_MASS" />+ <uses-permission android:name="android.permission.health.WRITE_BODY_WATER_MASS" />+ <uses-permission android:name="android.permission.health.READ_HEART_RATE" />+ <uses-permission android:name="android.permission.health.WRITE_HEART_RATE" />+ <uses-permission android:name="android.permission.health.READ_RESTING_HEART_RATE" />+ <uses-permission android:name="android.permission.health.WRITE_RESTING_HEART_RATE" />+ <uses-permission android:name="android.permission.health.READ_OXYGEN_SATURATION" />+ <uses-permission android:name="android.permission.health.WRITE_OXYGEN_SATURATION" />+ <uses-permission android:name="android.permission.health.READ_STEPS" />+ <uses-permission android:name="android.permission.health.WRITE_STEPS" />+ <uses-permission android:name="android.permission.health.READ_SLEEP" />+ <uses-permission android:name="android.permission.health.WRITE_SLEEP" />+ <uses-permission android:name="android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND" />++ <application+ android:allowBackup="true"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher"+ android:supportsRtl="true"+ android:theme="@style/Theme.General">++ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <!-- Receives the OAuth2 redirect (com.vayunmathur.everysync:/oauth). -->+ <activity+ android:name=".auth.OAuthCallbackActivity"+ android:exported="true"+ android:launchMode="singleTask"+ android:theme="@android:style/Theme.NoDisplay">+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="com.vayunmathur.everysync" android:host="oauth" />+ </intent-filter>+ </activity>++ <!-- Health Connect permission rationale (Android 13 and 14+). -->+ <activity+ android:name=".ui.PermissionsRationaleActivity"+ android:exported="true">+ <intent-filter>+ <action android:name="androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE" />+ </intent-filter>+ </activity>+ <activity-alias+ android:name="ViewPermissionUsageActivity"+ android:exported="true"+ android:targetActivity=".ui.PermissionsRationaleActivity"+ android:permission="android.permission.START_VIEW_PERMISSION_USAGE">+ <intent-filter>+ <action android:name="android.intent.action.VIEW_PERMISSION_USAGE" />+ <category android:name="android.intent.category.HEALTH_PERMISSIONS" />+ </intent-filter>+ </activity-alias>++ <!-- Account authenticator: all EverySync accounts share one account type. -->+ <service+ android:name=".auth.AuthenticatorService"+ android:exported="false">+ <intent-filter>+ <action android:name="android.accounts.AccountAuthenticator" />+ </intent-filter>+ <meta-data+ android:name="android.accounts.AccountAuthenticator"+ android:resource="@xml/authenticator" />+ </service>++ <!-- Contacts sync adapter. -->+ <service+ android:name=".sync.ContactsSyncService"+ android:exported="false">+ <intent-filter>+ <action android:name="android.content.SyncAdapter" />+ </intent-filter>+ <meta-data+ android:name="android.content.SyncAdapter"+ android:resource="@xml/syncadapter_contacts" />+ <meta-data+ android:name="android.provider.CONTACTS_STRUCTURE"+ android:resource="@xml/contacts" />+ </service>++ <!-- Calendar sync adapter. -->+ <service+ android:name=".sync.CalendarSyncService"+ android:exported="false">+ <intent-filter>+ <action android:name="android.content.SyncAdapter" />+ </intent-filter>+ <meta-data+ android:name="android.content.SyncAdapter"+ android:resource="@xml/syncadapter_calendar" />+ </service>++ </application>++</manifest>
everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt b/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.ktnew file mode 100644index 0000000000..6e35c540aa--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/MainActivity.kt@@ -0,0 +1,58 @@+package com.vayunmathur.everysync++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.everysync.sync.SyncScheduler+import com.vayunmathur.everysync.ui.AccountDetailScreen+import com.vayunmathur.everysync.ui.AccountsScreen+import com.vayunmathur.everysync.ui.AddAccountScreen+import com.vayunmathur.everysync.ui.DavLoginScreen+import com.vayunmathur.everysync.ui.EverySyncViewModel+import com.vayunmathur.everysync.ui.SettingsScreen+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.DialogPage+import com.vayunmathur.library.util.ListPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.rememberNavBackStack+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+ private val viewModel: EverySyncViewModel by viewModels()++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ SyncScheduler.schedulePeriodic(this)+ setContent {+ DynamicTheme {+ Navigation(viewModel)+ }+ }+ }+}++@Serializable+sealed interface Route : NavKey {+ @Serializable data object Accounts : Route+ @Serializable data object AddAccount : Route+ @Serializable data class DavLogin(val providerId: String) : Route+ @Serializable data class AccountDetail(val accountName: String) : Route+ @Serializable data object Settings : Route+}++@Composable+fun Navigation(viewModel: EverySyncViewModel) {+ val backStack = rememberNavBackStack<Route>(Route.Accounts)+ MainNavigation(backStack) {+ entry<Route.Accounts>(metadata = ListPage()) { AccountsScreen(backStack, viewModel) }+ entry<Route.AddAccount>(metadata = ListPage()) { AddAccountScreen(backStack, viewModel) }+ entry<Route.DavLogin>(metadata = DialogPage()) { DavLoginScreen(backStack, viewModel, it.providerId) }+ entry<Route.AccountDetail>(metadata = ListPage()) { AccountDetailScreen(backStack, viewModel, it.accountName) }+ entry<Route.Settings>(metadata = ListPage()) { SettingsScreen(backStack, viewModel) }+ }+}
everysync/src/main/java/com/vayunmathur/everysync/Settings.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/Settings.kt b/everysync/src/main/java/com/vayunmathur/everysync/Settings.ktnew file mode 100644index 0000000000..61d4a056c7--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/Settings.kt@@ -0,0 +1,43 @@+package com.vayunmathur.everysync++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.flow.Flow++/** Global EverySync settings backed by DataStore. */+object Settings {+ const val CONFLICT_LWW = "lww"+ const val CONFLICT_REMOTE = "remote"+ const val CONFLICT_LOCAL = "local"++ private const val KEY_INTERVAL = "global_interval_minutes"+ private const val KEY_WIFI_ONLY = "wifi_only"+ private const val KEY_CONFLICT = "conflict_policy"++ fun intervalMinutes(context: Context): Long =+ DataStoreUtils.getInstance(context).getLong(KEY_INTERVAL) ?: 60L++ suspend fun setIntervalMinutes(context: Context, minutes: Long) {+ DataStoreUtils.getInstance(context).setLong(KEY_INTERVAL, minutes.coerceAtLeast(15))+ }++ fun intervalFlow(context: Context): Flow<Long> =+ DataStoreUtils.getInstance(context).longFlow(KEY_INTERVAL, 60L)++ fun wifiOnly(context: Context): Boolean =+ DataStoreUtils.getInstance(context).getBoolean(KEY_WIFI_ONLY, false)++ suspend fun setWifiOnly(context: Context, value: Boolean) {+ DataStoreUtils.getInstance(context).setBoolean(KEY_WIFI_ONLY, value)+ }++ fun wifiOnlyFlow(context: Context): Flow<Boolean> =+ DataStoreUtils.getInstance(context).booleanFlow(KEY_WIFI_ONLY)++ fun conflictPolicy(context: Context): String =+ DataStoreUtils.getInstance(context).getString(KEY_CONFLICT)?.ifBlank { null } ?: CONFLICT_LWW++ suspend fun setConflictPolicy(context: Context, policy: String) {+ DataStoreUtils.getInstance(context).setString(KEY_CONFLICT, policy)+ }+}
everysync/src/main/java/com/vayunmathur/everysync/auth/AccountConfig.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountConfig.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountConfig.ktnew file mode 100644index 0000000000..e8603b4571--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountConfig.kt@@ -0,0 +1,28 @@+package com.vayunmathur.everysync.auth++import com.vayunmathur.everysync.provider.DataType+import kotlinx.serialization.Serializable++/**+ * A configured EverySync account. Persisted as JSON in [AccountStore]; the+ * matching [android.accounts.Account] (type `com.vayunmathur.everysync`) is+ * registered with AccountManager so other apps see synced data under it.+ *+ * Secrets (OAuth tokens, DAV passwords) live in the encrypted [TokenStore],+ * keyed by [accountName] โ never in this object.+ */+@Serializable+data class AccountConfig(+ /** Unique account name, also the AccountManager account name. */+ val accountName: String,+ val providerId: String,+ /** For DAV providers: discovered/base principal URL. */+ val davBaseUrl: String? = null,+ val davUsername: String? = null,+ /** Data types the user enabled for this account. */+ val enabledTypes: Set<DataType> = emptySet(),+ /** Per-account sync interval override in minutes (null = use global). */+ val intervalMinutes: Int? = null,+ val lastSyncEpochMs: Long = 0L,+ val lastSyncError: String? = null,+)
everysync/src/main/java/com/vayunmathur/everysync/auth/AccountStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountStore.ktnew file mode 100644index 0000000000..d2936363e8--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/AccountStore.kt@@ -0,0 +1,91 @@+package com.vayunmathur.everysync.auth++import android.accounts.Account+import android.accounts.AccountManager+import android.content.Context+import android.util.Log+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Persists [AccountConfig]s in DataStore and keeps the AccountManager entries in+ * sync. All EverySync accounts share the account type `com.vayunmathur.everysync`+ * (see [ACCOUNT_TYPE]) so the sync-adapter framework can drive them.+ */+class AccountStore private constructor(private val context: Context) {+ private val ds = DataStoreUtils.getInstance(context)+ private val json = Json { ignoreUnknownKeys = true }++ fun accountsFlow(): Flow<List<AccountConfig>> =+ ds.stringFlow(KEY).map { decode(it) }++ fun getAll(): List<AccountConfig> = decode(ds.getString(KEY))++ fun get(accountName: String): AccountConfig? =+ getAll().firstOrNull { it.accountName == accountName }++ suspend fun upsert(config: AccountConfig) {+ val current = getAll().filterNot { it.accountName == config.accountName }+ ds.setString(KEY, json.encodeToString(current + config))+ ensureSystemAccount(config.accountName)+ }++ suspend fun remove(accountName: String) {+ val current = getAll().filterNot { it.accountName == accountName }+ ds.setString(KEY, json.encodeToString(current))+ TokenStore.getInstance(context).clear(accountName)+ removeSystemAccount(accountName)+ }++ private fun ensureSystemAccount(accountName: String) {+ try {+ val am = AccountManager.get(context)+ val exists = am.getAccountsByType(ACCOUNT_TYPE).any { it.name == accountName }+ if (!exists) {+ am.addAccountExplicitly(Account(accountName, ACCOUNT_TYPE), null, null)+ }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to register system account", e)+ }+ }++ private fun removeSystemAccount(accountName: String) {+ try {+ val am = AccountManager.get(context)+ am.getAccountsByType(ACCOUNT_TYPE)+ .firstOrNull { it.name == accountName }+ ?.let { am.removeAccountExplicitly(it) }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to remove system account", e)+ }+ }++ fun systemAccount(accountName: String) = Account(accountName, ACCOUNT_TYPE)++ private fun decode(raw: String?): List<AccountConfig> {+ if (raw.isNullOrBlank()) return emptyList()+ return try {+ json.decodeFromString<List<AccountConfig>>(raw)+ } catch (e: Exception) {+ Log.e(TAG, "Failed to decode accounts", e)+ emptyList()+ }+ }++ companion object {+ const val ACCOUNT_TYPE = "com.vayunmathur.everysync"+ private const val KEY = "everysync_accounts"+ private const val TAG = "AccountStore"++ @Volatile+ private var instance: AccountStore? = null++ fun getInstance(context: Context): AccountStore =+ instance ?: synchronized(this) {+ instance ?: AccountStore(context.applicationContext).also { instance = it }+ }+ }+}
everysync/src/main/java/com/vayunmathur/everysync/auth/Authenticator.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/Authenticator.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/Authenticator.ktnew file mode 100644index 0000000000..7c8ad8b8d6--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/Authenticator.kt@@ -0,0 +1,32 @@+package com.vayunmathur.everysync.auth++import android.accounts.AbstractAccountAuthenticator+import android.accounts.Account+import android.accounts.AccountAuthenticatorResponse+import android.app.Service+import android.content.Context+import android.content.Intent+import android.os.Bundle+import android.os.IBinder++/**+ * Bare authenticator so EverySync accounts (type `com.vayunmathur.everysync`)+ * appear to the system and the sync-adapter framework. Account creation happens+ * in-app (OAuth / DAV login), not via the system "Add account" flow, so all+ * methods are no-ops โ mirrors `contacts/.../auth/Authenticator.kt`.+ */+class Authenticator(context: Context) : AbstractAccountAuthenticator(context) {+ override fun editProperties(response: AccountAuthenticatorResponse?, accountType: String?): Bundle? = null+ override fun addAccount(response: AccountAuthenticatorResponse?, accountType: String?, authTokenType: String?, requiredFeatures: Array<out String>?, options: Bundle?): Bundle? = null+ override fun confirmCredentials(response: AccountAuthenticatorResponse?, account: Account?, options: Bundle?): Bundle? = null+ override fun getAuthToken(response: AccountAuthenticatorResponse?, account: Account?, authTokenType: String?, options: Bundle?): Bundle? = null+ override fun getAuthTokenLabel(authTokenType: String?): String? = null+ override fun updateCredentials(response: AccountAuthenticatorResponse?, account: Account?, authTokenType: String?, options: Bundle?): Bundle? = null+ override fun hasFeatures(response: AccountAuthenticatorResponse?, account: Account?, features: Array<out String>?): Bundle? = null+}++class AuthenticatorService : Service() {+ private val authenticator by lazy { Authenticator(this) }++ override fun onBind(intent: Intent?): IBinder = authenticator.iBinder+}
everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.ktnew file mode 100644index 0000000000..242f0f2377--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.kt@@ -0,0 +1,35 @@+package com.vayunmathur.everysync.auth++import android.content.Intent+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.lifecycle.lifecycleScope+import com.vayunmathur.everysync.MainActivity+import com.vayunmathur.everysync.sync.SyncScheduler+import kotlinx.coroutines.launch++/**+ * Receives the OAuth2 redirect (`com.vayunmathur.everysync:/oauth`), completes the+ * PKCE token exchange, then returns to [MainActivity] and kicks off a first sync.+ */+class OAuthCallbackActivity : ComponentActivity() {+ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ val data = intent?.data+ if (data == null) {+ finish()+ return+ }+ lifecycleScope.launch {+ val accountName = OAuthManager.complete(applicationContext, data)+ if (accountName != null) {+ SyncScheduler.syncNow(applicationContext, accountName)+ }+ startActivity(+ Intent(this@OAuthCallbackActivity, MainActivity::class.java)+ .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP),+ )+ finish()+ }+ }+}
everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.ktnew file mode 100644index 0000000000..320e1cc500--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt@@ -0,0 +1,43 @@+package com.vayunmathur.everysync.auth++import com.vayunmathur.everysync.BuildConfig++/**+ * OAuth2 endpoints + scopes for a provider. Client IDs come from [BuildConfig]+ * (public PKCE clients โ no secret shipped, except Withings which requires one+ * per its API and is passed at token exchange).+ */+data class OAuthConfig(+ val authEndpoint: String,+ val tokenEndpoint: String,+ val clientId: String,+ val scopes: List<String>,+ /** Withings' API is a confidential client; empty for pure PKCE providers. */+ val clientSecret: String = "",+ /** Extra query params appended to the authorization request. */+ val extraAuthParams: Map<String, String> = emptyMap(),+) {+ companion object {+ const val REDIRECT_URI = "com.vayunmathur.everysync:/oauth"++ val GOOGLE = OAuthConfig(+ authEndpoint = "https://accounts.google.com/o/oauth2/v2/auth",+ tokenEndpoint = "https://oauth2.googleapis.com/token",+ clientId = BuildConfig.GOOGLE_OAUTH_CLIENT_ID,+ scopes = listOf(+ "https://www.googleapis.com/auth/contacts",+ "https://www.googleapis.com/auth/calendar",+ ),+ // Force a refresh token to be returned on first consent.+ extraAuthParams = mapOf("access_type" to "offline", "prompt" to "consent"),+ )++ val WITHINGS = OAuthConfig(+ authEndpoint = "https://account.withings.com/oauth2_user/authorize2",+ tokenEndpoint = "https://wbsapi.withings.net/v2/oauth2",+ clientId = BuildConfig.WITHINGS_OAUTH_CLIENT_ID,+ clientSecret = BuildConfig.WITHINGS_OAUTH_CLIENT_SECRET,+ scopes = listOf("user.metrics", "user.activity"),+ )+ }+}
everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.ktnew file mode 100644index 0000000000..9cde3d37f3--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.kt@@ -0,0 +1,174 @@+package com.vayunmathur.everysync.auth++import android.content.Context+import android.net.Uri+import android.util.Log+import androidx.browser.customtabs.CustomTabsIntent+import com.vayunmathur.everysync.provider.ProviderRegistry+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.util.DataStoreUtils+import java.security.MessageDigest+import java.security.SecureRandom+import kotlin.io.encoding.Base64+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull++/**+ * OAuth2 Authorization Code + PKCE (RFC 7636). The authorization request opens in+ * a Custom Tab; the redirect (`com.vayunmathur.everysync:/oauth`) is caught by+ * [OAuthCallbackActivity], which calls [complete] to exchange the code for tokens.+ */+object OAuthManager {+ private const val TAG = "OAuthManager"+ private const val PENDING_KEY = "everysync_pending_oauth"+ private val json = Json { ignoreUnknownKeys = true }++ @Serializable+ private data class Pending(val providerId: String, val verifier: String, val state: String)++ suspend fun start(context: Context, providerId: String) {+ val provider = ProviderRegistry.get(providerId) ?: return+ val config = provider.oauthConfig() ?: return+ val verifier = randomUrlSafe(64)+ val challenge = codeChallenge(verifier)+ val state = randomUrlSafe(24)+ DataStoreUtils.getInstance(context)+ .setString(PENDING_KEY, json.encodeToString(Pending(providerId, verifier, state)))++ val url = Uri.parse(config.authEndpoint).buildUpon()+ .appendQueryParameter("client_id", config.clientId)+ .appendQueryParameter("redirect_uri", OAuthConfig.REDIRECT_URI)+ .appendQueryParameter("response_type", "code")+ .appendQueryParameter("scope", config.scopes.joinToString(" "))+ .appendQueryParameter("code_challenge", challenge)+ .appendQueryParameter("code_challenge_method", "S256")+ .appendQueryParameter("state", state)+ .apply { config.extraAuthParams.forEach { (k, v) -> appendQueryParameter(k, v) } }+ .build()++ CustomTabsIntent.Builder().build().launchUrl(context, url)+ }++ /** Handle the OAuth redirect. Returns the created account name on success. */+ suspend fun complete(context: Context, redirect: Uri): String? {+ val ds = DataStoreUtils.getInstance(context)+ val pending = ds.getString(PENDING_KEY)?.let {+ runCatching { json.decodeFromString<Pending>(it) }.getOrNull()+ } ?: return null+ val code = redirect.getQueryParameter("code") ?: return null+ val state = redirect.getQueryParameter("state")+ if (state != pending.state) {+ Log.e(TAG, "OAuth state mismatch")+ return null+ }+ val provider = ProviderRegistry.get(pending.providerId) ?: return null+ val config = provider.oauthConfig() ?: return null++ val tokens = exchangeCode(config, code, pending.verifier) ?: return null+ val accountName = try {+ provider.resolveAccountName(context, tokens)+ } catch (e: Exception) {+ Log.e(TAG, "resolveAccountName failed", e)+ "${provider.displayName} account"+ }+ TokenStore.getInstance(context).putTokens(accountName, tokens)+ AccountStore.getInstance(context).upsert(+ AccountConfig(+ accountName = accountName,+ providerId = provider.id,+ enabledTypes = provider.capabilities,+ ),+ )+ ds.setString(PENDING_KEY, "")+ return accountName+ }++ /** Return a valid access token, refreshing it first if it has expired. */+ suspend fun validAccessToken(context: Context, accountName: String, providerId: String): String? {+ val store = TokenStore.getInstance(context)+ val tokens = store.getTokens(accountName) ?: return null+ val fresh = if (tokens.expiresAtMs != 0L && tokens.expiresAtMs < System.currentTimeMillis() + 60_000) {+ refresh(context, accountName, providerId, tokens) ?: tokens+ } else tokens+ return fresh.accessToken+ }++ private suspend fun refresh(context: Context, accountName: String, providerId: String, tokens: OAuthTokens): OAuthTokens? {+ val refreshToken = tokens.refreshToken ?: return null+ val config = ProviderRegistry.get(providerId)?.oauthConfig() ?: return null+ val form = buildMap {+ put("client_id", config.clientId)+ put("grant_type", "refresh_token")+ put("refresh_token", refreshToken)+ if (config.clientSecret.isNotBlank()) put("client_secret", config.clientSecret)+ // Withings requires an action param.+ if (config.tokenEndpoint.contains("withings")) put("action", "requesttoken")+ }+ val parsed = postForm(config.tokenEndpoint, form) ?: return null+ val updated = tokens.copy(+ accessToken = parsed.accessToken,+ refreshToken = parsed.refreshToken ?: tokens.refreshToken,+ expiresAtMs = parsed.expiresAtMs,+ )+ TokenStore.getInstance(context).putTokens(accountName, updated)+ return updated+ }++ private suspend fun exchangeCode(config: OAuthConfig, code: String, verifier: String): OAuthTokens? {+ val form = buildMap {+ put("client_id", config.clientId)+ put("grant_type", "authorization_code")+ put("code", code)+ put("redirect_uri", OAuthConfig.REDIRECT_URI)+ put("code_verifier", verifier)+ if (config.clientSecret.isNotBlank()) put("client_secret", config.clientSecret)+ if (config.tokenEndpoint.contains("withings")) put("action", "requesttoken")+ }+ return postForm(config.tokenEndpoint, form)+ }++ private suspend fun postForm(endpoint: String, form: Map<String, String>): OAuthTokens? {+ return try {+ val body = form.entries.joinToString("&") {+ "${Uri.encode(it.key)}=${Uri.encode(it.value)}"+ }+ val resp = NetworkClient.performRequest(+ endpoint, "POST",+ mapOf("Content-Type" to "application/x-www-form-urlencoded"),+ body,+ )+ val root = json.parseToJsonElement(resp.body) as? JsonObject ?: return null+ // Withings wraps the payload in a "body" object with a status code.+ val payload = (root["body"] as? JsonObject) ?: root+ val access = payload["access_token"]?.jsonPrimitive?.contentOrNullSafe() ?: return null+ val refresh = payload["refresh_token"]?.jsonPrimitive?.contentOrNullSafe()+ val expiresIn = payload["expires_in"]?.jsonPrimitive?.longOrNull ?: 0L+ OAuthTokens(+ accessToken = access,+ refreshToken = refresh,+ expiresAtMs = if (expiresIn > 0) System.currentTimeMillis() + expiresIn * 1000 else 0L,+ )+ } catch (e: Exception) {+ Log.e(TAG, "token endpoint call failed", e)+ null+ }+ }++ private fun kotlinx.serialization.json.JsonPrimitive.contentOrNullSafe(): String? =+ runCatching { this.content }.getOrNull()?.ifBlank { null }++ private fun randomUrlSafe(bytes: Int): String {+ val buf = ByteArray(bytes)+ SecureRandom().nextBytes(buf)+ return Base64.UrlSafe.encode(buf).replace("=", "")+ }++ private fun codeChallenge(verifier: String): String {+ val digest = MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray())+ return Base64.UrlSafe.encode(digest).replace("=", "")+ }+}
everysync/src/main/java/com/vayunmathur/everysync/auth/TokenStore.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/auth/TokenStore.kt b/everysync/src/main/java/com/vayunmathur/everysync/auth/TokenStore.ktnew file mode 100644index 0000000000..0c1c095d02--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/TokenStore.kt@@ -0,0 +1,140 @@+package com.vayunmathur.everysync.auth++import android.content.Context+import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import android.util.Log+import com.vayunmathur.library.util.DataStoreUtils+import java.security.KeyStore+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/** OAuth token triple persisted (encrypted) per account. */+@Serializable+data class OAuthTokens(+ val accessToken: String,+ val refreshToken: String? = null,+ /** Absolute expiry (epoch ms). 0 = unknown. */+ val expiresAtMs: Long = 0L,+)++/** DAV credentials persisted (encrypted) per account. */+@Serializable+data class DavCredentials(+ val baseUrl: String,+ val username: String,+ val password: String,+)++/**+ * Encrypted secret storage. Secrets are AES-GCM encrypted with a non-exportable+ * key held in the Android Keystore, then the ciphertext is stored as a byte+ * array in [DataStoreUtils]. Nothing sensitive is ever written in plaintext.+ */+class TokenStore private constructor(context: Context) {+ private val ds = DataStoreUtils.getInstance(context)+ private val json = Json { ignoreUnknownKeys = true }++ private fun secretKey(): SecretKey {+ val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+ (ks.getEntry(KEY_ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }+ val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)+ generator.init(+ KeyGenParameterSpec.Builder(+ KEY_ALIAS,+ KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,+ )+ .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+ .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+ .build(),+ )+ return generator.generateKey()+ }++ private fun encrypt(plain: ByteArray): ByteArray {+ val cipher = Cipher.getInstance(TRANSFORMATION)+ cipher.init(Cipher.ENCRYPT_MODE, secretKey())+ val iv = cipher.iv+ val ct = cipher.doFinal(plain)+ // Prefix the 12-byte GCM IV so we can recover it on decrypt.+ return ByteArray(iv.size + ct.size).also {+ iv.copyInto(it, 0)+ ct.copyInto(it, iv.size)+ }+ }++ private fun decrypt(blob: ByteArray): ByteArray {+ val iv = blob.copyOfRange(0, GCM_IV_LEN)+ val ct = blob.copyOfRange(GCM_IV_LEN, blob.size)+ val cipher = Cipher.getInstance(TRANSFORMATION)+ cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))+ return cipher.doFinal(ct)+ }++ suspend fun putTokens(accountName: String, tokens: OAuthTokens) {+ store("$OAUTH_PREFIX$accountName", json.encodeToString(tokens))+ }++ fun getTokens(accountName: String): OAuthTokens? =+ load("$OAUTH_PREFIX$accountName")?.let {+ runCatching { json.decodeFromString<OAuthTokens>(it) }.getOrNull()+ }++ suspend fun putDav(accountName: String, creds: DavCredentials) {+ store("$DAV_PREFIX$accountName", json.encodeToString(creds))+ }++ fun getDav(accountName: String): DavCredentials? =+ load("$DAV_PREFIX$accountName")?.let {+ runCatching { json.decodeFromString<DavCredentials>(it) }.getOrNull()+ }++ suspend fun clear(accountName: String) {+ // Overwrite with empty blobs; DataStore has no per-key delete here.+ ds.setByteArray("$OAUTH_PREFIX$accountName", ByteArray(0))+ ds.setByteArray("$DAV_PREFIX$accountName", ByteArray(0))+ }++ private suspend fun store(key: String, value: String) {+ try {+ ds.setByteArray(key, encrypt(value.toByteArray()))+ } catch (e: Exception) {+ Log.e(TAG, "Failed to store secret", e)+ }+ }++ private fun load(key: String): String? {+ val blob = ds.getByteArray(key) ?: return null+ if (blob.size <= GCM_IV_LEN) return null+ return try {+ String(decrypt(blob))+ } catch (e: Exception) {+ Log.e(TAG, "Failed to load secret", e)+ null+ }+ }++ companion object {+ private const val ANDROID_KEYSTORE = "AndroidKeyStore"+ private const val KEY_ALIAS = "everysync_token_key"+ private const val TRANSFORMATION = "AES/GCM/NoPadding"+ private const val GCM_IV_LEN = 12+ private const val GCM_TAG_BITS = 128+ private const val OAUTH_PREFIX = "tok_oauth_"+ private const val DAV_PREFIX = "tok_dav_"+ private const val TAG = "TokenStore"++ @Volatile+ private var instance: TokenStore? = null++ fun getInstance(context: Context): TokenStore =+ instance ?: synchronized(this) {+ instance ?: TokenStore(context.applicationContext).also { instance = it }+ }+ }+}
everysync/src/main/java/com/vayunmathur/everysync/format/ICalendar.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/format/ICalendar.kt b/everysync/src/main/java/com/vayunmathur/everysync/format/ICalendar.ktnew file mode 100644index 0000000000..83ba61aefe--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/format/ICalendar.kt@@ -0,0 +1,157 @@+package com.vayunmathur.everysync.format++import com.vayunmathur.everysync.model.RemoteEvent+import java.text.SimpleDateFormat+import java.util.Locale+import java.util.TimeZone++/**+ * Minimal iCalendar (RFC 5545) VEVENT reader/writer covering the fields+ * EverySync maps into CalendarContract. Self-contained; RRULE lines are carried+ * through verbatim.+ */+object ICalendar {++ /** Parse a VCALENDAR body into its VEVENTs. [calendarId] tags each result. */+ fun parse(text: String, calendarId: String, fallbackUid: String? = null): List<RemoteEvent> {+ val lines = unfold(text)+ val events = mutableListOf<RemoteEvent>()+ var cur: MutableMap<String, Pair<String, String>>? = null // key -> (params, value)+ for (line in lines) {+ val trimmed = line.trimEnd()+ when {+ trimmed.equals("BEGIN:VEVENT", true) -> cur = mutableMapOf()+ trimmed.equals("END:VEVENT", true) -> {+ cur?.let { events += toEvent(it, calendarId, fallbackUid) }+ cur = null+ }+ cur != null -> {+ val prop = splitProperty(trimmed)+ if (prop != null) {+ val (name, params, value) = prop+ cur[name.uppercase()] = params to value+ }+ }+ }+ }+ return events+ }++ fun serialize(e: RemoteEvent): String = buildString {+ append("BEGIN:VCALENDAR\r\n")+ append("VERSION:2.0\r\n")+ append("PRODID:-//vayunmathur//EverySync//EN\r\n")+ append("BEGIN:VEVENT\r\n")+ append("UID:${e.uid}\r\n")+ if (e.allDay) {+ append("DTSTART;VALUE=DATE:${dateOnly(e.startMillis)}\r\n")+ append("DTEND;VALUE=DATE:${dateOnly(e.endMillis)}\r\n")+ } else {+ append("DTSTART:${utc(e.startMillis)}\r\n")+ append("DTEND:${utc(e.endMillis)}\r\n")+ }+ if (e.summary.isNotBlank()) append("SUMMARY:${esc(e.summary)}\r\n")+ if (e.description.isNotBlank()) append("DESCRIPTION:${esc(e.description)}\r\n")+ if (e.location.isNotBlank()) append("LOCATION:${esc(e.location)}\r\n")+ e.rrule?.takeIf { it.isNotBlank() }?.let { append("RRULE:${it.removePrefix("RRULE:")}\r\n") }+ append("END:VEVENT\r\n")+ append("END:VCALENDAR\r\n")+ }++ private fun toEvent(+ props: Map<String, Pair<String, String>>,+ calendarId: String,+ fallbackUid: String?,+ ): RemoteEvent {+ val uid = props["UID"]?.second?.ifBlank { null } ?: fallbackUid ?: props.hashCode().toString()+ val (startMillis, startAllDay, tz) = parseTime(props["DTSTART"])+ val (endMillisRaw, _, _) = parseTime(props["DTEND"])+ val start = startMillis ?: 0L+ var end = endMillisRaw ?: (start + if (startAllDay) DAY_MS else HOUR_MS)+ if (startAllDay && end == start) end = start + DAY_MS+ return RemoteEvent(+ uid = uid,+ calendarId = calendarId,+ summary = unescape(props["SUMMARY"]?.second ?: ""),+ description = unescape(props["DESCRIPTION"]?.second ?: ""),+ location = unescape(props["LOCATION"]?.second ?: ""),+ startMillis = start,+ endMillis = end,+ allDay = startAllDay,+ timezone = tz ?: "UTC",+ rrule = props["RRULE"]?.second?.ifBlank { null },+ )+ }++ /** Returns (epochMillis?, isAllDay, tzid?). */+ private fun parseTime(prop: Pair<String, String>?): Triple<Long?, Boolean, String?> {+ if (prop == null) return Triple(null, false, null)+ val (params, value) = prop+ val up = params.uppercase()+ val allDay = up.contains("VALUE=DATE") || (value.length == 8 && value.all { it.isDigit() })+ return try {+ when {+ allDay -> {+ val fmt = SimpleDateFormat("yyyyMMdd", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }+ Triple(fmt.parse(value)?.time, true, "UTC")+ }+ value.endsWith("Z") -> {+ val fmt = SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }+ Triple(fmt.parse(value)?.time, false, "UTC")+ }+ else -> {+ val tzid = extractTzid(params)+ val fmt = SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.US).apply {+ timeZone = tzid?.let { TimeZone.getTimeZone(it) } ?: TimeZone.getTimeZone("UTC")+ }+ Triple(fmt.parse(value)?.time, false, tzid ?: "UTC")+ }+ }+ } catch (_: Exception) {+ Triple(null, allDay, null)+ }+ }++ private fun extractTzid(params: String): String? =+ params.split(";").map { it.split("=", limit = 2) }+ .firstOrNull { it.size == 2 && it[0].uppercase() == "TZID" }?.get(1)++ private fun utc(millis: Long): String =+ SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.US)+ .apply { timeZone = TimeZone.getTimeZone("UTC") }.format(millis)++ private fun dateOnly(millis: Long): String =+ SimpleDateFormat("yyyyMMdd", Locale.US)+ .apply { timeZone = TimeZone.getTimeZone("UTC") }.format(millis)++ private fun unfold(text: String): List<String> {+ val out = mutableListOf<String>()+ for (raw in text.replace("\r\n", "\n").split("\n")) {+ if ((raw.startsWith(" ") || raw.startsWith("\t")) && out.isNotEmpty()) {+ out[out.lastIndex] = out.last() + raw.trimStart()+ } else {+ out.add(raw)+ }+ }+ return out+ }++ private fun splitProperty(line: String): Triple<String, String, String>? {+ val colon = line.indexOf(':')+ if (colon <= 0) return null+ val left = line.take(colon)+ val value = line.substring(colon + 1)+ val semi = left.indexOf(';')+ return if (semi > 0) Triple(left.take(semi), left.substring(semi + 1), value)+ else Triple(left, "", value)+ }++ private fun esc(s: String): String =+ s.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,").replace("\n", "\\n")++ private fun unescape(s: String): String =+ s.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")++ private const val HOUR_MS = 60L * 60L * 1000L+ private const val DAY_MS = 24L * HOUR_MS+}
everysync/src/main/java/com/vayunmathur/everysync/format/VCard.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/format/VCard.kt b/everysync/src/main/java/com/vayunmathur/everysync/format/VCard.ktnew file mode 100644index 0000000000..a50ca989de--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/format/VCard.kt@@ -0,0 +1,177 @@+package com.vayunmathur.everysync.format++import android.provider.ContactsContract.CommonDataKinds.Email+import android.provider.ContactsContract.CommonDataKinds.Phone+import android.provider.ContactsContract.CommonDataKinds.StructuredPostal+import com.vayunmathur.everysync.model.RemoteContact+import com.vayunmathur.everysync.model.TypedValue++/**+ * Minimal vCard 3.0/4.0 reader/writer covering the fields EverySync maps into+ * ContactsContract. Self-contained so `:everysync` needs no cross-module+ * dependency on the contacts app's VcfUtils.+ */+object VCard {++ fun parse(text: String, fallbackUid: String? = null): RemoteContact {+ val lines = unfold(text)+ var uid = fallbackUid ?: ""+ var fn = ""+ var prefix = ""+ var first = ""+ var middle = ""+ var last = ""+ var suffix = ""+ var org = ""+ var note = ""+ var bday: String? = null+ val phones = mutableListOf<TypedValue>()+ val emails = mutableListOf<TypedValue>()+ val addresses = mutableListOf<TypedValue>()++ for (line in lines) {+ val (name, params, value) = splitProperty(line) ?: continue+ when (name.uppercase()) {+ "UID" -> uid = value.ifBlank { uid }+ "FN" -> fn = unescape(value)+ "N" -> {+ val parts = value.split(";")+ last = unescape(parts.getOrElse(0) { "" })+ first = unescape(parts.getOrElse(1) { "" })+ middle = unescape(parts.getOrElse(2) { "" })+ prefix = unescape(parts.getOrElse(3) { "" })+ suffix = unescape(parts.getOrElse(4) { "" })+ }+ "ORG" -> org = unescape(value.split(";").firstOrNull() ?: value)+ "NOTE" -> note = unescape(value)+ "BDAY" -> bday = normalizeDate(value)+ "TEL" -> phones += TypedValue(unescape(value), phoneType(params))+ "EMAIL" -> emails += TypedValue(unescape(value), emailType(params))+ "ADR" -> addresses += TypedValue(formatAddress(value), addressType(params))+ }+ }+ if (fn.isBlank()) fn = listOf(prefix, first, middle, last, suffix).filter { it.isNotBlank() }.joinToString(" ")+ return RemoteContact(+ uid = uid,+ displayName = fn,+ prefix = prefix,+ firstName = first,+ middleName = middle,+ lastName = last,+ suffix = suffix,+ organization = org,+ note = note,+ phones = phones,+ emails = emails,+ addresses = addresses,+ birthday = bday,+ )+ }++ fun serialize(c: RemoteContact): String = buildString {+ append("BEGIN:VCARD\r\n")+ append("VERSION:3.0\r\n")+ append("UID:${c.uid}\r\n")+ append("N:${esc(c.lastName)};${esc(c.firstName)};${esc(c.middleName)};${esc(c.prefix)};${esc(c.suffix)}\r\n")+ append("FN:${esc(c.displayName)}\r\n")+ if (c.organization.isNotBlank()) append("ORG:${esc(c.organization)}\r\n")+ for (p in c.phones) append("TEL;TYPE=${phoneTypeName(p.type)}:${esc(p.value)}\r\n")+ for (e in c.emails) append("EMAIL;TYPE=${emailTypeName(e.type)}:${esc(e.value)}\r\n")+ for (a in c.addresses) append("ADR;TYPE=${addressTypeName(a.type)}:;;${esc(a.value)};;;;\r\n")+ c.birthday?.let { append("BDAY:$it\r\n") }+ if (c.note.isNotBlank()) append("NOTE:${esc(c.note)}\r\n")+ append("END:VCARD\r\n")+ }++ // --- helpers ---++ /** RFC 6350 line unfolding: continuation lines start with space/tab. */+ private fun unfold(text: String): List<String> {+ val out = mutableListOf<String>()+ for (raw in text.replace("\r\n", "\n").split("\n")) {+ if ((raw.startsWith(" ") || raw.startsWith("\t")) && out.isNotEmpty()) {+ out[out.lastIndex] = out.last() + raw.trimStart()+ } else {+ out.add(raw)+ }+ }+ return out+ }++ private data class Prop(val name: String, val params: String, val value: String)++ private fun splitProperty(line: String): Prop? {+ val colon = line.indexOf(':')+ if (colon <= 0) return null+ val left = line.take(colon)+ val value = line.substring(colon + 1)+ val semi = left.indexOf(';')+ return if (semi > 0) Prop(left.take(semi), left.substring(semi + 1), value)+ else Prop(left, "", value)+ }++ private fun paramTypes(params: String): List<String> =+ params.split(";")+ .flatMap { it.removePrefix("TYPE=").removePrefix("type=").split(",") }+ .map { it.trim().uppercase() }+ .filter { it.isNotBlank() }++ private fun phoneType(params: String): Int = when {+ paramTypes(params).any { it == "CELL" || it == "MOBILE" } -> Phone.TYPE_MOBILE+ paramTypes(params).contains("WORK") -> Phone.TYPE_WORK+ paramTypes(params).contains("HOME") -> Phone.TYPE_HOME+ paramTypes(params).contains("FAX") -> Phone.TYPE_FAX_HOME+ else -> Phone.TYPE_OTHER+ }++ private fun phoneTypeName(type: Int): String = when (type) {+ Phone.TYPE_MOBILE -> "CELL"+ Phone.TYPE_WORK -> "WORK"+ Phone.TYPE_HOME -> "HOME"+ Phone.TYPE_FAX_HOME, Phone.TYPE_FAX_WORK -> "FAX"+ else -> "VOICE"+ }++ private fun emailType(params: String): Int = when {+ paramTypes(params).contains("WORK") -> Email.TYPE_WORK+ paramTypes(params).contains("HOME") -> Email.TYPE_HOME+ else -> Email.TYPE_OTHER+ }++ private fun emailTypeName(type: Int): String = when (type) {+ Email.TYPE_WORK -> "WORK"+ Email.TYPE_HOME -> "HOME"+ else -> "INTERNET"+ }++ private fun addressType(params: String): Int = when {+ paramTypes(params).contains("WORK") -> StructuredPostal.TYPE_WORK+ paramTypes(params).contains("HOME") -> StructuredPostal.TYPE_HOME+ else -> StructuredPostal.TYPE_OTHER+ }++ private fun addressTypeName(type: Int): String = when (type) {+ StructuredPostal.TYPE_WORK -> "WORK"+ StructuredPostal.TYPE_HOME -> "HOME"+ else -> "OTHER"+ }++ /** ADR is ;;street;city;region;code;country โ flatten to a display string. */+ private fun formatAddress(value: String): String =+ value.split(";").map { unescape(it) }.filter { it.isNotBlank() }.joinToString(", ")++ private fun normalizeDate(value: String): String? {+ val v = value.trim()+ return when {+ v.matches(Regex("\\d{4}-\\d{2}-\\d{2}")) -> v+ v.matches(Regex("\\d{8}")) -> "${v.take(4)}-${v.substring(4, 6)}-${v.substring(6, 8)}"+ else -> v.takeIf { it.isNotBlank() }+ }+ }++ private fun esc(s: String): String =+ s.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,").replace("\n", "\\n")++ private fun unescape(s: String): String =+ s.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")+}
everysync/src/main/java/com/vayunmathur/everysync/model/RemoteModels.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/model/RemoteModels.kt b/everysync/src/main/java/com/vayunmathur/everysync/model/RemoteModels.ktnew file mode 100644index 0000000000..27fe6c98a6--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/model/RemoteModels.kt@@ -0,0 +1,78 @@+package com.vayunmathur.everysync.model++/** A contact resolved from a remote source (CardDAV vCard or Google People). */+data class RemoteContact(+ /** Stable remote identifier (vCard UID or People resourceName). */+ val uid: String,+ /** Server ETag for change detection, if known. */+ val etag: String? = null,+ val displayName: String = "",+ val prefix: String = "",+ val firstName: String = "",+ val middleName: String = "",+ val lastName: String = "",+ val suffix: String = "",+ val organization: String = "",+ val note: String = "",+ /** number -> type (ContactsContract.CommonDataKinds.Phone type int). */+ val phones: List<TypedValue> = emptyList(),+ val emails: List<TypedValue> = emptyList(),+ val addresses: List<TypedValue> = emptyList(),+ /** ISO-8601 birthday (yyyy-MM-dd) or null. */+ val birthday: String? = null,+ /** For CardDAV: the resource path on the server (collection-relative). */+ val href: String? = null,+ val deleted: Boolean = false,+)++data class TypedValue(val value: String, val type: Int)++/** A calendar collection (CalDAV collection or Google calendarList entry). */+data class RemoteCalendar(+ val id: String,+ val displayName: String,+ val color: Int? = null,+ /** CalDAV collection ctag for cheap change detection. */+ val ctag: String? = null,+ /** CalDAV collection URL. */+ val url: String? = null,+)++/** A calendar event resolved from a remote source. */+data class RemoteEvent(+ val uid: String,+ val etag: String? = null,+ val calendarId: String,+ val summary: String = "",+ val description: String = "",+ val location: String = "",+ val startMillis: Long = 0L,+ val endMillis: Long = 0L,+ val allDay: Boolean = false,+ val timezone: String = "UTC",+ /** Raw RRULE line (without the "RRULE:" prefix), or null. */+ val rrule: String? = null,+ val href: String? = null,+ val deleted: Boolean = false,+)++/** A health measurement destined for Health Connect. */+data class RemoteMeasurement(+ /** Provider-scoped stable id, used as Health Connect clientRecordId. */+ val clientRecordId: String,+ val type: MeasurementType,+ val value: Double,+ /** Secondary value (e.g. diastolic for blood pressure). */+ val value2: Double = 0.0,+ val timeMillis: Long,+)++enum class MeasurementType {+ WEIGHT,+ HEIGHT,+ BODY_FAT,+ HEART_RATE,+ RESTING_HEART_RATE,+ OXYGEN_SATURATION,+ STEPS,+}
everysync/src/main/java/com/vayunmathur/everysync/provider/DataType.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/DataType.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/DataType.ktnew file mode 100644index 0000000000..331067c697--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/DataType.kt@@ -0,0 +1,27 @@+package com.vayunmathur.everysync.provider++/** The three domains EverySync can land into on-device system providers. */+enum class DataType {+ CONTACTS,+ CALENDAR,+ HEALTH,+}++/** How an account authenticates against its provider. */+enum class AuthType {+ /** OAuth2 Authorization Code + PKCE via Custom Tabs (Google, Withings). */+ OAUTH,++ /** CalDAV / CardDAV with a base URL + app-specific password (generic, Apple/iCloud). */+ DAV,++ /** No remote auth: data already lives in Health Connect (Samsung / Google Health). */+ HEALTH_CONNECT,+}++/** Direction a sync runs in. */+enum class SyncDirection {+ PULL,+ PUSH,+ BOTH,+}
everysync/src/main/java/com/vayunmathur/everysync/provider/ProviderRegistry.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/ProviderRegistry.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/ProviderRegistry.ktnew file mode 100644index 0000000000..3ee9bf1ddf--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/ProviderRegistry.kt@@ -0,0 +1,24 @@+package com.vayunmathur.everysync.provider++import com.vayunmathur.everysync.provider.impl.GenericCalDavProvider+import com.vayunmathur.everysync.provider.impl.GenericCardDavProvider+import com.vayunmathur.everysync.provider.impl.GoogleHealthProvider+import com.vayunmathur.everysync.provider.impl.GoogleProvider+import com.vayunmathur.everysync.provider.impl.ICloudProvider+import com.vayunmathur.everysync.provider.impl.SamsungHealthProvider+import com.vayunmathur.everysync.provider.impl.WithingsProvider++/** Static list of every provider EverySync ships. Drives the "Add account" grid. */+object ProviderRegistry {+ val all: List<SyncProvider> = listOf(+ GoogleProvider(),+ ICloudProvider(),+ GenericCalDavProvider(),+ GenericCardDavProvider(),+ WithingsProvider(),+ SamsungHealthProvider(),+ GoogleHealthProvider(),+ )++ fun get(id: String): SyncProvider? = all.firstOrNull { it.id == id }+}
everysync/src/main/java/com/vayunmathur/everysync/provider/SyncProvider.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/SyncProvider.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/SyncProvider.ktnew file mode 100644index 0000000000..24275bc9bd--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/SyncProvider.kt@@ -0,0 +1,40 @@+package com.vayunmathur.everysync.provider++import android.content.Context+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.OAuthConfig+import com.vayunmathur.everysync.auth.OAuthTokens++/**+ * A cloud service EverySync can sync into the on-device system providers.+ *+ * Direct-cloud providers (Google, generic CalDAV/CardDAV, Apple/iCloud, Withings)+ * make real network round-trips. Health-Connect-backed providers (Samsung Health,+ * Google Health) read data already present in Health Connect on-device.+ */+interface SyncProvider {+ val id: String+ val displayName: String+ val iconRes: Int+ val authType: AuthType+ val capabilities: Set<DataType>++ /** OAuth configuration for [AuthType.OAUTH] providers, else null. */+ fun oauthConfig(): OAuthConfig? = null++ /** Preset DAV base URL for [AuthType.DAV] providers (e.g. iCloud), else null (user enters one). */+ val davPresetUrl: String? get() = null++ /** Whether this provider is serviced through Health Connect rather than a direct cloud API. */+ val viaHealthConnect: Boolean get() = false++ /**+ * Resolve a stable, human-readable account name from freshly obtained OAuth+ * tokens (e.g. the user's email). Default returns a short token fingerprint.+ */+ suspend fun resolveAccountName(context: Context, tokens: OAuthTokens): String =+ "$displayName (${tokens.accessToken.take(6)})"++ /** Run one sync pass for [config] in the requested [direction]. */+ suspend fun sync(context: Context, config: AccountConfig, direction: SyncDirection)+}
everysync/src/main/java/com/vayunmathur/everysync/provider/SyncState.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/SyncState.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/SyncState.ktnew file mode 100644index 0000000000..c50eb6f045--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/SyncState.kt@@ -0,0 +1,19 @@+package com.vayunmathur.everysync.provider++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils++/**+ * Per-account, per-scope sync cursors (Google syncTokens, CalDAV ctags,+ * Withings lastupdate, Health Connect changes tokens) persisted in DataStore.+ */+object SyncState {+ private fun key(account: String, scope: String) = "syncstate_${account}_$scope"++ fun get(context: Context, account: String, scope: String): String? =+ DataStoreUtils.getInstance(context).getString(key(account, scope))?.ifBlank { null }++ suspend fun set(context: Context, account: String, scope: String, value: String?) {+ DataStoreUtils.getInstance(context).setString(key(account, scope), value ?: "")+ }+}
everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProvider.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProvider.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProvider.ktnew file mode 100644index 0000000000..430a60adb7--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProvider.kt@@ -0,0 +1,136 @@+package com.vayunmathur.everysync.provider.impl++import android.content.Context+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.TokenStore+import com.vayunmathur.everysync.format.ICalendar+import com.vayunmathur.everysync.format.VCard+import com.vayunmathur.everysync.provider.AuthType+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.provider.SyncDirection+import com.vayunmathur.everysync.provider.SyncProvider+import com.vayunmathur.everysync.remote.DavClient+import com.vayunmathur.everysync.sink.CalendarSink+import com.vayunmathur.everysync.sink.ContactsSink+import java.util.UUID++/**+ * Base CalDAV/CardDAV provider. Resource hrefs are used as the local SOURCE_ID /+ * _SYNC_ID so ETag comparison is direct; server deletions are detected by set+ * difference. Two-way: local edits are pushed back via PUT/DELETE with If-Match.+ */+abstract class DavProvider(+ override val id: String,+ override val displayName: String,+ override val iconRes: Int,+ override val capabilities: Set<DataType>,+ override val davPresetUrl: String? = null,+) : SyncProvider {+ override val authType = AuthType.DAV++ /** Base URL to discover addressbook collections from. */+ protected open fun contactsBaseUrl(config: AccountConfig, creds: com.vayunmathur.everysync.auth.DavCredentials): String =+ config.davBaseUrl ?: creds.baseUrl++ /** Base URL to discover calendar collections from. */+ protected open fun calendarBaseUrl(config: AccountConfig, creds: com.vayunmathur.everysync.auth.DavCredentials): String =+ config.davBaseUrl ?: creds.baseUrl++ override suspend fun sync(context: Context, config: AccountConfig, direction: SyncDirection) {+ val creds = TokenStore.getInstance(context).getDav(config.accountName) ?: return+ val client = DavClient(creds)+ val account = config.accountName++ if (DataType.CONTACTS in capabilities && DataType.CONTACTS in config.enabledTypes) {+ syncContacts(context, account, client, contactsBaseUrl(config, creds), direction)+ }+ if (DataType.CALENDAR in capabilities && DataType.CALENDAR in config.enabledTypes) {+ syncCalendars(context, account, client, calendarBaseUrl(config, creds), direction)+ }+ }++ private suspend fun syncContacts(context: Context, account: String, client: DavClient, baseUrl: String, direction: SyncDirection) {+ val collections = client.discoverCollections(baseUrl, isCalendar = false)+ val allRemoteHrefs = mutableSetOf<String>()++ if (direction != SyncDirection.PUSH) {+ val local = ContactsSink.localUidToEtag(context, account)+ for (col in collections) {+ val resources = client.listResources(col.url)+ allRemoteHrefs += resources.map { it.href }+ val changed = resources.filter { local[it.href] != it.etag }+ val fetched = client.multiget(col.url, changed.map { it.href }, isCalendar = false)+ for (res in fetched) {+ val data = res.data ?: continue+ val parsed = VCard.parse(data, fallbackUid = res.href)+ ContactsSink.upsert(context, account, parsed.copy(uid = res.href, etag = res.etag, href = res.href))+ }+ }+ // Server-side deletions.+ (local.keys - allRemoteHrefs).forEach { ContactsSink.delete(context, account, it) }+ }++ if (direction != SyncDirection.PULL && collections.isNotEmpty()) {+ val collectionUrl = collections.first().url.trimEnd('/')+ for (change in ContactsSink.getLocalChanges(context, account)) {+ when {+ change.deleted && change.sourceId != null -> client.delete(change.sourceId, change.etag)+ !change.deleted && change.contact != null -> {+ val href = change.sourceId ?: "$collectionUrl/${UUID.randomUUID()}.vcf"+ val vcard = VCard.serialize(change.contact.copy(uid = change.contact.uid.ifBlank { href }))+ val newEtag = client.put(href, "text/vcard; charset=utf-8", vcard, change.etag)+ if (change.sourceId == null) {+ ContactsSink.setSourceId(context, account, change.rawContactId, href, newEtag)+ } else {+ ContactsSink.clearDirty(context, account, change.rawContactId)+ }+ }+ }+ }+ }+ }++ private suspend fun syncCalendars(context: Context, account: String, client: DavClient, baseUrl: String, direction: SyncDirection) {+ val collections = client.discoverCollections(baseUrl, isCalendar = true)+ for (col in collections) {+ val localCalId = CalendarSink.getOrCreateCalendarId(context, account, col.url, col.displayName, col.color)+ if (localCalId == -1L) continue++ if (direction != SyncDirection.PUSH) {+ val local = CalendarSink.localUidToEtag(context, account, localCalId)+ val resources = client.listResources(col.url)+ val remoteHrefs = resources.map { it.href }.toSet()+ val changed = resources.filter { local[it.href] != it.etag }+ val fetched = client.multiget(col.url, changed.map { it.href }, isCalendar = true)+ for (res in fetched) {+ val data = res.data ?: continue+ ICalendar.parse(data, calendarId = localCalId.toString(), fallbackUid = res.href).forEach { ev ->+ CalendarSink.upsertEvent(context, account, localCalId, ev.copy(uid = res.href, etag = res.etag, href = res.href))+ }+ }+ (local.keys - remoteHrefs).forEach { CalendarSink.deleteEvent(context, account, localCalId, it) }+ }++ if (direction != SyncDirection.PULL) {+ val collectionUrl = col.url.trimEnd('/')+ for (change in CalendarSink.getLocalChanges(context, account, localCalId)) {+ when {+ change.deleted && change.syncId != null -> client.delete(change.syncId, change.etag)+ !change.deleted && change.event != null -> {+ val href = change.syncId ?: "$collectionUrl/${UUID.randomUUID()}.ics"+ val ics = ICalendar.serialize(change.event.copy(uid = change.event.uid.ifBlank { href }))+ val newEtag = client.put(href, "text/calendar; charset=utf-8", ics, change.etag)+ if (change.syncId == null) {+ // Re-create under the server href so future syncs match.+ CalendarSink.deleteEvent(context, account, localCalId, change.event.uid)+ CalendarSink.upsertEvent(context, account, localCalId, change.event.copy(uid = href, etag = newEtag, href = href))+ } else {+ CalendarSink.clearDirty(context, account, change.eventId)+ }+ }+ }+ }+ }+ }+ }+}
everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProviders.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProviders.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProviders.ktnew file mode 100644index 0000000000..c85f245a94--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProviders.kt@@ -0,0 +1,38 @@+package com.vayunmathur.everysync.provider.impl++import com.vayunmathur.everysync.R+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.DavCredentials+import com.vayunmathur.everysync.provider.DataType++/**+ * Apple / iCloud, delivered as a preconfigured CalDAV + CardDAV account (Apple has+ * no public REST API). Requires an app-specific password. Contacts and calendars+ * live on different iCloud hosts.+ */+class ICloudProvider : DavProvider(+ id = "icloud",+ displayName = "Apple / iCloud",+ iconRes = R.drawable.ic_provider,+ capabilities = setOf(DataType.CONTACTS, DataType.CALENDAR),+ davPresetUrl = "https://caldav.icloud.com",+) {+ override fun contactsBaseUrl(config: AccountConfig, creds: DavCredentials) = "https://contacts.icloud.com"+ override fun calendarBaseUrl(config: AccountConfig, creds: DavCredentials) = "https://caldav.icloud.com"+}++/** Generic CalDAV server (RFC 4791). User supplies the collection/principal URL. */+class GenericCalDavProvider : DavProvider(+ id = "caldav",+ displayName = "CalDAV server",+ iconRes = R.drawable.ic_provider,+ capabilities = setOf(DataType.CALENDAR),+)++/** Generic CardDAV server (RFC 6352). User supplies the collection/principal URL. */+class GenericCardDavProvider : DavProvider(+ id = "carddav",+ displayName = "CardDAV server",+ iconRes = R.drawable.ic_provider,+ capabilities = setOf(DataType.CONTACTS),+)
everysync/src/main/java/com/vayunmathur/everysync/provider/impl/GoogleProvider.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/GoogleProvider.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/GoogleProvider.ktnew file mode 100644index 0000000000..5cf927fd7e--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/GoogleProvider.kt@@ -0,0 +1,112 @@+package com.vayunmathur.everysync.provider.impl++import android.content.Context+import android.util.Log+import com.vayunmathur.everysync.R+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.OAuthConfig+import com.vayunmathur.everysync.auth.OAuthManager+import com.vayunmathur.everysync.auth.OAuthTokens+import com.vayunmathur.everysync.provider.AuthType+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.provider.SyncDirection+import com.vayunmathur.everysync.provider.SyncProvider+import com.vayunmathur.everysync.provider.SyncState+import com.vayunmathur.everysync.remote.GoogleCalendarClient+import com.vayunmathur.everysync.remote.GooglePeopleClient+import com.vayunmathur.everysync.sink.CalendarSink+import com.vayunmathur.everysync.sink.ContactsSink+import com.vayunmathur.library.network.NetworkClient+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonPrimitive++/** Google (People API + Calendar API), OAuth PKCE, contacts + calendar, two-way. */+class GoogleProvider : SyncProvider {+ override val id = "google"+ override val displayName = "Google"+ override val iconRes = R.drawable.ic_provider+ override val authType = AuthType.OAUTH+ override val capabilities = setOf(DataType.CONTACTS, DataType.CALENDAR)++ override fun oauthConfig(): OAuthConfig = OAuthConfig.GOOGLE++ override suspend fun resolveAccountName(context: Context, tokens: OAuthTokens): String {+ return try {+ val resp = NetworkClient.performRequest(+ "https://www.googleapis.com/oauth2/v3/userinfo", "GET",+ mapOf("Authorization" to "Bearer ${tokens.accessToken}"),+ )+ val email = (JSON.parseToJsonElement(resp.body) as? JsonObject)+ ?.get("email")?.jsonPrimitive?.content+ if (!email.isNullOrBlank()) "$email (Google)" else "Google account"+ } catch (e: Exception) {+ Log.e(TAG, "resolveAccountName failed", e)+ "Google account"+ }+ }++ override suspend fun sync(context: Context, config: AccountConfig, direction: SyncDirection) {+ val token = OAuthManager.validAccessToken(context, config.accountName, id) ?: return+ val account = config.accountName++ if (DataType.CONTACTS in config.enabledTypes) syncContacts(context, account, token, direction)+ if (DataType.CALENDAR in config.enabledTypes) syncCalendars(context, account, token, direction)+ }++ private suspend fun syncContacts(context: Context, account: String, token: String, direction: SyncDirection) {+ val people = GooglePeopleClient(token)+ if (direction != SyncDirection.PUSH) {+ val result = people.listConnections(SyncState.get(context, account, "google_contacts"))+ for (c in result.contacts) {+ if (c.deleted) ContactsSink.delete(context, account, c.uid)+ else ContactsSink.upsert(context, account, c)+ }+ result.nextSyncToken?.let { SyncState.set(context, account, "google_contacts", it) }+ }+ if (direction != SyncDirection.PULL) {+ for (change in ContactsSink.getLocalChanges(context, account)) {+ when {+ change.deleted && change.sourceId != null -> people.deleteContact(change.sourceId)+ !change.deleted && change.sourceId == null && change.contact != null -> {+ val newUid = people.createContact(change.contact)+ if (newUid != null) ContactsSink.setSourceId(context, account, change.rawContactId, newUid, null)+ }+ }+ if (!change.deleted) ContactsSink.clearDirty(context, account, change.rawContactId)+ }+ }+ }++ private suspend fun syncCalendars(context: Context, account: String, token: String, direction: SyncDirection) {+ val cal = GoogleCalendarClient(token)+ val remoteCalendars = cal.listCalendars()+ for (rc in remoteCalendars) {+ val localCalId = CalendarSink.getOrCreateCalendarId(context, account, rc.id, rc.displayName, rc.color)+ if (localCalId == -1L) continue+ if (direction != SyncDirection.PUSH) {+ val result = cal.listEvents(rc.id, SyncState.get(context, account, "google_cal_${rc.id}"))+ for (e in result.events) {+ if (e.deleted) CalendarSink.deleteEvent(context, account, localCalId, e.uid)+ else CalendarSink.upsertEvent(context, account, localCalId, e)+ }+ result.nextSyncToken?.let { SyncState.set(context, account, "google_cal_${rc.id}", it) }+ }+ if (direction != SyncDirection.PULL) {+ for (change in CalendarSink.getLocalChanges(context, account, localCalId)) {+ when {+ change.deleted && change.syncId != null -> cal.deleteEvent(rc.id, change.syncId)+ !change.deleted && change.syncId == null && change.event != null ->+ cal.createEvent(rc.id, change.event)+ !change.deleted -> CalendarSink.clearDirty(context, account, change.eventId)+ }+ }+ }+ }+ }++ companion object {+ private const val TAG = "GoogleProvider"+ private val JSON = Json { ignoreUnknownKeys = true }+ }+}
everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthConnectProviders.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthConnectProviders.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthConnectProviders.ktnew file mode 100644index 0000000000..db8483d980--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthConnectProviders.kt@@ -0,0 +1,38 @@+package com.vayunmathur.everysync.provider.impl++import android.content.Context+import com.vayunmathur.everysync.R+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.provider.AuthType+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.provider.SyncDirection+import com.vayunmathur.everysync.provider.SyncProvider+import com.vayunmathur.everysync.provider.SyncState+import com.vayunmathur.everysync.remote.HealthConnectBridge++/**+ * Health-Connect-backed provider (Samsung Health / Google Health). These have no+ * open cloud REST API โ their data is written into Health Connect on-device โ so+ * "sync" walks the Health Connect changes feed to confirm/track records. Clearly+ * labelled in the UI as being serviced through Health Connect.+ */+abstract class HealthConnectProvider(+ override val id: String,+ override val displayName: String,+) : SyncProvider {+ override val iconRes = R.drawable.ic_provider+ override val authType = AuthType.HEALTH_CONNECT+ override val capabilities = setOf(DataType.HEALTH)+ override val viaHealthConnect = true++ override suspend fun sync(context: Context, config: AccountConfig, direction: SyncDirection) {+ if (DataType.HEALTH !in config.enabledTypes) return+ val token = SyncState.get(context, config.accountName, "hc_changes_token")+ val result = HealthConnectBridge.pullChanges(context, token)+ SyncState.set(context, config.accountName, "hc_changes_token", result.nextToken)+ }+}++class SamsungHealthProvider : HealthConnectProvider("samsung_health", "Samsung Health")++class GoogleHealthProvider : HealthConnectProvider("google_health", "Google Health")
everysync/src/main/java/com/vayunmathur/everysync/provider/impl/WithingsProvider.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/WithingsProvider.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/WithingsProvider.ktnew file mode 100644index 0000000000..894beb822b--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/WithingsProvider.kt@@ -0,0 +1,41 @@+package com.vayunmathur.everysync.provider.impl++import android.content.Context+import com.vayunmathur.everysync.R+import com.vayunmathur.everysync.auth.AccountConfig+import com.vayunmathur.everysync.auth.OAuthConfig+import com.vayunmathur.everysync.auth.OAuthManager+import com.vayunmathur.everysync.auth.OAuthTokens+import com.vayunmathur.everysync.provider.AuthType+import com.vayunmathur.everysync.provider.DataType+import com.vayunmathur.everysync.provider.SyncDirection+import com.vayunmathur.everysync.provider.SyncProvider+import com.vayunmathur.everysync.provider.SyncState+import com.vayunmathur.everysync.remote.WithingsClient+import com.vayunmathur.everysync.sink.HealthSink++/**+ * Withings, OAuth2, the one direct health-cloud integration. Pulls body + vitals+ * measurements into Health Connect (pull-dominant โ Withings is upstream).+ */+class WithingsProvider : SyncProvider {+ override val id = "withings"+ override val displayName = "Withings"+ override val iconRes = R.drawable.ic_provider+ override val authType = AuthType.OAUTH+ override val capabilities = setOf(DataType.HEALTH)++ override fun oauthConfig(): OAuthConfig = OAuthConfig.WITHINGS++ override suspend fun resolveAccountName(context: Context, tokens: OAuthTokens): String =+ "Withings (${tokens.accessToken.take(6)})"++ override suspend fun sync(context: Context, config: AccountConfig, direction: SyncDirection) {+ if (DataType.HEALTH !in config.enabledTypes) return+ val token = OAuthManager.validAccessToken(context, config.accountName, id) ?: return+ val since = SyncState.get(context, config.accountName, "withings_lastupdate")?.toLongOrNull() ?: 0L+ val measurements = WithingsClient(token).getMeasurements(since)+ HealthSink.upsert(context, measurements)+ SyncState.set(context, config.accountName, "withings_lastupdate", (System.currentTimeMillis() / 1000).toString())+ }+}
everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.ktnew file mode 100644index 0000000000..9aacd17cba--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.kt@@ -0,0 +1,207 @@+package com.vayunmathur.everysync.remote++import android.util.Log+import com.vayunmathur.everysync.auth.DavCredentials+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.SimpleResponse+import org.w3c.dom.Element+import java.io.ByteArrayInputStream+import java.net.URI+import javax.xml.parsers.DocumentBuilderFactory+import kotlin.io.encoding.Base64++/** A single WebDAV resource (vCard / iCalendar object) with its ETag. */+data class DavResource(+ val href: String,+ val etag: String?,+ val data: String? = null,+)++/** A discovered DAV collection (addressbook or calendar). */+data class DavCollection(+ val url: String,+ val displayName: String,+ val ctag: String? = null,+ val color: Int? = null,+)++/**+ * WebDAV client for CalDAV (RFC 4791) and CardDAV (RFC 6352) over the shared+ * ktor [NetworkClient], using the custom methods PROPFIND / REPORT / PUT / DELETE.+ * Change detection uses collection ctags and per-resource ETags; the caller+ * decides what to re-fetch.+ */+class DavClient(private val creds: DavCredentials) {++ private fun authHeaders(extra: Map<String, String> = emptyMap()): Map<String, String> {+ val basic = Base64.encode("${creds.username}:${creds.password}".toByteArray())+ return mapOf("Authorization" to "Basic $basic") + extra+ }++ private suspend fun request(url: String, method: String, headers: Map<String, String>, body: String?): SimpleResponse =+ NetworkClient.performRequest(url, method, headers, body)++ /** Discover addressbook or calendar collections under [baseUrl]. */+ suspend fun discoverCollections(baseUrl: String, isCalendar: Boolean): List<DavCollection> {+ val propBody = if (isCalendar) {+ """<?xml version="1.0"?>+ <d:propfind xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:ic="http://apple.com/ns/ical/">+ <d:prop><d:resourcetype/><d:displayname/><cs:getctag/><ic:calendar-color/></d:prop>+ </d:propfind>"""+ } else {+ """<?xml version="1.0"?>+ <d:propfind xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/">+ <d:prop><d:resourcetype/><d:displayname/><cs:getctag/></d:prop>+ </d:propfind>"""+ }+ val collectionTag = if (isCalendar) "calendar" else "addressbook"+ val out = mutableListOf<DavCollection>()+ try {+ val resp = request(baseUrl, "PROPFIND", authHeaders(mapOf("Depth" to "1", "Content-Type" to "application/xml")), propBody)+ val responses = parseResponses(resp.body)+ for (r in responses) {+ val types = r.resourceTypes+ if (types.contains(collectionTag)) {+ out += DavCollection(+ url = resolve(baseUrl, r.href),+ displayName = r.displayName ?: r.href.trimEnd('/').substringAfterLast('/'),+ ctag = r.ctag,+ color = r.color,+ )+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "discoverCollections failed", e)+ }+ // Fallback: treat the URL itself as the collection.+ if (out.isEmpty()) {+ out += DavCollection(url = baseUrl, displayName = baseUrl.trimEnd('/').substringAfterLast('/'))+ }+ return out+ }++ /** List resources (href + etag only) in a collection. */+ suspend fun listResources(collectionUrl: String): List<DavResource> {+ val body = """<?xml version="1.0"?>+ <d:propfind xmlns:d="DAV:"><d:prop><d:getetag/></d:prop></d:propfind>"""+ return try {+ val resp = request(collectionUrl, "PROPFIND", authHeaders(mapOf("Depth" to "1", "Content-Type" to "application/xml")), body)+ parseResponses(resp.body)+ .filter { !it.href.trimEnd('/').equals(URI(collectionUrl).path.trimEnd('/')) && it.etag != null }+ .map { DavResource(resolve(collectionUrl, it.href), it.etag) }+ } catch (e: Exception) {+ Log.e(TAG, "listResources failed", e); emptyList()+ }+ }++ /** Fetch full object bodies (address-data / calendar-data) for the given hrefs. */+ suspend fun multiget(collectionUrl: String, hrefs: List<String>, isCalendar: Boolean): List<DavResource> {+ if (hrefs.isEmpty()) return emptyList()+ val ns = if (isCalendar) "urn:ietf:params:xml:ns:caldav" else "urn:ietf:params:xml:ns:carddav"+ val reportName = if (isCalendar) "c:calendar-multiget" else "c:addressbook-multiget"+ val dataElem = if (isCalendar) "c:calendar-data" else "c:address-data"+ val hrefXml = hrefs.joinToString("") { "<d:href>${URI(it).path}</d:href>" }+ val body = """<?xml version="1.0"?>+ <$reportName xmlns:d="DAV:" xmlns:c="$ns">+ <d:prop><d:getetag/><$dataElem/></d:prop>+ $hrefXml+ </$reportName>"""+ return try {+ val resp = request(collectionUrl, "REPORT", authHeaders(mapOf("Depth" to "1", "Content-Type" to "application/xml")), body)+ parseResponses(resp.body).map { DavResource(resolve(collectionUrl, it.href), it.etag, it.data) }+ } catch (e: Exception) {+ Log.e(TAG, "multiget failed", e); emptyList()+ }+ }++ /** PUT an object, returning the new ETag if the server supplied one. */+ suspend fun put(url: String, contentType: String, body: String, ifMatch: String? = null): String? {+ val headers = authHeaders(buildMap {+ put("Content-Type", contentType)+ if (ifMatch != null) put("If-Match", ifMatch)+ })+ return try {+ val resp = request(url, "PUT", headers, body)+ resp.headers["ETag"]?.firstOrNull() ?: resp.headers["Etag"]?.firstOrNull()+ } catch (e: Exception) {+ Log.e(TAG, "put failed", e); null+ }+ }++ suspend fun delete(url: String, ifMatch: String? = null) {+ val headers = authHeaders(if (ifMatch != null) mapOf("If-Match" to ifMatch) else emptyMap())+ try {+ request(url, "DELETE", headers, null)+ } catch (e: Exception) {+ Log.e(TAG, "delete failed", e)+ }+ }++ // --- XML parsing ---++ private data class ParsedResponse(+ val href: String,+ val etag: String?,+ val data: String?,+ val displayName: String?,+ val ctag: String?,+ val color: Int?,+ val resourceTypes: Set<String>,+ )++ private fun parseResponses(xml: String): List<ParsedResponse> {+ if (xml.isBlank()) return emptyList()+ val out = mutableListOf<ParsedResponse>()+ try {+ val factory = DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true }+ val doc = factory.newDocumentBuilder().parse(ByteArrayInputStream(xml.toByteArray()))+ val responses = doc.getElementsByTagNameNS("*", "response")+ for (i in 0 until responses.length) {+ val resp = responses.item(i) as? Element ?: continue+ val href = firstText(resp, "href") ?: continue+ out += ParsedResponse(+ href = href,+ etag = firstText(resp, "getetag")?.trim('"'),+ data = firstText(resp, "address-data") ?: firstText(resp, "calendar-data"),+ displayName = firstText(resp, "displayname"),+ ctag = firstText(resp, "getctag"),+ color = firstText(resp, "calendar-color")?.let { parseColor(it) },+ resourceTypes = resourceTypes(resp),+ )+ }+ } catch (e: Exception) {+ Log.e(TAG, "parseResponses failed", e)+ }+ return out+ }++ private fun firstText(scope: Element, localName: String): String? {+ val nodes = scope.getElementsByTagNameNS("*", localName)+ return if (nodes.length > 0) nodes.item(0).textContent?.trim()?.ifBlank { null } else null+ }++ private fun resourceTypes(resp: Element): Set<String> {+ val types = mutableSetOf<String>()+ val rt = resp.getElementsByTagNameNS("*", "resourcetype")+ if (rt.length > 0) {+ val children = (rt.item(0) as Element).childNodes+ for (i in 0 until children.length) {+ (children.item(i) as? Element)?.localName?.let { types += it.lowercase() }+ }+ }+ return types+ }++ private fun parseColor(value: String): Int? = try {+ val hex = value.trim().removePrefix("#").take(6)+ (0xFF000000.toInt()) or hex.toInt(16)+ } catch (_: Exception) { null }++ private fun resolve(base: String, href: String): String = try {+ URI(base).resolve(href).toString()+ } catch (_: Exception) { href }++ companion object {+ private const val TAG = "DavClient"+ }+}
everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleCalendarClient.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleCalendarClient.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleCalendarClient.ktnew file mode 100644index 0000000000..601d1d235b--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleCalendarClient.kt@@ -0,0 +1,171 @@+package com.vayunmathur.everysync.remote++import android.util.Log+import com.vayunmathur.everysync.model.RemoteCalendar+import com.vayunmathur.everysync.model.RemoteEvent+import com.vayunmathur.library.network.NetworkClient+import java.text.SimpleDateFormat+import java.util.Locale+import java.util.TimeZone+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive++data class GoogleEventsResult(val events: List<RemoteEvent>, val nextSyncToken: String?)++/**+ * Google Calendar API client. Lists calendars, then pulls events incrementally+ * via `syncToken` (cancelled events come back with status=cancelled โ deletions).+ */+class GoogleCalendarClient(private val accessToken: String) {+ private val json = Json { ignoreUnknownKeys = true }+ private fun headers() = mapOf("Authorization" to "Bearer $accessToken")++ suspend fun listCalendars(): List<RemoteCalendar> {+ val out = mutableListOf<RemoteCalendar>()+ try {+ val resp = NetworkClient.performRequest(+ "https://www.googleapis.com/calendar/v3/users/me/calendarList", "GET", headers(),+ )+ val root = json.parseToJsonElement(resp.body) as? JsonObject ?: return out+ (root["items"] as? JsonArray)?.forEach { item ->+ val o = item.jsonObject+ val id = o["id"]?.jsonPrimitive?.contentSafe() ?: return@forEach+ out += RemoteCalendar(+ id = id,+ displayName = o["summary"]?.jsonPrimitive?.contentSafe() ?: id,+ color = parseColor(o["backgroundColor"]?.jsonPrimitive?.contentSafe()),+ )+ }+ } catch (e: Exception) {+ Log.e(TAG, "listCalendars failed", e)+ }+ return out+ }++ suspend fun listEvents(calendarId: String, syncToken: String?): GoogleEventsResult {+ val events = mutableListOf<RemoteEvent>()+ var pageToken: String? = null+ var nextSyncToken: String? = null+ try {+ do {+ val url = buildString {+ append("https://www.googleapis.com/calendar/v3/calendars/")+ append(java.net.URLEncoder.encode(calendarId, "UTF-8"))+ append("/events?maxResults=250&singleEvents=false")+ if (syncToken != null) append("&syncToken=$syncToken")+ if (pageToken != null) append("&pageToken=$pageToken")+ }+ val resp = NetworkClient.performRequest(url, "GET", headers())+ val root = json.parseToJsonElement(resp.body) as? JsonObject ?: break+ (root["items"] as? JsonArray)?.forEach { item ->+ parseEvent(item.jsonObject, calendarId)?.let { events += it }+ }+ pageToken = root["nextPageToken"]?.jsonPrimitive?.contentSafe()+ nextSyncToken = root["nextSyncToken"]?.jsonPrimitive?.contentSafe() ?: nextSyncToken+ } while (pageToken != null)+ } catch (e: Exception) {+ Log.e(TAG, "listEvents failed", e)+ }+ return GoogleEventsResult(events, nextSyncToken)+ }++ private fun parseEvent(o: JsonObject, calendarId: String): RemoteEvent? {+ val id = o["id"]?.jsonPrimitive?.contentSafe() ?: return null+ val status = o["status"]?.jsonPrimitive?.contentSafe()+ if (status == "cancelled") return RemoteEvent(uid = id, calendarId = calendarId, deleted = true)++ val start = o["start"]?.jsonObject+ val end = o["end"]?.jsonObject+ val allDay = start?.get("date") != null+ val startMillis = parseTime(start, allDay)+ val endMillis = parseTime(end, allDay)+ val rrule = (o["recurrence"] as? JsonArray)+ ?.map { it.jsonPrimitive.content }+ ?.firstOrNull { it.startsWith("RRULE") }+ ?.removePrefix("RRULE:")+ return RemoteEvent(+ uid = id,+ etag = o["etag"]?.jsonPrimitive?.contentSafe(),+ calendarId = calendarId,+ summary = o["summary"]?.jsonPrimitive?.contentSafe() ?: "",+ description = o["description"]?.jsonPrimitive?.contentSafe() ?: "",+ location = o["location"]?.jsonPrimitive?.contentSafe() ?: "",+ startMillis = startMillis,+ endMillis = endMillis,+ allDay = allDay,+ timezone = start?.get("timeZone")?.jsonPrimitive?.contentSafe() ?: "UTC",+ rrule = rrule,+ )+ }++ private fun parseTime(node: JsonObject?, allDay: Boolean): Long {+ node ?: return 0L+ return try {+ if (allDay) {+ val d = node["date"]?.jsonPrimitive?.contentSafe() ?: return 0L+ SimpleDateFormat("yyyy-MM-dd", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.parse(d)?.time ?: 0L+ } else {+ val dt = node["dateTime"]?.jsonPrimitive?.contentSafe() ?: return 0L+ // RFC 3339, e.g. 2024-01-02T15:04:05-08:00+ val fmt = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.US)+ fmt.parse(dt)?.time ?: 0L+ }+ } catch (_: Exception) { 0L }+ }++ private fun parseColor(hex: String?): Int? = try {+ hex?.removePrefix("#")?.take(6)?.let { (0xFF000000.toInt()) or it.toInt(16) }+ } catch (_: Exception) { null }++ /** Create an event from a local edit. Returns the new event id (uid). */+ suspend fun createEvent(calendarId: String, e: RemoteEvent): String? {+ return try {+ val resp = NetworkClient.performRequest(+ "https://www.googleapis.com/calendar/v3/calendars/${java.net.URLEncoder.encode(calendarId, "UTF-8")}/events",+ "POST", headers() + mapOf("Content-Type" to "application/json"), eventBody(e),+ )+ (json.parseToJsonElement(resp.body) as? JsonObject)?.get("id")?.jsonPrimitive?.contentSafe()+ } catch (ex: Exception) {+ Log.e(TAG, "createEvent failed", ex); null+ }+ }++ suspend fun deleteEvent(calendarId: String, eventId: String) {+ try {+ NetworkClient.performRequest(+ "https://www.googleapis.com/calendar/v3/calendars/${java.net.URLEncoder.encode(calendarId, "UTF-8")}/events/${java.net.URLEncoder.encode(eventId, "UTF-8")}",+ "DELETE", headers(),+ )+ } catch (ex: Exception) {+ Log.e(TAG, "deleteEvent failed", ex)+ }+ }++ private fun eventBody(e: RemoteEvent): String {+ val iso = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }+ val dateOnly = SimpleDateFormat("yyyy-MM-dd", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }+ val startNode = if (e.allDay) "{\"date\":\"${dateOnly.format(e.startMillis)}\"}" else "{\"dateTime\":\"${iso.format(e.startMillis)}\"}"+ val endNode = if (e.allDay) "{\"date\":\"${dateOnly.format(e.endMillis)}\"}" else "{\"dateTime\":\"${iso.format(e.endMillis)}\"}"+ val sb = StringBuilder("{")+ sb.append("\"summary\":${q(e.summary)}")+ if (e.description.isNotBlank()) sb.append(",\"description\":${q(e.description)}")+ if (e.location.isNotBlank()) sb.append(",\"location\":${q(e.location)}")+ sb.append(",\"start\":$startNode,\"end\":$endNode")+ e.rrule?.takeIf { it.isNotBlank() }?.let { sb.append(",\"recurrence\":[\"RRULE:${it.removePrefix("RRULE:")}\"]") }+ sb.append("}")+ return sb.toString()+ }++ private fun q(s: String) = "\"${s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n")}\""++ private fun kotlinx.serialization.json.JsonPrimitive.contentSafe(): String? =+ runCatching { content }.getOrNull()?.ifBlank { null }++ companion object {+ private const val TAG = "GoogleCalendarClient"+ }+}
everysync/src/main/java/com/vayunmathur/everysync/remote/GooglePeopleClient.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/GooglePeopleClient.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/GooglePeopleClient.ktnew file mode 100644index 0000000000..e2bdbf39c2--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/GooglePeopleClient.kt@@ -0,0 +1,135 @@+package com.vayunmathur.everysync.remote++import android.util.Log+import com.vayunmathur.everysync.model.RemoteContact+import com.vayunmathur.everysync.model.TypedValue+import com.vayunmathur.library.network.NetworkClient+import android.provider.ContactsContract.CommonDataKinds.Email+import android.provider.ContactsContract.CommonDataKinds.Phone+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive++data class GoogleContactsResult(val contacts: List<RemoteContact>, val nextSyncToken: String?)++/**+ * Google People API client. Incremental sync uses `syncToken`: pass the token+ * from the previous pull to receive only changes (including deletions).+ */+class GooglePeopleClient(private val accessToken: String) {+ private val json = Json { ignoreUnknownKeys = true }+ private val fields = "names,emailAddresses,phoneNumbers,addresses,organizations,biographies,birthdays,metadata"++ private fun headers() = mapOf("Authorization" to "Bearer $accessToken")++ /** Pull connections. [syncToken] null = full sync (also requests a token). */+ suspend fun listConnections(syncToken: String?): GoogleContactsResult {+ val contacts = mutableListOf<RemoteContact>()+ var pageToken: String? = null+ var nextSyncToken: String? = null+ try {+ do {+ val url = buildString {+ append("https://people.googleapis.com/v1/people/me/connections")+ append("?personFields=$fields&pageSize=200&requestSyncToken=true")+ if (syncToken != null) append("&syncToken=$syncToken")+ if (pageToken != null) append("&pageToken=$pageToken")+ }+ val resp = NetworkClient.performRequest(url, "GET", headers())+ val root = json.parseToJsonElement(resp.body) as? JsonObject ?: break+ (root["connections"] as? JsonArray)?.forEach { person ->+ parsePerson(person.jsonObject)?.let { contacts += it }+ }+ pageToken = root["nextPageToken"]?.jsonPrimitive?.contentSafe()+ nextSyncToken = root["nextSyncToken"]?.jsonPrimitive?.contentSafe() ?: nextSyncToken+ } while (pageToken != null)+ } catch (e: Exception) {+ Log.e(TAG, "listConnections failed", e)+ }+ return GoogleContactsResult(contacts, nextSyncToken)+ }++ /** Create a contact from a local edit. Returns the new resourceName (uid). */+ suspend fun createContact(c: RemoteContact): String? {+ return try {+ val resp = NetworkClient.performRequest(+ "https://people.googleapis.com/v1/people:createContact",+ "POST", headers() + mapOf("Content-Type" to "application/json"), personBody(c),+ )+ (json.parseToJsonElement(resp.body) as? JsonObject)?.get("resourceName")?.jsonPrimitive?.contentSafe()+ } catch (e: Exception) {+ Log.e(TAG, "createContact failed", e); null+ }+ }++ suspend fun deleteContact(resourceName: String) {+ try {+ NetworkClient.performRequest(+ "https://people.googleapis.com/v1/$resourceName:deleteContact", "DELETE", headers(),+ )+ } catch (e: Exception) {+ Log.e(TAG, "deleteContact failed", e)+ }+ }++ private fun parsePerson(p: JsonObject): RemoteContact? {+ val resourceName = p["resourceName"]?.jsonPrimitive?.contentSafe() ?: return null+ val etag = p["etag"]?.jsonPrimitive?.contentSafe()+ val deleted = (p["metadata"] as? JsonObject)?.get("deleted")?.jsonPrimitive?.contentSafe() == "true"+ if (deleted) return RemoteContact(uid = resourceName, etag = etag, deleted = true)++ val name = (p["names"] as? JsonArray)?.firstOrNull()?.jsonObject+ val org = (p["organizations"] as? JsonArray)?.firstOrNull()?.jsonObject+ val note = (p["biographies"] as? JsonArray)?.firstOrNull()?.jsonObject?.get("value")?.jsonPrimitive?.contentSafe() ?: ""+ val bday = (p["birthdays"] as? JsonArray)?.firstOrNull()?.jsonObject?.get("date")?.jsonObject?.let { d ->+ val y = d["year"]?.jsonPrimitive?.contentSafe() ?: "1604"+ val m = d["month"]?.jsonPrimitive?.contentSafe()?.padStart(2, '0') ?: return@let null+ val day = d["day"]?.jsonPrimitive?.contentSafe()?.padStart(2, '0') ?: return@let null+ "$y-$m-$day"+ }+ return RemoteContact(+ uid = resourceName,+ etag = etag,+ displayName = name?.get("displayName")?.jsonPrimitive?.contentSafe() ?: "",+ firstName = name?.get("givenName")?.jsonPrimitive?.contentSafe() ?: "",+ middleName = name?.get("middleName")?.jsonPrimitive?.contentSafe() ?: "",+ lastName = name?.get("familyName")?.jsonPrimitive?.contentSafe() ?: "",+ prefix = name?.get("honorificPrefix")?.jsonPrimitive?.contentSafe() ?: "",+ suffix = name?.get("honorificSuffix")?.jsonPrimitive?.contentSafe() ?: "",+ organization = org?.get("name")?.jsonPrimitive?.contentSafe() ?: "",+ note = note,+ birthday = bday,+ phones = (p["phoneNumbers"] as? JsonArray)?.mapNotNull {+ it.jsonObject["value"]?.jsonPrimitive?.contentSafe()?.let { v -> TypedValue(v, Phone.TYPE_MOBILE) }+ } ?: emptyList(),+ emails = (p["emailAddresses"] as? JsonArray)?.mapNotNull {+ it.jsonObject["value"]?.jsonPrimitive?.contentSafe()?.let { v -> TypedValue(v, Email.TYPE_HOME) }+ } ?: emptyList(),+ addresses = (p["addresses"] as? JsonArray)?.mapNotNull {+ it.jsonObject["formattedValue"]?.jsonPrimitive?.contentSafe()?.let { v -> TypedValue(v, 1) }+ } ?: emptyList(),+ )+ }++ private fun personBody(c: RemoteContact): String {+ val sb = StringBuilder("{")+ sb.append("\"names\":[{\"givenName\":${q(c.firstName)},\"familyName\":${q(c.lastName)}}]")+ if (c.emails.isNotEmpty()) sb.append(",\"emailAddresses\":[${c.emails.joinToString(",") { "{\"value\":${q(it.value)}}" }}]")+ if (c.phones.isNotEmpty()) sb.append(",\"phoneNumbers\":[${c.phones.joinToString(",") { "{\"value\":${q(it.value)}}" }}]")+ if (c.organization.isNotBlank()) sb.append(",\"organizations\":[{\"name\":${q(c.organization)}}]")+ sb.append("}")+ return sb.toString()+ }++ private fun q(s: String) = "\"${s.replace("\\", "\\\\").replace("\"", "\\\"")}\""++ private fun kotlinx.serialization.json.JsonPrimitive.contentSafe(): String? =+ runCatching { content }.getOrNull()?.ifBlank { null }++ companion object {+ private const val TAG = "GooglePeopleClient"+ }+}
everysync/src/main/java/com/vayunmathur/everysync/remote/HealthConnectBridge.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/HealthConnectBridge.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/HealthConnectBridge.ktnew file mode 100644index 0000000000..dc07f6c48c--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/HealthConnectBridge.kt@@ -0,0 +1,56 @@+package com.vayunmathur.everysync.remote++import android.content.Context+import android.util.Log+import androidx.health.connect.client.HealthConnectClient+import androidx.health.connect.client.records.HeartRateRecord+import androidx.health.connect.client.records.RestingHeartRateRecord+import androidx.health.connect.client.records.SleepSessionRecord+import androidx.health.connect.client.records.StepsRecord+import androidx.health.connect.client.records.WeightRecord+import androidx.health.connect.client.request.ChangesTokenRequest++/**+ * Bridge for providers serviced through Health Connect (Samsung Health, Google+ * Health). Their data already lives in Health Connect on-device, so this simply+ * walks the changes feed to confirm/track records rather than making a cloud+ * call. Returns the number of upserted records seen and the next changes token.+ */+object HealthConnectBridge {+ private const val TAG = "HealthConnectBridge"++ private val RECORD_TYPES = setOf(+ WeightRecord::class,+ StepsRecord::class,+ HeartRateRecord::class,+ RestingHeartRateRecord::class,+ SleepSessionRecord::class,+ )++ data class Result(val upserted: Int, val deleted: Int, val nextToken: String)++ /** Walk the changes feed from [token] (null = initialize a fresh token). */+ suspend fun pullChanges(context: Context, token: String?): Result {+ val client = HealthConnectClient.getOrCreate(context)+ var current = token ?: client.getChangesToken(ChangesTokenRequest(recordTypes = RECORD_TYPES))+ var upserted = 0+ var deleted = 0+ try {+ var hasMore = true+ while (hasMore) {+ val response = client.getChanges(current)+ upserted += response.changes.count {+ it is androidx.health.connect.client.changes.UpsertionChange+ }+ deleted += response.changes.count {+ it is androidx.health.connect.client.changes.DeletionChange+ }+ current = response.nextChangesToken+ hasMore = response.hasMore+ }+ } catch (e: Exception) {+ Log.e(TAG, "pullChanges failed", e)+ }+ return Result(upserted, deleted, current)+ }+}
everysync/src/main/java/com/vayunmathur/everysync/remote/WithingsClient.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/WithingsClient.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/WithingsClient.ktnew file mode 100644index 0000000000..cb4ac83c36--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/WithingsClient.kt@@ -0,0 +1,76 @@+package com.vayunmathur.everysync.remote++import android.util.Log+import com.vayunmathur.everysync.model.MeasurementType+import com.vayunmathur.everysync.model.RemoteMeasurement+import com.vayunmathur.library.network.NetworkClient+import kotlin.math.pow+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive++/**+ * Withings REST client. Pulls body + vitals measurements and maps them to+ * [RemoteMeasurement]s for Health Connect. Each measure's stable group id makes+ * the Health Connect clientRecordId idempotent across syncs.+ */+class WithingsClient(private val accessToken: String) {+ private val json = Json { ignoreUnknownKeys = true }++ /** Pull measurements updated since [sinceEpochSecs] (0 = all). */+ suspend fun getMeasurements(sinceEpochSecs: Long): List<RemoteMeasurement> {+ val out = mutableListOf<RemoteMeasurement>()+ try {+ val body = buildString {+ append("action=getmeas&meastypes=1,6,9,10,11")+ if (sinceEpochSecs > 0) append("&lastupdate=$sinceEpochSecs")+ }+ val resp = NetworkClient.performRequest(+ "https://wbsapi.withings.net/measure", "POST",+ mapOf(+ "Authorization" to "Bearer $accessToken",+ "Content-Type" to "application/x-www-form-urlencoded",+ ),+ body,+ )+ val root = json.parseToJsonElement(resp.body) as? JsonObject ?: return out+ val groups = (root["body"] as? JsonObject)?.get("measuregrps") as? JsonArray ?: return out+ for (g in groups) {+ val grp = g.jsonObject+ val grpId = grp["grpid"]?.jsonPrimitive?.content ?: continue+ val date = (grp["date"]?.jsonPrimitive?.content?.toLongOrNull() ?: continue) * 1000+ (grp["measures"] as? JsonArray)?.forEach { m ->+ val measure = m.jsonObject+ val type = measure["type"]?.jsonPrimitive?.content?.toIntOrNull() ?: return@forEach+ val value = measure["value"]?.jsonPrimitive?.content?.toDoubleOrNull() ?: return@forEach+ val unit = measure["unit"]?.jsonPrimitive?.content?.toIntOrNull() ?: 0+ val real = value * 10.0.pow(unit)+ val mapped = mapType(type) ?: return@forEach+ out += RemoteMeasurement(+ clientRecordId = "withings:$grpId:$type",+ type = mapped,+ value = if (mapped == MeasurementType.BODY_FAT) real else real,+ timeMillis = date,+ )+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "getMeasurements failed", e)+ }+ return out+ }++ private fun mapType(withingsType: Int): MeasurementType? = when (withingsType) {+ 1 -> MeasurementType.WEIGHT+ 6 -> MeasurementType.BODY_FAT+ 11 -> MeasurementType.HEART_RATE+ else -> null // 9/10 (blood pressure) intentionally skipped for now+ }++ companion object {+ private const val TAG = "WithingsClient"+ }+}
everysync/src/main/java/com/vayunmathur/everysync/sink/CalendarSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sink/CalendarSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/sink/CalendarSink.ktnew file mode 100644index 0000000000..63eed4bc61--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/sink/CalendarSink.kt@@ -0,0 +1,240 @@+package com.vayunmathur.everysync.sink++import android.content.ContentValues+import android.content.Context+import android.net.Uri+import android.provider.CalendarContract+import android.util.Log+import androidx.core.database.getStringOrNull+import com.vayunmathur.everysync.auth.AccountStore+import com.vayunmathur.everysync.model.RemoteEvent++/** A locally-edited event detected via the platform DIRTY/DELETED flags. */+data class LocalEventChange(+ val eventId: Long,+ val syncId: String?,+ val etag: String?,+ val deleted: Boolean,+ val event: RemoteEvent?,+)++/**+ * Creates one CalendarContract calendar per remote collection under the EverySync+ * account and writes events via sync-adapter URIs. The remote UID goes in+ * Events._SYNC_ID, the ETag in SYNC_DATA1 and the href in SYNC_DATA2.+ */+object CalendarSink {+ private const val TAG = "CalendarSink"+ private val ACCOUNT_TYPE = AccountStore.ACCOUNT_TYPE++ private fun Uri.asSyncAdapter(accountName: String): Uri =+ buildUpon()+ .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")+ .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, accountName)+ .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE)+ .build()++ fun getOrCreateCalendarId(+ context: Context,+ accountName: String,+ remoteCalendarId: String,+ displayName: String,+ color: Int?,+ ): Long {+ try {+ context.contentResolver.query(+ CalendarContract.Calendars.CONTENT_URI,+ arrayOf(CalendarContract.Calendars._ID),+ "${CalendarContract.Calendars.ACCOUNT_NAME} = ? AND ${CalendarContract.Calendars.ACCOUNT_TYPE} = ? AND ${CalendarContract.Calendars.NAME} = ?",+ arrayOf(accountName, ACCOUNT_TYPE, remoteCalendarId),+ null,+ )?.use { if (it.moveToFirst()) return it.getLong(0) }+ } catch (e: Exception) {+ Log.e(TAG, "query calendar failed", e)+ }++ val values = ContentValues().apply {+ put(CalendarContract.Calendars.ACCOUNT_NAME, accountName)+ put(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE)+ put(CalendarContract.Calendars.OWNER_ACCOUNT, accountName)+ put(CalendarContract.Calendars.NAME, remoteCalendarId)+ put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, displayName)+ put(CalendarContract.Calendars.CALENDAR_COLOR, color ?: 0xFF3F51B5.toInt())+ put(CalendarContract.Calendars.VISIBLE, 1)+ put(CalendarContract.Calendars.SYNC_EVENTS, 1)+ put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER)+ put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, java.util.TimeZone.getDefault().id)+ }+ return try {+ context.contentResolver.insert(+ CalendarContract.Calendars.CONTENT_URI.asSyncAdapter(accountName), values,+ )?.lastPathSegment?.toLong() ?: -1L+ } catch (e: Exception) {+ Log.e(TAG, "create calendar failed", e)+ -1L+ }+ }++ fun localUidToEtag(context: Context, accountName: String, localCalendarId: Long): Map<String, String?> {+ val out = mutableMapOf<String, String?>()+ try {+ context.contentResolver.query(+ CalendarContract.Events.CONTENT_URI,+ arrayOf(CalendarContract.Events._SYNC_ID, CalendarContract.Events.SYNC_DATA1),+ "${CalendarContract.Events.CALENDAR_ID} = ? AND ${CalendarContract.Events.DELETED} = 0",+ arrayOf(localCalendarId.toString()),+ null,+ )?.use { c ->+ while (c.moveToNext()) {+ val uid = c.getStringOrNull(0) ?: continue+ out[uid] = c.getStringOrNull(1)+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "localUidToEtag failed", e)+ }+ return out+ }++ private fun eventId(context: Context, localCalendarId: Long, uid: String): Long? =+ try {+ context.contentResolver.query(+ CalendarContract.Events.CONTENT_URI,+ arrayOf(CalendarContract.Events._ID),+ "${CalendarContract.Events.CALENDAR_ID} = ? AND ${CalendarContract.Events._SYNC_ID} = ?",+ arrayOf(localCalendarId.toString(), uid),+ null,+ )?.use { if (it.moveToFirst()) it.getLong(0) else null }+ } catch (e: Exception) {+ Log.e(TAG, "eventId failed", e); null+ }++ fun upsertEvent(context: Context, accountName: String, localCalendarId: Long, e: RemoteEvent) {+ val values = ContentValues().apply {+ put(CalendarContract.Events.CALENDAR_ID, localCalendarId)+ put(CalendarContract.Events._SYNC_ID, e.uid)+ put(CalendarContract.Events.SYNC_DATA1, e.etag)+ put(CalendarContract.Events.SYNC_DATA2, e.href)+ put(CalendarContract.Events.TITLE, e.summary)+ put(CalendarContract.Events.DESCRIPTION, e.description)+ put(CalendarContract.Events.EVENT_LOCATION, e.location)+ put(CalendarContract.Events.DTSTART, e.startMillis)+ put(CalendarContract.Events.ALL_DAY, if (e.allDay) 1 else 0)+ put(CalendarContract.Events.EVENT_TIMEZONE, if (e.allDay) "UTC" else e.timezone)+ put(CalendarContract.Events.DIRTY, 0)+ if (e.rrule.isNullOrBlank()) {+ put(CalendarContract.Events.DTEND, e.endMillis)+ } else {+ // Recurring events must use DURATION instead of DTEND.+ put(CalendarContract.Events.RRULE, e.rrule.removePrefix("RRULE:"))+ val durSecs = ((e.endMillis - e.startMillis) / 1000).coerceAtLeast(0)+ put(CalendarContract.Events.DURATION, "P${durSecs}S")+ }+ }+ try {+ val existing = eventId(context, localCalendarId, e.uid)+ if (existing != null) {+ context.contentResolver.update(+ CalendarContract.Events.CONTENT_URI.asSyncAdapter(accountName),+ values, "${CalendarContract.Events._ID} = ?", arrayOf(existing.toString()),+ )+ } else {+ context.contentResolver.insert(+ CalendarContract.Events.CONTENT_URI.asSyncAdapter(accountName), values,+ )+ }+ } catch (e2: Exception) {+ Log.e(TAG, "upsertEvent failed", e2)+ }+ }++ fun deleteEvent(context: Context, accountName: String, localCalendarId: Long, uid: String) {+ val id = eventId(context, localCalendarId, uid) ?: return+ try {+ context.contentResolver.delete(+ CalendarContract.Events.CONTENT_URI.asSyncAdapter(accountName),+ "${CalendarContract.Events._ID} = ?", arrayOf(id.toString()),+ )+ } catch (e: Exception) {+ Log.e(TAG, "deleteEvent failed", e)+ }+ }++ fun localCalendars(context: Context, accountName: String): List<Long> {+ val ids = mutableListOf<Long>()+ try {+ context.contentResolver.query(+ CalendarContract.Calendars.CONTENT_URI,+ arrayOf(CalendarContract.Calendars._ID),+ "${CalendarContract.Calendars.ACCOUNT_NAME} = ? AND ${CalendarContract.Calendars.ACCOUNT_TYPE} = ?",+ arrayOf(accountName, ACCOUNT_TYPE), null,+ )?.use { c -> while (c.moveToNext()) ids += c.getLong(0) }+ } catch (e: Exception) {+ Log.e(TAG, "localCalendars failed", e)+ }+ return ids+ }++ fun getLocalChanges(context: Context, accountName: String, localCalendarId: Long): List<LocalEventChange> {+ val changes = mutableListOf<LocalEventChange>()+ try {+ context.contentResolver.query(+ CalendarContract.Events.CONTENT_URI,+ arrayOf(+ CalendarContract.Events._ID,+ CalendarContract.Events._SYNC_ID,+ CalendarContract.Events.SYNC_DATA1,+ CalendarContract.Events.DELETED,+ CalendarContract.Events.TITLE,+ CalendarContract.Events.DESCRIPTION,+ CalendarContract.Events.EVENT_LOCATION,+ CalendarContract.Events.DTSTART,+ CalendarContract.Events.DTEND,+ CalendarContract.Events.ALL_DAY,+ CalendarContract.Events.EVENT_TIMEZONE,+ CalendarContract.Events.RRULE,+ ),+ "${CalendarContract.Events.CALENDAR_ID} = ? AND (${CalendarContract.Events.DIRTY} = 1 OR ${CalendarContract.Events.DELETED} = 1)",+ arrayOf(localCalendarId.toString()), null,+ )?.use { c ->+ while (c.moveToNext()) {+ val deleted = c.getInt(3) == 1+ val uid = c.getStringOrNull(1)+ changes += LocalEventChange(+ eventId = c.getLong(0),+ syncId = uid,+ etag = c.getStringOrNull(2),+ deleted = deleted,+ event = if (deleted || uid == null) null else RemoteEvent(+ uid = uid,+ calendarId = localCalendarId.toString(),+ summary = c.getStringOrNull(4) ?: "",+ description = c.getStringOrNull(5) ?: "",+ location = c.getStringOrNull(6) ?: "",+ startMillis = c.getLong(7),+ endMillis = c.getLong(8),+ allDay = c.getInt(9) == 1,+ timezone = c.getStringOrNull(10) ?: "UTC",+ rrule = c.getStringOrNull(11),+ ),+ )+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "getLocalChanges failed", e)+ }+ return changes+ }++ fun clearDirty(context: Context, accountName: String, eventId: Long) {+ try {+ context.contentResolver.update(+ CalendarContract.Events.CONTENT_URI.asSyncAdapter(accountName),+ ContentValues().apply { put(CalendarContract.Events.DIRTY, 0) },+ "${CalendarContract.Events._ID} = ?", arrayOf(eventId.toString()),+ )+ } catch (e: Exception) {+ Log.e(TAG, "clearDirty failed", e)+ }+ }+}
everysync/src/main/java/com/vayunmathur/everysync/sink/ContactsSink.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/sink/ContactsSink.kt b/everysync/src/main/java/com/vayunmathur/everysync/sink/ContactsSink.ktnew file mode 100644index 0000000000..e13b7ecd5a--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/sink/ContactsSink.kt@@ -0,0 +1,293 @@+package com.vayunmathur.everysync.sink++import android.content.ContentProviderOperation+import android.content.Context+import android.net.Uri+import android.provider.ContactsContract+import android.provider.ContactsContract.CommonDataKinds.Email+import android.provider.ContactsContract.CommonDataKinds.Event+import android.provider.ContactsContract.CommonDataKinds.Note+import android.provider.ContactsContract.CommonDataKinds.Organization+import android.provider.ContactsContract.CommonDataKinds.Phone+import android.provider.ContactsContract.CommonDataKinds.StructuredName+import android.provider.ContactsContract.CommonDataKinds.StructuredPostal+import android.util.Log+import androidx.core.database.getStringOrNull+import com.vayunmathur.everysync.auth.AccountStore+import com.vayunmathur.everysync.model.RemoteContact+import com.vayunmathur.everysync.model.TypedValue++/** A locally-edited contact detected via the platform DIRTY/DELETED flags. */+data class LocalContactChange(+ val rawContactId: Long,+ val sourceId: String?,+ val etag: String?,+ val deleted: Boolean,+ val contact: RemoteContact?,+)++/**+ * Writes [RemoteContact]s into ContactsContract under the EverySync account using+ * sync-adapter URIs (so our writes don't get flagged DIRTY). The remote UID is+ * stored in RawContacts.SOURCE_ID, the ETag in SYNC1 and the server href in SYNC2.+ */+object ContactsSink {+ private const val TAG = "ContactsSink"+
Diff truncated.