| 1 | package tw.nekomimi.nekogram |
| 2 | |
| 3 | import android.os.Build |
| 4 | import androidx.annotation.RequiresApi |
| 5 | import cn.hutool.core.codec.Base64 |
| 6 | import cn.hutool.core.util.StrUtil |
| 7 | import okhttp3.Dns |
| 8 | import okhttp3.HttpUrl |
| 9 | import okhttp3.HttpUrl.Companion.toHttpUrlOrNull |
| 10 | import tw.nekomimi.nekogram.tcp2ws.Tcp2wsServer |
| 11 | import tw.nekomimi.nkmr.NekomuraConfig |
| 12 | import java.net.InetAddress |
| 13 | |
| 14 | class WsLoader { |
| 15 | |
| 16 | lateinit var server: Tcp2wsServer |
| 17 | |
| 18 | fun init(bean: Bean, port: Int) { |
| 19 | server = Tcp2wsServer(bean, port) |
| 20 | } |
| 21 | |
| 22 | fun start() { |
| 23 | server.start() |
| 24 | } |
| 25 | |
| 26 | fun stop() { |
| 27 | if (::server.isInitialized) { |
| 28 | server.interrupt() |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | companion object { |
| 33 | |
| 34 | fun parse(url: String): Bean { |
| 35 | val lnk = url.replace("ws://", "http://") |
| 36 | .replace("wss://", "https://") |
| 37 | .toHttpUrlOrNull() ?: error("Invalid link") |
| 38 | val payloadStr = lnk.queryParameter("payload") ?: error("Missing payload") |
| 39 | val payload = Base64.decodeStr(payloadStr).split(",") |
| 40 | if (payload.size < 5) error("Invalid payload") |
| 41 | return Bean( |
| 42 | lnk.host, |
| 43 | payload, |
| 44 | lnk.isHttps, |
| 45 | lnk.fragment ?: "" |
| 46 | ) |
| 47 | } |
| 48 | |
| 49 | } |
| 50 | |
| 51 | data class Bean( |
| 52 | var server: String = "", |
| 53 | var payload: List<String> = arrayListOf(), |
| 54 | var tls: Boolean = true, |
| 55 | var remarks: String = "" |
| 56 | ) { |
| 57 | |
| 58 | var payloadStr: String |
| 59 | get() = Base64.encodeUrlSafe(payload.joinToString(",")) |
| 60 | set(value) { |
| 61 | payload = Base64.decodeStr(value).split(",") |
| 62 | } |
| 63 | |
| 64 | override fun toString(): String { |
| 65 | val builder = HttpUrl.Builder() |
| 66 | .scheme("http") |
| 67 | .host(server) |
| 68 | .addQueryParameter("payload", payloadStr); |
| 69 | if (remarks.isNotBlank()) { |
| 70 | builder.fragment(remarks) |
| 71 | } |
| 72 | return builder.build().toString().replace("http://", if (tls) "wss://" else "ws://") |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // For OKHttp in ProxyHandler.java |
| 77 | class CustomDns : Dns { |
| 78 | override fun lookup(hostname: String): List<InetAddress> { |
| 79 | val list = ArrayList<InetAddress>() |
| 80 | val ip = NekomuraConfig.customPublicProxyIP.String() |
| 81 | if (StrUtil.isBlank(ip)) { |
| 82 | return Dns.SYSTEM.lookup(hostname) |
| 83 | } |
| 84 | return try { |
| 85 | list.add(InetAddress.getByName(ip)) |
| 86 | list |
| 87 | } catch (e: Exception) { |
| 88 | Dns.SYSTEM.lookup(hostname) |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | } |