This commit is contained in:
1 parent
fb5cb226ee
commit
1dcbffd6f2
8 files changed
+115
-46
No files matched your search
@@ -11,6 +11,7 @@ import de.jeanlucmakiola.calendula.domain.ics.IcsImportSummary
|
||||
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.emptyFlow
|
||||
import kotlinx.coroutines.flow.flowOf
|
||||
import kotlin.time.Instant
|
||||
|
||||
interface CalendarRepository {
|
||||
@@ -141,6 +142,9 @@ interface CalendarRepository {
|
||||
*/
|
||||
suspend fun requestSync(): SyncRequestResult = SyncRequestResult.NothingToSync
|
||||
|
||||
/** Whether [requestSync] has anyone to ask: a visible calendar with a sync adapter behind it. */
|
||||
val canRequestSync: Flow<Boolean> get() = flowOf(false)
|
||||
|
||||
/** Every provider notification and [refresh], including the app's own writes. */
|
||||
val providerChanges: Flow<Unit> get() = emptyFlow()
|
||||
}
|
||||
|
||||
+32
-12
@@ -110,8 +110,8 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
private suspend fun syncAccountsOf(calendarIds: suspend () -> Collection<Long?>): Set<SyncAccount> =
|
||||
try {
|
||||
calendarIds().filterNotNull().distinct()
|
||||
.mapNotNull { dataSource.calendarAccount(it) }
|
||||
.filterTo(linkedSetOf()) { it.isSyncable }
|
||||
.mapNotNull { accountOf(it) }
|
||||
.filterTo(linkedSetOf()) { canSync(it) }
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
@@ -119,19 +119,39 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
emptySet()
|
||||
}
|
||||
|
||||
private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try {
|
||||
syncRequester.requestSync(account, userInitiated)
|
||||
/** From the shared per-tick read; a calendar newer than it is read on its own. */
|
||||
private suspend fun accountOf(calendarId: Long): SyncAccount? =
|
||||
calendarsSnapshot().firstOrNull { it.id == calendarId }
|
||||
?.let { SyncAccount(it.accountName, it.accountType) }
|
||||
?: dataSource.calendarAccount(calendarId)
|
||||
|
||||
private fun canSync(account: SyncAccount): Boolean = account.isSyncable && try {
|
||||
syncRequester.hasAdapter(account.type)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Sync request failed", e)
|
||||
Log.w(TAG, "Sync adapters unreadable", e)
|
||||
false
|
||||
}
|
||||
|
||||
private fun eventCalendar(eventId: Long): suspend () -> Collection<Long?> =
|
||||
{ listOf(dataSource.eventCalendarId(eventId)) }
|
||||
private fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try {
|
||||
syncRequester.requestSync(account, userInitiated)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Sync request refused", e)
|
||||
false
|
||||
}
|
||||
|
||||
private fun eventCalendar(eventId: Long, original: EventForm? = null): suspend () -> Collection<Long?> =
|
||||
{ listOf(original?.calendarId ?: dataSource.eventCalendarId(eventId)) }
|
||||
|
||||
private fun syncTargets(calendars: List<CalendarSource>): Set<SyncAccount> =
|
||||
calendars.syncAccounts().filterTo(linkedSetOf(), ::canSync)
|
||||
|
||||
override val canRequestSync: Flow<Boolean>
|
||||
get() = calendars().map { syncTargets(it).isNotEmpty() }.distinctUntilChanged().flowOn(io)
|
||||
|
||||
override suspend fun requestSync(): SyncRequestResult = withContext(io) {
|
||||
val accounts = try {
|
||||
dataSource.calendars().syncAccounts()
|
||||
syncTargets(calendars().first())
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
@@ -363,7 +383,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
eventId: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
) = write({ listOf(dataSource.eventCalendarId(eventId), updated.calendarId) }) {
|
||||
) = write({ listOf(original.calendarId ?: dataSource.eventCalendarId(eventId), updated.calendarId) }) {
|
||||
dataSource.updateEvent(eventId, original, updated, allDayReminderTimeMinutes())
|
||||
}
|
||||
|
||||
@@ -376,7 +396,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
targetCalendarId: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
): Long = write({ listOf(dataSource.eventCalendarId(eventId), targetCalendarId) }) {
|
||||
): Long = write({ listOf(original.calendarId ?: dataSource.eventCalendarId(eventId), targetCalendarId) }) {
|
||||
dataSource.moveEvent(
|
||||
eventId, targetCalendarId, original, updated, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -387,7 +407,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
beginMillis: Long,
|
||||
original: EventForm,
|
||||
form: EventForm,
|
||||
): Long = write(eventCalendar(eventId)) {
|
||||
): Long = write(eventCalendar(eventId, original)) {
|
||||
dataSource.updateOccurrence(
|
||||
eventId, beginMillis, original, form, allDayReminderTimeMinutes(),
|
||||
)
|
||||
@@ -398,7 +418,7 @@ class CalendarRepositoryImpl @Inject constructor(
|
||||
beginMillis: Long,
|
||||
original: EventForm,
|
||||
updated: EventForm,
|
||||
): Long = write(eventCalendar(eventId)) {
|
||||
): Long = write(eventCalendar(eventId, original)) {
|
||||
dataSource.updateEventFromOccurrence(
|
||||
eventId, beginMillis, original, updated, allDayReminderTimeMinutes(),
|
||||
)
|
||||
|
||||
@@ -4,7 +4,6 @@ import android.accounts.Account
|
||||
import android.content.ContentResolver
|
||||
import android.os.Bundle
|
||||
import android.provider.CalendarContract
|
||||
import android.util.Log
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
@@ -21,16 +20,24 @@ data class SyncAccount(val name: String, val type: String) {
|
||||
* itself stays the adapter's job; this only schedules it.
|
||||
*/
|
||||
interface SyncRequester {
|
||||
/** Whether a calendar sync adapter is installed for [accountType]; without one a request does nothing. */
|
||||
fun hasAdapter(accountType: String): Boolean
|
||||
|
||||
/**
|
||||
* Returns whether the request reached the system. [userInitiated] marks it
|
||||
* manual, which also overrides master-sync-off — only for a user's tap.
|
||||
* Schedule a sync of [account]; may throw if the system refuses. [userInitiated]
|
||||
* marks it manual, which also overrides master-sync-off — only for a user's tap.
|
||||
*/
|
||||
fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean
|
||||
fun requestSync(account: SyncAccount, userInitiated: Boolean)
|
||||
}
|
||||
|
||||
@Singleton
|
||||
class AndroidSyncRequester @Inject constructor() : SyncRequester {
|
||||
override fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean = try {
|
||||
override fun hasAdapter(accountType: String): Boolean =
|
||||
ContentResolver.getSyncAdapterTypes().any {
|
||||
it.authority == CalendarContract.AUTHORITY && it.accountType == accountType
|
||||
}
|
||||
|
||||
override fun requestSync(account: SyncAccount, userInitiated: Boolean) {
|
||||
val extras = Bundle().apply {
|
||||
putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true)
|
||||
if (userInitiated) putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true)
|
||||
@@ -40,16 +47,12 @@ class AndroidSyncRequester @Inject constructor() : SyncRequester {
|
||||
CalendarContract.AUTHORITY,
|
||||
extras,
|
||||
)
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
Log.w("SyncRequester", "Sync request refused", e)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/** The distinct accounts behind the visible, synced calendars — what a manual refresh asks. */
|
||||
/** The distinct non-local accounts behind the visible calendars — what a manual refresh asks. */
|
||||
fun List<CalendarSource>.syncAccounts(): Set<SyncAccount> =
|
||||
filter { !it.isLocal && it.isVisibleInSystem }
|
||||
filter { it.isVisibleInSystem }
|
||||
.map { SyncAccount(it.accountName, it.accountType) }
|
||||
.filterTo(linkedSetOf()) { it.isSyncable }
|
||||
|
||||
|
||||
@@ -599,13 +599,15 @@ fun CalendarHost(
|
||||
onOpenSettings()
|
||||
switchScope.launch { drawerState.close() }
|
||||
},
|
||||
sync = DrawerSync(
|
||||
inFlight = syncInFlight,
|
||||
onSync = {
|
||||
sync.requestSync()
|
||||
switchScope.launch { drawerState.close() }
|
||||
},
|
||||
).takeIf { syncAvailable },
|
||||
sync = remember(syncAvailable, syncInFlight) {
|
||||
DrawerSync(
|
||||
inFlight = syncInFlight,
|
||||
onSync = {
|
||||
sync.requestSync()
|
||||
switchScope.launch { drawerState.close() }
|
||||
},
|
||||
).takeIf { syncAvailable }
|
||||
},
|
||||
)
|
||||
},
|
||||
) {
|
||||
@@ -635,7 +637,8 @@ fun CalendarHost(
|
||||
onDismissChip = {
|
||||
reschedule.consumeOutcome()
|
||||
eventActions.consumeFailure()
|
||||
sync.consumeResult()
|
||||
// Only the chip on show: a receipt queued behind it still gets its turn.
|
||||
if (moveOutcome == null && selectionFailure == null) sync.consumeResult()
|
||||
},
|
||||
)
|
||||
CalendarFab(chromeHost, todayInToolbar, fabSelection)
|
||||
|
||||
@@ -7,7 +7,6 @@ import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import de.jeanlucmakiola.calendula.R
|
||||
import de.jeanlucmakiola.calendula.data.calendar.CalendarRepository
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult
|
||||
import de.jeanlucmakiola.calendula.data.calendar.syncAccounts
|
||||
import de.jeanlucmakiola.floret.android.stateWhileSubscribed
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.async
|
||||
@@ -15,8 +14,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.firstOrNull
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import javax.inject.Inject
|
||||
@@ -33,8 +31,7 @@ class SyncViewModel @Inject constructor(
|
||||
) : ViewModel() {
|
||||
|
||||
/** Whether any visible calendar has a sync adapter behind it. */
|
||||
val available: StateFlow<Boolean> = repository.calendars()
|
||||
.map { it.syncAccounts().isNotEmpty() }
|
||||
val available: StateFlow<Boolean> = repository.canRequestSync
|
||||
.catch { emit(false) }
|
||||
.stateWhileSubscribed(scope = viewModelScope, initialValue = false)
|
||||
|
||||
@@ -53,7 +50,7 @@ class SyncViewModel @Inject constructor(
|
||||
try {
|
||||
// Listening before asking, so a sync that lands at once still counts.
|
||||
val settled = async(start = CoroutineStart.UNDISPATCHED) {
|
||||
withTimeoutOrNull(SETTLE_MILLIS) { repository.providerChanges.first() }
|
||||
withTimeoutOrNull(SETTLE_MILLIS) { repository.providerChanges.firstOrNull() }
|
||||
}
|
||||
val outcome = repository.requestSync()
|
||||
_result.value = outcome
|
||||
|
||||
@@ -48,15 +48,24 @@ fun testRepository(
|
||||
syncRequester: SyncRequester = RecordingSyncRequester(),
|
||||
): CalendarRepositoryImpl = CalendarRepositoryImpl(source, prefs, settings, io, syncRequester)
|
||||
|
||||
/** Records every sync request; [accepts] false models the system refusing one. */
|
||||
class RecordingSyncRequester(var accepts: Boolean = true) : SyncRequester {
|
||||
/**
|
||||
* Records every sync request; [accepts] false models the system refusing one,
|
||||
* [adapterTypes] the installed calendar sync adapters (null: every type has one).
|
||||
*/
|
||||
class RecordingSyncRequester(
|
||||
var accepts: Boolean = true,
|
||||
var adapterTypes: Set<String>? = null,
|
||||
) : SyncRequester {
|
||||
data class Request(val account: SyncAccount, val userInitiated: Boolean)
|
||||
|
||||
val requests = mutableListOf<Request>()
|
||||
|
||||
override fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean {
|
||||
override fun hasAdapter(accountType: String): Boolean =
|
||||
adapterTypes?.contains(accountType) ?: true
|
||||
|
||||
override fun requestSync(account: SyncAccount, userInitiated: Boolean) {
|
||||
if (!accepts) throw SecurityException("refused")
|
||||
requests += Request(account, userInitiated)
|
||||
return accepts
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import de.jeanlucmakiola.calendula.domain.FormTime
|
||||
import de.jeanlucmakiola.calendula.domain.ics.ParsedIcsEvent
|
||||
import de.jeanlucmakiola.calendula.testRepository
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
@@ -135,10 +136,7 @@ class SyncNudgeTest {
|
||||
|
||||
@Test
|
||||
fun `a throwing requester never fails the save`(@TempDir dir: Path) = runTest {
|
||||
val throwing = object : SyncRequester {
|
||||
override fun requestSync(account: SyncAccount, userInitiated: Boolean): Boolean =
|
||||
throw SecurityException("no")
|
||||
}
|
||||
val throwing = RecordingSyncRequester(accepts = false)
|
||||
val source = fake().apply { nextInsertId = 77L }
|
||||
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = throwing)
|
||||
|
||||
@@ -187,4 +185,30 @@ class SyncNudgeTest {
|
||||
|
||||
assertThat(calendars.syncAccounts()).containsExactly(dav)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `accounts without a calendar sync adapter are never asked`(@TempDir dir: Path) = runTest {
|
||||
val sync = RecordingSyncRequester(adapterTypes = setOf(dav.type))
|
||||
val repo = testRepository(fake(), dir, Dispatchers.Unconfined, syncRequester = sync)
|
||||
|
||||
repo.createEvent(form(3L))
|
||||
assertThat(sync.requests).isEmpty()
|
||||
|
||||
assertThat(repo.requestSync()).isEqualTo(SyncRequestResult.Requested)
|
||||
assertThat(sync.requests).containsExactly(Request(dav, true))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `canRequestSync needs a visible calendar with an adapter`(@TempDir dir: Path) = runTest {
|
||||
val sync = RecordingSyncRequester(adapterTypes = setOf(google.type))
|
||||
val source = fake().apply {
|
||||
calendarsResult = listOf(cal(1L, dav), cal(3L, google, visible = false), cal(4L, local))
|
||||
}
|
||||
val repo = testRepository(source, dir, Dispatchers.Unconfined, syncRequester = sync)
|
||||
|
||||
assertThat(repo.canRequestSync.first()).isFalse()
|
||||
|
||||
sync.adapterTypes = setOf(dav.type)
|
||||
assertThat(repo.canRequestSync.first()).isTrue()
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,10 @@ import de.jeanlucmakiola.calendula.RecordingSyncRequester
|
||||
import de.jeanlucmakiola.calendula.data.calendar.FakeCalendarDataSource
|
||||
import de.jeanlucmakiola.calendula.data.calendar.SyncRequestResult
|
||||
import de.jeanlucmakiola.calendula.domain.CalendarSource
|
||||
import de.jeanlucmakiola.calendula.testPrefs
|
||||
import de.jeanlucmakiola.calendula.testRepository
|
||||
import de.jeanlucmakiola.calendula.testSettings
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.test.StandardTestDispatcher
|
||||
import kotlinx.coroutines.test.advanceTimeBy
|
||||
@@ -29,7 +32,13 @@ class SyncViewModelTest {
|
||||
private fun viewModel(dir: Path, sync: RecordingSyncRequester = RecordingSyncRequester()):
|
||||
Pair<SyncViewModel, FakeCalendarDataSource> {
|
||||
val source = FakeCalendarDataSource().apply { calendarsResult = listOf(synced) }
|
||||
return SyncViewModel(testRepository(source, dir, dispatcher, syncRequester = sync)) to source
|
||||
val repo = testRepository(
|
||||
source, dir, dispatcher,
|
||||
prefs = testPrefs(dir, CoroutineScope(dispatcher)),
|
||||
settings = testSettings(dir, CoroutineScope(dispatcher)),
|
||||
syncRequester = sync,
|
||||
)
|
||||
return SyncViewModel(repo) to source
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user