feat(#240): per-account Don't ask for sync access, undone from the calendar manager

This commit is contained in:
makiolaj committed 2026-11-14 00:51:00 +01:00
1 parent 14a0725b21
commit a026f24bed
12 files changed
+203 -6

No files matched your search

@@ -149,6 +149,12 @@ interface CalendarRepository {
*/
val syncTargets: Flow<SyncTargets> get() = flowOf(SyncTargets.None)
/** Accounts the user said not to be asked about granting access for. */
val syncAccessDismissed: Flow<Set<SyncAccount>> get() = flowOf(emptySet())
/** Stop or resume asking for [account]'s sync-request access. */
suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {}
/** Every provider notification and [refresh], including the app's own writes. */
val providerChanges: Flow<Unit> get() = emptyFlow()
}
@@ -182,15 +182,22 @@ class CalendarRepositoryImpl @Inject constructor(
): suspend () -> Collection<Long?> =
{ listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId), *others) }
private fun targetsOf(calendars: List<CalendarSource>): SyncTargets =
reach(calendars.syncAccounts().withAdapter())
private fun targetsOf(calendars: List<CalendarSource>, dismissed: Set<SyncAccount>): SyncTargets =
reach(calendars.syncAccounts().withAdapter()).let {
if (dismissed.isEmpty()) it else it.copy(needsAccess = it.needsAccess - dismissed)
}
override val syncTargets: Flow<SyncTargets>
get() = calendars().map { targetsOf(it) }.flowOn(io)
get() = calendars().combine(prefs.syncAccessDismissed, ::targetsOf).flowOn(io)
override val syncAccessDismissed: Flow<Set<SyncAccount>> = prefs.syncAccessDismissed
override suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) =
prefs.setSyncAccessDismissed(account, dismissed)
override suspend fun requestSync(): SyncRequestResult = withContext(io) {
val targets = try {
targetsOf(calendars().first())
targetsOf(calendars().first(), prefs.syncAccessDismissed.first())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
@@ -7,6 +7,8 @@ import de.jeanlucmakiola.floret.prefs.PrefStore
import de.jeanlucmakiola.floret.prefs.nullableBooleanPref
import de.jeanlucmakiola.floret.prefs.nullableLongPref
import de.jeanlucmakiola.floret.prefs.nullableStringPref
import de.jeanlucmakiola.floret.prefs.stringSetPref
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Singleton
@@ -72,7 +74,28 @@ class CalendarPrefs @Inject constructor(
suspend fun setLastUsedCalendarId(id: Long) = prefs.set(LAST_USED_CALENDAR, id)
/**
* Synced accounts the user chose never to be asked to grant sync-request
* access for (#240): no grant row, no "other accounts" receipt.
*/
val syncAccessDismissed: Flow<Set<SyncAccount>> = prefs.flow(SYNC_ACCESS_DISMISSED)
suspend fun setSyncAccessDismissed(account: SyncAccount, dismissed: Boolean) {
prefs.update(SYNC_ACCESS_DISMISSED) { if (dismissed) it + account else it - account }
}
private companion object {
val SYNC_ACCESS_DISMISSED = stringSetPref("sync_access_dismissed").map<Set<SyncAccount>>(
{ stored -> stored.mapNotNullTo(mutableSetOf()) { it.toSyncAccount() } },
{ accounts -> accounts.mapTo(mutableSetOf()) { "${it.type}$FIELD_SEPARATOR${it.name}" } },
)
const val FIELD_SEPARATOR = '\u001F'
fun String.toSyncAccount(): SyncAccount? {
val split = indexOf(FIELD_SEPARATOR)
return if (split <= 0) null else SyncAccount(name = substring(split + 1), type = substring(0, split))
}
val HIDDEN_IDS = idSetPref("hidden_calendar_ids")
val DISABLED_IDS = idSetPref("disabled_calendar_ids")
val VISIBILITY_NOTICE = nullableBooleanPref("visibility_notice_pending")
@@ -56,6 +56,7 @@ import de.jeanlucmakiola.calendula.ui.common.CalendarDrawer
import de.jeanlucmakiola.calendula.ui.common.DrawerSync
import de.jeanlucmakiola.calendula.ui.common.SyncViewModel
import de.jeanlucmakiola.calendula.ui.common.RefreshSyncAccessOnOpen
import de.jeanlucmakiola.calendula.ui.common.SyncAccessSheet
import de.jeanlucmakiola.calendula.ui.common.rememberSyncAccessPicker
import de.jeanlucmakiola.calendula.ui.common.messageRes
import de.jeanlucmakiola.calendula.ui.common.CalendarFab
@@ -455,6 +456,7 @@ fun CalendarHost(
val selectionFailureMessage = eventActionFailureMessage(selectionFailure)
val syncMessage = syncResult?.let { stringResource(it.messageRes()) }
val launchAccessPicker = rememberSyncAccessPicker(sync)
var showSyncAccess by remember { mutableStateOf(false) }
val onEditEvent: (EventInstance) -> Unit = { event -> editKey = event.occurrenceKey() }
// A tap opens the edit form instead of the detail screen when the user chose
// so (#178) — only for events whose calendar takes writes. Both are read at
@@ -612,7 +614,7 @@ fun CalendarHost(
sync.requestSync()
switchScope.launch { drawerState.close() }
},
onGrantAccess = { launchAccessPicker(syncTargets.needsAccess) },
onGrantAccess = { showSyncAccess = true },
)
},
)
@@ -714,6 +716,15 @@ fun CalendarHost(
},
)
if (showSyncAccess) {
SyncAccessSheet(
accounts = syncTargets.needsAccess.toList(),
onGrant = { launchAccessPicker(setOf(it)) },
onDismissAccount = { sync.setAccessDismissed(it, dismissed = true) },
onDismiss = { showSyncAccess = false },
)
}
// The delete prompt and failure chip of a selected event's actions (#141).
EventSelectionHost(host = chromeHost, viewModel = eventActions)
@@ -85,6 +85,9 @@ import de.jeanlucmakiola.calendula.ui.common.curatedSourcePackage
import de.jeanlucmakiola.calendula.ui.common.orUnnamed
import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.ui.common.sourceAppName
import de.jeanlucmakiola.floret.components.positionOf
import de.jeanlucmakiola.floret.components.GroupedSectionHeader
import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme
import de.jeanlucmakiola.floret.identity.collapseExit
@@ -130,6 +133,7 @@ fun CalendarsScreen(
val calendars by viewModel.calendars.collectAsStateWithLifecycle()
val deleteLockedIds by viewModel.deleteLockedCalendarIds.collectAsStateWithLifecycle()
val error by viewModel.error.collectAsStateWithLifecycle()
val syncAccessDismissed by viewModel.syncAccessDismissed.collectAsStateWithLifecycle()
// null = list; NEW_CALENDAR_ID = create; any other id = edit that calendar.
// [editorSession] bumps on every open so the editor's field state resets for
@@ -174,6 +178,8 @@ fun CalendarsScreen(
onEdit = { calendar -> editorSession++; editorId = calendar.id },
onSetVisible = viewModel::setCalendarVisible,
onSetAccountVisible = viewModel::setAccountVisible,
syncAccessDismissed = syncAccessDismissed,
onAskSyncAccessAgain = viewModel::askSyncAccessAgain,
)
}
}
@@ -191,6 +197,8 @@ private fun CalendarsList(
onEdit: (CalendarSource) -> Unit,
onSetVisible: (Long, Boolean) -> Unit,
onSetAccountVisible: (Collection<Long>, Boolean) -> Unit,
syncAccessDismissed: List<SyncAccount>,
onAskSyncAccessAgain: (SyncAccount) -> Unit,
) {
val context = LocalContext.current
val snackbarHostState = remember { SnackbarHostState() }
@@ -321,6 +329,25 @@ private fun CalendarsList(
}
}
}
if (syncAccessDismissed.isNotEmpty()) {
Spacer(Modifier.height(16.dp))
GroupedSectionHeader(stringResource(R.string.calendars_sync_access_header))
GroupedHint(stringResource(R.string.calendars_sync_access_hint), style = MaterialTheme.typography.bodySmall)
syncAccessDismissed.forEachIndexed { index, account ->
GroupedRow(
title = account.name,
summary = sourceAppName(account.type),
position = positionOf(index, syncAccessDismissed.size),
leading = { SourceLogo(account.type) },
trailing = {
TextButton(onClick = { onAskSyncAccessAgain(account) }) {
Text(stringResource(R.string.calendars_sync_access_ask_again))
}
},
)
}
}
}
}
@@ -9,6 +9,7 @@ import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import de.jeanlucmakiola.calendula.data.backup.BackupScheduler
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.data.ics.IcsExporter
import de.jeanlucmakiola.calendula.data.prefs.BackupStatus
import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs
@@ -56,6 +57,17 @@ class CalendarsViewModel @Inject constructor(
initialValue = emptyList(),
)
/** Accounts the drawer was told not to ask sync-request access for (#240). */
val syncAccessDismissed: StateFlow<List<SyncAccount>> =
repository.syncAccessDismissed
.map { set -> set.sortedWith(compareBy({ it.name.lowercase() }, { it.type })) }
.catch { emit(emptyList()) }
.stateWhileSubscribed(scope = viewModelScope, initialValue = emptyList())
fun askSyncAccessAgain(account: SyncAccount) {
viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed = false) }
}
/**
* The Backup & restore screen's own view of that list, with the loading and
* failure states [calendars] flattens away — it starts empty and catches to
@@ -4,7 +4,12 @@ import android.content.ActivityNotFoundException
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ManageAccounts
import androidx.compose.material3.DrawerState
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.DrawerValue
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
@@ -12,12 +17,18 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.data.calendar.accountAccessIntent
import de.jeanlucmakiola.floret.components.FullScreenPicker
import de.jeanlucmakiola.floret.components.GroupedHint
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.positionOf
/**
* Launches the system account picker for accounts sync requests can't reach yet
@@ -53,3 +64,36 @@ fun RefreshSyncAccessOnOpen(drawerState: DrawerState, sync: SyncViewModel) {
if (drawerState.targetValue == DrawerValue.Open) sync.refreshAccess()
}
}
/**
* The accounts sync requests can't reach yet (#240), one row each: tapping one
* opens the system picker for just that account, "Don't ask" stops offering it.
* Closes itself once no account is left.
*/
@Composable
fun SyncAccessSheet(
accounts: List<SyncAccount>,
onGrant: (SyncAccount) -> Unit,
onDismissAccount: (SyncAccount) -> Unit,
onDismiss: () -> Unit,
) {
LaunchedEffect(accounts.isEmpty()) { if (accounts.isEmpty()) onDismiss() }
FullScreenPicker(title = stringResource(R.string.drawer_sync_access), onDismiss = onDismiss, predictiveBack = true) {
GroupedHint(stringResource(R.string.sync_access_hint), verticalPadding = 8.dp)
accounts.forEachIndexed { index, account ->
GroupedRow(
title = account.name,
summary = sourceAppName(account.type),
position = positionOf(index, accounts.size),
minHeight = 64.dp,
leading = { Icon(Icons.Filled.ManageAccounts, contentDescription = null) },
trailing = {
TextButton(onClick = { onDismissAccount(account) }) {
Text(stringResource(R.string.sync_access_dont_ask))
}
},
onClick = { onGrant(account) },
)
}
}
}
@@ -6,6 +6,7 @@ import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.jeanlucmakiola.calendula.R
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult
import de.jeanlucmakiola.calendula.data.calendar.SyncTargets
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
@@ -79,6 +80,11 @@ class SyncViewModel @Inject constructor(
}
}
/** Stop asking for [account]'s access (#240); undone from the calendar manager. */
fun setAccessDismissed(account: SyncAccount, dismissed: Boolean) {
viewModelScope.launch { repository.setSyncAccessDismissed(account, dismissed) }
}
fun consumeResult() {
_result.value = null
}
+5
View File
@@ -398,6 +398,11 @@
<string name="drawer_sync_now">Sync now</string>
<string name="drawer_sync_access">Allow sync requests</string>
<string name="drawer_sync_access_summary">Pick each account Calendula may ask to sync</string>
<string name="sync_access_hint">Android only lets Calendula ask an account to sync once you pick it here. Tap an account to allow it, or choose Don\'t ask to stop offering it.</string>
<string name="sync_access_dont_ask">Don\'t ask</string>
<string name="calendars_sync_access_header">Not asked to sync</string>
<string name="calendars_sync_access_hint">Calendula won\'t offer to request syncs for these accounts. Ask again to bring them back to Allow sync requests in the menu.</string>
<string name="calendars_sync_access_ask_again">Ask again</string>
<string name="sync_access_picker_description">Choose an account Calendula may ask to sync your calendars</string>
<string name="sync_requested">Sync requested</string>
<string name="sync_request_failed">Couldn\'t request a sync</string>
@@ -271,4 +271,43 @@ class SyncNudgeTest {
assertThat(sync.requests).containsExactly(auto(dav))
}
@Test
fun `a dismissed hidden account no longer needs access`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(hiddenTypes = setOf(google.type))
sync.knownAccounts = setOf(dav, google)
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.setSyncAccessDismissed(google, dismissed = true)
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), emptySet()))
assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested)
repo.setSyncAccessDismissed(google, dismissed = false)
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets(setOf(dav), setOf(google)))
}
@Test
fun `with every hidden account dismissed there is nothing to sync or grant`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester(hiddenTypes = setOf(dav.type, google.type))
sync.knownAccounts = setOf(dav, google)
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.setSyncAccessDismissed(dav, dismissed = true)
repo.setSyncAccessDismissed(google, dismissed = true)
assertThat(repo.syncTargets.first()).isEqualTo(SyncTargets.None)
assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.NothingToSync)
}
@Test
fun `a dismissed account that becomes visible is still asked`(@TempDir dir: Path) = runTest {
val sync = RecordingSyncRequester()
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
repo.setSyncAccessDismissed(dav, dismissed = true)
repo.createEvent(form(1L))
assertThat(sync.requests).containsExactly(auto(dav))
}
}
@@ -2,6 +2,7 @@ package de.jeanlucmakiola.calendula.data.prefs
import androidx.datastore.preferences.core.stringPreferencesKey
import com.google.common.truth.Truth.assertThat
import de.jeanlucmakiola.calendula.data.calendar.SyncAccount
import de.jeanlucmakiola.calendula.testDataStore
import de.jeanlucmakiola.calendula.testPrefs
import kotlinx.coroutines.flow.first
@@ -108,4 +109,18 @@ class CalendarPrefsTest {
prefs.setVisibilityNoticePending(false)
assertThat(prefs.visibilityNoticePending.first()).isFalse()
}
@Test
fun `sync access dismissals round-trip per account, names with any characters`(@TempDir tempDir: Path) = runTest {
val prefs = testPrefs(tempDir)
val dav = SyncAccount("me@dav.example/cal, 1", "bitfire.at.davdroid")
val google = SyncAccount("me@dav.example/cal, 1", "com.google")
prefs.setSyncAccessDismissed(dav, dismissed = true)
prefs.setSyncAccessDismissed(google, dismissed = true)
assertThat(prefs.syncAccessDismissed.first()).containsExactly(dav, google)
prefs.setSyncAccessDismissed(dav, dismissed = false)
assertThat(prefs.syncAccessDismissed.first()).containsExactly(google)
}
}
+3 -1
View File
@@ -25,7 +25,9 @@ the package list (recurring writes, save conflicts, reminder delivery).
picker (`AccountManager.newChooseAccountIntent`) — the picked account
becomes visible to the app. Access is re-read on every request and on
every resume and drawer open, so a revoke simply puts the account back behind the
grant row. Whether and when the adapter syncs stays its call.
grant row. Per account the user can choose "Don't ask" instead
(`CalendarPrefs.syncAccessDismissed`); such accounts drop out of the grant
row and the receipts, and the calendar manager lists them to ask again. Whether and when the adapter syncs stays its call.
2. **Observer-driven UI.** A `ContentObserver` on the provider triggers
re-queries; every screen recomposes from fresh provider state. After a
write, nothing is patched by hand — the views refresh from the provider.