Modern Apps git

← Modern-Apps.git

everysync: fix calendar sync

Commit
c97db3d8f5123251b20a54d6a2a036dd952431be
Author
Vayun Mathur <[email protected]>
When
2026-07-20 18:03 UTC (4 months ago)
Parents
c3af499

Diff

everysync/src/main/AndroidManifest.xml
diff --git a/everysync/src/main/AndroidManifest.xml b/everysync/src/main/AndroidManifest.xmlindex 53f15deddd..3c7c3bcde1 100644--- a/everysync/src/main/AndroidManifest.xml+++ b/everysync/src/main/AndroidManifest.xml@@ -64,21 +64,20 @@             </intent-filter>         </activity> -        <!-- Receives the OAuth2 redirect (https://everysync.vayunmathur.com/oauth) as-             a verified Android App Link, so the OS routes it straight to the app. -->+        <!-- Receives the OAuth2 redirect (com.vayunmathur.everysync:/oauth). The+             custom scheme is the app id, registered as the iOS OAuth client's+             bundle ID in Google Cloud. Scheme-only filter so the hostless+             `com.vayunmathur.everysync:/oauth` is matched. -->         <activity             android:name=".auth.OAuthCallbackActivity"             android:exported="true"             android:launchMode="singleTask"-            android:theme="@android:style/Theme.NoDisplay">-            <intent-filter android:autoVerify="true">+            android:theme="@android:style/Theme.Translucent.NoTitleBar">+            <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="https"-                    android:host="everysync.vayunmathur.com"-                    android:path="/oauth" />+                <data android:scheme="com.vayunmathur.everysync" />             </intent-filter>         </activity> 
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.ktindex b34beec62c..242f0f2377 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthCallbackActivity.kt@@ -9,7 +9,7 @@ import com.vayunmathur.everysync.sync.SyncScheduler import kotlinx.coroutines.launch  /**- * Receives the OAuth2 redirect (`https://everysync.vayunmathur.com/oauth`), completes the+ * 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() {
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.ktindex 0e0b1dbc98..32d3c5bacc 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthConfig.kt@@ -22,31 +22,37 @@ data class OAuthConfig(     val hasClientId: Boolean get() = clientId.isNotBlank()      companion object {-        const val REDIRECT_URI = "https://everysync.vayunmathur.com/oauth"+        // iOS-type Google OAuth client → custom URI scheme redirect. The scheme is+        // the app id (registered as the iOS client's "bundle ID" in Google Cloud).+        // Per Google's installed-app spec the path uses a single slash. iOS clients+        // do NOT accept https redirects (that's Web-client only), and Android-type+        // clients don't allow custom schemes at all — hence the iOS client.+        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",+                "openid",+                "email",+                "https://www.googleapis.com/auth/carddav",                 "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"),         ) -        // Google Health via the Google Fitness REST API — same Google OAuth client,-        // fitness read scopes. (Google's Fit REST API is being wound down; configure-        // the client ID to use it while available.)-        val GOOGLE_FIT = OAuthConfig(+        // Google Health via the Google Health API v4 (health.googleapis.com) —+        // same Google OAuth client, read-only Google Health scopes. Replaces the+        // wound-down Google Fitness REST API and its fitness.* scopes.+        val GOOGLE_HEALTH = 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/fitness.activity.read",-                "https://www.googleapis.com/auth/fitness.body.read",-                "https://www.googleapis.com/auth/fitness.heart_rate.read",+                "https://www.googleapis.com/auth/googlehealth.activity_and_fitness.readonly",+                "https://www.googleapis.com/auth/googlehealth.health_metrics_and_measurements.readonly",             ),             extraAuthParams = mapOf("access_type" to "offline", "prompt" to "consent"),         )
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.ktindex c2b879b6dc..21d83a8da6 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/auth/OAuthManager.kt@@ -19,7 +19,7 @@ import kotlinx.serialization.json.longOrNull  /**  * OAuth2 Authorization Code + PKCE (RFC 7636). The authorization request opens in- * a Custom Tab; the redirect (`https://everysync.vayunmathur.com/oauth`) is caught by+ * a Custom Tab; the redirect (`com.vayunmathur.everysync:/oauth`) is caught by  * [OAuthCallbackActivity], which calls [complete] to exchange the code for tokens.  */ object OAuthManager {
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.ktindex a1719b94a9..5234f92c6f 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProvider.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/DavProvider.kt@@ -4,16 +4,12 @@ import android.content.Context import androidx.compose.runtime.Composable 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+import com.vayunmathur.everysync.remote.DavSync  /**  * Base CalDAV/CardDAV provider. Resource hrefs are used as the local SOURCE_ID /@@ -43,95 +39,10 @@ abstract class DavProvider(         val account = config.accountName          if (DataType.CONTACTS in capabilities && DataType.CONTACTS in config.enabledTypes) {-            syncContacts(context, account, client, contactsBaseUrl(config, creds), direction)+            DavSync.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)-                            }-                        }-                    }-                }-            }+            DavSync.syncCalendars(context, account, client, calendarBaseUrl(config, creds), direction)         }     } }
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.ktindex f8ed4b5a6b..b37b0e1805 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/GoogleProvider.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/GoogleProvider.kt@@ -11,18 +11,15 @@ 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.everysync.remote.DavClient+import com.vayunmathur.everysync.remote.DavSync import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.ui.IconProvider 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. */+/** Google via CardDAV (contacts) + CalDAV (calendar), OAuth PKCE Bearer, two-way. */ class GoogleProvider : SyncProvider {     override val id = "google"     override val displayName = "Google"@@ -33,79 +30,59 @@ class GoogleProvider : SyncProvider {     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"-        }+        val email = fetchEmail(tokens.accessToken)+        return if (!email.isNullOrBlank()) "$email (Google)" else "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+        val email = fetchEmail(token) ?: emailFromAccountName(account)+        if (email == null) {+            Log.e(TAG, "sync: could not resolve Google account email for '$account'")+            return+        } -        if (DataType.CONTACTS in config.enabledTypes) syncContacts(context, account, token, direction)-        if (DataType.CALENDAR in config.enabledTypes) syncCalendars(context, account, token, direction)-    }+        val client = DavClient { "Bearer $token" } -    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 (DataType.CONTACTS in config.enabledTypes) {+            DavSync.syncContacts(+                context, account, client,+                "https://www.googleapis.com/carddav/v1/principals/$email/lists/default",+                direction,+            )         }-        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)-            }+        if (DataType.CALENDAR in config.enabledTypes) {+            // Google's CalDAV principal is /caldav/v2/$email/user, but that is not a+            // collection — if principal→home-set discovery fails, the fallback needs a+            // real calendar collection to list. Point at the primary calendar's events+            // collection so discovery always resolves at least the primary calendar+            // (secondary calendars still come through the principal/home-set chain).+            DavSync.syncCalendars(+                context, account, client,+                "https://apidata.googleusercontent.com/caldav/v2/$email/events",+                direction,+            )         }     } -    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)-                    }-                }-            }-        }+    /** Fetch the account email from the OAuth userinfo endpoint. */+    private suspend fun fetchEmail(token: String): String? = try {+        val resp = NetworkClient.performRequest(+            "https://www.googleapis.com/oauth2/v3/userinfo", "GET",+            mapOf("Authorization" to "Bearer $token"),+        )+        (JSON.parseToJsonElement(resp.body) as? JsonObject)+            ?.get("email")?.jsonPrimitive?.content?.ifBlank { null }+    } catch (e: Exception) {+        Log.e(TAG, "fetchEmail failed", e)+        null     } +    /** Fall back to parsing the account name, which has the form "email (Google)". */+    private fun emailFromAccountName(accountName: String): String? =+        accountName.substringBefore(" (Google)").takeIf { "@" in it }+     companion object {         private const val TAG = "GoogleProvider"         private val JSON = Json { ignoreUnknownKeys = true }
everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.kt b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.ktindex 58e80f0b41..e0f10b5d41 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/provider/impl/HealthOAuthProviders.kt@@ -12,7 +12,7 @@ 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.GoogleFitClient+import com.vayunmathur.everysync.remote.GoogleHealthClient import com.vayunmathur.everysync.sink.HealthSink import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.ui.IconProvider@@ -21,7 +21,7 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonPrimitive  /**- * Google Health via the Google Fitness REST API (OAuth PKCE). Pulls measurements+ * Google Health via the Google Health API v4 (OAuth PKCE). Pulls measurements  * into Health Connect. Pull-dominant — the cloud is the source of truth.  */ class GoogleHealthProvider : SyncProvider {@@ -31,7 +31,7 @@ class GoogleHealthProvider : SyncProvider {     override val authType = AuthType.OAUTH     override val capabilities = setOf(DataType.HEALTH) -    override fun oauthConfig(): OAuthConfig = OAuthConfig.GOOGLE_FIT+    override fun oauthConfig(): OAuthConfig = OAuthConfig.GOOGLE_HEALTH      override suspend fun resolveAccountName(context: Context, tokens: OAuthTokens): String {         return try {@@ -51,9 +51,9 @@ class GoogleHealthProvider : SyncProvider {     override suspend fun sync(context: Context, config: AccountConfig, direction: SyncDirection) {         if (DataType.HEALTH !in config.enabledTypes || direction == SyncDirection.PUSH) return         val token = OAuthManager.validAccessToken(context, config.accountName, id) ?: return-        val since = SyncState.get(context, config.accountName, "googlefit_since")?.toLongOrNull() ?: 0L-        HealthSink.upsert(context, GoogleFitClient(token).getMeasurements(since))-        SyncState.set(context, config.accountName, "googlefit_since", System.currentTimeMillis().toString())+        val since = SyncState.get(context, config.accountName, "googlehealth_since")?.toLongOrNull() ?: 0L+        HealthSink.upsert(context, GoogleHealthClient(token).getMeasurements(since))+        SyncState.set(context, config.accountName, "googlehealth_since", System.currentTimeMillis().toString())     }      companion object {
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.ktindex 3293000962..b50c102927 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/DavClient.kt@@ -31,12 +31,15 @@ data class DavCollection(  * Change detection uses collection ctags and per-resource ETags; the caller  * decides what to re-fetch.  */-class DavClient(private val creds: DavCredentials) {+class DavClient(private val authHeader: () -> String) { -    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-    }+    /** Basic-auth client for username/password DAV servers (iCloud, generic). */+    constructor(creds: DavCredentials) : this({+        "Basic " + Base64.encode("${creds.username}:${creds.password}".toByteArray())+    })++    private fun authHeaders(extra: Map<String, String> = emptyMap()): Map<String, String> =+        mapOf("Authorization" to authHeader()) + extra      private suspend fun request(url: String, method: String, headers: Map<String, String>, body: String?): SimpleResponse =         NetworkClient.performRequest(url, method, headers, body)@@ -61,6 +64,7 @@ class DavClient(private val creds: DavCredentials) {         } catch (e: Exception) {             Log.e(TAG, "discoverCollections failed", e)         }+        Log.i(TAG, "discoverCollections(isCalendar=$isCalendar) base=$baseUrl -> ${out.size} collection(s): ${out.map { it.url }}")         return out     } 
everysync/src/main/java/com/vayunmathur/everysync/remote/DavSync.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/DavSync.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/DavSync.ktnew file mode 100644index 0000000000..dc7e74a976--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/DavSync.kt@@ -0,0 +1,104 @@+package com.vayunmathur.everysync.remote++import android.content.Context+import com.vayunmathur.everysync.format.ICalendar+import com.vayunmathur.everysync.format.VCard+import com.vayunmathur.everysync.provider.SyncDirection+import com.vayunmathur.everysync.sink.CalendarSink+import com.vayunmathur.everysync.sink.ContactsSink+import java.util.UUID++/**+ * Shared two-way CalDAV/CardDAV sync routines against [ContactsSink] /+ * [CalendarSink]. Resource hrefs are used as the local SOURCE_ID / _SYNC_ID so+ * ETag comparison is direct; server deletions are detected by set difference.+ * Local edits are pushed back via PUT/DELETE with If-Match. Used by every DAV+ * caller regardless of auth (Basic for iCloud/generic, Bearer for Google).+ */+object DavSync {++    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)+                        }+                    }+                }+            }+        }+    }++    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/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.ktdeleted file mode 100644index 601d1d235b..0000000000--- a/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleCalendarClient.kt+++ /dev/null@@ -1,171 +0,0 @@-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/GoogleFitClient.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleFitClient.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleFitClient.ktdeleted file mode 100644index a73e953d58..0000000000--- a/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleFitClient.kt+++ /dev/null@@ -1,86 +0,0 @@-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 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--/**- * Google Health via the Google Fitness REST API. Aggregates steps / weight /- * heart-rate into daily buckets and maps them to [RemoteMeasurement]s for Health- * Connect. Bucket start time makes the clientRecordId idempotent across syncs.- */-class GoogleFitClient(private val accessToken: String) {-    private val json = Json { ignoreUnknownKeys = true }-    private fun headers() = mapOf(-        "Authorization" to "Bearer $accessToken",-        "Content-Type" to "application/json",-    )--    suspend fun getMeasurements(sinceMillis: Long): List<RemoteMeasurement> {-        val out = mutableListOf<RemoteMeasurement>()-        val now = System.currentTimeMillis()-        val start = if (sinceMillis > 0) sinceMillis else now - 30L * 24 * 60 * 60 * 1000-        val body = """-            {-              "aggregateBy": [-                {"dataTypeName": "com.google.step_count.delta"},-                {"dataTypeName": "com.google.weight.summary"},-                {"dataTypeName": "com.google.heart_rate.summary"}-              ],-              "bucketByTime": {"durationMillis": 86400000},-              "startTimeMillis": $start,-              "endTimeMillis": $now-            }-        """.trimIndent()-        try {-            val resp = NetworkClient.performRequest(-                "https://fitness.googleapis.com/fitness/v1/users/me/dataset:aggregate",-                "POST", headers(), body,-            )-            val root = json.parseToJsonElement(resp.body) as? JsonObject ?: return out-            (root["bucket"] as? JsonArray)?.forEach { bucketEl ->-                val bucket = bucketEl.jsonObject-                val bucketStart = bucket["startTimeMillis"]?.jsonPrimitive?.content?.toLongOrNull() ?: return@forEach-                (bucket["dataset"] as? JsonArray)?.forEachIndexed { idx, dsEl ->-                    val type = when (idx) {-                        0 -> MeasurementType.STEPS-                        1 -> MeasurementType.WEIGHT-                        else -> MeasurementType.HEART_RATE-                    }-                    (dsEl.jsonObject["point"] as? JsonArray)?.forEach { pointEl ->-                        val value = firstValue(pointEl.jsonObject, type) ?: return@forEach-                        out += RemoteMeasurement(-                            clientRecordId = "googlefit:${type.name}:$bucketStart",-                            type = type,-                            value = value,-                            timeMillis = bucketStart,-                        )-                    }-                }-            }-        } catch (e: Exception) {-            Log.e(TAG, "getMeasurements failed", e)-        }-        return out-    }--    private fun firstValue(point: JsonObject, type: MeasurementType): Double? {-        val values = point["value"] as? JsonArray ?: return null-        val first = values.firstOrNull()?.jsonObject ?: return null-        return when (type) {-            MeasurementType.STEPS -> first["intVal"]?.jsonPrimitive?.content?.toDoubleOrNull()-            else -> first["fpVal"]?.jsonPrimitive?.content?.toDoubleOrNull()-        }-    }--    companion object {-        private const val TAG = "GoogleFitClient"-    }-}
everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleHealthClient.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleHealthClient.kt b/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleHealthClient.ktnew file mode 100644index 0000000000..52888dadc2--- /dev/null+++ b/everysync/src/main/java/com/vayunmathur/everysync/remote/GoogleHealthClient.kt@@ -0,0 +1,122 @@+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 java.time.Instant+import java.time.LocalDate+import java.time.ZoneId+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive++/**+ * Google Health API v4 (`health.googleapis.com`), replacing the wound-down Google+ * Fitness REST API. Pulls per-day rollups (`dataPoints:dailyRollUp`) for steps,+ * weight, and heart rate and maps them to [RemoteMeasurement]s for Health+ * Connect. The civil day start makes the clientRecordId idempotent across syncs.+ */+class GoogleHealthClient(private val accessToken: String) {+    private val json = Json { ignoreUnknownKeys = true }+    private fun headers() = mapOf(+        "Authorization" to "Bearer $accessToken",+        "Content-Type" to "application/json",+    )++    suspend fun getMeasurements(sinceMillis: Long): List<RemoteMeasurement> =+        SPECS.flatMap { dailyRollUp(it, sinceMillis) }++    private suspend fun dailyRollUp(spec: Spec, sinceMillis: Long): List<RemoteMeasurement> {+        val zone = ZoneId.systemDefault()+        val today = LocalDate.now(zone)+        val sinceDate = if (sinceMillis > 0) {+            Instant.ofEpochMilli(sinceMillis).atZone(zone).toLocalDate()+        } else {+            today.minusDays(DEFAULT_LOOKBACK_DAYS)+        }+        // Clamp to the data type's server-side maximum civil-day range.+        val earliest = today.minusDays(spec.maxRangeDays.toLong())+        val start = if (sinceDate.isBefore(earliest)) earliest else sinceDate+        val end = today.plusDays(1) // exclusive end, so today is included++        val body = """+            {+              "range": {+                "start": {"date": ${dateJson(start)}},+                "end": {"date": ${dateJson(end)}}+              },+              "windowSizeDays": 1+            }+        """.trimIndent()++        val out = mutableListOf<RemoteMeasurement>()+        try {+            val resp = NetworkClient.performRequest(+                "https://health.googleapis.com/v4/users/me/dataTypes/${spec.dataType}/dataPoints:dailyRollUp",+                "POST", headers(), body,+            )+            val root = json.parseToJsonElement(resp.body) as? JsonObject ?: return out+            (root["rollupDataPoints"] as? JsonArray)?.forEach { el ->+                val rollup = el.jsonObject+                val dayMillis = civilStartMillis(rollup, zone) ?: return@forEach+                val value = spec.extract(rollup) ?: return@forEach+                out += RemoteMeasurement(+                    clientRecordId = "googlehealth:${spec.type.name}:$dayMillis",+                    type = spec.type,+                    value = value,+                    timeMillis = dayMillis,+                )+            }+        } catch (e: Exception) {+            Log.e(TAG, "dailyRollUp(${spec.dataType}) failed", e)+        }+        return out+    }++    private fun dateJson(d: LocalDate): String =+        """{"year": ${d.year}, "month": ${d.monthValue}, "day": ${d.dayOfMonth}}"""++    /** Convert a rollup point's `civilStartTime.date` to epoch millis at local midnight. */+    private fun civilStartMillis(rollup: JsonObject, zone: ZoneId): Long? {+        val date = rollup["civilStartTime"]?.jsonObject?.get("date")?.jsonObject ?: return null+        val year = date["year"]?.jsonPrimitive?.content?.toIntOrNull() ?: return null+        val month = date["month"]?.jsonPrimitive?.content?.toIntOrNull() ?: return null+        val day = date["day"]?.jsonPrimitive?.content?.toIntOrNull() ?: return null+        return LocalDate.of(year, month, day).atStartOfDay(zone).toInstant().toEpochMilli()+    }++    private data class Spec(+        /** Data type path segment, kebab-case per the v4 API. */+        val dataType: String,+        val type: MeasurementType,+        /** Server-side max civil-day range for `dailyRollUp` on this type. */+        val maxRangeDays: Int,+        /** Pull the value out of a rollup data point, applying unit conversion. */+        val extract: (JsonObject) -> Double?,+    )++    companion object {+        private const val TAG = "GoogleHealthClient"+        private const val DEFAULT_LOOKBACK_DAYS = 30L++        private val SPECS = listOf(+            Spec("steps", MeasurementType.STEPS, maxRangeDays = 90) {+                it.rollupValue("steps", "countSum")+            },+            // weightGramsAvg is in grams; Health Connect wants kilograms.+            Spec("weight", MeasurementType.WEIGHT, maxRangeDays = 90) {+                it.rollupValue("weight", "weightGramsAvg")?.div(1000.0)+            },+            Spec("heart-rate", MeasurementType.HEART_RATE, maxRangeDays = 14) {+                it.rollupValue("heartRate", "beatsPerMinuteAvg")+            },+        )++        /** Read a numeric field nested under a rollup value object (int64 arrives as a string). */+        private fun JsonObject.rollupValue(field: String, key: String): Double? =+            this[field]?.jsonObject?.get(key)?.jsonPrimitive?.content?.toDoubleOrNull()+    }+}
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.ktdeleted file mode 100644index e2bdbf39c2..0000000000--- a/everysync/src/main/java/com/vayunmathur/everysync/remote/GooglePeopleClient.kt+++ /dev/null@@ -1,135 +0,0 @@-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/ui/AddAccountScreen.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/ui/AddAccountScreen.kt b/everysync/src/main/java/com/vayunmathur/everysync/ui/AddAccountScreen.ktindex cfd71ae75b..f089445ba5 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/ui/AddAccountScreen.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/ui/AddAccountScreen.kt@@ -40,7 +40,14 @@ fun AddAccountScreen(backStack: NavBackStack<Route>, viewModel: EverySyncViewMod                 ListItem(                     modifier = Modifier.clickable {                         when (provider.authType) {-                            AuthType.OAUTH -> viewModel.startOAuth(provider.id)+                            AuthType.OAUTH -> {+                                viewModel.startOAuth(provider.id)+                                // OAuth continues in a Custom Tab and returns via+                                // OAuthCallbackActivity → MainActivity, which retains+                                // this back stack. Reset to the accounts list now so+                                // the user lands on home (not here) when they return.+                                backStack.reset(Route.Accounts)+                            }                             AuthType.DAV -> backStack.add(Route.DavLogin(provider.id))                             AuthType.HEALTH_CONNECT -> viewModel.addHealthConnectAccount(provider.id) { backStack.pop() }                         }
everysync/src/main/java/com/vayunmathur/everysync/ui/DavLoginScreen.kt
diff --git a/everysync/src/main/java/com/vayunmathur/everysync/ui/DavLoginScreen.kt b/everysync/src/main/java/com/vayunmathur/everysync/ui/DavLoginScreen.ktindex 89d9ea9020..f0ded248a3 100644--- a/everysync/src/main/java/com/vayunmathur/everysync/ui/DavLoginScreen.kt+++ b/everysync/src/main/java/com/vayunmathur/everysync/ui/DavLoginScreen.kt@@ -82,7 +82,7 @@ fun DavLoginScreen(backStack: NavBackStack<Route>, viewModel: EverySyncViewModel             TextButton(                 enabled = username.isNotBlank() && password.isNotBlank() && baseUrl.isNotBlank(),                 onClick = {-                    viewModel.davLogin(providerId, baseUrl.trim(), username.trim(), password) { backStack.pop() }+                    viewModel.davLogin(providerId, baseUrl.trim(), username.trim(), password) { backStack.reset(Route.Accounts) }                 },             ) { Text(stringResource(R.string.login)) }         },