InstanceUrl.kt 1.77 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
package fr.chenry.android.freshrss.utils

import android.text.SpannableStringBuilder
import androidx.core.content.ContextCompat
import androidx.core.text.bold
import androidx.core.text.color
import fr.chenry.android.freshrss.FreshRSSApplication
import fr.chenry.android.freshrss.R
import java.net.URL

class InstanceUrl(val protocole: String, base: String) {
    val isMalformed: Boolean

    val base = base
        .replace(".*://".toRegex(), "")
        .replace("//+".toRegex(), "/")
        .replace("/$".toRegex(), "")

    private val hasApiEndpoint: Boolean = this.base.endsWith(apiEndpoint)
    private val endpoint: String = if(hasApiEndpoint) "" else apiEndpoint

    init {
        isMalformed = Try {URL("$protocole${this.base}")}.getOrNull() == null
    }

    fun toSpanString(): CharSequence = SpannableStringBuilder().apply {
        val urlString = base.let {if(hasApiEndpoint) it else it.replace(apiEndpoint, "")}
        color(ContextCompat.getColor(FreshRSSApplication.context, R.color.grey)) {append(protocole)}
        bold {append(urlString)}
        if(!hasApiEndpoint)
            color(ContextCompat.getColor(FreshRSSApplication.context, R.color.grey)) {append(apiEndpoint)}
    }

    override fun toString(): String = "$protocole$base$endpoint"

    companion object {
        private const val apiEndpoint = "/api/greader.php"
        val authorizedProtocols = arrayOf("https://", "http://")

        fun parse(url: String): InstanceUrl {
            "(.*://)".toPattern().matcher(url).let {
                if(it.find()) {
                    val protocol = it.group(0)
                    if(authorizedProtocols.contains(protocol)) return InstanceUrl(protocol, url)
                }
            }

            return InstanceUrl(authorizedProtocols[0], url)
        }
    }
}