Skip to content

Commit

Permalink
优化地区检测机制
Browse files Browse the repository at this point in the history
Resolves #124
Resolves #125
  • Loading branch information
aaa1115910 committed Feb 2, 2024
1 parent c388254 commit 91cff92
Showing 1 changed file with 25 additions and 19 deletions.
44 changes: 25 additions & 19 deletions app/src/main/kotlin/dev/aaa1115910/bv/util/NetworkUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,18 @@ import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.HttpRequestRetry
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.withContext

object NetworkUtil {
private lateinit var client: HttpClient
private const val LOC_CHECK_URL = "https://www.cloudflare.com/cdn-cgi/trace"
private val locCheckUrls = listOf(
"https://www.cloudflare.com/cdn-cgi/trace",
"https://1.1.1.1/cdn-cgi/trace"
)
private val logger = KotlinLogging.logger { }
var networkCheckResult: Map<String, String> = emptyMap()

init {
createClient()
Expand All @@ -25,22 +31,22 @@ object NetworkUtil {
}
}

suspend fun isMainlandChina(): Boolean {
return runCatching {
val result = client.get(LOC_CHECK_URL).bodyAsText()
logger.info { "Network result:\n$result" }

networkCheckResult = result
.lines()
.filter { it != "" }
.associate {
val splits = it.split("=")
splits[0] to splits[1]
}

require(networkCheckResult["loc"] != "CN") { "BV doesn't support use in mainland China" }

false
}.getOrDefault(true)
suspend fun isMainlandChina() = withContext(Dispatchers.IO) {
locCheckUrls.map { locCheckUrl ->
async {
runCatching {
val result = client.get(locCheckUrl).bodyAsText()
logger.info { "Network result:\n$result" }

val networkCheckResult = result
.lines()
.filter { it.isNotBlank() }
.associate { with(it.split("=")) { this[0] to this[1] } }

require(networkCheckResult["loc"] != "CN") { "BV doesn't support use in mainland China" }
false
}.getOrDefault(true)
}
}.awaitAll().all { it }
}
}

0 comments on commit 91cff92

Please sign in to comment.