package studio.daybreak.mail import android.util.Base64 import org.json.JSONArray import org.json.JSONObject import org.w3c.dom.Element import java.io.ByteArrayInputStream import java.net.URL import java.nio.charset.StandardCharsets import java.util.Locale import java.util.UUID import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody.Companion.toRequestBody import java.util.concurrent.TimeUnit import javax.xml.parsers.DocumentBuilderFactory internal object AndroidDavService { private val httpClient = OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .followRedirects(false) .followSslRedirects(false) .build() fun list(): JSONObject { val store = AndroidAccountVault.read() return JSONObject() .put("caldav", AndroidAccountVault.publicDavAccounts("caldav")) .put("carddav", AndroidAccountVault.publicDavAccounts("carddav")) .put("activeCaldavId", store.optString("activeCaldavId")) .put("activeCarddavId", store.optString("activeCarddavId")) } fun connect(input: JSONObject): JSONObject { val type = type(input.optString("type")) val serverUrl = input.optString("serverUrl").trim() val username = input.optString("username").trim() val password = input.optString("password") val url = DavUrlPolicy.parseServerUrl(serverUrl) require(username.isNotBlank() && password.isNotBlank()) { "Enter the DAV username and password." } val collections = discoverCollections(url.toString(), username, password, type) require(collections.length() > 0) { "No ${if (type == "caldav") "calendars" else "address books"} were found on this server." } val account = JSONObject() .put("id", UUID.randomUUID().toString()) .put("type", type) .put("serverUrl", url.toString()) .put("username", username) .put("password", password) .put("collections", collections) val saved = AndroidAccountVault.putDavAccount(type, account) val publicConfig = publicDav(saved) return JSONObject() .put("config", publicConfig) .put("collections", collections) .put("accounts", list()) } fun activate(typeInput: String, id: String): JSONObject { val type = type(typeInput) val config = AndroidAccountVault.activeDav(type, id) ?: throw IllegalStateException("That DAV account could not be found.") val store = AndroidAccountVault.read() store.put(if (type == "caldav") "activeCaldavId" else "activeCarddavId", config.optString("id")) AndroidAccountVault.write(store) return JSONObject().put("id", config.optString("id")) } fun remove(typeInput: String, id: String): JSONObject = AndroidAccountVault.removeDavAccount(type(typeInput), id) fun sync(typeInput: String): JSONObject { val type = type(typeInput) val account = AndroidAccountVault.activeDav(type) ?: throw IllegalStateException("Connect a ${if (type == "caldav") "CalDAV" else "CardDAV"} server first.") val collectionKey = if (type == "caldav") "calendar" else "addressbook" val result = JSONArray() val collections = account.optJSONArray("collections") ?: JSONArray() for (index in 0 until collections.length()) { val collection = collections.getJSONObject(index) val objects = listObjects(account, collection, type) for (obj in objects) { val href = obj.optString("href") val data = obj.optString("data") if (data.isBlank()) continue if (type == "caldav") parseCalendar(data, account, collection, obj).forEach(result::put) else parseContacts(data, account, collection, obj).forEach(result::put) } } return JSONObject().put("items", result).put("account", publicDav(account)) .put("collectionType", collectionKey) } fun saveEvent(input: JSONObject): JSONObject? { val remote = input.optJSONObject("_dav") ?: JSONObject() val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId").ifBlank { null }) ?: return null val collections = account.optJSONArray("collections") ?: JSONArray() val collection = findCollection(collections, remote.optString("collectionUrl")) ?: throw IllegalStateException("No writable calendar was found.") val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() } val filename = "$uid.ics" val collectionUrl = collection.optString("url") val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename } val data = calendarData(input, uid) val response = request(account, target, "PUT", data, mapOf("Content-Type" to "text/calendar; charset=utf-8")) require(response.code in 200..299) { "The calendar server rejected the event (${response.code})." } return JSONObject() .put("accountId", account.optString("id")) .put("collectionUrl", collectionUrl) .put("objectUrl", target) .put("etag", response.headers["etag"] ?: remote.optString("etag")) .put("uid", uid) } fun deleteEvent(remote: JSONObject) { val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId")) ?: throw IllegalStateException("That calendar account could not be found.") val url = remote.optString("objectUrl") if (url.isBlank()) return val response = request(account, url, "DELETE", null) require(response.code in 200..299 || response.code == 404) { "The calendar server rejected the deletion (${response.code})." } } fun saveContact(input: JSONObject): JSONObject? { val remote = input.optJSONObject("_dav") ?: JSONObject() val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId").ifBlank { null }) ?: return null val collections = account.optJSONArray("collections") ?: JSONArray() val collection = findCollection(collections, remote.optString("collectionUrl")) ?: throw IllegalStateException("No writable address book was found.") val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() } val filename = "$uid.vcf" val collectionUrl = collection.optString("url") val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename } val response = request(account, target, "PUT", vcardData(input, uid), mapOf("Content-Type" to "text/vcard; charset=utf-8")) require(response.code in 200..299) { "The address book server rejected the contact (${response.code})." } return JSONObject() .put("accountId", account.optString("id")) .put("collectionUrl", collectionUrl) .put("objectUrl", target) .put("etag", response.headers["etag"] ?: remote.optString("etag")) .put("uid", uid) } fun deleteContact(remote: JSONObject) { val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId")) ?: throw IllegalStateException("That address book account could not be found.") val url = remote.optString("objectUrl") if (url.isBlank()) return val response = request(account, url, "DELETE", null) require(response.code in 200..299 || response.code == 404) { "The address book server rejected the deletion (${response.code})." } } private data class HttpResult(val code: Int, val body: ByteArray, val headers: Map) private fun request( account: JSONObject, address: String, method: String, body: String?, headers: Map = emptyMap() ): HttpResult { DavUrlPolicy.requireSameOrigin(account.optString("serverUrl"), address) val requestBody = body?.toRequestBody(headers["Content-Type"]?.toMediaTypeOrNull()) val builder = Request.Builder() .url(address) .header("Authorization", basicAuth(account)) .header("User-Agent", "ep-mail-Android") for ((key, value) in headers) builder.header(key, value) builder.method(method, requestBody) httpClient.newCall(builder.build()).execute().use { response -> val bytes = response.body?.bytes() ?: ByteArray(0) val responseHeaders = response.headers.toMultimap().mapValues { (_, values) -> values.firstOrNull().orEmpty() } return HttpResult(response.code, bytes, responseHeaders) } } private fun discoverCollections(serverUrl: String, username: String, password: String, type: String): JSONArray { val base = JSONObject().put("serverUrl", serverUrl).put("username", username).put("password", password) val setName = if (type == "caldav") "calendar-home-set" else "addressbook-home-set" val rootResponse = request(base, serverUrl, "PROPFIND", propfindBody(setName), mapOf( "Depth" to "0", "Content-Type" to "application/xml; charset=utf-8" )) require(rootResponse.code in 200..299 || rootResponse.code == 207) { "Could not access the DAV server (${rootResponse.code})." } val rootDocument = parseXml(rootResponse.body) var homeUrl = findHref(rootDocument, setName)?.let { resolveUrl(serverUrl, it) } if (homeUrl == null) { val principal = findHref(rootDocument, "current-user-principal") if (principal != null) { val principalUrl = resolveUrl(serverUrl, principal) val principalResponse = request(base, principalUrl, "PROPFIND", propfindBody(setName), mapOf( "Depth" to "0", "Content-Type" to "application/xml; charset=utf-8" )) if (principalResponse.code in 200..299 || principalResponse.code == 207) { homeUrl = findHref(parseXml(principalResponse.body), setName)?.let { resolveUrl(principalUrl, it) } } } } val collectionUrl = homeUrl ?: serverUrl val response = request(base, collectionUrl, "PROPFIND", collectionBody(), mapOf( "Depth" to "1", "Content-Type" to "application/xml; charset=utf-8" )) require(response.code in 200..299 || response.code == 207) { "Could not discover DAV collections (${response.code})." } val document = parseXml(response.body) val requiredType = if (type == "caldav") "calendar" else "addressbook" val result = JSONArray() val responses = document.getElementsByTagNameNS("*", "response") for (index in 0 until responses.length) { val responseElement = responses.item(index) as? Element ?: continue val href = childText(responseElement, "href") ?: continue if (responseElement.getElementsByTagNameNS("*", requiredType).length == 0) continue val resolved = resolveUrl(collectionUrl, href) val displayName = textContent(responseElement, "displayname").orEmpty().ifBlank { resolved } result.put(JSONObject().put("url", resolved).put("name", displayName)) } return result } private fun listObjects(account: JSONObject, collection: JSONObject, type: String): List { val collectionUrl = collection.optString("url") val response = request(account, collectionUrl, "PROPFIND", collectionBody(), mapOf( "Depth" to "1", "Content-Type" to "application/xml; charset=utf-8" )) require(response.code in 200..299 || response.code == 207) { "Could not read DAV collection ${collection.optString("name")} (${response.code})." } val document = parseXml(response.body) val responses = document.getElementsByTagNameNS("*", "response") val result = ArrayList() for (index in 0 until responses.length) { val element = responses.item(index) as? Element ?: continue val href = childText(element, "href") ?: continue val objectUrl = resolveUrl(collectionUrl, href) if (objectUrl.trimEnd('/') == collectionUrl.trimEnd('/')) continue val data = if (type == "caldav") textContent(element, "calendar-data") else textContent(element, "address-data") val content = if (!data.isNullOrBlank()) data else { val fetched = request(account, objectUrl, "GET", null) if (fetched.code !in 200..299) continue String(fetched.body, StandardCharsets.UTF_8) } result.add(JSONObject() .put("href", objectUrl) .put("etag", textContent(element, "getetag").orEmpty()) .put("data", content)) } return result } private fun parseCalendar(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List { val unfolded = unfold(data) return Regex("BEGIN:VEVENT(.*?)END:VEVENT", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)) .findAll(unfolded).mapNotNull { match -> val block = match.groupValues[1] val fields = parseProperties(block) val uid = fields["UID"].orEmpty().ifBlank { UUID.randomUUID().toString() } val (date, time) = parseDate(fields["DTSTART"].orEmpty()) ?: return@mapNotNull null JSONObject() .put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}") .put("title", unescape(fields["SUMMARY"].orEmpty()).ifBlank { "(no title)" }) .put("date", date) .put("time", time) .put("with", Regex("(?im)^ATTENDEE[^:]*:(?:mailto:)?([^\\r\\n]+)").findAll(block) .map { it.groupValues[1].trim() }.joinToString(", ")) .put("place", unescape(fields["LOCATION"].orEmpty())) .put("notes", unescape(fields["DESCRIPTION"].orEmpty())) .put("_dav", JSONObject() .put("accountId", account.optString("id")) .put("collectionUrl", collection.optString("url")) .put("objectUrl", resource.optString("href")) .put("etag", resource.optString("etag")) .put("uid", uid)) }.toList() } private fun parseContacts(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List { val cards = Regex("BEGIN:VCARD(.*?)END:VCARD", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)) return cards.findAll(unfold(data)).mapNotNull { match -> val block = match.groupValues[1] val fields = parseProperties(block) val name = unescape(fields["FN"].orEmpty()).trim() if (name.isBlank()) return@mapNotNull null val uid = fields["UID"].orEmpty() JSONObject() .put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}") .put("name", name) .put("email", unescape(fields["EMAIL"].orEmpty())) .put("note", unescape(fields["NOTE"].orEmpty())) .put("initials", name.split(Regex("\\s+")).mapNotNull { it.firstOrNull()?.toString() } .joinToString("").take(2).uppercase(Locale.getDefault())) .put("color", "#dce9dd") .put("_dav", JSONObject() .put("accountId", account.optString("id")) .put("collectionUrl", collection.optString("url")) .put("objectUrl", resource.optString("href")) .put("etag", resource.optString("etag")) .put("uid", uid)) }.toList() } private fun calendarData(event: JSONObject, uid: String): String { val date = event.optString("date").replace("-", "") val time = event.optString("time") val start = if (time.isBlank()) "DTSTART;VALUE=DATE:$date" else "DTSTART;TZID=UTC:${date}T${time.replace(":", "")}00" val end = if (time.isBlank()) "" else { val parts = time.split(":") val mins = (parts.getOrNull(0)?.toIntOrNull() ?: 0) * 60 + (parts.getOrNull(1)?.toIntOrNull() ?: 0) + 60 val endTime = "%04d%02d00".format(Locale.ROOT, (mins / 60) % 24, mins % 60) "DTEND;TZID=UTC:${date}T$endTime\r\n" } return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${escape(uid)}\r\nDTSTAMP:${utcNow()}\r\n$start\r\n$end${property("SUMMARY", event.optString("title"))}${property("LOCATION", event.optString("place"))}${property("DESCRIPTION", event.optString("notes"))}END:VEVENT\r\nEND:VCALENDAR\r\n" } private fun vcardData(contact: JSONObject, uid: String): String { val name = contact.optString("name").trim().split(Regex("\\s+")) val first = name.firstOrNull().orEmpty() val last = name.drop(1).joinToString(" ") return "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${escape(uid)}\r\nFN:${escape(contact.optString("name"))}\r\nN:${escape(last)};${escape(first)};;;\r\nEMAIL:${escape(contact.optString("email"))}\r\n${if (contact.optString("note").isNotBlank()) "NOTE:${escape(contact.optString("note"))}\r\n" else ""}END:VCARD\r\n" } private fun propfindBody(homeSet: String) = """ """.trimIndent() private fun collectionBody() = """ """.trimIndent() private fun parseXml(bytes: ByteArray): org.w3c.dom.Document { val factory = DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true isXIncludeAware = false isExpandEntityReferences = false setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) setFeature("http://xml.org/sax/features/external-general-entities", false) setFeature("http://xml.org/sax/features/external-parameter-entities", false) } return factory.newDocumentBuilder().parse(ByteArrayInputStream(bytes)) } private fun findHref(document: org.w3c.dom.Document, propertyName: String): String? { val elements = document.getElementsByTagNameNS("*", propertyName) for (index in 0 until elements.length) { val href = (elements.item(index) as? Element)?.getElementsByTagNameNS("*", "href")?.item(0)?.textContent if (!href.isNullOrBlank()) return href.trim() } return null } private fun textContent(element: Element, propertyName: String): String? { val nodes = element.getElementsByTagNameNS("*", propertyName) return if (nodes.length == 0) null else nodes.item(0)?.textContent?.trim() } private fun childText(element: Element, childName: String): String? { val children = element.childNodes for (index in 0 until children.length) { val node = children.item(index) if (node is Element && node.localName == childName) return node.textContent.trim() } return null } private fun resolveUrl(base: String, href: String): String = URL(URL(base), href).toString() private fun basicAuth(account: JSONObject): String { val raw = "${account.optString("username")}:${account.optString("password")}" return "Basic " + Base64.encodeToString(raw.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP) } private fun publicDav(account: JSONObject) = JSONObject() .put("id", account.optString("id")) .put("serverUrl", account.optString("serverUrl")) .put("username", account.optString("username")) .put("collections", account.optJSONArray("collections") ?: JSONArray()) private fun type(value: String) = when (value) { "caldav", "carddav" -> value else -> throw IllegalArgumentException("Choose a supported CalDAV or CardDAV account.") } private fun findCollection(collections: JSONArray, url: String): JSONObject? { for (index in 0 until collections.length()) { val collection = collections.getJSONObject(index) if (url.isBlank() || collection.optString("url") == url) return collection } return null } private fun encode(value: String) = java.net.URLEncoder.encode(value, "UTF-8") private fun escape(value: String) = value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;") private fun unescape(value: String) = value.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\") private fun property(name: String, value: String) = if (value.isBlank()) "" else "$name:${escape(value)}\r\n" private fun utcNow() = java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ROOT) .apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }.format(java.util.Date()) private fun unfold(data: String) = data.replace("\r\n ", "").replace("\n ", "").replace("\r\n\t", "").replace("\n\t", "") private fun parseProperties(block: String): Map { val result = LinkedHashMap() for (line in block.lines()) { val colon = line.indexOf(':') if (colon <= 0) continue val name = line.substring(0, colon).substringBefore(';').uppercase(Locale.ROOT) result.putIfAbsent(name, line.substring(colon + 1).trim()) } return result } private fun parseDate(raw: String): Pair? { if (raw.isBlank()) return null val rawValue = raw.substringAfter(':', raw) return try { when { rawValue.length == 8 -> "${rawValue.substring(0, 4)}-${rawValue.substring(4, 6)}-${rawValue.substring(6, 8)}" to "" rawValue.length >= 15 -> { val digits = rawValue.replace("T", "").replace("Z", "").take(14) val date = "${digits.substring(0, 4)}-${digits.substring(4, 6)}-${digits.substring(6, 8)}" val time = "${digits.substring(8, 10)}:${digits.substring(10, 12)}" date to time } else -> null } } catch (_: Exception) { null } } }