diff --git a/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/RemoteListRepository.kt b/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/RemoteListRepository.kt index 91a2c96..088a737 100644 --- a/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/RemoteListRepository.kt +++ b/app/src/full/java/de/jeanlucmakiola/agendula/data/sync/RemoteListRepository.kt @@ -14,6 +14,7 @@ import de.jeanlucmakiola.caldav.CollectionAdmin import de.jeanlucmakiola.caldav.CollectionOutcome import de.jeanlucmakiola.caldav.CollectionSupport import de.jeanlucmakiola.caldav.DavCollectionAdmin +import de.jeanlucmakiola.caldav.HomeSets import de.jeanlucmakiola.caldav.ResourceNames import de.jeanlucmakiola.caldav.ServerTrust import kotlinx.coroutines.CoroutineDispatcher @@ -211,9 +212,12 @@ class RemoteListRepository @Inject constructor( // Only the first home set is stored, so the others are asked for. A // principal that does not answer leaves the stored check above as the // guard, rather than blocking every delete on this account (#180). - val homeSets = account.principalUrl?.toHttpUrlOrNull()?.let(admin::homeSets).orEmpty() - if (homeSets.any { CollectionHref.same(it.toString(), list.href) }) { - return@withContext Outcome.AccountHome + when (val homeSets = account.principalUrl?.toHttpUrlOrNull()?.let(admin::homeSets)) { + is HomeSets.Listed -> if (homeSets.urls.any { CollectionHref.same(it.toString(), list.href) }) { + return@withContext Outcome.AccountHome + } + is HomeSets.Refused -> return@withContext Outcome.Refused(homeSets.code) + HomeSets.Unknown, null -> Unit } when (val outcome = admin.delete(url)) { diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/data/CollectionHref.kt b/app/src/main/java/de/jeanlucmakiola/agendula/data/CollectionHref.kt index 6c279cd..855b755 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/data/CollectionHref.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/data/CollectionHref.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.agendula.data import java.net.URI +import java.util.concurrent.ConcurrentHashMap /** Compares collection URLs the way a server means them, not the way it spells them. */ object CollectionHref { @@ -11,18 +12,37 @@ object CollectionHref { return key(a) == key(b) } - private fun key(href: String): String = runCatching { - val uri = URI(URI(href).toASCIIString()) + /** Memoised: the lists flow maps every row on every sync, and hrefs rarely change. */ + private fun key(href: String): String { + keys[href]?.let { return it } + if (keys.size > MAX_CACHED) keys.clear() + return parse(href).also { keys[href] = it } + } + + private fun parse(href: String): String = runCatching { + val uri = URI(URI(escapePath(href)).toASCIIString()) val scheme = uri.scheme.lowercase() - val host = (uri.host ?: uri.rawAuthority.substringAfterLast('@').substringBeforeLast(':')).lowercase() + val authority = uri.rawAuthority.substringAfterLast('@') + val host = (uri.host ?: authority.substringBeforeLast(':')).lowercase() + val explicitPort = if (uri.host != null) uri.port else authority.substringAfterLast(':', "").toIntOrNull() ?: -1 val port = when { - uri.port != -1 -> uri.port + explicitPort != -1 -> explicitPort scheme == "https" -> HTTPS_PORT scheme == "http" -> HTTP_PORT else -> -1 } "$scheme://$host:$port${normalizeEscapes(uri.rawPath.orEmpty()).trimEnd('/')}" - }.getOrElse { href.trimEnd('/') } + }.getOrElse { href.lowercase().trimEnd('/') } + + /** Escapes what servers leave raw in paths but [URI] refuses, such as `[` and a space. */ + private fun escapePath(href: String): String { + val pathStart = href.indexOf('/', href.indexOf("://").let { if (it < 0) 0 else it + SCHEME_SEPARATOR }) + if (pathStart < 0) return href + val path = href.substring(pathStart).map { c -> + if (c in UNSAFE) "%" + c.code.toString(HEX).uppercase().padStart(2, '0') else c.toString() + } + return href.substring(0, pathStart) + path.joinToString("") + } /** Decodes escaped ASCII but `%2F`, which is part of a segment, not a separator. */ private fun normalizeEscapes(path: String): String = ESCAPE.replace(path) { match -> @@ -30,7 +50,11 @@ object CollectionHref { if (code == '/'.code || code >= ASCII_END) match.value.uppercase() else code.toChar().toString() } + private val keys = ConcurrentHashMap() private val ESCAPE = Regex("%([0-9A-Fa-f]{2})") + private const val UNSAFE = " \"<>[]\\^`{|}" + private const val SCHEME_SEPARATOR = 3 + private const val MAX_CACHED = 512 private const val HEX = 16 private const val ASCII_END = 0x80 private const val HTTPS_PORT = 443 diff --git a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt index 6914b3e..00982d9 100644 --- a/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/agendula/ui/lists/ListsScreen.kt @@ -260,7 +260,7 @@ internal fun listWriteFailureMessage(failure: ListWriteFailure): Int = when (fai ListWriteFailure.OFFLINE -> R.string.list_save_failed_offline ListWriteFailure.READ_ONLY -> R.string.list_save_failed_read_only ListWriteFailure.UNSUPPORTED -> R.string.list_save_failed_unsupported - ListWriteFailure.ACCOUNT_HOME -> R.string.list_delete_account_home + ListWriteFailure.ACCOUNT_HOME -> R.string.list_delete_failed_account_home } @Composable diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 30ec94e..5ad4b35 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -325,6 +325,7 @@ Delete list Could not save the list. Could not delete the list. + That list is the account\u2019s calendar itself. This list is the account’s calendar itself, so it can’t be deleted here. Deleting it would also delete the calendar’s events. Delete list? Where diff --git a/app/src/test/java/de/jeanlucmakiola/agendula/data/CollectionHrefTest.kt b/app/src/test/java/de/jeanlucmakiola/agendula/data/CollectionHrefTest.kt index 2a9ef22..2c0bd74 100644 --- a/app/src/test/java/de/jeanlucmakiola/agendula/data/CollectionHrefTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/agendula/data/CollectionHrefTest.kt @@ -19,6 +19,8 @@ class CollectionHrefTest { assertThat(CollectionHref.same("https://h.example/kalender/gr%C3%BCn/", "https://h.example/kalender/grün")).isTrue() assertThat(CollectionHref.same("https://h.example/cal/[1]/", "https://h.example/cal/[1]")).isTrue() assertThat(CollectionHref.same("https://h.example/cal/a%2Fb/", "https://h.example/cal/a/b/")).isFalse() + assertThat(CollectionHref.same("https://my_server.lan:8443/cal/1/", "https://my_server.lan/cal/1/")).isFalse() + assertThat(CollectionHref.same("https://h.example/cal/[1]/", "https://H.example/cal/%5B1%5D")).isTrue() } @Test diff --git a/caldav/src/main/kotlin/de/jeanlucmakiola/caldav/CollectionAdmin.kt b/caldav/src/main/kotlin/de/jeanlucmakiola/caldav/CollectionAdmin.kt index d975a03..f154cb1 100644 --- a/caldav/src/main/kotlin/de/jeanlucmakiola/caldav/CollectionAdmin.kt +++ b/caldav/src/main/kotlin/de/jeanlucmakiola/caldav/CollectionAdmin.kt @@ -5,6 +5,7 @@ import at.bitfire.dav4jvm.Property import at.bitfire.dav4jvm.Response import at.bitfire.dav4jvm.XmlUtils import at.bitfire.dav4jvm.XmlUtils.insertTag +import at.bitfire.dav4jvm.exception.HttpException import at.bitfire.dav4jvm.property.ResourceType import okhttp3.HttpUrl import okhttp3.MediaType.Companion.toMediaType @@ -96,8 +97,19 @@ interface CollectionAdmin { /** DELETE. The tasks go with it, on the server and everywhere else. */ fun delete(url: HttpUrl): CollectionOutcome - /** The `calendar-home-set` hrefs [principal] reports now, or null when it did not answer. */ - fun homeSets(principal: HttpUrl): List? + /** The `calendar-home-set` hrefs [principal] reports now. */ + fun homeSets(principal: HttpUrl): HomeSets +} + +/** What a principal said about its home sets. */ +sealed interface HomeSets { + data class Listed(val urls: List) : HomeSets + + /** Rejected credentials or throttling: another request would only add to it. */ + data class Refused(val code: Int) : HomeSets + + /** Any other failure; the caller decides what not knowing means. */ + data object Unknown : HomeSets } class DavCollectionAdmin( @@ -138,8 +150,14 @@ class DavCollectionAdmin( CollectionSupport.NONE } - override fun homeSets(principal: HttpUrl): List? = - runCatching { calendarHomeSets(httpClient, principal).urls }.getOrNull() + override fun homeSets(principal: HttpUrl): HomeSets = + runCatching { calendarHomeSets(httpClient, principal).urls }.fold( + onSuccess = { HomeSets.Listed(it) }, + onFailure = { error -> + val code = (error as? HttpException)?.code ?: -1 + if (code == UNAUTHORIZED || code == TOO_MANY_REQUESTS) HomeSets.Refused(code) else HomeSets.Unknown + }, + ) /** * A home set that is itself a calendar, as on all-inkl.com (#180), cannot @@ -336,6 +354,8 @@ class DavCollectionAdmin( const val COMPONENT = "VTODO" const val NOT_FOUND = 404 const val GONE = 410 + const val UNAUTHORIZED = 401 + const val TOO_MANY_REQUESTS = 429 val MIME_XML = "application/xml; charset=utf-8".toMediaType() val MKCALENDAR = Property.Name(XmlUtils.NS_CALDAV, "mkcalendar") diff --git a/caldav/src/test/kotlin/de/jeanlucmakiola/caldav/CollectionAdminTest.kt b/caldav/src/test/kotlin/de/jeanlucmakiola/caldav/CollectionAdminTest.kt index 7297278..b8eddcb 100644 --- a/caldav/src/test/kotlin/de/jeanlucmakiola/caldav/CollectionAdminTest.kt +++ b/caldav/src/test/kotlin/de/jeanlucmakiola/caldav/CollectionAdminTest.kt @@ -95,15 +95,23 @@ class CollectionAdminTest { ), ) - assertThat(admin.homeSets(server.url("/principals/me/"))) - .containsExactly(server.url("/calendars/me/1/"), server.url("/calendars/me/2/")) + assertThat(admin.homeSets(server.url("/principals/me/"))).isEqualTo( + HomeSets.Listed(listOf(server.url("/calendars/me/1/"), server.url("/calendars/me/2/"))), + ) } @Test fun `a principal that does not answer has no known home sets`() { server.enqueue(MockResponse().setResponseCode(500)) - assertThat(admin.homeSets(server.url("/principals/me/"))).isNull() + assertThat(admin.homeSets(server.url("/principals/me/"))).isEqualTo(HomeSets.Unknown) + } + + @Test + fun `rejected credentials on the principal are reported, not shrugged off`() { + server.enqueue(MockResponse().setResponseCode(401)) + + assertThat(admin.homeSets(server.url("/principals/me/"))).isEqualTo(HomeSets.Refused(401)) } private fun resourceType(types: String) = MockResponse()