2019-07-12 20:38:15 +02:00
|
|
|
/* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
2019-02-12 20:13:09 +01:00
|
|
|
|
|
|
|
package org.mozilla.fenix.ext
|
|
|
|
|
2019-06-07 18:33:07 +02:00
|
|
|
import android.content.Context
|
2019-06-10 16:12:11 +02:00
|
|
|
import androidx.core.net.toUri
|
2019-06-10 22:46:55 +02:00
|
|
|
import kotlinx.coroutines.runBlocking
|
2019-04-11 20:58:07 +02:00
|
|
|
import java.net.MalformedURLException
|
|
|
|
import java.net.URL
|
2019-06-07 18:33:07 +02:00
|
|
|
import mozilla.components.support.ktx.android.net.hostWithoutCommonPrefixes
|
2019-04-11 20:58:07 +02:00
|
|
|
|
2019-02-12 20:13:09 +01:00
|
|
|
/**
|
|
|
|
* Replaces the keys with the values with the map provided.
|
|
|
|
*/
|
|
|
|
fun String.replace(pairs: Map<String, String>): String {
|
|
|
|
var result = this
|
|
|
|
pairs.forEach { (l, r) -> result = result.replace(l, r) }
|
|
|
|
return result
|
|
|
|
}
|
2019-04-11 20:58:07 +02:00
|
|
|
|
2019-05-13 22:50:42 +02:00
|
|
|
/**
|
|
|
|
* Try to parse and get host part if this [String] is valid URL.
|
|
|
|
* Returns **null** otherwise.
|
|
|
|
*/
|
|
|
|
fun String?.getHostFromUrl(): String? = try {
|
|
|
|
URL(this).host
|
|
|
|
} catch (e: MalformedURLException) {
|
|
|
|
null
|
2019-04-11 20:58:07 +02:00
|
|
|
}
|
2019-05-06 20:20:19 +02:00
|
|
|
|
2019-06-07 18:33:07 +02:00
|
|
|
/**
|
|
|
|
* Trim a host's prefix and suffix
|
|
|
|
*/
|
2019-06-10 22:46:55 +02:00
|
|
|
fun String.urlToTrimmedHost(context: Context): String {
|
2019-05-06 20:20:19 +02:00
|
|
|
return try {
|
2019-06-10 16:12:11 +02:00
|
|
|
val host = toUri().hostWithoutCommonPrefixes ?: return this
|
2019-06-10 22:46:55 +02:00
|
|
|
runBlocking {
|
|
|
|
context.components.publicSuffixList.stripPublicSuffix(host).await()
|
|
|
|
}
|
2019-05-06 20:20:19 +02:00
|
|
|
} catch (e: MalformedURLException) {
|
2019-06-07 18:33:07 +02:00
|
|
|
this
|
2019-05-06 20:20:19 +02:00
|
|
|
}
|
|
|
|
}
|