Add code to extract the base domain from a hostname

This commit is contained in:
cketti 2023-05-09 16:41:05 +02:00
parent 510950da65
commit 9f4597b48c
3 changed files with 55 additions and 0 deletions

View file

@ -0,0 +1,10 @@
package app.k9mail.autodiscovery.autoconfig
/**
* Extract the base domain from a host name.
*
* An implementation needs to respect the [Public Suffix List](https://publicsuffix.org/).
*/
interface BaseDomainExtractor {
fun extractBaseDomain(domain: String): String
}

View file

@ -0,0 +1,16 @@
package app.k9mail.autodiscovery.autoconfig
import okhttp3.HttpUrl
class OkHttpBaseDomainExtractor : BaseDomainExtractor {
override fun extractBaseDomain(domain: String): String {
return domain.toHttpUrlOrNull().topPrivateDomain() ?: domain
}
private fun String.toHttpUrlOrNull(): HttpUrl {
return HttpUrl.Builder()
.scheme("https")
.host(this)
.build()
}
}

View file

@ -0,0 +1,29 @@
package app.k9mail.autodiscovery.autoconfig
import assertk.assertThat
import assertk.assertions.isEqualTo
import org.junit.Test
class OkHttpBaseDomainExtractorTest {
private val baseDomainExtractor = OkHttpBaseDomainExtractor()
@Test
fun `basic domain`() {
assertThat(baseDomainExtractor.extractBaseDomain("domain.example")).isEqualTo("domain.example")
}
@Test
fun `basic subdomain`() {
assertThat(baseDomainExtractor.extractBaseDomain("subdomain.domain.example")).isEqualTo("domain.example")
}
@Test
fun `domain with public suffix`() {
assertThat(baseDomainExtractor.extractBaseDomain("example.co.uk")).isEqualTo("example.co.uk")
}
@Test
fun `subdomain with public suffix`() {
assertThat(baseDomainExtractor.extractBaseDomain("subdomain.example.co.uk")).isEqualTo("example.co.uk")
}
}