diff --git a/app/src/main/kotlin/com/hippo/ehviewer/client/EhUrl.kt b/app/src/main/kotlin/com/hippo/ehviewer/client/EhUrl.kt index 96a187ef8..b97c67328 100644 --- a/app/src/main/kotlin/com/hippo/ehviewer/client/EhUrl.kt +++ b/app/src/main/kotlin/com/hippo/ehviewer/client/EhUrl.kt @@ -16,6 +16,10 @@ package com.hippo.ehviewer.client import com.hippo.ehviewer.Settings +import io.ktor.http.Parameters +import io.ktor.http.ParametersBuilder +import io.ktor.http.URLBuilder +import io.ktor.http.URLProtocol import okhttp3.HttpUrl object EhUrl { @@ -147,6 +151,19 @@ object EhUrl { } } +inline fun ehUrl(path: String, builder: ParametersBuilder.() -> Unit) = URLBuilder( + protocol = URLProtocol.HTTPS, + host = EhUrl.domain, + pathSegments = listOf(path), + parameters = Parameters.build(builder), +) + +fun ParametersBuilder.addQueryParameterIfNotBlank(name: String, value: String?) = apply { + if (!value.isNullOrBlank()) append(name, value) +} + +fun ParametersBuilder.addQueryParameter(name: String, value: String) = append(name, value) + inline fun httpsUrl(builder: HttpUrl.Builder.() -> Unit) = HttpUrl.Builder().apply(builder).scheme("https").build() inline fun ehUrl(builder: HttpUrl.Builder.() -> Unit) = httpsUrl { apply(builder).host(EhUrl.domain) } fun HttpUrl.Builder.addQueryParameterIfNotBlank(name: String, value: String?) = apply { diff --git a/app/src/main/kotlin/com/hippo/ehviewer/client/data/FavListUrlBuilder.kt b/app/src/main/kotlin/com/hippo/ehviewer/client/data/FavListUrlBuilder.kt index 80f65c3de..493b811c1 100644 --- a/app/src/main/kotlin/com/hippo/ehviewer/client/data/FavListUrlBuilder.kt +++ b/app/src/main/kotlin/com/hippo/ehviewer/client/data/FavListUrlBuilder.kt @@ -17,6 +17,7 @@ package com.hippo.ehviewer.client.data import android.os.Parcelable import com.hippo.ehviewer.client.EhUrl +import com.hippo.ehviewer.client.addQueryParameter import com.hippo.ehviewer.client.addQueryParameterIfNotBlank import com.hippo.ehviewer.client.ehUrl import kotlinx.parcelize.Parcelize @@ -34,24 +35,20 @@ data class FavListUrlBuilder( prev = index.takeUnless { isNext } } - fun build() = ehUrl { - addPathSegment(EhUrl.FAV_PATH) - if (isValidFavCat(favCat)) { - addQueryParameter("favcat", "$favCat") - } else if (favCat == FAV_CAT_ALL) { - addQueryParameter("favcat", "all") + fun build() = ehUrl(EhUrl.FAV_PATH) { + when { + isValidFavCat(favCat) -> addQueryParameter("favcat", "$favCat") + favCat == FAV_CAT_ALL -> addQueryParameter("favcat", "all") } addQueryParameterIfNotBlank("f_search", keyword) addQueryParameterIfNotBlank("prev", prev) addQueryParameterIfNotBlank("next", next) addQueryParameterIfNotBlank("seek", jumpTo) - }.toString() + }.buildString() companion object { const val FAV_CAT_ALL = -1 const val FAV_CAT_LOCAL = -2 - fun isValidFavCat(favCat: Int): Boolean { - return favCat in 0..9 - } + fun isValidFavCat(favCat: Int) = favCat in 0..9 } }