From 872f9ce199ebe6eba469b79617113e0ca7099b73 Mon Sep 17 00:00:00 2001 From: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Date: Sat, 6 Feb 2021 22:15:16 -0500 Subject: [PATCH 1/6] Add MMKV and data class - Move ServerActivity to MMKV - Move ServerCustomConfigActivity to MMKV - Cleanup ServerActivities - Cleanup V2rayConfigUtil - Change data reads in RecyclerAdapter and ConfigManager - Cleanup some constants --- V2rayNG/app/build.gradle | 1 + V2rayNG/app/src/main/AndroidManifest.xml | 8 +- .../kotlin/com/v2ray/ang/AngApplication.kt | 2 + .../main/kotlin/com/v2ray/ang/AppConfig.kt | 30 +- .../kotlin/com/v2ray/ang/dto/EConfigType.kt | 14 +- .../v2ray/ang/dto/ServerAffiliationInfo.kt | 10 + .../kotlin/com/v2ray/ang/dto/ServerConfig.kt | 51 ++ .../kotlin/com/v2ray/ang/dto/V2rayConfig.kt | 210 +++++-- .../v2ray/ang/service/V2RayServiceManager.kt | 9 +- .../com/v2ray/ang/service/V2RayVpnService.kt | 8 +- .../kotlin/com/v2ray/ang/ui/MainActivity.kt | 39 +- .../com/v2ray/ang/ui/MainRecyclerAdapter.kt | 124 ++-- .../com/v2ray/ang/ui/PerAppProxyActivity.kt | 4 +- .../com/v2ray/ang/ui/Server2Activity.kt | 152 ----- .../com/v2ray/ang/ui/Server3Activity.kt | 175 ------ .../com/v2ray/ang/ui/Server4Activity.kt | 159 ----- .../kotlin/com/v2ray/ang/ui/ServerActivity.kt | 350 +++++++---- .../ang/ui/ServerCustomConfigActivity.kt | 127 ++++ .../com/v2ray/ang/ui/SettingsActivity.kt | 53 +- .../com/v2ray/ang/util/AngConfigManager.kt | 514 ++++++++++------ .../kotlin/com/v2ray/ang/util/MmkvManager.kt | 64 ++ .../main/kotlin/com/v2ray/ang/util/Utils.kt | 14 +- .../com/v2ray/ang/util/V2rayConfigUtil.kt | 567 ++++-------------- .../com/v2ray/ang/viewmodel/MainViewModel.kt | 55 +- .../v2ray/ang/viewmodel/SettingsViewModel.kt | 19 +- ....xml => activity_server_custom_config.xml} | 0 ...r3.xml => activity_server_shadowsocks.xml} | 0 ..._server4.xml => activity_server_socks.xml} | 52 +- ...y_server.xml => activity_server_vmess.xml} | 50 +- V2rayNG/app/src/main/res/values/arrays.xml | 29 + 30 files changed, 1371 insertions(+), 1519 deletions(-) create mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt create mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt delete mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server2Activity.kt delete mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server3Activity.kt delete mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server4Activity.kt create mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt create mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt rename V2rayNG/app/src/main/res/layout/{activity_server2.xml => activity_server_custom_config.xml} (100%) rename V2rayNG/app/src/main/res/layout/{activity_server3.xml => activity_server_shadowsocks.xml} (100%) rename V2rayNG/app/src/main/res/layout/{activity_server4.xml => activity_server_socks.xml} (63%) rename V2rayNG/app/src/main/res/layout/{activity_server.xml => activity_server_vmess.xml} (86%) diff --git a/V2rayNG/app/build.gradle b/V2rayNG/app/build.gradle index 2a4086bb..3288a1d3 100644 --- a/V2rayNG/app/build.gradle +++ b/V2rayNG/app/build.gradle @@ -89,6 +89,7 @@ dependencies { implementation 'com.android.support.constraint:constraint-layout:2.0.1' // DSL + implementation 'com.tencent:mmkv-static:1.0.19' implementation 'com.google.code.gson:gson:2.8.6' implementation 'io.reactivex:rxjava:1.3.4' implementation 'io.reactivex:rxandroid:1.2.1' diff --git a/V2rayNG/app/src/main/AndroidManifest.xml b/V2rayNG/app/src/main/AndroidManifest.xml index bc377599..543343ae 100644 --- a/V2rayNG/app/src/main/AndroidManifest.xml +++ b/V2rayNG/app/src/main/AndroidManifest.xml @@ -60,13 +60,7 @@ android:name=".ui.ServerActivity" android:windowSoftInputMode="stateUnchanged" /> - - diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt index 649e0594..320c98b8 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt @@ -2,6 +2,7 @@ package com.v2ray.ang import android.support.multidex.MultiDexApplication import android.support.v7.preference.PreferenceManager +import com.tencent.mmkv.MMKV import com.v2ray.ang.util.AngConfigManager import me.dozen.dpreference.DPreference @@ -28,5 +29,6 @@ class AngApplication : MultiDexApplication() { //Logger.init().logLevel(if (BuildConfig.DEBUG) LogLevel.FULL else LogLevel.NONE) AngConfigManager.inject(this) + MMKV.initialize(this) } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt index fd4af4b4..4eee79da 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt @@ -13,11 +13,33 @@ object AppConfig { const val PREF_CURR_CONFIG_DOMAIN = "pref_v2ray_config_domain" const val PREF_CURR_CONFIG_OUTBOUND_TAGS = "pref_v2ray_config_outbound_tags" const val PREF_INAPP_BUY_IS_PREMIUM = "pref_inapp_buy_is_premium" - const val PREF_MODE = "pref_mode" - const val VMESS_PROTOCOL: String = "vmess://" - const val SS_PROTOCOL: String = "ss://" - const val SOCKS_PROTOCOL: String = "socks://" + const val PREF_MODE = "pref_mode" + // const val PREF_BYPASS_MAINLAND = "pref_bypass_mainland" + // const val PREF_START_ON_BOOT = "pref_start_on_boot" + const val PREF_PER_APP_PROXY = "pref_per_app_proxy" + // const val PREF_MUX_ENAimport libv2ray.Libv2rayBLED = "pref_mux_enabled" + const val PREF_SPEED_ENABLED = "pref_speed_enabled" + const val PREF_SNIFFING_ENABLED = "pref_sniffing_enabled" + const val PREF_PROXY_SHARING = "pref_proxy_sharing_enabled" + const val PREF_LOCAL_DNS_ENABLED = "pref_local_dns_enabled" + const val PREF_REMOTE_DNS = "pref_remote_dns" + const val PREF_DOMESTIC_DNS = "pref_domestic_dns" + // const val PREF_SOCKS_PORT = "pref_socks_port" +// const val PREF_HTTP_PORT = "pref_http_port" + const val PREF_ROUTING_DOMAIN_STRATEGY = "pref_routing_domain_strategy" + const val PREF_ROUTING_MODE = "pref_routing_mode" + const val PREF_ROUTING_CUSTOM = "pref_routing_custom" + // const val PREF_DONATE = "pref_donate" + // const val PREF_LICENSES = "pref_licenses" +// const val PREF_FEEDBACK = "pref_feedback" +// const val PREF_TG_GROUP = "pref_tg_group" + // const val PREF_AUTO_RESTART = "pref_auto_restart" + const val PREF_FORWARD_IPV6 = "pref_forward_ipv6" + + const val HTTP_PROTOCOL: String = "http://" + const val HTTPS_PROTOCOL: String = "https://" + const val BROADCAST_ACTION_SERVICE = "com.v2ray.ang.action.service" const val BROADCAST_ACTION_ACTIVITY = "com.v2ray.ang.action.activity" const val BROADCAST_ACTION_WIDGET_CLICK = "com.v2ray.ang.action.widget.click" diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/EConfigType.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/EConfigType.kt index 0f98ff7b..3f12160f 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/EConfigType.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/EConfigType.kt @@ -1,12 +1,14 @@ package com.v2ray.ang.dto -enum class EConfigType(val value: Int) { - VMESS(1), - CUSTOM(2), - SHADOWSOCKS(3), - SOCKS(4); +enum class EConfigType(val value: Int, val protocolScheme: String) { + VMESS(1, "vmess://"), + CUSTOM(2, ""), + SHADOWSOCKS(3, "ss://"), + SOCKS(4, "socks://"), + VLESS(5, "vless://"), + TROJAN(6, "trojan://"); companion object { fun fromInt(value: Int) = values().firstOrNull { it.value == value } } -} \ No newline at end of file +} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt new file mode 100644 index 00000000..100044d2 --- /dev/null +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt @@ -0,0 +1,10 @@ +package com.v2ray.ang.dto + +data class ServerAffiliationInfo(var testDelayMillis: Long) { + fun getTestDelayString(): String { + if (testDelayMillis == 0L) { + return "" + } + return testDelayMillis.toString() + "ms" + } +} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt new file mode 100644 index 00000000..eff2f0f8 --- /dev/null +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt @@ -0,0 +1,51 @@ +package com.v2ray.ang.dto + +data class ServerConfig( + val configVersion: Int = 3, + val configType: EConfigType, + val subscriptionId: String = "", + val addedTime: Long = System.currentTimeMillis(), + var remarks: String = "", + val outboundBean: V2rayConfig.OutboundBean? = null, + var fullConfig: V2rayConfig? = null +) { + companion object { + fun create(configType: EConfigType): ServerConfig { + when(configType) { + EConfigType.VMESS, EConfigType.VLESS -> + return ServerConfig( + configType = configType, + outboundBean = V2rayConfig.OutboundBean( + protocol = configType.name.toLowerCase(), + settings = V2rayConfig.OutboundBean.OutSettingsBean( + vnext = listOf(V2rayConfig.OutboundBean.OutSettingsBean.VnextBean( + users = listOf(V2rayConfig.OutboundBean.OutSettingsBean.VnextBean.UsersBean())))), + streamSettings = V2rayConfig.OutboundBean.StreamSettingsBean())) + EConfigType.CUSTOM -> + return ServerConfig(configType = configType) + EConfigType.SHADOWSOCKS, EConfigType.SOCKS -> + return ServerConfig( + configType = configType, + outboundBean = V2rayConfig.OutboundBean( + protocol = configType.name.toLowerCase(), + settings = V2rayConfig.OutboundBean.OutSettingsBean( + servers = listOf(V2rayConfig.OutboundBean.OutSettingsBean.ServersBean())))) + EConfigType.TROJAN -> + return ServerConfig( + configType = configType, + outboundBean = V2rayConfig.OutboundBean( + protocol = configType.name.toLowerCase(), + settings = V2rayConfig.OutboundBean.OutSettingsBean( + servers = listOf(V2rayConfig.OutboundBean.OutSettingsBean.ServersBean())), + streamSettings = V2rayConfig.OutboundBean.StreamSettingsBean())) + } + } + } + + fun getProxyOutbound(): V2rayConfig.OutboundBean? { + if (configType != EConfigType.CUSTOM) { + return outboundBean + } + return fullConfig?.getProxyOutbound() + } +} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt index 57fd191f..bd37b416 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt @@ -1,29 +1,40 @@ package com.v2ray.ang.dto data class V2rayConfig( - val stats: Any?=null, + val stats: Any? = null, val log: LogBean, val policy: PolicyBean, val inbounds: ArrayList, var outbounds: ArrayList, var dns: DnsBean, val routing: RoutingBean) { + companion object { + const val DEFAULT_PORT = 443 + const val DEFAULT_SECURITY = "auto" + const val DEFAULT_LEVEL = 8 + const val DEFAULT_NETWORK = "tcp" + const val DEFAULT_FLOW = "xtls-rprx-splice" + + const val TLS = "tls" + const val XTLS = "xtls" + const val HTTP = "http" + } data class LogBean(val access: String, val error: String, - val loglevel: String) + var loglevel: String?) data class InboundBean( var tag: String, var port: Int, var protocol: String, - var listen: String?=null, + var listen: String? = null, val settings: InSettingsBean, val sniffing: SniffingBean?) { data class InSettingsBean(val auth: String? = null, val udp: Boolean? = null, - val userLevel: Int? =null, + val userLevel: Int? = null, val address: String? = null, val port: Int? = null, val network: String? = null) @@ -32,60 +43,76 @@ data class V2rayConfig( val destOverride: List) } - data class OutboundBean(val tag: String, + data class OutboundBean(val tag: String = "proxy", var protocol: String, var settings: OutSettingsBean?, - var streamSettings: StreamSettingsBean?, - var mux: MuxBean?) { + var streamSettings: StreamSettingsBean? = null, + val mux: MuxBean? = MuxBean(false)) { - data class OutSettingsBean(var vnext: List?, - var servers: List?, - var response: Response) { + data class OutSettingsBean(var vnext: List? = null, + var servers: List? = null, + var response: Response? = null) { - data class VnextBean(var address: String, - var port: Int, + data class VnextBean(var address: String = "", + var port: Int = DEFAULT_PORT, var users: List) { - data class UsersBean(var id: String, - var alterId: Int, - var security: String, - var level: Int) + data class UsersBean(var id: String = "", + var alterId: Int? = null, + var security: String = DEFAULT_SECURITY, + var level: Int = DEFAULT_LEVEL, + var encryption: String = "", + var flow: String = "") } - data class ServersBean(var address: String, - var method: String, - var ota: Boolean, - var password: String, - var port: Int, - var level: Int) + data class ServersBean(var address: String = "", + var method: String = "chacha20-poly1305", + var ota: Boolean = false, + var password: String = "", + var port: Int = DEFAULT_PORT, + var level: Int = DEFAULT_LEVEL, + var users: List? = null) { + + + data class SocksUsersBean(var user: String = "", + var pass: String = "", + var level: Int = DEFAULT_LEVEL) + } data class Response(var type: String) } - data class StreamSettingsBean(var network: String, - var security: String, - var tcpSettings: TcpSettingsBean?, - var kcpSettings: KcpSettingsBean?, - var wsSettings: WsSettingsBean?, - var httpSettings: HttpSettingsBean?, - var tlsSettings: TlsSettingsBean?, - var quicSettings: QuicSettingBean? + data class StreamSettingsBean(var network: String = DEFAULT_NETWORK, + var security: String = "", + var tcpSettings: TcpSettingsBean? = null, + var kcpSettings: KcpSettingsBean? = null, + var wsSettings: WsSettingsBean? = null, + var httpSettings: HttpSettingsBean? = null, + var tlsSettings: TlsSettingsBean? = null, + var quicSettings: QuicSettingBean? = null, + var xtlsSettings: TlsSettingsBean? = null ) { data class TcpSettingsBean(var header: HeaderBean = HeaderBean()) { data class HeaderBean(var type: String = "none", - var request: Any? = null, - var response: Any? = null) + var request: RequestBean? = null, + var response: Any? = null) { + data class RequestBean(var path: List = ArrayList(), + var headers: HeadersBean = HeadersBean()) { + data class HeadersBean(var Host: List = ArrayList()) + } + } } data class KcpSettingsBean(var mtu: Int = 1350, - var tti: Int = 20, + var tti: Int = 50, var uplinkCapacity: Int = 12, var downlinkCapacity: Int = 100, var congestion: Boolean = false, var readBufferSize: Int = 1, var writeBufferSize: Int = 1, - var header: HeaderBean = HeaderBean()) { + var header: HeaderBean = HeaderBean(), + var seed: String? = "") { data class HeaderBean(var type: String = "none") } @@ -97,7 +124,7 @@ data class V2rayConfig( data class HttpSettingsBean(var host: List = ArrayList(), var path: String = "") - data class TlsSettingsBean(var allowInsecure: Boolean = true, + data class TlsSettingsBean(var allowInsecure: Boolean = false, var serverName: String = "") data class QuicSettingBean(var security: String = "none", @@ -107,34 +134,106 @@ data class V2rayConfig( } } - data class MuxBean(var enabled: Boolean) + data class MuxBean(var enabled: Boolean, var concurrency: Int = 8) fun getServerAddress(): String? { - if (protocol.equals(EConfigType.VMESS.name.toLowerCase())) { + if (protocol.equals(EConfigType.VMESS.name, true) + || protocol.equals(EConfigType.VLESS.name, true)) { return settings?.vnext?.get(0)?.address - } else if (protocol.equals(EConfigType.SHADOWSOCKS.name.toLowerCase()) || protocol.equals(EConfigType.SOCKS.name.toLowerCase())) { + } else if (protocol.equals(EConfigType.SHADOWSOCKS.name, true) + || protocol.equals(EConfigType.SOCKS.name, true) + || protocol.equals(EConfigType.TROJAN.name, true)) { return settings?.servers?.get(0)?.address } return null } fun getServerPort(): Int? { - if (protocol.equals(EConfigType.VMESS.name.toLowerCase())) { + if (protocol.equals(EConfigType.VMESS.name, true) + || protocol.equals(EConfigType.VLESS.name, true)) { return settings?.vnext?.get(0)?.port - } else if (protocol.equals(EConfigType.SHADOWSOCKS.name.toLowerCase()) || protocol.equals(EConfigType.SOCKS.name.toLowerCase())) { + } else if (protocol.equals(EConfigType.SHADOWSOCKS.name, true) + || protocol.equals(EConfigType.SOCKS.name, true) + || protocol.equals(EConfigType.TROJAN.name, true)) { return settings?.servers?.get(0)?.port } return null } + + fun getPassword(): String? { + if (protocol.equals(EConfigType.VMESS.name, true) + || protocol.equals(EConfigType.VLESS.name, true)) { + return settings?.vnext?.get(0)?.users?.get(0)?.id + } else if (protocol.equals(EConfigType.SHADOWSOCKS.name, true) + || protocol.equals(EConfigType.TROJAN.name, true)) { + return settings?.servers?.get(0)?.password + } else if (protocol.equals(EConfigType.SOCKS.name, true)) { + return settings?.servers?.get(0)?.users?.get(0)?.pass + } + return null + } + + fun getSecurityEncryption(): String? { + if (protocol.equals(EConfigType.VMESS.name, true)) { + return settings?.vnext?.get(0)?.users?.get(0)?.security + } else if (protocol.equals(EConfigType.VLESS.name, true)) { + return settings?.vnext?.get(0)?.users?.get(0)?.encryption + } else if (protocol.equals(EConfigType.SHADOWSOCKS.name, true)) { + return settings?.servers?.get(0)?.method + } + return null + } + + fun getTransportSettingDetails(): List? { + if (protocol.equals(EConfigType.VMESS.name, true) + || protocol.equals(EConfigType.VLESS.name, true)) { + val transport = streamSettings?.network ?: return null + return when(transport) { + "tcp" -> { + val tcpSetting = streamSettings?.tcpSettings ?: return null + listOf(tcpSetting.header.type, + tcpSetting.header.request?.headers?.Host?.joinToString().orEmpty(), + tcpSetting.header.request?.path?.joinToString().orEmpty()) + } + "kcp" -> { + val kcpSetting = streamSettings?.kcpSettings ?: return null + listOf(kcpSetting.header.type, + "", + kcpSetting.seed.orEmpty()) + } + "ws" -> { + val wsSetting = streamSettings?.wsSettings ?: return null + listOf("", + wsSetting.headers.Host, + wsSetting.path) + } + "h2" -> { + val h2Setting = streamSettings?.httpSettings ?: return null + listOf("", + h2Setting.host.joinToString(), + h2Setting.path) + } + "quic" -> { + val quicSetting = streamSettings?.quicSettings ?: return null + listOf(quicSetting.header.type, + quicSetting.key, + quicSetting.key) + } + else -> null + } + } + return null + } } //data class DnsBean(var servers: List) - data class DnsBean(var servers: List?=null, - var hosts: Map?=null + data class DnsBean(var servers: List? = null, + var hosts: Map? = null ) { data class ServersBean(var address: String = "", var port: Int = 0, - var domains: List?) + var domains: List?, + var expectIPs: List?) } data class RoutingBean(var domainStrategy: String, @@ -149,11 +248,24 @@ data class V2rayConfig( } data class PolicyBean(var levels: Map, - var system: Any?=null) { + var system: Any? = null) { data class LevelBean( - var handshake: Int? = null, - var connIdle: Int? = null, - var uplinkOnly: Int? = null, - var downlinkOnly: Int? = null) + var handshake: Int? = null, + var connIdle: Int? = null, + var uplinkOnly: Int? = null, + var downlinkOnly: Int? = null) } -} \ No newline at end of file + + fun getProxyOutbound(): OutboundBean? { + outbounds.forEach { outbound -> + if (outbound.protocol.equals(EConfigType.VMESS.name, true) || + outbound.protocol.equals(EConfigType.VLESS.name, true) || + outbound.protocol.equals(EConfigType.SHADOWSOCKS.name, true) || + outbound.protocol.equals(EConfigType.SOCKS.name, true) || + outbound.protocol.equals(EConfigType.TROJAN.name, true)) { + return outbound + } + } + return null + } +} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt index 86e8ff05..0f8b05fb 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt @@ -21,7 +21,6 @@ import com.v2ray.ang.extension.toSpeedString import com.v2ray.ang.extension.toast import com.v2ray.ang.extension.v2RayApplication import com.v2ray.ang.ui.MainActivity -import com.v2ray.ang.ui.SettingsActivity import com.v2ray.ang.util.MessageUtil import com.v2ray.ang.util.Utils import go.Seq @@ -60,7 +59,7 @@ object V2RayServiceManager { private var mNotificationManager: NotificationManager? = null fun startV2Ray(context: Context) { - if (context.v2RayApplication.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_PROXY_SHARING, false)) { + if (context.v2RayApplication.defaultDPreference.getPrefBoolean(AppConfig.PREF_PROXY_SHARING, false)) { context.toast(R.string.toast_warning_pref_proxysharing_short) }else{ context.toast(R.string.toast_services_start) @@ -136,8 +135,8 @@ object V2RayServiceManager { } v2rayPoint.configureFileContent = service.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG, "") - v2rayPoint.enableLocalDNS = service.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_LOCAL_DNS_ENABLED, false) - v2rayPoint.forwardIpv6 = service.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_FORWARD_IPV6, false) + v2rayPoint.enableLocalDNS = service.defaultDPreference.getPrefBoolean(AppConfig.PREF_LOCAL_DNS_ENABLED, false) + v2rayPoint.forwardIpv6 = service.defaultDPreference.getPrefBoolean(AppConfig.PREF_FORWARD_IPV6, false) v2rayPoint.domainName = service.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG_DOMAIN, "") v2rayPoint.proxyOnly = service.defaultDPreference.getPrefString(AppConfig.PREF_MODE, "VPN") != "VPN" currentConfigName = service.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG_NAME, "NG") @@ -308,7 +307,7 @@ object V2RayServiceManager { val service = serviceControl?.get()?.getService() ?: return if (mSubscription == null && v2rayPoint.isRunning && - service.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_SPEED_ENABLED, false)) { + service.defaultDPreference.getPrefBoolean(AppConfig.PREF_SPEED_ENABLED, false)) { var lastZeroSpeed = false val outboundTags = service.defaultDPreference.getPrefStringOrderedSet(AppConfig.PREF_CURR_CONFIG_OUTBOUND_TAGS, LinkedHashSet()) outboundTags.remove(TAG_DIRECT) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt index 7339f9fe..181b6c43 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt @@ -10,10 +10,10 @@ import android.os.ParcelFileDescriptor import android.os.StrictMode import android.support.annotation.RequiresApi import android.util.Log +import com.v2ray.ang.AppConfig import com.v2ray.ang.R import com.v2ray.ang.extension.defaultDPreference import com.v2ray.ang.ui.PerAppProxyActivity -import com.v2ray.ang.ui.SettingsActivity import com.v2ray.ang.util.Utils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope @@ -91,8 +91,8 @@ class V2RayVpnService : VpnService(), ServiceControl { // If the old interface has exactly the same parameters, use it! // Configure a builder while parsing the parameters. val builder = Builder() - val enableLocalDns = defaultDPreference.getPrefBoolean(SettingsActivity.PREF_LOCAL_DNS_ENABLED, false) - val routingMode = defaultDPreference.getPrefString(SettingsActivity.PREF_ROUTING_MODE, "0") + val enableLocalDns = defaultDPreference.getPrefBoolean(AppConfig.PREF_LOCAL_DNS_ENABLED, false) + val routingMode = defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") parameters.split(" ") .map { it.split(",") } @@ -129,7 +129,7 @@ class V2RayVpnService : VpnService(), ServiceControl { builder.setSession(V2RayServiceManager.currentConfigName) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && - defaultDPreference.getPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, false)) { + defaultDPreference.getPrefBoolean(AppConfig.PREF_PER_APP_PROXY, false)) { val apps = defaultDPreference.getPrefStringSet(PerAppProxyActivity.PREF_PER_APP_PROXY_SET, null) val bypassApps = defaultDPreference.getPrefBoolean(PerAppProxyActivity.PREF_BYPASS_APPS, false) apps?.forEach { diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt index 23358065..db93eae4 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt @@ -20,6 +20,7 @@ import com.tbruyelle.rxpermissions.RxPermissions import com.v2ray.ang.AppConfig import com.v2ray.ang.BuildConfig import com.v2ray.ang.R +import com.v2ray.ang.dto.EConfigType import com.v2ray.ang.extension.defaultDPreference import com.v2ray.ang.extension.toast import com.v2ray.ang.helper.SimpleItemTouchHelperCallback @@ -47,7 +48,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList private val adapter by lazy { MainRecyclerAdapter(this) } private var mItemTouchHelper: ItemTouchHelper? = null - private val mainViewModel: MainViewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) } + val mainViewModel: MainViewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -101,9 +102,9 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList mainViewModel.updateListAction.observe(this, { val index = it ?: return@observe if (index >= 0) { - adapter.updateSelectedItem(index) + adapter.notifyItemChanged(index) } else { - adapter.updateConfigList() + adapter.notifyDataSetChanged() } }) mainViewModel.updateTestResultAction.observe(this, { tv_test_state.text = it }) @@ -113,9 +114,11 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList if (isRunning) { fab.setImageResource(R.drawable.ic_v) tv_test_state.text = getString(R.string.connection_connected) + layout_test.isFocusable = true } else { fab.setImageResource(R.drawable.ic_v_idle) tv_test_state.text = getString(R.string.connection_not_connected) + layout_test.isFocusable = false } hideCircle() }) @@ -135,7 +138,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList public override fun onResume() { super.onResume() - adapter.updateConfigList() + adapter.notifyDataSetChanged() } public override fun onPause() { @@ -171,9 +174,6 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList return true } - private fun getOptionIntent() = Intent().putExtra("position", -1) - .putExtra("isRunning", mainViewModel.isRunning.value == true) - override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.import_qrcode -> { importQRcode(REQUEST_SCAN) @@ -184,18 +184,18 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList true } R.id.import_manually_vmess -> { - startActivity(getOptionIntent().setClass(this, ServerActivity::class.java)) - adapter.updateConfigList() + startActivity(Intent().putExtra("createConfigType", EConfigType.VMESS.value). + setClass(this, ServerActivity::class.java)) true } R.id.import_manually_ss -> { - startActivity(getOptionIntent().setClass(this, Server3Activity::class.java)) - adapter.updateConfigList() + startActivity(Intent().putExtra("createConfigType", EConfigType.SHADOWSOCKS.value). + setClass(this, ServerActivity::class.java)) true } R.id.import_manually_socks -> { - startActivity(getOptionIntent().setClass(this, Server4Activity::class.java)) - adapter.updateConfigList() + startActivity(Intent().putExtra("createConfigType", EConfigType.SOCKS.value). + setClass(this, ServerActivity::class.java)) true } R.id.import_config_custom_clipboard -> { @@ -226,8 +226,8 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList } R.id.export_all -> { - if (AngConfigManager.shareAll2Clipboard() == 0) { - //remove toast, otherwise it will block previous warning message + if (AngConfigManager.shareNonCustomConfigsToClipboard(mainViewModel.serverList) == 0) { + toast(R.string.toast_success) } else { toast(R.string.toast_failure) } @@ -288,10 +288,13 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList } fun importBatchConfig(server: String?, subid: String = "") { - val count = AngConfigManager.importBatchConfig(server, subid) + var count = AngConfigManager.importBatchConfig(server, subid) + if (count <= 0) { + count = AngConfigManager.importBatchConfig(Utils.decode(server!!), subid) + } if (count > 0) { toast(R.string.toast_success) - adapter.updateConfigList() + adapter.notifyDataSetChanged() } else { toast(R.string.toast_failure) } @@ -462,7 +465,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList toast(resId) } else { toast(R.string.toast_success) - adapter.updateConfigList() + adapter.notifyDataSetChanged() } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt index ebd40b0d..55f3cb3a 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt @@ -2,22 +2,22 @@ package com.v2ray.ang.ui import android.content.Intent import android.graphics.Color +import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.support.v7.widget.RecyclerView -import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import com.tencent.mmkv.MMKV import com.v2ray.ang.AppConfig import com.v2ray.ang.R -import com.v2ray.ang.dto.AngConfig import com.v2ray.ang.dto.EConfigType import com.v2ray.ang.extension.toast import com.v2ray.ang.helper.ItemTouchHelperAdapter import com.v2ray.ang.helper.ItemTouchHelperViewHolder import com.v2ray.ang.util.AngConfigManager +import com.v2ray.ang.util.MmkvManager import com.v2ray.ang.util.Utils -import com.v2ray.ang.util.V2rayConfigUtil import kotlinx.android.synthetic.main.item_qrcode.view.* import kotlinx.android.synthetic.main.item_recycler_main.view.* import rx.Observable @@ -32,7 +32,7 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter by lazy { mActivity.resources.getStringArray(R.array.share_method) } @@ -45,64 +45,53 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter try { when (i) { 0 -> { - if (configType == EConfigType.CUSTOM) { + if (config.configType == EConfigType.CUSTOM) { shareFullContent(position) } else { - val iv = mActivity.layoutInflater.inflate(R.layout.item_qrcode, null) - iv.iv_qcode.setImageBitmap(AngConfigManager.share2QRCode(position)) + val iv = LayoutInflater.from(mActivity).inflate(R.layout.item_qrcode, null) + iv.iv_qcode.setImageBitmap(AngConfigManager.share2QRCode(guid)) AlertDialog.Builder(mActivity).setView(iv).show() } } 1 -> { - if (AngConfigManager.share2Clipboard(position) == 0) { + if (AngConfigManager.share2Clipboard(guid) == 0) { mActivity.toast(R.string.toast_success) } else { mActivity.toast(R.string.toast_failure) @@ -118,24 +107,17 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter - return MainViewHolder(LayoutInflater.from(parent.context) + MainViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.item_recycler_main, parent, false)) else -> - return FooterViewHolder(LayoutInflater.from(parent.context) + FooterViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.item_recycler_footer, parent, false)) } } - fun updateConfigList() { - configs = AngConfigManager.configs - notifyDataSetChanged() - } - -// fun updateSelectedItem() { -// updateSelectedItem(configs.index) -// } - - fun updateSelectedItem(pos: Int) { - //notifyItemChanged(pos) - notifyItemRangeChanged(pos, itemCount - pos) - } - override fun getItemViewType(position: Int): Int { - if (position == configs.vmess.count()) { - return VIEW_TYPE_FOOTER + return if (position == mActivity.mainViewModel.serverList.size) { + VIEW_TYPE_FOOTER } else { - return VIEW_TYPE_ITEM + VIEW_TYPE_ITEM } } open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) class MainViewHolder(itemView: View) : BaseViewHolder(itemView), ItemTouchHelperViewHolder { - val subscription = itemView.tv_subscription + val subscription = itemView.tv_subscription!! val radio = itemView.btn_radio!! val name = itemView.tv_name!! val test_result = itemView.tv_test_result!! @@ -246,7 +214,7 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter - defaultDPreference.setPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, isChecked) + defaultDPreference.setPrefBoolean(AppConfig.PREF_PER_APP_PROXY, isChecked) } - switch_per_app_proxy.isChecked = defaultDPreference.getPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, false) + switch_per_app_proxy.isChecked = defaultDPreference.getPrefBoolean(AppConfig.PREF_PER_APP_PROXY, false) switch_bypass_apps.setOnCheckedChangeListener { buttonView, isChecked -> defaultDPreference.setPrefBoolean(PREF_BYPASS_APPS, isChecked) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server2Activity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server2Activity.kt deleted file mode 100644 index 23d995a1..00000000 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server2Activity.kt +++ /dev/null @@ -1,152 +0,0 @@ -package com.v2ray.ang.ui - -import android.os.Bundle -import android.support.v7.app.AlertDialog -import android.text.Editable -import android.text.TextUtils -import android.view.Menu -import android.view.MenuItem -import com.google.gson.Gson -import com.v2ray.ang.AppConfig -import com.v2ray.ang.R -import com.v2ray.ang.extension.defaultDPreference -import com.v2ray.ang.dto.AngConfig -import com.v2ray.ang.extension.toast -import com.v2ray.ang.util.AngConfigManager -import com.v2ray.ang.util.Utils -import kotlinx.android.synthetic.main.activity_server2.* -import java.lang.Exception - -class Server2Activity : BaseActivity() { - companion object { - private const val REQUEST_SCAN = 1 - } - - var del_config: MenuItem? = null - var save_config: MenuItem? = null - - private lateinit var configs: AngConfig - private var edit_index: Int = -1 //当前编辑的服务器 - private var edit_guid: String = "" - private var isRunning: Boolean = false - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_server2) - - configs = AngConfigManager.configs - edit_index = intent.getIntExtra("position", -1) - isRunning = intent.getBooleanExtra("isRunning", false) - title = getString(R.string.title_server) - - if (edit_index >= 0) { - edit_guid = configs.vmess[edit_index].guid - bindingServer(configs.vmess[edit_index]) - } else { - clearServer() - } - supportActionBar?.setDisplayHomeAsUpEnabled(true) - } - - /** - * bingding seleced server config - */ - fun bindingServer(vmess: AngConfig.VmessBean): Boolean { - et_remarks.text = Utils.getEditable(vmess.remarks) - tv_content.text = Editable.Factory.getInstance().newEditable(defaultDPreference.getPrefString(AppConfig.ANG_CONFIG + edit_guid, "")) - return true - } - - /** - * clear or init server config - */ - fun clearServer(): Boolean { - et_remarks.text = null - return true - } - - /** - * save server config - */ - fun saveServer(): Boolean { - val vmess = configs.vmess[edit_index] - - vmess.remarks = et_remarks.text.toString() - - if (TextUtils.isEmpty(vmess.remarks)) { - toast(R.string.server_lab_remarks) - return false - } - - try { - Gson().fromJson(tv_content.text.toString(), Object::class.java) - } catch (e: Exception) { - e.printStackTrace() - toast(R.string.toast_malformed_josn) - return false - } - - if (AngConfigManager.addCustomServer(vmess, edit_index) == 0) { - //update config - defaultDPreference.setPrefString(AppConfig.ANG_CONFIG + edit_guid, tv_content.text.toString()) - AngConfigManager.genStoreV2rayConfigIfActive(edit_index) - toast(R.string.toast_success) - finish() - return true - } else { - toast(R.string.toast_failure) - return false - } - } - - /** - * save server config - */ - fun deleteServer(): Boolean { - if (edit_index >= 0) { - AlertDialog.Builder(this).setMessage(R.string.del_config_comfirm) - .setPositiveButton(android.R.string.ok) { _, _ -> - if (AngConfigManager.removeServer(edit_index) == 0) { - toast(R.string.toast_success) - finish() - } else { - toast(R.string.toast_failure) - } - } - .show() - } else { - } - return true - } - - override fun onCreateOptionsMenu(menu: Menu?): Boolean { - menuInflater.inflate(R.menu.action_server, menu) - del_config = menu?.findItem(R.id.del_config) - save_config = menu?.findItem(R.id.save_config) - - if (edit_index >= 0) { - if (isRunning) { - if (edit_index == configs.index) { - del_config?.isVisible = false - save_config?.isVisible = false - } - } - } else { - del_config?.isVisible = false - } - - return super.onCreateOptionsMenu(menu) - } - - override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { - R.id.del_config -> { - deleteServer() - true - } - R.id.save_config -> { - saveServer() - true - } - else -> super.onOptionsItemSelected(item) - } -} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server3Activity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server3Activity.kt deleted file mode 100644 index f117b642..00000000 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server3Activity.kt +++ /dev/null @@ -1,175 +0,0 @@ -package com.v2ray.ang.ui - -import android.os.Bundle -import android.support.v7.app.AlertDialog -import android.text.TextUtils -import android.view.Menu -import android.view.MenuItem -import com.v2ray.ang.R -import com.v2ray.ang.dto.AngConfig -import com.v2ray.ang.extension.toast -import com.v2ray.ang.util.AngConfigManager -import com.v2ray.ang.util.Utils -import kotlinx.android.synthetic.main.activity_server3.* - -class Server3Activity : BaseActivity() { - companion object { - private const val REQUEST_SCAN = 1 - } - - var del_config: MenuItem? = null - var save_config: MenuItem? = null - - private lateinit var configs: AngConfig - private var edit_index: Int = -1 //当前编辑的服务器 - private var edit_guid: String = "" - private var isRunning: Boolean = false - private val securitys: Array by lazy { - resources.getStringArray(R.array.ss_securitys) - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_server3) - - configs = AngConfigManager.configs - edit_index = intent.getIntExtra("position", -1) - isRunning = intent.getBooleanExtra("isRunning", false) - title = getString(R.string.title_server) - - if (edit_index >= 0) { - edit_guid = configs.vmess[edit_index].guid - bindingServer(configs.vmess[edit_index]) - } else { - clearServer() - } - supportActionBar?.setDisplayHomeAsUpEnabled(true) - } - - /** - * bingding seleced server config - */ - fun bindingServer(vmess: AngConfig.VmessBean): Boolean { - et_remarks.text = Utils.getEditable(vmess.remarks) - - et_address.text = Utils.getEditable(vmess.address) - et_port.text = Utils.getEditable(vmess.port.toString()) - et_id.text = Utils.getEditable(vmess.id) - val security = Utils.arrayFind(securitys, vmess.security) - if (security >= 0) { - sp_security.setSelection(security) - } - - return true - } - - /** - * clear or init server config - */ - fun clearServer(): Boolean { - et_remarks.text = null - et_address.text = null - et_port.text = Utils.getEditable("10086") - et_id.text = null - sp_security.setSelection(0) - - return true - } - - /** - * save server config - */ - fun saveServer(): Boolean { - val vmess: AngConfig.VmessBean - if (edit_index >= 0) { - vmess = configs.vmess[edit_index] - } else { - vmess = AngConfig.VmessBean() - } - - vmess.guid = edit_guid - vmess.remarks = et_remarks.text.toString() - vmess.address = et_address.text.toString() - vmess.port = Utils.parseInt(et_port.text.toString()) - vmess.id = et_id.text.toString() - vmess.security = securitys[sp_security.selectedItemPosition] - - if (TextUtils.isEmpty(vmess.remarks)) { - toast(R.string.server_lab_remarks) - return false - } - if (TextUtils.isEmpty(vmess.address)) { - toast(R.string.server_lab_address3) - return false - } - if (TextUtils.isEmpty(vmess.port.toString()) || vmess.port <= 0) { - toast(R.string.server_lab_port3) - return false - } - if (TextUtils.isEmpty(vmess.id)) { - toast(R.string.server_lab_id3) - return false - } - - if (AngConfigManager.addShadowsocksServer(vmess, edit_index) == 0) { - AngConfigManager.genStoreV2rayConfigIfActive(edit_index) - toast(R.string.toast_success) - finish() - return true - } else { - toast(R.string.toast_failure) - return false - } - } - - /** - * save server config - */ - fun deleteServer(): Boolean { - if (edit_index >= 0) { - AlertDialog.Builder(this).setMessage(R.string.del_config_comfirm) - .setPositiveButton(android.R.string.ok) { _, _ -> - if (AngConfigManager.removeServer(edit_index) == 0) { - toast(R.string.toast_success) - finish() - } else { - toast(R.string.toast_failure) - } - } - .show() - } else { - } - return true - } - - override fun onCreateOptionsMenu(menu: Menu?): Boolean { - menuInflater.inflate(R.menu.action_server, menu) - del_config = menu?.findItem(R.id.del_config) - save_config = menu?.findItem(R.id.save_config) - - if (edit_index >= 0) { - if (isRunning) { - if (edit_index == configs.index) { - del_config?.isVisible = false - save_config?.isVisible = false - } - } - } else { - del_config?.isVisible = false - } - - return super.onCreateOptionsMenu(menu) - } - - override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { - R.id.del_config -> { - deleteServer() - true - } - R.id.save_config -> { - saveServer() - true - } - else -> super.onOptionsItemSelected(item) - } -} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server4Activity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server4Activity.kt deleted file mode 100644 index d5f88ce7..00000000 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server4Activity.kt +++ /dev/null @@ -1,159 +0,0 @@ -package com.v2ray.ang.ui - -import android.os.Bundle -import android.support.v7.app.AlertDialog -import android.text.TextUtils -import android.view.Menu -import android.view.MenuItem -import com.v2ray.ang.R -import com.v2ray.ang.dto.AngConfig -import com.v2ray.ang.extension.toast -import com.v2ray.ang.util.AngConfigManager -import com.v2ray.ang.util.Utils -import kotlinx.android.synthetic.main.activity_server4.* - -class Server4Activity : BaseActivity() { - companion object { - private const val REQUEST_SCAN = 1 - } - - var del_config: MenuItem? = null - var save_config: MenuItem? = null - - private lateinit var configs: AngConfig - private var edit_index: Int = -1 //当前编辑的服务器 - private var edit_guid: String = "" - private var isRunning: Boolean = false - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContentView(R.layout.activity_server4) - - configs = AngConfigManager.configs - edit_index = intent.getIntExtra("position", -1) - isRunning = intent.getBooleanExtra("isRunning", false) - title = getString(R.string.title_server) - - if (edit_index >= 0) { - edit_guid = configs.vmess[edit_index].guid - bindingServer(configs.vmess[edit_index]) - } else { - clearServer() - } - supportActionBar?.setDisplayHomeAsUpEnabled(true) - } - - /** - * bingding seleced server config - */ - fun bindingServer(vmess: AngConfig.VmessBean): Boolean { - et_remarks.text = Utils.getEditable(vmess.remarks) - - et_address.text = Utils.getEditable(vmess.address) - et_port.text = Utils.getEditable(vmess.port.toString()) - - return true - } - - /** - * clear or init server config - */ - fun clearServer(): Boolean { - et_remarks.text = null - et_address.text = null - et_port.text = Utils.getEditable("10086") - - return true - } - - /** - * save server config - */ - fun saveServer(): Boolean { - val vmess: AngConfig.VmessBean - if (edit_index >= 0) { - vmess = configs.vmess[edit_index] - } else { - vmess = AngConfig.VmessBean() - } - - vmess.guid = edit_guid - vmess.remarks = et_remarks.text.toString() - vmess.address = et_address.text.toString() - vmess.port = Utils.parseInt(et_port.text.toString()) - - if (TextUtils.isEmpty(vmess.remarks)) { - toast(R.string.server_lab_remarks) - return false - } - if (TextUtils.isEmpty(vmess.address)) { - toast(R.string.server_lab_address3) - return false - } - if (TextUtils.isEmpty(vmess.port.toString()) || vmess.port <= 0) { - toast(R.string.server_lab_port3) - return false - } - - if (AngConfigManager.addSocksServer(vmess, edit_index) == 0) { - AngConfigManager.genStoreV2rayConfigIfActive(edit_index) - toast(R.string.toast_success) - finish() - return true - } else { - toast(R.string.toast_failure) - return false - } - } - - /** - * save server config - */ - fun deleteServer(): Boolean { - if (edit_index >= 0) { - AlertDialog.Builder(this).setMessage(R.string.del_config_comfirm) - .setPositiveButton(android.R.string.ok) { _, _ -> - if (AngConfigManager.removeServer(edit_index) == 0) { - toast(R.string.toast_success) - finish() - } else { - toast(R.string.toast_failure) - } - } - .show() - } else { - } - return true - } - - override fun onCreateOptionsMenu(menu: Menu?): Boolean { - menuInflater.inflate(R.menu.action_server, menu) - del_config = menu?.findItem(R.id.del_config) - save_config = menu?.findItem(R.id.save_config) - - if (edit_index >= 0) { - if (isRunning) { - if (edit_index == configs.index) { - del_config?.isVisible = false - save_config?.isVisible = false - } - } - } else { - del_config?.isVisible = false - } - - return super.onCreateOptionsMenu(menu) - } - - override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { - R.id.del_config -> { - deleteServer() - true - } - R.id.save_config -> { - saveServer() - true - } - else -> super.onOptionsItemSelected(item) - } -} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt index b8b7a641..95d95390 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt @@ -5,50 +5,79 @@ import android.support.v7.app.AlertDialog import android.text.TextUtils import android.view.Menu import android.view.MenuItem +import com.tencent.mmkv.MMKV import com.v2ray.ang.R -import com.v2ray.ang.dto.AngConfig +import com.v2ray.ang.dto.EConfigType +import com.v2ray.ang.dto.ServerConfig +import com.v2ray.ang.dto.V2rayConfig +import com.v2ray.ang.dto.V2rayConfig.Companion.DEFAULT_NETWORK +import com.v2ray.ang.dto.V2rayConfig.Companion.DEFAULT_PORT +import com.v2ray.ang.dto.V2rayConfig.Companion.HTTP +import com.v2ray.ang.dto.V2rayConfig.Companion.TLS +import com.v2ray.ang.dto.V2rayConfig.Companion.XTLS import com.v2ray.ang.extension.toast -import com.v2ray.ang.util.AngConfigManager +import com.v2ray.ang.util.MmkvManager +import com.v2ray.ang.util.MmkvManager.ID_MAIN +import com.v2ray.ang.util.MmkvManager.KEY_SELECTED_SERVER import com.v2ray.ang.util.Utils -import kotlinx.android.synthetic.main.activity_server.* +import kotlinx.android.synthetic.main.activity_server_socks.* +import kotlinx.android.synthetic.main.activity_server_vmess.* +import kotlinx.android.synthetic.main.activity_server_vmess.et_address +import kotlinx.android.synthetic.main.activity_server_vmess.et_id +import kotlinx.android.synthetic.main.activity_server_vmess.et_path +import kotlinx.android.synthetic.main.activity_server_vmess.et_port +import kotlinx.android.synthetic.main.activity_server_vmess.et_remarks +import kotlinx.android.synthetic.main.activity_server_vmess.et_request_host +import kotlinx.android.synthetic.main.activity_server_vmess.sp_allow_insecure +import kotlinx.android.synthetic.main.activity_server_vmess.sp_header_type +import kotlinx.android.synthetic.main.activity_server_vmess.sp_network +import kotlinx.android.synthetic.main.activity_server_vmess.sp_stream_security class ServerActivity : BaseActivity() { - companion object { - private const val REQUEST_SCAN = 1 + + private val mainStorage by lazy { MMKV.mmkvWithID(ID_MAIN, MMKV.MULTI_PROCESS_MODE) } + private val editGuid by lazy { intent.getStringExtra("guid").orEmpty() } + private val isRunning by lazy { editGuid.isNotEmpty() && editGuid == mainStorage?.decodeString(KEY_SELECTED_SERVER) } + private val createConfigType by lazy { + EConfigType.fromInt(intent.getIntExtra("createConfigType", EConfigType.VMESS.value)) ?: EConfigType.VMESS } - - var del_config: MenuItem? = null - var save_config: MenuItem? = null - - private lateinit var configs: AngConfig - private var edit_index: Int = -1 //当前编辑的服务器 - private var edit_guid: String = "" - private var isRunning: Boolean = false private val securitys: Array by lazy { resources.getStringArray(R.array.securitys) } + private val shadowsocksSecuritys: Array by lazy { + resources.getStringArray(R.array.ss_securitys) + } + private val flows: Array by lazy { + resources.getStringArray(R.array.flows) + } private val networks: Array by lazy { resources.getStringArray(R.array.networks) } private val headertypes: Array by lazy { resources.getStringArray(R.array.headertypes) } - private val streamsecuritys: Array by lazy { - resources.getStringArray(R.array.streamsecuritys) + private val streamSecuritys: Array by lazy { + resources.getStringArray(R.array.streamsecurityxs) + } + private val allowinsecures: Array by lazy { + resources.getStringArray(R.array.allowinsecures) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - setContentView(R.layout.activity_server) - - configs = AngConfigManager.configs - edit_index = intent.getIntExtra("position", -1) - isRunning = intent.getBooleanExtra("isRunning", false) title = getString(R.string.title_server) - if (edit_index >= 0) { - edit_guid = configs.vmess[edit_index].guid - bindingServer(configs.vmess[edit_index]) + val config = MmkvManager.decodeServerConfig(editGuid) + when(config?.configType ?: createConfigType) { + EConfigType.VMESS -> setContentView(R.layout.activity_server_vmess) + EConfigType.CUSTOM -> return + EConfigType.SHADOWSOCKS -> setContentView(R.layout.activity_server_shadowsocks) + EConfigType.SOCKS -> setContentView(R.layout.activity_server_socks) +// EConfigType.VLESS -> setContentView(R.layout.activity_server_vless) +// EConfigType.TROJAN -> setContentView(R.layout.activity_server_trojan) + } + if (config != null) { + bindingServer(config) } else { clearServer() } @@ -58,33 +87,49 @@ class ServerActivity : BaseActivity() { /** * bingding seleced server config */ - fun bindingServer(vmess: AngConfig.VmessBean): Boolean { - et_remarks.text = Utils.getEditable(vmess.remarks) + private fun bindingServer(config: ServerConfig): Boolean { + val outbound = config.getProxyOutbound() ?: return false + val streamSetting = config.outboundBean?.streamSettings ?: return false - et_address.text = Utils.getEditable(vmess.address) - et_port.text = Utils.getEditable(vmess.port.toString()) - et_id.text = Utils.getEditable(vmess.id) - et_alterId.text = Utils.getEditable(vmess.alterId.toString()) - - val security = Utils.arrayFind(securitys, vmess.security) + et_remarks.text = Utils.getEditable(config.remarks) + et_address.text = Utils.getEditable(outbound.getServerAddress().orEmpty()) + et_port.text = Utils.getEditable(outbound.getServerPort()?.or(DEFAULT_PORT).toString()) + et_id.text = Utils.getEditable(outbound.getPassword().orEmpty()) + et_alterId?.text = Utils.getEditable(outbound.settings?.vnext?.get(0)?.users?.get(0)?.alterId.toString()) + if (config.configType == EConfigType.SOCKS) { + et_security.text = Utils.getEditable(outbound.settings?.servers?.get(0)?.users?.get(0)?.user.orEmpty()) + } else if (config.configType == EConfigType.VLESS) { + et_security.text = Utils.getEditable(outbound.getSecurityEncryption().orEmpty()) + val flow = Utils.arrayFind(flows, outbound.settings?.vnext?.get(0)?.users?.get(0)?.flow.orEmpty()) + if (flow >= 0) { + //sp_flow.setSelection(flow) + } + } + val securityEncryptions = if (config.configType == EConfigType.SHADOWSOCKS) shadowsocksSecuritys else securitys + val security = Utils.arrayFind(securityEncryptions, outbound.getSecurityEncryption().orEmpty()) if (security >= 0) { - sp_security.setSelection(security) - } - val network = Utils.arrayFind(networks, vmess.network) - if (network >= 0) { - sp_network.setSelection(network) + sp_security?.setSelection(security) } - val headerType = Utils.arrayFind(headertypes, vmess.headerType) - if (headerType >= 0) { - sp_header_type.setSelection(headerType) - } - et_request_host.text = Utils.getEditable(vmess.requestHost) - et_path.text = Utils.getEditable(vmess.path) - - val streamSecurity = Utils.arrayFind(streamsecuritys, vmess.streamSecurity) + val streamSecurity = Utils.arrayFind(streamSecuritys, streamSetting.security) if (streamSecurity >= 0) { - sp_stream_security.setSelection(streamSecurity) + sp_stream_security?.setSelection(streamSecurity) + streamSetting.tlsSettings?: streamSetting.xtlsSettings?.let { tlsSetting -> + val allowinsecure = Utils.arrayFind(allowinsecures, tlsSetting.allowInsecure.toString()) + if (allowinsecure >= 0) { + sp_allow_insecure?.setSelection(allowinsecure) + } + et_request_host.text = Utils.getEditable(tlsSetting.serverName) + } + } + val network = Utils.arrayFind(networks, streamSetting.network) + if (network >= 0) { + sp_network?.setSelection(network) + } + outbound.getTransportSettingDetails()?.let { transportDetails -> + sp_header_type.setSelection(Utils.arrayFind(headertypes, transportDetails[0])) + et_request_host.text = Utils.getEditable(transportDetails[1]) + et_path.text = Utils.getEditable(transportDetails[2]) } return true } @@ -92,113 +137,202 @@ class ServerActivity : BaseActivity() { /** * clear or init server config */ - fun clearServer(): Boolean { + private fun clearServer(): Boolean { et_remarks.text = null et_address.text = null - et_port.text = Utils.getEditable("10086") + et_port.text = Utils.getEditable(DEFAULT_PORT.toString()) et_id.text = null - et_alterId.text = Utils.getEditable("64") - sp_security.setSelection(0) - sp_network.setSelection(0) + et_alterId?.text = Utils.getEditable("0") + sp_security?.setSelection(0) + sp_network?.setSelection(0) - sp_header_type.setSelection(0) - et_request_host.text = null - et_path.text = null - sp_stream_security.setSelection(0) + sp_header_type?.setSelection(0) + et_request_host?.text = null + et_path?.text = null + sp_stream_security?.setSelection(0) + sp_allow_insecure?.setSelection(0) + + //et_security.text = null + //sp_flow?.setSelection(0) return true } /** * save server config */ - fun saveServer(): Boolean { - val vmess: AngConfig.VmessBean - if (edit_index >= 0) { - vmess = configs.vmess[edit_index] - } else { - vmess = AngConfig.VmessBean() - } - - vmess.guid = edit_guid - vmess.remarks = et_remarks.text.toString() - vmess.address = et_address.text.toString() - vmess.port = Utils.parseInt(et_port.text.toString()) - vmess.id = et_id.text.toString() - vmess.alterId = Utils.parseInt(et_alterId.text.toString()) - vmess.security = securitys[sp_security.selectedItemPosition] - vmess.network = networks[sp_network.selectedItemPosition] - - vmess.headerType = headertypes[sp_header_type.selectedItemPosition] - vmess.requestHost = et_request_host.text.toString() - vmess.path = et_path.text.toString() - vmess.streamSecurity = streamsecuritys[sp_stream_security.selectedItemPosition] - - if (TextUtils.isEmpty(vmess.remarks)) { + private fun saveServer(): Boolean { + if (TextUtils.isEmpty(et_remarks.text.toString())) { toast(R.string.server_lab_remarks) return false } - if (TextUtils.isEmpty(vmess.address)) { + if (TextUtils.isEmpty(et_address.text.toString())) { toast(R.string.server_lab_address) return false } - if (TextUtils.isEmpty(vmess.port.toString()) || vmess.port <= 0) { + val port = Utils.parseInt(et_port.text.toString()) + if (port <= 0) { toast(R.string.server_lab_port) return false } - if (TextUtils.isEmpty(vmess.id)) { + val config = MmkvManager.decodeServerConfig(editGuid) ?: ServerConfig.create(createConfigType) + if (config.configType != EConfigType.SOCKS && TextUtils.isEmpty(et_id.text.toString())) { toast(R.string.server_lab_id) return false } - if (TextUtils.isEmpty(vmess.alterId.toString()) || vmess.alterId < 0) { - toast(R.string.server_lab_alterid) - return false + et_alterId?.let { + val alterId = Utils.parseInt(et_alterId.text.toString()) + if (alterId < 0) { + toast(R.string.server_lab_alterid) + return false + } } - if (AngConfigManager.addServer(vmess, edit_index) == 0) { - AngConfigManager.genStoreV2rayConfigIfActive(edit_index) - toast(R.string.toast_success) - finish() - return true - } else { - toast(R.string.toast_failure) - return false + config.remarks = et_remarks.text.toString().trim() + config.outboundBean?.settings?.vnext?.get(0)?.let { vnext -> + saveVnext(vnext, port, config) + } + config.outboundBean?.settings?.servers?.get(0)?.let { server -> + saveServers(server, port, config) + } + config.outboundBean?.streamSettings?.let { + saveStreamSettings(it) + } + + MmkvManager.encodeServerConfig(editGuid, config) + toast(R.string.toast_success) + finish() + return true + } + + private fun saveVnext(vnext: V2rayConfig.OutboundBean.OutSettingsBean.VnextBean, port: Int, config: ServerConfig) { + vnext.address = et_address.text.toString().trim() + vnext.port = port + vnext.users[0].id = et_id.text.toString().trim() + if (config.configType == EConfigType.VMESS) { + vnext.users[0].alterId = Utils.parseInt(et_alterId.text.toString()) + vnext.users[0].security = securitys[sp_security.selectedItemPosition] + } else if (config.configType == EConfigType.VLESS) { + vnext.users[0].encryption = et_security.text.toString().trim() + if (streamSecuritys[sp_stream_security.selectedItemPosition] == XTLS) { +// vnext.users[0].flow = if (flows[sp_flow.selectedItemPosition].isBlank()) DEFAULT_FLOW +// else flows[sp_flow.selectedItemPosition] + } + } + } + + private fun saveServers(server: V2rayConfig.OutboundBean.OutSettingsBean.ServersBean, port: Int, config: ServerConfig) { + server.address = et_address.text.toString().trim() + server.port = port + if (config.configType == EConfigType.SHADOWSOCKS) { + server.password = et_id.text.toString().trim() + server.method = shadowsocksSecuritys[sp_security.selectedItemPosition] + } else if (config.configType == EConfigType.SOCKS && !TextUtils.isEmpty(et_security.text) && !TextUtils.isEmpty(et_id.text)) { + val socksUsersBean = V2rayConfig.OutboundBean.OutSettingsBean.ServersBean.SocksUsersBean() + socksUsersBean.user = et_security.text.toString().trim() + socksUsersBean.pass = et_id.text.toString().trim() + server.users = listOf(socksUsersBean) + } else if (config.configType == EConfigType.TROJAN) { + server.password = et_id.text.toString().trim() + } + } + + private fun saveStreamSettings(streamSetting: V2rayConfig.OutboundBean.StreamSettingsBean) { + streamSetting.network = if (sp_network != null) networks[sp_network.selectedItemPosition] else DEFAULT_NETWORK + val headerType = if (sp_header_type != null) headertypes[sp_header_type.selectedItemPosition] else "" + val requestHost = et_request_host.text.toString().trim() + val path = et_path?.text.toString().trim() + var sni = requestHost + when (streamSetting.network) { + "tcp" -> if (headerType == HTTP) { + val tcpSetting = V2rayConfig.OutboundBean.StreamSettingsBean.TcpSettingsBean() + tcpSetting.header.type = headerType + if (!TextUtils.isEmpty(requestHost) || !TextUtils.isEmpty(path)) { + val requestObj = V2rayConfig.OutboundBean.StreamSettingsBean.TcpSettingsBean.HeaderBean.RequestBean() + requestObj.headers.Host = requestHost.split(",").map { it.trim() } + requestObj.path = path.split(",").map { it.trim() } + tcpSetting.header.request = requestObj + sni = requestObj.headers.Host.getOrNull(0) ?: sni + } + streamSetting.tcpSettings = tcpSetting + } + "kcp" -> { + val kcpsetting = V2rayConfig.OutboundBean.StreamSettingsBean.KcpSettingsBean() + kcpsetting.header.type = headerType + if (TextUtils.isEmpty(path)) { + kcpsetting.seed = null + } else { + kcpsetting.seed = path + } + streamSetting.kcpSettings = kcpsetting + } + "ws" -> { + val wssetting = V2rayConfig.OutboundBean.StreamSettingsBean.WsSettingsBean() + if (!TextUtils.isEmpty(requestHost)) { + wssetting.headers.Host = requestHost + sni = requestHost + } + if (!TextUtils.isEmpty(path)) { + wssetting.path = path + } + streamSetting.wsSettings = wssetting + } + "h2" -> { + val h2Setting = V2rayConfig.OutboundBean.StreamSettingsBean.HttpSettingsBean() + if (!TextUtils.isEmpty(requestHost)) { + h2Setting.host = requestHost.split(",").map { it.trim() } + sni = h2Setting.host.getOrNull(0) ?: sni + } + h2Setting.path = path + streamSetting.httpSettings = h2Setting + } + "quic" -> { + val quicsetting = V2rayConfig.OutboundBean.StreamSettingsBean.QuicSettingBean() + quicsetting.security = requestHost + quicsetting.key = path + quicsetting.header.type = headerType + streamSetting.quicSettings = quicsetting + } + } + + streamSetting.security = if (sp_stream_security != null) streamSecuritys[sp_stream_security.selectedItemPosition] else TLS + val tlsSetting = V2rayConfig.OutboundBean.StreamSettingsBean.TlsSettingsBean( + allowInsecure = if (sp_allow_insecure != null) allowinsecures[sp_allow_insecure.selectedItemPosition].toBoolean() else false, + serverName = sni + ) + if (streamSetting.security == TLS) { + streamSetting.tlsSettings = tlsSetting + } else if (streamSetting.security == XTLS) { + streamSetting.xtlsSettings = tlsSetting } } /** * save server config */ - fun deleteServer(): Boolean { - if (edit_index >= 0) { + private fun deleteServer(): Boolean { + if (editGuid.isNotEmpty()) { AlertDialog.Builder(this).setMessage(R.string.del_config_comfirm) .setPositiveButton(android.R.string.ok) { _, _ -> - if (AngConfigManager.removeServer(edit_index) == 0) { - toast(R.string.toast_success) - finish() - } else { - toast(R.string.toast_failure) - } + MmkvManager.removeServer(editGuid) + finish() } .show() - } else { } return true } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.action_server, menu) - del_config = menu?.findItem(R.id.del_config) - save_config = menu?.findItem(R.id.save_config) + val delButton = menu?.findItem(R.id.del_config) + val saveButton = menu?.findItem(R.id.save_config) - if (edit_index >= 0) { + if (editGuid.isNotEmpty()) { if (isRunning) { - if (edit_index == configs.index) { - del_config?.isVisible = false - save_config?.isVisible = false - } + delButton?.isVisible = false + saveButton?.isVisible = false } } else { - del_config?.isVisible = false + delButton?.isVisible = false } return super.onCreateOptionsMenu(menu) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt new file mode 100644 index 00000000..a5c604c5 --- /dev/null +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt @@ -0,0 +1,127 @@ +package com.v2ray.ang.ui + +import android.os.Bundle +import android.support.v7.app.AlertDialog +import android.text.TextUtils +import android.view.Menu +import android.view.MenuItem +import com.google.gson.Gson +import com.tencent.mmkv.MMKV +import com.v2ray.ang.R +import com.v2ray.ang.dto.EConfigType +import com.v2ray.ang.dto.ServerConfig +import com.v2ray.ang.dto.V2rayConfig +import com.v2ray.ang.extension.toast +import com.v2ray.ang.util.MmkvManager +import com.v2ray.ang.util.Utils +import kotlinx.android.synthetic.main.activity_server_custom_config.* +import java.lang.Exception + +class ServerCustomConfigActivity : BaseActivity() { + + private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } + private val editGuid by lazy { intent.getStringExtra("guid").orEmpty() } + private val isRunning by lazy { editGuid.isNotEmpty() && editGuid == mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER) } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_server_custom_config) + title = getString(R.string.title_server) + + val config = MmkvManager.decodeServerConfig(editGuid) + if (config != null) { + bindingServer(config) + } else { + clearServer() + } + supportActionBar?.setDisplayHomeAsUpEnabled(true) + } + + /** + * bingding seleced server config + */ + private fun bindingServer(config: ServerConfig): Boolean { + et_remarks.text = Utils.getEditable(config.remarks) + tv_content.text = Utils.getEditable(Gson().toJson(config.fullConfig)) + return true + } + + /** + * clear or init server config + */ + private fun clearServer(): Boolean { + et_remarks.text = null + return true + } + + /** + * save server config + */ + private fun saveServer(): Boolean { + if (TextUtils.isEmpty(et_remarks.text.toString())) { + toast(R.string.server_lab_remarks) + return false + } + + val v2rayConfig = try { + Gson().fromJson(tv_content.text.toString(), V2rayConfig::class.java) + } catch (e: Exception) { + e.printStackTrace() + toast(R.string.toast_malformed_josn) + return false + } + + val config = MmkvManager.decodeServerConfig(editGuid) ?: ServerConfig.create(EConfigType.CUSTOM) + config.remarks = et_remarks.text.toString().trim() + config.fullConfig = v2rayConfig + + MmkvManager.encodeServerConfig(editGuid, config) + toast(R.string.toast_success) + finish() + return true + } + + /** + * save server config + */ + private fun deleteServer(): Boolean { + if (editGuid.isNotEmpty()) { + AlertDialog.Builder(this).setMessage(R.string.del_config_comfirm) + .setPositiveButton(android.R.string.ok) { _, _ -> + MmkvManager.removeServer(editGuid) + finish() + } + .show() + } + return true + } + + override fun onCreateOptionsMenu(menu: Menu?): Boolean { + menuInflater.inflate(R.menu.action_server, menu) + val delButton = menu?.findItem(R.id.del_config) + val saveButton = menu?.findItem(R.id.save_config) + + if (editGuid.isNotEmpty()) { + if (isRunning) { + delButton?.isVisible = false + saveButton?.isVisible = false + } + } else { + delButton?.isVisible = false + } + + return super.onCreateOptionsMenu(menu) + } + + override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { + R.id.del_config -> { + deleteServer() + true + } + R.id.save_config -> { + saveServer() + true + } + else -> super.onOptionsItemSelected(item) + } +} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SettingsActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SettingsActivity.kt index 6bdadcc6..39dd03a8 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SettingsActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SettingsActivity.kt @@ -13,31 +13,6 @@ import com.v2ray.ang.util.Utils import com.v2ray.ang.viewmodel.SettingsViewModel class SettingsActivity : BaseActivity() { - companion object { - // const val PREF_BYPASS_MAINLAND = "pref_bypass_mainland" - // const val PREF_START_ON_BOOT = "pref_start_on_boot" - const val PREF_PER_APP_PROXY = "pref_per_app_proxy" -// const val PREF_MUX_ENAimport libv2ray.Libv2rayBLED = "pref_mux_enabled" - const val PREF_SPEED_ENABLED = "pref_speed_enabled" - const val PREF_SNIFFING_ENABLED = "pref_sniffing_enabled" - const val PREF_PROXY_SHARING = "pref_proxy_sharing_enabled" - const val PREF_LOCAL_DNS_ENABLED = "pref_local_dns_enabled" - const val PREF_REMOTE_DNS = "pref_remote_dns" - const val PREF_DOMESTIC_DNS = "pref_domestic_dns" - -// const val PREF_SOCKS_PORT = "pref_socks_port" -// const val PREF_HTTP_PORT = "pref_http_port" - - const val PREF_ROUTING_DOMAIN_STRATEGY = "pref_routing_domain_strategy" - const val PREF_ROUTING_MODE = "pref_routing_mode" - const val PREF_ROUTING_CUSTOM = "pref_routing_custom" -// const val PREF_DONATE = "pref_donate" - // const val PREF_LICENSES = "pref_licenses" -// const val PREF_FEEDBACK = "pref_feedback" -// const val PREF_TG_GROUP = "pref_tg_group" - // const val PREF_AUTO_RESTART = "pref_auto_restart" - const val PREF_FORWARD_IPV6 = "pref_forward_ipv6" - } private val settingsViewModel by lazy { ViewModelProviders.of(this).get(SettingsViewModel::class.java) } @@ -53,17 +28,17 @@ class SettingsActivity : BaseActivity() { } class SettingsFragment : PreferenceFragmentCompat() { - private val perAppProxy by lazy { findPreference(PREF_PER_APP_PROXY) as CheckBoxPreference } - private val sppedEnabled by lazy { findPreference(PREF_SPEED_ENABLED) as CheckBoxPreference } - private val sniffingEnabled by lazy { findPreference(PREF_SNIFFING_ENABLED) as CheckBoxPreference } - private val proxySharing by lazy { findPreference(PREF_PROXY_SHARING) as CheckBoxPreference } - private val domainStrategy by lazy { findPreference(PREF_ROUTING_DOMAIN_STRATEGY) as ListPreference } - private val routingMode by lazy { findPreference(PREF_ROUTING_MODE) as ListPreference } + private val perAppProxy by lazy { findPreference(AppConfig.PREF_PER_APP_PROXY) as CheckBoxPreference } + private val sppedEnabled by lazy { findPreference(AppConfig.PREF_SPEED_ENABLED) as CheckBoxPreference } + private val sniffingEnabled by lazy { findPreference(AppConfig.PREF_SNIFFING_ENABLED) as CheckBoxPreference } + private val proxySharing by lazy { findPreference(AppConfig.PREF_PROXY_SHARING) as CheckBoxPreference } + private val domainStrategy by lazy { findPreference(AppConfig.PREF_ROUTING_DOMAIN_STRATEGY) as ListPreference } + private val routingMode by lazy { findPreference(AppConfig.PREF_ROUTING_MODE) as ListPreference } - private val forwardIpv6 by lazy { findPreference(PREF_FORWARD_IPV6) as CheckBoxPreference } - private val enableLocalDns by lazy { findPreference(PREF_LOCAL_DNS_ENABLED) as CheckBoxPreference } - private val domesticDns by lazy { findPreference(PREF_DOMESTIC_DNS) as EditTextPreference } - private val remoteDns by lazy { findPreference(PREF_REMOTE_DNS) as EditTextPreference } + private val forwardIpv6 by lazy { findPreference(AppConfig.PREF_FORWARD_IPV6) as CheckBoxPreference } + private val enableLocalDns by lazy { findPreference(AppConfig.PREF_LOCAL_DNS_ENABLED) as CheckBoxPreference } + private val domesticDns by lazy { findPreference(AppConfig.PREF_DOMESTIC_DNS) as EditTextPreference } + private val remoteDns by lazy { findPreference(AppConfig.PREF_REMOTE_DNS) as EditTextPreference } // val autoRestart by lazy { findPreference(PREF_AUTO_RESTART) as CheckBoxPreference } @@ -71,7 +46,7 @@ class SettingsActivity : BaseActivity() { // val socksPort by lazy { findPreference(PREF_SOCKS_PORT) as EditTextPreference } // val httpPort by lazy { findPreference(PREF_HTTP_PORT) as EditTextPreference } - private val routingCustom: Preference by lazy { findPreference(PREF_ROUTING_CUSTOM) } + private val routingCustom: Preference by lazy { findPreference(AppConfig.PREF_ROUTING_CUSTOM) } // val donate: Preference by lazy { findPreference(PREF_DONATE) } // val licenses: Preference by lazy { findPreference(PREF_LICENSES) } // val feedback: Preference by lazy { findPreference(PREF_FEEDBACK) } @@ -214,8 +189,8 @@ class SettingsActivity : BaseActivity() { super.onStart() val defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity) updatePerAppProxy(defaultSharedPreferences.getString(AppConfig.PREF_MODE, "VPN")) - remoteDns.summary = defaultSharedPreferences.getString(PREF_REMOTE_DNS, "") - domesticDns.summary = defaultSharedPreferences.getString(PREF_DOMESTIC_DNS, "") + remoteDns.summary = defaultSharedPreferences.getString(AppConfig.PREF_REMOTE_DNS, "") + domesticDns.summary = defaultSharedPreferences.getString(AppConfig.PREF_DOMESTIC_DNS, "") if (remoteDns.summary == "") { remoteDns.summary = AppConfig.DNS_AGENT @@ -233,7 +208,7 @@ class SettingsActivity : BaseActivity() { if (mode == "VPN") { perAppProxy.isEnabled = true perAppProxy.isChecked = PreferenceManager.getDefaultSharedPreferences(activity) - .getBoolean(PREF_PER_APP_PROXY, false) + .getBoolean(AppConfig.PREF_PER_APP_PROXY, false) } else { perAppProxy.isEnabled = false perAppProxy.isChecked = false diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt index aabc013b..b4818f81 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt @@ -2,21 +2,14 @@ package com.v2ray.ang.util import android.graphics.Bitmap import android.text.TextUtils -import android.util.Log import com.google.gson.Gson import com.v2ray.ang.AngApplication -import com.v2ray.ang.AppConfig import com.v2ray.ang.AppConfig.ANG_CONFIG -import com.v2ray.ang.AppConfig.PREF_CURR_CONFIG -import com.v2ray.ang.AppConfig.PREF_CURR_CONFIG_GUID -import com.v2ray.ang.AppConfig.PREF_CURR_CONFIG_NAME -import com.v2ray.ang.AppConfig.SOCKS_PROTOCOL -import com.v2ray.ang.AppConfig.SS_PROTOCOL -import com.v2ray.ang.AppConfig.VMESS_PROTOCOL +import com.v2ray.ang.AppConfig.HTTPS_PROTOCOL +import com.v2ray.ang.AppConfig.HTTP_PROTOCOL import com.v2ray.ang.R -import com.v2ray.ang.dto.AngConfig -import com.v2ray.ang.dto.EConfigType -import com.v2ray.ang.dto.VmessQRCode +import com.v2ray.ang.dto.* +import com.v2ray.ang.dto.V2rayConfig.Companion.TLS import java.net.URI import java.net.URLDecoder import java.util.* @@ -52,9 +45,9 @@ object AngConfigManager { upgradeServerVersion(angConfig.vmess[i]) } - if (configs.subItem == null) { - configs.subItem = arrayListOf(AngConfig.SubItemBean()) - } +// if (configs.subItem == null) { +// configs.subItem = arrayListOf(AngConfig.SubItemBean()) +// } } catch (e: Exception) { e.printStackTrace() @@ -69,6 +62,15 @@ object AngConfigManager { vmess.configVersion = 2 vmess.configType = EConfigType.VMESS.value + vmess.address = vmess.address.trim() + vmess.id = vmess.id.trim() + vmess.security = vmess.security.trim() + vmess.network = vmess.network.trim() + vmess.headerType = vmess.headerType.trim() + vmess.requestHost = vmess.requestHost.trim() + vmess.path = vmess.path.trim() + vmess.streamSecurity = vmess.streamSecurity.trim() + if (index >= 0) { //edit angConfig.vmess[index] = vmess @@ -149,19 +151,13 @@ object AngConfigManager { fun setActiveServer(index: Int): Int { try { if (index < 0 || index > angConfig.vmess.count() - 1) { - app.curIndex = -1 return -1 } angConfig.index = index - app.curIndex = index + storeConfigFile() - if (!genStoreV2rayConfig()) { - Log.d(AppConfig.ANG_PACKAGE, "set active index $index but generate full configuration failed!") - return -1 - } } catch (e: Exception) { e.printStackTrace() - app.curIndex = -1 return -1 } return 0 @@ -179,68 +175,6 @@ object AngConfigManager { } } - fun genStoreV2rayConfigIfActive(index: Int) { - if (index == configs.index) { - if (!genStoreV2rayConfig()) { - Log.d(AppConfig.ANG_PACKAGE, "update config $index but generate full configuration failed!") - } - } - } - - /** - * gen and store v2ray config file - */ - fun genStoreV2rayConfig(): Boolean { - try { - angConfig.vmess.getOrNull(angConfig.index)?.let { - val result = V2rayConfigUtil.getV2rayConfig(app, it) - if (result.status) { - app.defaultDPreference.setPrefString(PREF_CURR_CONFIG, result.content) - app.defaultDPreference.setPrefString(PREF_CURR_CONFIG_GUID, currConfigGuid()) - app.defaultDPreference.setPrefString(PREF_CURR_CONFIG_NAME, currConfigName()) - return true - } - } - } catch (e: Exception) { - e.printStackTrace() - } - return false - } - - fun currGeneratedV2rayConfig(): String { - return app.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG, "") - } - - fun currConfigType(): EConfigType? { - if (angConfig.index < 0 - || angConfig.vmess.count() <= 0 - || angConfig.index > angConfig.vmess.count() - 1 - ) { - return null - } - return EConfigType.fromInt(angConfig.vmess[angConfig.index].configType) - } - - fun currConfigName(): String { - if (angConfig.index < 0 - || angConfig.vmess.count() <= 0 - || angConfig.index > angConfig.vmess.count() - 1 - ) { - return "" - } - return angConfig.vmess[angConfig.index].remarks - } - - fun currConfigGuid(): String { - if (angConfig.index < 0 - || angConfig.vmess.count() <= 0 - || angConfig.index > angConfig.vmess.count() - 1 - ) { - return "" - } - return angConfig.vmess[angConfig.index].guid - } - /** * import config form qrcode or... */ @@ -250,9 +184,15 @@ object AngConfigManager { return R.string.toast_none_data } + //maybe sub + if (server.startsWith(HTTP_PROTOCOL) || server.startsWith(HTTPS_PROTOCOL)) { + addSubItem(server) + return 0 + } + var vmess = AngConfig.VmessBean() - if (server.startsWith(VMESS_PROTOCOL)) { + if (server.startsWith(EConfigType.VMESS.protocolScheme)) { val indexSplit = server.indexOf("?") val newVmess = tryParseNewVmess(server) @@ -263,7 +203,7 @@ object AngConfigManager { vmess = ResolveVmess4Kitsunebi(server) } else { - var result = server.replace(VMESS_PROTOCOL, "") + var result = server.replace(EConfigType.VMESS.protocolScheme, "") result = Utils.decode(result) if (TextUtils.isEmpty(result)) { return R.string.toast_decoding_failed @@ -299,8 +239,8 @@ object AngConfigManager { upgradeServerVersion(vmess) addServer(vmess, -1) - } else if (server.startsWith(SS_PROTOCOL)) { - var result = server.replace(SS_PROTOCOL, "") + } else if (server.startsWith(EConfigType.SHADOWSOCKS.protocolScheme)) { + var result = server.replace(EConfigType.SHADOWSOCKS.protocolScheme, "") val indexSplit = result.indexOf("#") if (indexSplit > 0) { try { @@ -334,8 +274,8 @@ object AngConfigManager { vmess.subid = subid addShadowsocksServer(vmess, -1) - } else if (server.startsWith(SOCKS_PROTOCOL)) { - var result = server.replace(SOCKS_PROTOCOL, "") + } else if (server.startsWith(EConfigType.SOCKS.protocolScheme)) { + var result = server.replace(EConfigType.SOCKS.protocolScheme, "") val indexSplit = result.indexOf("#") if (indexSplit > 0) { try { @@ -348,23 +288,88 @@ object AngConfigManager { } //part decode - val indexS = result.indexOf(":") - if (indexS < 0) { + val indexS = result.indexOf("@") + if (indexS > 0) { + //result = Utils.decode(result.substring(0, indexS)) + result.substring(indexS, result.length) + } else { result = Utils.decode(result) } - val legacyPattern = "^(.+?):(\\d+?)$".toRegex() + val legacyPattern = "^(.*):(.*)@(.+?):(\\d+?)$".toRegex() val match = legacyPattern.matchEntire(result) if (match == null) { return R.string.toast_incorrect_protocol } - vmess.address = match.groupValues[1] + vmess.security = match.groupValues[1].toLowerCase() + vmess.id = match.groupValues[2] + vmess.address = match.groupValues[3] if (vmess.address.firstOrNull() == '[' && vmess.address.lastOrNull() == ']') vmess.address = vmess.address.substring(1, vmess.address.length - 1) - vmess.port = match.groupValues[2].toInt() + vmess.port = match.groupValues[4].toInt() vmess.subid = subid addSocksServer(vmess, -1) + + } else if (server.startsWith(EConfigType.TROJAN.protocolScheme)) { + val uri = URI(server) + + vmess.address = uri.host + vmess.port = uri.port + vmess.id = uri.userInfo + vmess.remarks = uri.fragment ?: "" + vmess.subid = subid + if (!TextUtils.isEmpty((uri.rawQuery))) { + val queryParam = uri.rawQuery.split("&") + .map { it.split("=").let { (k, v) -> k to URLDecoder.decode(v, "utf-8")!! } } + .toMap() + vmess.requestHost = queryParam["sni"] ?: "" + } + + addTrojanServer(vmess, -1) + + } else if (server.startsWith(EConfigType.VLESS.protocolScheme)) { + val uri = URI(server) + + vmess.address = uri.host + vmess.port = uri.port + vmess.id = uri.userInfo + vmess.remarks = uri.fragment ?: "" + vmess.subid = subid + + val queryParam = uri.rawQuery.split("&") + .map { it.split("=").let { (k, v) -> k to URLDecoder.decode(v, "utf-8")!! } } + .toMap() + + //vmess.flow = queryParam["flow"] ?: "" + vmess.security = queryParam["encryption"] ?: "none" + vmess.streamSecurity = queryParam["security"] ?: "" + vmess.network = queryParam["type"] ?: "tcp" + when (vmess.network) { + "tcp" -> { + vmess.headerType = queryParam["headerType"] ?: "none" + vmess.requestHost = queryParam["host"] ?: "" + } + "h2", + "http" -> { + vmess.network = "h2" + vmess.requestHost = queryParam["host"] ?: "" + vmess.path = queryParam["path"] ?: "/" + } + "ws" -> { + vmess.requestHost = queryParam["host"] ?: "" + vmess.path = queryParam["path"] ?: "/" + } + "kcp" -> { + vmess.headerType = queryParam["headerType"] ?: "none" + vmess.path = queryParam["seed"] ?: "" + } + "quic" -> { + vmess.headerType = queryParam["headerType"] ?: "none" + vmess.requestHost = queryParam["quicSecurity"] ?: "none" + vmess.path = queryParam["key"] ?: "" + } + } + addVlessServer(vmess, -1) } else { return R.string.toast_incorrect_protocol } @@ -398,7 +403,7 @@ object AngConfigManager { vmess.port = uri.port vmess.id = uuid vmess.alterId = alterId.toInt() - vmess.streamSecurity = if (tls) "tls" else "" + vmess.streamSecurity = if (tls) TLS else "" vmess.remarks = uri.fragment vmess.security = "auto" @@ -440,7 +445,7 @@ object AngConfigManager { val vmess = AngConfig.VmessBean() - var result = server.replace(VMESS_PROTOCOL, "") + var result = server.replace(EConfigType.VMESS.protocolScheme, "") val indexSplit = result.indexOf("?") if (indexSplit > 0) { result = result.substring(0, indexSplit) @@ -474,47 +479,121 @@ object AngConfigManager { /** * share config */ - fun shareConfig(index: Int): String { + fun shareConfig(guid: String): String { try { - if (index < 0 || index > angConfig.vmess.count() - 1) { - return "" - } + val config = MmkvManager.decodeServerConfig(guid) ?: return "" + val outbound = config.getProxyOutbound() ?: return "" + val streamSetting = outbound.streamSettings ?: return "" + return config.configType.protocolScheme + when (config.configType) { + EConfigType.VMESS -> { + val vmessQRCode = VmessQRCode() + vmessQRCode.v = "2" + vmessQRCode.ps = config.remarks + vmessQRCode.add = outbound.getServerAddress().orEmpty() + vmessQRCode.port = outbound.getServerPort().toString() + vmessQRCode.id = outbound.getPassword().orEmpty() + vmessQRCode.aid = outbound.settings?.vnext?.get(0)?.users?.get(0)?.alterId.toString() + vmessQRCode.net = streamSetting.network + vmessQRCode.tls = streamSetting.security + outbound.getTransportSettingDetails()?.let { transportDetails -> + vmessQRCode.type = transportDetails[0] + vmessQRCode.host = transportDetails[1] + vmessQRCode.path = transportDetails[2] + } + val json = Gson().toJson(vmessQRCode) + Utils.encode(json) + } + EConfigType.CUSTOM -> "" + EConfigType.SHADOWSOCKS, EConfigType.SOCKS -> { + val remark = "#" + Utils.urlEncode(config.remarks) + val url = String.format("%s:%s@%s:%s", + outbound.getSecurityEncryption(), + outbound.getPassword(), + outbound.getServerAddress(), + outbound.getServerPort()) + Utils.encode(url) + remark + } + EConfigType.VLESS -> { + val remark = "#" + Utils.urlEncode(config.remarks) - val vmess = angConfig.vmess[index] - if (angConfig.vmess[index].configType == EConfigType.VMESS.value) { + val dicQuery = HashMap() + outbound.settings?.vnext?.get(0)?.users?.get(0)?.flow?.let { + if (!TextUtils.isEmpty(it)) { + dicQuery["flow"] = it + } + } + dicQuery["encryption"] = if (outbound.getSecurityEncryption().isNullOrEmpty()) "none" + else outbound.getSecurityEncryption().orEmpty() + dicQuery["security"] = if (streamSetting.security.isEmpty()) "none" + else streamSetting.security + dicQuery["type"] = if (streamSetting.network.isEmpty()) V2rayConfig.DEFAULT_NETWORK + else streamSetting.network - val vmessQRCode = VmessQRCode() - vmessQRCode.v = vmess.configVersion.toString() - vmessQRCode.ps = vmess.remarks - vmessQRCode.add = vmess.address - vmessQRCode.port = vmess.port.toString() - vmessQRCode.id = vmess.id - vmessQRCode.aid = vmess.alterId.toString() - vmessQRCode.net = vmess.network - vmessQRCode.type = vmess.headerType - vmessQRCode.host = vmess.requestHost - vmessQRCode.path = vmess.path - vmessQRCode.tls = vmess.streamSecurity - val json = Gson().toJson(vmessQRCode) - val conf = VMESS_PROTOCOL + Utils.encode(json) + outbound.getTransportSettingDetails()?.let { transportDetails -> + when (streamSetting.network) { + "tcp" -> { + dicQuery["headerType"] = if (transportDetails[0].isEmpty()) "none" + else transportDetails[0] + if (!TextUtils.isEmpty(transportDetails[1])) { + dicQuery["host"] = Utils.urlEncode(transportDetails[1]) + } + } + "kcp" -> { + dicQuery["headerType"] = if (transportDetails[0].isEmpty()) "none" + else transportDetails[0] + if (!TextUtils.isEmpty(transportDetails[2])) { + dicQuery["seed"] = Utils.urlEncode(transportDetails[2]) + } + } + "ws" -> { + if (!TextUtils.isEmpty(transportDetails[1])) { + dicQuery["host"] = Utils.urlEncode(transportDetails[1]) + } + if (!TextUtils.isEmpty(transportDetails[2])) { + dicQuery["path"] = Utils.urlEncode(transportDetails[2]) + } + } + "http", "h2" -> { + dicQuery["type"] = "http" + if (!TextUtils.isEmpty(transportDetails[1])) { + dicQuery["host"] = Utils.urlEncode(transportDetails[1]) + } + if (!TextUtils.isEmpty(transportDetails[2])) { + dicQuery["path"] = Utils.urlEncode(transportDetails[2]) + } + } + "quic" -> { + dicQuery["headerType"] = if (transportDetails[0].isEmpty()) "none" + else transportDetails[0] + dicQuery["quicSecurity"] = Utils.urlEncode(transportDetails[1]) + dicQuery["key"] = Utils.urlEncode(transportDetails[2]) + } + } + } + val query = "?" + dicQuery.toList().joinToString( + separator = "&", + transform = { it.first + "=" + it.second }) - return conf - } else if (angConfig.vmess[index].configType == EConfigType.SHADOWSOCKS.value) { - val remark = "#" + Utils.urlEncode(vmess.remarks) - val url = String.format("%s:%s@%s:%s", - vmess.security, - vmess.id, - vmess.address, - vmess.port) - return SS_PROTOCOL + Utils.encode(url) + remark - } else if (angConfig.vmess[index].configType == EConfigType.SOCKS.value) { - val remark = "#" + Utils.urlEncode(vmess.remarks) - val url = String.format("%s:%s", - vmess.address, - vmess.port) - return SOCKS_PROTOCOL + Utils.encode(url) + remark - } else { - return "" + val url = String.format("%s@%s:%s", + outbound.getPassword(), + outbound.getServerAddress(), + outbound.getServerPort()) + url + query + remark + } + EConfigType.TROJAN -> { + val remark = "#" + Utils.urlEncode(config.remarks) + var query = "" + streamSetting.tlsSettings?: streamSetting.xtlsSettings?.let { tlsSetting -> + if (!TextUtils.isEmpty(tlsSetting.serverName)) { + query = "?sni=${tlsSetting.serverName}" + } + } + val url = String.format("%s@%s:%s", + outbound.getPassword(), + outbound.getServerAddress(), + outbound.getServerPort()) + url + query + remark + } } } catch (e: Exception) { e.printStackTrace() @@ -525,9 +604,9 @@ object AngConfigManager { /** * share2Clipboard */ - fun share2Clipboard(index: Int): Int { + fun share2Clipboard(guid: String): Int { try { - val conf = shareConfig(index) + val conf = shareConfig(guid) if (TextUtils.isEmpty(conf)) { return -1 } @@ -544,11 +623,11 @@ object AngConfigManager { /** * share2Clipboard */ - fun shareAll2Clipboard(): Int { + fun shareNonCustomConfigsToClipboard(serverList: List): Int { try { val sb = StringBuilder() - for (k in 0 until angConfig.vmess.count()) { - val url = shareConfig(k) + for (guid in serverList) { + val url = shareConfig(guid) if (TextUtils.isEmpty(url)) { continue } @@ -568,9 +647,9 @@ object AngConfigManager { /** * share2QRCode */ - fun share2QRCode(index: Int): Bitmap? { + fun share2QRCode(guid: String): Bitmap? { try { - val conf = shareConfig(index) + val conf = shareConfig(guid) if (TextUtils.isEmpty(conf)) { return null } @@ -586,9 +665,10 @@ object AngConfigManager { /** * shareFullContent2Clipboard */ - fun shareFullContent2Clipboard(index: Int): Int { + fun shareFullContent2Clipboard(guid: String?): Int { try { - val result = V2rayConfigUtil.getV2rayConfig(app, angConfig.vmess[index]) + if (guid == null) return -1 + val result = V2rayConfigUtil.getV2rayConfig(app, guid) if (result.status) { Utils.setClipboard(app.applicationContext, result.content) } else { @@ -609,34 +689,10 @@ object AngConfigManager { if (server == null || TextUtils.isEmpty(server)) { return R.string.toast_none_data } - - val guid = System.currentTimeMillis().toString() - app.defaultDPreference.setPrefString(ANG_CONFIG + guid, server) - - //add - val vmess = AngConfig.VmessBean() - vmess.configVersion = 2 - vmess.configType = EConfigType.CUSTOM.value - vmess.guid = guid - vmess.remarks = vmess.guid - - vmess.security = "" - vmess.network = "" - vmess.headerType = "" - vmess.address = "" - vmess.port = 0 - vmess.id = "" - vmess.alterId = 0 - vmess.network = "" - vmess.headerType = "" - vmess.requestHost = "" - vmess.streamSecurity = "" - - angConfig.vmess.add(vmess) - if (angConfig.vmess.count() == 1) { - angConfig.index = 0 - } - storeConfigFile() + val config = ServerConfig.create(EConfigType.CUSTOM) + config.remarks = System.currentTimeMillis().toString() + config.fullConfig = Gson().fromJson(server, V2rayConfig::class.java) + MmkvManager.encodeServerConfig("", config) } catch (e: Exception) { e.printStackTrace() return -1 @@ -715,37 +771,15 @@ object AngConfigManager { } } - - fun addCustomServer(vmess: AngConfig.VmessBean, index: Int): Int { - try { - vmess.configVersion = 2 - vmess.configType = EConfigType.CUSTOM.value - - if (index >= 0) { - //edit - angConfig.vmess[index] = vmess - } else { - //add - vmess.guid = System.currentTimeMillis().toString() - angConfig.vmess.add(vmess) - if (angConfig.vmess.count() == 1) { - angConfig.index = 0 - } - } - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - fun addShadowsocksServer(vmess: AngConfig.VmessBean, index: Int): Int { try { vmess.configVersion = 2 vmess.configType = EConfigType.SHADOWSOCKS.value + vmess.address = vmess.address.trim() + vmess.id = vmess.id.trim() + vmess.security = vmess.security.trim() + if (index >= 0) { //edit angConfig.vmess[index] = vmess @@ -771,6 +805,8 @@ object AngConfigManager { vmess.configVersion = 2 vmess.configType = EConfigType.SOCKS.value + vmess.address = vmess.address.trim() + if (index >= 0) { //edit angConfig.vmess[index] = vmess @@ -829,6 +865,7 @@ object AngConfigManager { return 0 } + fun saveSubItem(subItem: ArrayList): Int { try { if (subItem.count() <= 0) { @@ -883,6 +920,19 @@ object AngConfigManager { return 0 } + private fun addSubItem(url: String): Int { + //already exists + angConfig.subItem.forEach { + if (it.url == url) { + return 0 + } + } + val subItem = AngConfig.SubItemBean() + subItem.remarks = "import sub" + subItem.url = url + return addSubItem(subItem, -1) + } + /** * */ @@ -891,8 +941,9 @@ object AngConfigManager { if (index < 0 || index > angConfig.subItem.count() - 1) { return -1 } + val subid = angConfig.subItem[index].id + removeServerViaSubid(subid) - //删除 angConfig.subItem.removeAt(index) storeConfigFile() @@ -903,4 +954,73 @@ object AngConfigManager { return 0 } + /** + * add or edit server + */ + fun addVlessServer(vmess: AngConfig.VmessBean, index: Int): Int { + try { + vmess.configVersion = 2 + vmess.configType = EConfigType.VLESS.value + + vmess.address = vmess.address.trim() + vmess.id = vmess.id.trim() + vmess.alterId = 0 + //vmess.flow = vmess.flow.trim() + vmess.security = vmess.security.trim() + vmess.network = vmess.network.trim() + vmess.headerType = vmess.headerType.trim() + vmess.requestHost = vmess.requestHost.trim() + vmess.path = vmess.path.trim() + vmess.streamSecurity = vmess.streamSecurity.trim() + + if (index >= 0) { + //edit + angConfig.vmess[index] = vmess + } else { + //add + vmess.guid = Utils.getUuid() + angConfig.vmess.add(vmess) + if (angConfig.vmess.count() == 1) { + angConfig.index = 0 + } + } + + storeConfigFile() + } catch (e: Exception) { + e.printStackTrace() + return -1 + } + return 0 + } + + fun addTrojanServer(vmess: AngConfig.VmessBean, index: Int): Int { + try { + vmess.configVersion = 2 + vmess.configType = EConfigType.TROJAN.value + + vmess.address = vmess.address.trim() + vmess.id = vmess.id.trim() + + vmess.streamSecurity = TLS; + + if (index >= 0) { + //edit + angConfig.vmess[index] = vmess + } else { + //add + vmess.guid = System.currentTimeMillis().toString() + angConfig.vmess.add(vmess) + if (angConfig.vmess.count() == 1) { + angConfig.index = 0 + } + } + + storeConfigFile() + } catch (e: Exception) { + e.printStackTrace() + return -1 + } + return 0 + } + } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt new file mode 100644 index 00000000..45f5ed63 --- /dev/null +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt @@ -0,0 +1,64 @@ +package com.v2ray.ang.util + +import com.google.gson.Gson +import com.tencent.mmkv.MMKV +import com.v2ray.ang.dto.ServerAffiliationInfo +import com.v2ray.ang.dto.ServerConfig + +object MmkvManager { + const val ID_MAIN = "MAIN" + const val ID_SERVER_CONFIG = "SERVER_CONFIG" + const val ID_SERVER_AFF = "SERVER_AFF" + const val ID_SUB = "SUB" + const val ID_SETTING = "SETTING" + const val KEY_SELECTED_SERVER = "SELECTED_SERVER" + const val KEY_ANG_CONFIGS = "ANG_CONFIGS" + + private val serverStorage by lazy { MMKV.mmkvWithID(ID_SERVER_CONFIG, MMKV.MULTI_PROCESS_MODE) } + private val serverAffStorage by lazy { MMKV.mmkvWithID(ID_SERVER_AFF, MMKV.MULTI_PROCESS_MODE) } + + fun decodeServerConfig(guid: String): ServerConfig? { + if (guid.isBlank()) { + return null + } + val json = serverStorage?.decodeString(guid) + if (json.isNullOrBlank()) { + return null + } + return Gson().fromJson(json, ServerConfig::class.java) + } + + fun encodeServerConfig(guid: String, config: ServerConfig) { + val key = if (guid.isBlank()) { + Utils.getUuid() + } else { + guid + } + serverStorage?.encode(key, Gson().toJson(config)) + } + + fun removeServer(guid: String) { + serverStorage?.remove(guid) + serverAffStorage?.remove(guid) + } + + fun decodeServerAffiliationInfo(guid: String): ServerAffiliationInfo? { + if (guid.isBlank()) { + return null + } + val json = serverAffStorage?.decodeString(guid) + if (json.isNullOrBlank()) { + return null + } + return Gson().fromJson(json, ServerAffiliationInfo::class.java) + } + + fun clearAllTestDelayResults() { + serverAffStorage?.allKeys()?.forEach { key -> + decodeServerAffiliationInfo(key)?.let { aff -> + aff.testDelayMillis = 0 + serverAffStorage?.encode(key, Gson().toJson(aff)) + } + } + } +} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt index b6fde12b..ee751ad5 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt @@ -27,7 +27,6 @@ import com.v2ray.ang.extension.responseLength import com.v2ray.ang.extension.toast import com.v2ray.ang.extension.v2RayApplication import com.v2ray.ang.service.V2RayServiceManager -import com.v2ray.ang.ui.SettingsActivity import kotlinx.coroutines.isActive import me.dozen.dpreference.DPreference import java.io.IOException @@ -36,7 +35,7 @@ import kotlin.coroutines.coroutineContext object Utils { - val tcpTestingSockets = ArrayList() + private val tcpTestingSockets = ArrayList() /** * convert string to editalbe for kotlin @@ -126,7 +125,7 @@ object Utils { * get remote dns servers from preference */ fun getRemoteDnsServers(defaultDPreference: DPreference): ArrayList { - val remoteDns = defaultDPreference.getPrefString(SettingsActivity.PREF_REMOTE_DNS, AppConfig.DNS_AGENT) + val remoteDns = defaultDPreference.getPrefString(AppConfig.PREF_REMOTE_DNS, AppConfig.DNS_AGENT) val ret = ArrayList() if (!TextUtils.isEmpty(remoteDns)) { remoteDns @@ -147,7 +146,7 @@ object Utils { * get remote dns servers from preference */ fun getDomesticDnsServers(defaultDPreference: DPreference): ArrayList { - val domesticDns = defaultDPreference.getPrefString(SettingsActivity.PREF_DOMESTIC_DNS, AppConfig.DNS_DIRECT) + val domesticDns = defaultDPreference.getPrefString(AppConfig.PREF_DOMESTIC_DNS, AppConfig.DNS_DIRECT) val ret = ArrayList() if (!TextUtils.isEmpty(domesticDns)) { domesticDns @@ -430,19 +429,18 @@ object Utils { /** * tcping */ - suspend fun tcping(url: String, port: Int): String { + suspend fun tcping(url: String, port: Int): Long { var time = -1L for (k in 0 until 2) { val one = socketConnectTime(url, port) if (!coroutineContext.isActive) { break } - if (one != -1L ) - if(time == -1L || one < time) { + if (one != -1L && (time == -1L || one < time)) { time = one } } - return time.toString() + "ms" + return time } fun socketConnectTime(url: String, port: Int): Long { diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt index ee626334..cb4cd815 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt @@ -1,27 +1,19 @@ package com.v2ray.ang.util -import android.content.Context import android.text.TextUtils import android.util.Log import com.google.gson.* import com.v2ray.ang.AngApplication import com.v2ray.ang.AppConfig -import com.v2ray.ang.dto.AngConfig.VmessBean import com.v2ray.ang.dto.V2rayConfig -import com.v2ray.ang.ui.SettingsActivity import org.json.JSONException import org.json.JSONObject -import org.json.JSONArray import com.v2ray.ang.dto.EConfigType -import com.v2ray.ang.extension.defaultDPreference -import kotlin.collections.ArrayList -import kotlin.collections.LinkedHashSet object V2rayConfigUtil { - private val requestObj: JsonObject by lazy { - Gson().fromJson("""{"version":"1.1","method":"GET","path":["/"],"headers":{"User-Agent":["Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36","Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/53.0.2785.109 Mobile/14A456 Safari/601.1.46"],"Accept-Encoding":["gzip, deflate"],"Connection":["keep-alive"],"Pragma":"no-cache"}}""", JsonObject::class.java) - } - +// private val requestObj: JsonObject by lazy { +// Gson().fromJson("""{"version":"1.1","method":"GET","path":["/"],"headers":{"User-Agent":["Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36","Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/53.0.2785.109 Mobile/14A456 Safari/601.1.46"],"Accept-Encoding":["gzip, deflate"],"Connection":["keep-alive"],"Pragma":"no-cache"}}""", JsonObject::class.java) +// } // private val responseObj: JSONObject by lazy { // JSONObject("""{"version":"1.1","status":"200","reason":"OK","headers":{"Content-Type":["application/octet-stream","video/mpeg"],"Transfer-Encoding":["chunked"],"Connection":["keep-alive"],"Pragma":"no-cache"}}""") // } @@ -31,139 +23,84 @@ object V2rayConfigUtil { /** * 生成v2ray的客户端配置文件 */ - fun getV2rayConfig(app: AngApplication, vmess: VmessBean): Result { - var result = Result(false, "") + fun getV2rayConfig(app: AngApplication, guid: String): Result { try { - //检查设置 -// if (config.index < 0 -// || config.vmess.count() <= 0 -// || config.index > config.vmess.count() - 1 -// ) { -// return result -// } - - if (vmess.configType == EConfigType.CUSTOM.value) { - result = getV2rayConfigType2(app, vmess) - } else { - result = getV2rayConfigType1(app, vmess) + val config = MmkvManager.decodeServerConfig(guid) ?: return Result(false, "") + if (config.configType == EConfigType.CUSTOM) { + val customConfig = Gson().toJson(config.fullConfig) + Log.d("V2rayConfigUtilGoLog", customConfig) + return Result(true, customConfig) } - + val outbound = config.getProxyOutbound() ?: return Result(false, "") + val result = getV2rayNonCustomConfig(app, outbound) Log.d("V2rayConfigUtilGoLog", result.content) return result } catch (e: Exception) { e.printStackTrace() - return result - } - } - - fun getCustomConfigServerOutbound(content: Context, guid: String): V2rayConfig.OutboundBean? { - val jsonConfig = content.defaultDPreference.getPrefString(AppConfig.ANG_CONFIG + guid, "") - if (TextUtils.isEmpty(jsonConfig)) { - return null - } - val v2rayConfig: V2rayConfig? = try { - Gson().fromJson(jsonConfig, V2rayConfig::class.java) - } catch (e: JsonSyntaxException) { - e.printStackTrace() - null - } - v2rayConfig?.outbounds?.forEach { outbound -> - if (outbound.protocol.equals(EConfigType.VMESS.name, true) || - outbound.protocol.equals(EConfigType.SHADOWSOCKS.name, true) || - outbound.protocol.equals(EConfigType.SOCKS.name, true)) { - return outbound - } - } - return null - } - - /** - * 生成v2ray的客户端配置文件 - */ - private fun getV2rayConfigType1(app: AngApplication, vmess: VmessBean): Result { - val result = Result(false, "") - try { - //取得默认配置 - val assets = Utils.readTextFromAssets(app, "v2ray_config.json") - if (TextUtils.isEmpty(assets)) { - return result - } - - //转成Json - val v2rayConfig = Gson().fromJson(assets, V2rayConfig::class.java) ?: return result -// if (v2rayConfig == null) { -// return result -// } - - inbounds(vmess, v2rayConfig, app) - - outbounds(vmess, v2rayConfig, app) - - routing(vmess, v2rayConfig, app) - - if (app.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_LOCAL_DNS_ENABLED, false)) { - customLocalDns(vmess, v2rayConfig, app) - } else { - customRemoteDns(vmess, v2rayConfig, app) - } - - val finalConfig = GsonBuilder().setPrettyPrinting().create().toJson(v2rayConfig) - - result.status = true - result.content = finalConfig - return result - - } catch (e: Exception) { - e.printStackTrace() - return result + return Result(false, "") } } /** * 生成v2ray的客户端配置文件 */ - private fun getV2rayConfigType2(app: AngApplication, vmess: VmessBean): Result { + private fun getV2rayNonCustomConfig(app: AngApplication, outbound: V2rayConfig.OutboundBean): Result { val result = Result(false, "") - try { - val guid = vmess.guid - val jsonConfig = app.defaultDPreference.getPrefString(AppConfig.ANG_CONFIG + guid, "") - result.status = true - result.content = jsonConfig - parseDomainNameAndTag(app, jsonConfig) - return result - - } catch (e: Exception) { - e.printStackTrace() + //取得默认配置 + val assets = Utils.readTextFromAssets(app, "v2ray_config.json") + if (TextUtils.isEmpty(assets)) { return result } + + //转成Json + val v2rayConfig = Gson().fromJson(assets, V2rayConfig::class.java) ?: return result + + //v2rayConfig.log.loglevel = app.defaultDPreference.getPrefString(AppConfig.PREF_LOGLEVEL, "warning") + + inbounds(v2rayConfig, app) + + v2rayConfig.outbounds[0] = outbound + + routing(v2rayConfig, app) + + if (app.defaultDPreference.getPrefBoolean(AppConfig.PREF_LOCAL_DNS_ENABLED, false)) { + customLocalDns(v2rayConfig, app) + } else { + customRemoteDns(v2rayConfig, app) + } + + val finalConfig = GsonBuilder().setPrettyPrinting().create().toJson(v2rayConfig) + + result.status = true + result.content = finalConfig + return result } /** * */ - private fun inbounds(vmess: VmessBean, v2rayConfig: V2rayConfig, app: AngApplication): Boolean { + private fun inbounds(v2rayConfig: V2rayConfig, app: AngApplication): Boolean { try { + //val socksPort = Utils.parseInt(app.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_SOCKS_PORT, AppConfig.PORT_SOCKS)) + //val httpPort = Utils.parseInt(app.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_HTTP_PORT, AppConfig.PORT_HTTP)) + v2rayConfig.inbounds.forEach { curInbound -> - if (!app.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_PROXY_SHARING, false)) { + if (!app.defaultDPreference.getPrefBoolean(AppConfig.PREF_PROXY_SHARING, false)) { //bind all inbounds to localhost if the user requests curInbound.listen = "127.0.0.1" } } v2rayConfig.inbounds[0].port = 10808 -// val socksPort = Utils.parseInt(app.defaultDPreference.getPrefString(SettingsActivity.PREF_SOCKS_PORT, "10808")) -// val lanconnPort = Utils.parseInt(app.defaultDPreference.getPrefString(SettingsActivity.PREF_HTTP_PORT, "")) + v2rayConfig.inbounds[0].sniffing?.enabled = app.defaultDPreference.getPrefBoolean(AppConfig.PREF_SNIFFING_ENABLED, true) -// if (socksPort > 0) { -// v2rayConfig.inbounds[0].port = socksPort -// } -// if (lanconnPort > 0) { + //v2rayConfig.inbounds[1].port = httpPort + +// if (httpPort > 0) { // val httpCopy = v2rayConfig.inbounds[0].copy() -// httpCopy.port = lanconnPort +// httpCopy.port = httpPort // httpCopy.protocol = "http" // v2rayConfig.inbounds.add(httpCopy) // } - v2rayConfig.inbounds[0].sniffing?.enabled = app.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_SNIFFING_ENABLED, true) - } catch (e: Exception) { e.printStackTrace() return false @@ -171,230 +108,26 @@ object V2rayConfigUtil { return true } - /** - * vmess协议服务器配置 - */ - private fun outbounds(vmess: VmessBean, v2rayConfig: V2rayConfig, app: AngApplication): Boolean { - try { - val outbound = v2rayConfig.outbounds[0] - - val configType = EConfigType.fromInt(vmess.configType) - if (configType != null) { - outbound.protocol = configType.name.toLowerCase() - } - when (configType) { - EConfigType.VMESS -> { - outbound.settings?.servers = null - - val vnext = v2rayConfig.outbounds[0].settings?.vnext?.get(0) - vnext?.address = vmess.address - vnext?.port = vmess.port - val user = vnext?.users?.get(0) - user?.id = vmess.id - user?.alterId = vmess.alterId - user?.security = vmess.security - user?.level = 8 - - //Mux - val muxEnabled = false//app.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_MUX_ENABLED, false) - outbound.mux?.enabled = muxEnabled - - //远程服务器底层传输配置 - outbound.streamSettings = boundStreamSettings(vmess) - } - EConfigType.SHADOWSOCKS -> { - outbound.settings?.vnext = null - - val server = outbound.settings?.servers?.get(0) - server?.address = vmess.address - server?.method = vmess.security - server?.ota = false - server?.password = vmess.id - server?.port = vmess.port - server?.level = 8 - - //Mux - outbound.mux?.enabled = false - } - EConfigType.SOCKS -> { - outbound.settings?.vnext = null - - val server = outbound.settings?.servers?.get(0) - server?.address = vmess.address - server?.port = vmess.port - - //Mux - outbound.mux?.enabled = false - } - } - - val serverDomain = if (Utils.isIpv6Address(vmess.address)) { - String.format("[%s]:%s", vmess.address, vmess.port) - } else { - String.format("%s:%s", vmess.address, vmess.port) - } - app.defaultDPreference.setPrefString(AppConfig.PREF_CURR_CONFIG_DOMAIN, serverDomain) - val tags = LinkedHashSet() - v2rayConfig.outbounds.forEach { - if (!TextUtils.isEmpty(it.tag)) { - tags.add(it.tag) - } - } - app.defaultDPreference.setPrefStringOrderedSet(AppConfig.PREF_CURR_CONFIG_OUTBOUND_TAGS, tags) - } catch (e: Exception) { - e.printStackTrace() - return false - } - return true - } - - /** - * 远程服务器底层传输配置 - */ - private fun boundStreamSettings(vmess: VmessBean): V2rayConfig.OutboundBean.StreamSettingsBean { - val streamSettings = V2rayConfig.OutboundBean.StreamSettingsBean("", "", null, null, null, null, null, null) - try { - //远程服务器底层传输配置 - streamSettings.network = vmess.network - streamSettings.security = vmess.streamSecurity - - //streamSettings - when (streamSettings.network) { - "kcp" -> { - val kcpsettings = V2rayConfig.OutboundBean.StreamSettingsBean.KcpSettingsBean() - kcpsettings.mtu = 1350 - kcpsettings.tti = 50 - kcpsettings.uplinkCapacity = 12 - kcpsettings.downlinkCapacity = 100 - kcpsettings.congestion = false - kcpsettings.readBufferSize = 1 - kcpsettings.writeBufferSize = 1 - kcpsettings.header = V2rayConfig.OutboundBean.StreamSettingsBean.KcpSettingsBean.HeaderBean() - kcpsettings.header.type = vmess.headerType - streamSettings.kcpSettings = kcpsettings - } - "ws" -> { - val wssettings = V2rayConfig.OutboundBean.StreamSettingsBean.WsSettingsBean() - val host = vmess.requestHost.trim() - val path = vmess.path.trim() - - if (!TextUtils.isEmpty(host)) { - wssettings.headers = V2rayConfig.OutboundBean.StreamSettingsBean.WsSettingsBean.HeadersBean() - wssettings.headers.Host = host - } - if (!TextUtils.isEmpty(path)) { - wssettings.path = path - } - streamSettings.wsSettings = wssettings - - val tlssettings = V2rayConfig.OutboundBean.StreamSettingsBean.TlsSettingsBean() - tlssettings.allowInsecure = true - if (!TextUtils.isEmpty(host)) { - tlssettings.serverName = host - } - streamSettings.tlsSettings = tlssettings - } - "h2" -> { - val httpsettings = V2rayConfig.OutboundBean.StreamSettingsBean.HttpSettingsBean() - val host = vmess.requestHost.trim() - val path = vmess.path.trim() - - if (!TextUtils.isEmpty(host)) { - httpsettings.host = host.split(",").map { it.trim() } - } - httpsettings.path = path - streamSettings.httpSettings = httpsettings - - val tlssettings = V2rayConfig.OutboundBean.StreamSettingsBean.TlsSettingsBean() - tlssettings.allowInsecure = true - streamSettings.tlsSettings = tlssettings - } - "quic" -> { - val quicsettings = V2rayConfig.OutboundBean.StreamSettingsBean.QuicSettingBean() - val host = vmess.requestHost.trim() - val path = vmess.path.trim() - - quicsettings.security = host - quicsettings.key = path - - quicsettings.header = V2rayConfig.OutboundBean.StreamSettingsBean.QuicSettingBean.HeaderBean() - quicsettings.header.type = vmess.headerType - - streamSettings.quicSettings = quicsettings - } - else -> { - //tcp带http伪装 - if (vmess.headerType == "http") { - val tcpSettings = V2rayConfig.OutboundBean.StreamSettingsBean.TcpSettingsBean() - tcpSettings.header = V2rayConfig.OutboundBean.StreamSettingsBean.TcpSettingsBean.HeaderBean() - tcpSettings.header.type = vmess.headerType - -// if (requestObj.has("headers") -// || requestObj.optJSONObject("headers").has("Pragma")) { -// val arrHost = ArrayList() -// vmess.requestHost -// .split(",") -// .forEach { -// arrHost.add(it) -// } -// requestObj.optJSONObject("headers") -// .put("Host", arrHost) -// -// } - if (!TextUtils.isEmpty(vmess.requestHost)) { - val arrHost = ArrayList() - vmess.requestHost - .split(",") - .forEach { - arrHost.add("\"$it\"") - } - requestObj.getAsJsonObject("headers") - .add("Host", Gson().fromJson(arrHost.toString(), JsonArray::class.java)) - } - if (!TextUtils.isEmpty(vmess.path)) { - val arrPath = ArrayList() - vmess.path - .split(",") - .forEach { - arrPath.add("\"$it\"") - } - requestObj.add("path", Gson().fromJson(arrPath.toString(), JsonArray::class.java)) - } - tcpSettings.header.request = requestObj - //tcpSettings.header.response = responseObj - streamSettings.tcpSettings = tcpSettings - } - } - } - } catch (e: Exception) { - e.printStackTrace() - return streamSettings - } - return streamSettings - } - /** * routing */ - private fun routing(vmess: VmessBean, v2rayConfig: V2rayConfig, app: AngApplication): Boolean { + private fun routing(v2rayConfig: V2rayConfig, app: AngApplication): Boolean { try { routingUserRule(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_AGENT, ""), AppConfig.TAG_AGENT, v2rayConfig) routingUserRule(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_DIRECT, ""), AppConfig.TAG_DIRECT, v2rayConfig) routingUserRule(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED, ""), AppConfig.TAG_BLOCKED, v2rayConfig) - v2rayConfig.routing.domainStrategy = app.defaultDPreference.getPrefString(SettingsActivity.PREF_ROUTING_DOMAIN_STRATEGY, "IPIfNonMatch") - val routingMode = app.defaultDPreference.getPrefString(SettingsActivity.PREF_ROUTING_MODE, "0") + v2rayConfig.routing.domainStrategy = app.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_DOMAIN_STRATEGY, "IPIfNonMatch") + val routingMode = app.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") // Hardcode googleapis.cn val googleapisRoute = V2rayConfig.RoutingBean.RulesBean( - type = "field", - outboundTag = AppConfig.TAG_AGENT, - domain = arrayListOf("domain:googleapis.cn") + type = "field", + outboundTag = AppConfig.TAG_AGENT, + domain = arrayListOf("domain:googleapis.cn") ) when (routingMode) { - "0" -> { - } "1" -> { routingGeo("ip", "private", AppConfig.TAG_DIRECT, v2rayConfig) } @@ -459,18 +192,18 @@ object V2rayConfigUtil { rulesIP.ip = ArrayList() userRule.split(",").map { it.trim() }.forEach { - if (Utils.isIpAddress(it) || it.startsWith("geoip:")) { - rulesIP.ip?.add(it) - } else if (it.isNotEmpty()) + if (Utils.isIpAddress(it) || it.startsWith("geoip:")) { + rulesIP.ip?.add(it) + } else if (it.isNotEmpty()) // if (Utils.isValidUrl(it) // || it.startsWith("geosite:") // || it.startsWith("regexp:") // || it.startsWith("domain:") // || it.startsWith("full:")) - { - rulesDomain.domain?.add(it) - } - } + { + rulesDomain.domain?.add(it) + } + } if (rulesDomain.domain?.size!! > 0) { v2rayConfig.routing.rules.add(rulesDomain) } @@ -496,30 +229,33 @@ object V2rayConfigUtil { /** * Custom Dns */ - private fun customLocalDns(vmess: VmessBean, v2rayConfig: V2rayConfig, app: AngApplication): Boolean { + private fun customLocalDns(v2rayConfig: V2rayConfig, app: AngApplication): Boolean { try { val hosts = mutableMapOf() val servers = ArrayList() val remoteDns = Utils.getRemoteDnsServers(app.defaultDPreference) + remoteDns.forEach { servers.add(it) } val domesticDns = Utils.getDomesticDnsServers(app.defaultDPreference) + val geositeCn = arrayListOf("geosite:cn") + val geoipCn = arrayListOf("geoip:cn") val agDomain = userRule2Domian(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_AGENT, "")) if (agDomain.size > 0) { - servers.add(V2rayConfig.DnsBean.ServersBean(remoteDns.first(), 53, agDomain)) + servers.add(V2rayConfig.DnsBean.ServersBean(remoteDns.first(), 53, agDomain, null)) } val dirDomain = userRule2Domian(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_DIRECT, "")) if (dirDomain.size > 0) { - servers.add(V2rayConfig.DnsBean.ServersBean(domesticDns.first(), 53, dirDomain)) + servers.add(V2rayConfig.DnsBean.ServersBean(domesticDns.first(), 53, dirDomain, geoipCn)) } - val routingMode = app.defaultDPreference.getPrefString(SettingsActivity.PREF_ROUTING_MODE, "0") + val routingMode = app.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") if (routingMode == "2" || routingMode == "3") { - servers.add(V2rayConfig.DnsBean.ServersBean(domesticDns.first(), 53, arrayListOf("geosite:cn"))) + servers.add(V2rayConfig.DnsBean.ServersBean(domesticDns.first(), 53, geositeCn, geoipCn)) } val blkDomain = userRule2Domian(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED, "")) @@ -537,53 +273,57 @@ object V2rayConfigUtil { // DNS inbound对象 if (v2rayConfig.inbounds.none { e -> e.protocol == "dokodemo-door" && e.tag == "dns-in" }) { - val dnsInboundSettings = V2rayConfig.InboundBean.InSettingsBean( - address = remoteDns.first(), - port = 53, - network = "tcp,udp") + val dnsInboundSettings = V2rayConfig.InboundBean.InSettingsBean( + address = if (remoteDns.first().startsWith("https")) "1.1.1.1" else remoteDns.first(), + port = 53, + network = "tcp,udp") + //val localDnsPort = Utils.parseInt(app.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_LOCAL_DNS_PORT, AppConfig.PORT_LOCAL_DNS)) v2rayConfig.inbounds.add( - V2rayConfig.InboundBean( - tag = "dns-in", - port = 10807, - listen = "127.0.0.1", - protocol = "dokodemo-door", - settings = dnsInboundSettings, - sniffing = null)) + V2rayConfig.InboundBean( + tag = "dns-in", + port = 10807, + listen = "127.0.0.1", + protocol = "dokodemo-door", + settings = dnsInboundSettings, + sniffing = null)) } // DNS outbound对象 if (v2rayConfig.outbounds.none { e -> e.protocol == "dns" && e.tag == "dns-out" }) { v2rayConfig.outbounds.add( - V2rayConfig.OutboundBean( - protocol = "dns", - tag = "dns-out", - settings = null, - streamSettings = null, - mux = null)) + V2rayConfig.OutboundBean( + protocol = "dns", + tag = "dns-out", + settings = null, + streamSettings = null, + mux = null)) } // DNS routing - v2rayConfig.routing.rules.add(0, V2rayConfig.RoutingBean.RulesBean( - type = "field", - outboundTag = AppConfig.TAG_DIRECT, - port = "53", - ip = domesticDns, - domain = null) - ) - - v2rayConfig.routing.rules.add(0, V2rayConfig.RoutingBean.RulesBean( - type = "field", - outboundTag = AppConfig.TAG_AGENT, - port = "53", - ip = remoteDns, - domain = null) - ) + if (!domesticDns.first().startsWith("https")) { + v2rayConfig.routing.rules.add(0, V2rayConfig.RoutingBean.RulesBean( + type = "field", + outboundTag = AppConfig.TAG_DIRECT, + port = "53", + ip = arrayListOf(domesticDns.first()), + domain = null) + ) + } + if (!remoteDns.first().startsWith("https")) { + v2rayConfig.routing.rules.add(0, V2rayConfig.RoutingBean.RulesBean( + type = "field", + outboundTag = AppConfig.TAG_AGENT, + port = "53", + ip = arrayListOf(remoteDns.first()), + domain = null) + ) + } // DNS routing tag v2rayConfig.routing.rules.add(0, V2rayConfig.RoutingBean.RulesBean( type = "field", - inboundTag = arrayListOf("dns-in"), + inboundTag = arrayListOf("dns-in"), outboundTag = "dns-out", domain = null) ) @@ -598,15 +338,18 @@ object V2rayConfigUtil { /** * Custom Remote Dns */ - private fun customRemoteDns(vmess: VmessBean, v2rayConfig: V2rayConfig, app: AngApplication): Boolean { + private fun customRemoteDns(v2rayConfig: V2rayConfig, app: AngApplication): Boolean { try { val servers = ArrayList() + val hosts = mutableMapOf() Utils.getRemoteDnsServers(app.defaultDPreference).forEach { servers.add(it) } + // hardcode googleapi rule to fix play store problems + hosts.put("domain:googleapis.cn", "googleapis.com") - v2rayConfig.dns = V2rayConfig.DnsBean(servers = servers) + v2rayConfig.dns = V2rayConfig.DnsBean(servers = servers, hosts = hosts) } catch (e: Exception) { e.printStackTrace() return false @@ -618,92 +361,12 @@ object V2rayConfigUtil { * is valid config */ fun isValidConfig(conf: String): Boolean { - try { + return try { val jObj = JSONObject(conf) - var hasBound = false //hasBound = (jObj.has("outbounds") and jObj.has("inbounds")) or (jObj.has("outbound") and jObj.has("inbound")) - hasBound = (jObj.has("outbounds")) or (jObj.has("outbound")) - return hasBound + jObj.has("outbounds") or jObj.has("outbound") } catch (e: JSONException) { - return false + false } } - - private fun parseDomainNameAndTag(app: AngApplication, jsonConfig: String) { - try { - val jObj = JSONObject(jsonConfig) - var domainName = "" - val tags = LinkedHashSet() - if (jObj.has("outbound")) { - val (domain, tag) = parseDomainNameAndTag(jObj.optJSONObject("outbound")) - domainName = domain - if (!TextUtils.isEmpty(tag)) { - tags.add(tag) - } - } - if (jObj.has("outbounds")) { - for (i in 0..(jObj.optJSONArray("outbounds").length() - 1)) { - val (domain, tag) = parseDomainNameAndTag(jObj.optJSONArray("outbounds").getJSONObject(i)) - if (!TextUtils.isEmpty(domain) && TextUtils.isEmpty(domainName)) { - domainName = domain - } - if (!TextUtils.isEmpty(tag)) { - tags.add(tag) - } - } - } - if (jObj.has("outboundDetour")) { - for (i in 0..(jObj.optJSONArray("outboundDetour").length() - 1)) { - val (domain, tag) = parseDomainNameAndTag(jObj.optJSONArray("outboundDetour").getJSONObject(i)) - if (!TextUtils.isEmpty(domain) && TextUtils.isEmpty(domainName)) { - domainName = domain - } - if (!TextUtils.isEmpty(tag)) { - tags.add(tag) - } - } - } - if (!TextUtils.isEmpty(domainName)) { - app.defaultDPreference.setPrefString(AppConfig.PREF_CURR_CONFIG_DOMAIN, domainName) - } - app.defaultDPreference.setPrefStringOrderedSet(AppConfig.PREF_CURR_CONFIG_OUTBOUND_TAGS, tags) - } catch (e: Exception) { - e.printStackTrace() - } - } - - private fun parseDomainNameAndTag(outbound: JSONObject): Pair { - val tag = if (outbound.has("tag")) { - outbound.getString("tag") - } else { - "" - } - try { - if (outbound.has("settings")) { - val vnext: JSONArray? - if (outbound.optJSONObject("settings").has("vnext")) { - // vmess - vnext = outbound.optJSONObject("settings").optJSONArray("vnext") - } else if (outbound.optJSONObject("settings").has("servers")) { - // shadowsocks or socks - vnext = outbound.optJSONObject("settings").optJSONArray("servers") - } else { - return Pair("", tag) - } - for (i in 0..(vnext.length() - 1)) { - val item = vnext.getJSONObject(i) - val address = item.getString("address") - val port = item.getString("port") - if(Utils.isIpv6Address(address)) { - return Pair(String.format("[%s]:%s", address, port), tag) - } else { - return Pair(String.format("%s:%s", address, port), tag) - } - } - } - } catch (e: Exception) { - e.printStackTrace() - } - return Pair("", tag) - } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt index 1d0a35fc..605cc15c 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt @@ -8,18 +8,21 @@ import android.content.Context import android.content.Intent import android.content.IntentFilter import android.util.Log +import com.google.gson.Gson +import com.tencent.mmkv.MMKV import com.v2ray.ang.AngApplication import com.v2ray.ang.AppConfig import com.v2ray.ang.R -import com.v2ray.ang.dto.EConfigType import com.v2ray.ang.extension.toast -import com.v2ray.ang.util.AngConfigManager -import com.v2ray.ang.util.MessageUtil -import com.v2ray.ang.util.Utils -import com.v2ray.ang.util.V2rayConfigUtil +import com.v2ray.ang.util.* +import com.v2ray.ang.util.MmkvManager.KEY_ANG_CONFIGS import kotlinx.coroutines.* class MainViewModel(application: Application) : AndroidViewModel(application) { + private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } + private val serverAffStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SERVER_AFF, MMKV.MULTI_PROCESS_MODE) } + + val serverList by lazy { Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toList() } val isRunning by lazy { MutableLiveData() } val updateListAction by lazy { MutableLiveData() } val updateTestResultAction by lazy { MutableLiveData() } @@ -34,31 +37,37 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { override fun onCleared() { getApplication().unregisterReceiver(mMsgReceiver) + tcpingTestScope.coroutineContext[Job]?.cancelChildren() + Utils.closeAllTcpSockets() Log.i(AppConfig.ANG_PACKAGE, "Main ViewModel is cleared") super.onCleared() } + fun getGuid(index: Int): String? { + return serverList.getOrNull(index) + } + fun testAllTcping() { tcpingTestScope.coroutineContext[Job]?.cancelChildren() Utils.closeAllTcpSockets() - for (k in 0 until AngConfigManager.configs.vmess.count()) { - AngConfigManager.configs.vmess[k].testResult = "" - updateListAction.value = -1 // update all - } - for (k in 0 until AngConfigManager.configs.vmess.count()) { - var serverAddress = AngConfigManager.configs.vmess[k].address - var serverPort = AngConfigManager.configs.vmess[k].port - if (AngConfigManager.configs.vmess[k].configType == EConfigType.CUSTOM.value) { - val serverOutbound = V2rayConfigUtil.getCustomConfigServerOutbound(getApplication(), - AngConfigManager.configs.vmess[k].guid) ?: continue - serverAddress = serverOutbound.getServerAddress() ?: continue - serverPort = serverOutbound.getServerPort() ?: continue - } - tcpingTestScope.launch { - AngConfigManager.configs.vmess.getOrNull(k)?.let { // check null in case array is modified during testing - it.testResult = Utils.tcping(serverAddress, serverPort) - launch(Dispatchers.Main) { - updateListAction.value = k + MmkvManager.clearAllTestDelayResults() + updateListAction.value = -1 // update all + + getApplication().toast(R.string.connection_test_testing) + for (guid in serverList) { + MmkvManager.decodeServerConfig(guid)?.getProxyOutbound()?.let { outbound -> + val serverAddress = outbound.getServerAddress() + val serverPort = outbound.getServerPort() + if (serverAddress != null && serverPort != null) { + tcpingTestScope.launch { + val testResult = Utils.tcping(serverAddress, serverPort) + launch(Dispatchers.Main) { + MmkvManager.decodeServerAffiliationInfo(guid)?.let { aff -> + aff.testDelayMillis = testResult + serverAffStorage?.encode(guid, Gson().toJson(aff)) + updateListAction.value = serverList.indexOf(guid) + } + } } } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/SettingsViewModel.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/SettingsViewModel.kt index 95beb8cc..b2886046 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/SettingsViewModel.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/SettingsViewModel.kt @@ -6,8 +6,6 @@ import android.content.SharedPreferences import android.support.v7.preference.PreferenceManager import android.util.Log import com.v2ray.ang.AppConfig -import com.v2ray.ang.ui.SettingsActivity.Companion -import com.v2ray.ang.util.AngConfigManager import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch @@ -25,20 +23,17 @@ class SettingsViewModel(application: Application) : AndroidViewModel(application override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) { Log.d(AppConfig.ANG_PACKAGE, "Observe settings changed: $key") when(key) { - Companion.PREF_SNIFFING_ENABLED, - Companion.PREF_PROXY_SHARING, - Companion.PREF_LOCAL_DNS_ENABLED, - Companion.PREF_REMOTE_DNS, - Companion.PREF_DOMESTIC_DNS, - Companion.PREF_ROUTING_DOMAIN_STRATEGY, - Companion.PREF_ROUTING_MODE, + AppConfig.PREF_SNIFFING_ENABLED, + AppConfig.PREF_PROXY_SHARING, + AppConfig.PREF_LOCAL_DNS_ENABLED, + AppConfig.PREF_REMOTE_DNS, + AppConfig.PREF_DOMESTIC_DNS, + AppConfig.PREF_ROUTING_DOMAIN_STRATEGY, + AppConfig.PREF_ROUTING_MODE, AppConfig.PREF_V2RAY_ROUTING_AGENT, AppConfig.PREF_V2RAY_ROUTING_BLOCKED, AppConfig.PREF_V2RAY_ROUTING_DIRECT -> { GlobalScope.launch { - if (!AngConfigManager.genStoreV2rayConfig()) { - Log.d(AppConfig.ANG_PACKAGE, "$key changed but generate full configuration failed!") - } } } } diff --git a/V2rayNG/app/src/main/res/layout/activity_server2.xml b/V2rayNG/app/src/main/res/layout/activity_server_custom_config.xml similarity index 100% rename from V2rayNG/app/src/main/res/layout/activity_server2.xml rename to V2rayNG/app/src/main/res/layout/activity_server_custom_config.xml diff --git a/V2rayNG/app/src/main/res/layout/activity_server3.xml b/V2rayNG/app/src/main/res/layout/activity_server_shadowsocks.xml similarity index 100% rename from V2rayNG/app/src/main/res/layout/activity_server3.xml rename to V2rayNG/app/src/main/res/layout/activity_server_shadowsocks.xml diff --git a/V2rayNG/app/src/main/res/layout/activity_server4.xml b/V2rayNG/app/src/main/res/layout/activity_server_socks.xml similarity index 63% rename from V2rayNG/app/src/main/res/layout/activity_server4.xml rename to V2rayNG/app/src/main/res/layout/activity_server_socks.xml index 821d61ed..6658178d 100644 --- a/V2rayNG/app/src/main/res/layout/activity_server4.xml +++ b/V2rayNG/app/src/main/res/layout/activity_server_socks.xml @@ -80,11 +80,51 @@ + android:layout_width="match_parent" + android:layout_height="wrap_content" + android:layout_marginTop="@dimen/layout_margin_top_height" + android:orientation="vertical"> + + + + + + + + + + + + + + + + + + - \ No newline at end of file + diff --git a/V2rayNG/app/src/main/res/layout/activity_server.xml b/V2rayNG/app/src/main/res/layout/activity_server_vmess.xml similarity index 86% rename from V2rayNG/app/src/main/res/layout/activity_server.xml rename to V2rayNG/app/src/main/res/layout/activity_server_vmess.xml index 1630abc0..593cf334 100644 --- a/V2rayNG/app/src/main/res/layout/activity_server.xml +++ b/V2rayNG/app/src/main/res/layout/activity_server_vmess.xml @@ -143,15 +143,10 @@ android:orientation="vertical"> - - + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/server_lab_more_function" + android:textAppearance="@style/TextAppearance.AppCompat.Subhead" /> + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:text="@string/server_lab_network" /> + + + + + + + + + + + + + - \ No newline at end of file + diff --git a/V2rayNG/app/src/main/res/values/arrays.xml b/V2rayNG/app/src/main/res/values/arrays.xml index b75fae68..8965f0ac 100644 --- a/V2rayNG/app/src/main/res/values/arrays.xml +++ b/V2rayNG/app/src/main/res/values/arrays.xml @@ -53,6 +53,17 @@ tls + + + tls + xtls + + + + + true + false + 0 @@ -67,11 +78,29 @@ IPOnDemand + + debug + info + warning + error + none + + VPN Proxy only + + + xtls-rprx-origin + xtls-rprx-origin-udp443 + xtls-rprx-direct + xtls-rprx-direct-udp443 + xtls-rprx-splice + + + 0.0.0.0/5 From 375a209beb2405d6a52eeac298770d82b02588f3 Mon Sep 17 00:00:00 2001 From: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Date: Sun, 14 Feb 2021 18:54:51 -0500 Subject: [PATCH 2/6] Move main storage references to MMKV - Move current index to MMKV - Move ServiceManager to MMKV - Fix isRunning in ServerActivity - Drop support for VMESS qrcode v1 - Change all protocols importing --- .../kotlin/com/v2ray/ang/dto/ServerConfig.kt | 27 +- .../kotlin/com/v2ray/ang/dto/V2rayConfig.kt | 70 +- .../com/v2ray/ang/receiver/TaskerReceiver.kt | 8 +- .../com/v2ray/ang/service/QSTileService.kt | 2 +- .../v2ray/ang/service/V2RayServiceManager.kt | 32 +- .../com/v2ray/ang/service/V2RayVpnService.kt | 2 +- .../kotlin/com/v2ray/ang/ui/MainActivity.kt | 46 +- .../com/v2ray/ang/ui/MainRecyclerAdapter.kt | 66 +- .../kotlin/com/v2ray/ang/ui/ServerActivity.kt | 85 +-- .../ang/ui/ServerCustomConfigActivity.kt | 6 +- .../com/v2ray/ang/ui/SettingsActivity.kt | 4 +- .../kotlin/com/v2ray/ang/ui/TaskerActivity.kt | 15 +- .../com/v2ray/ang/util/AngConfigManager.kt | 679 ++++-------------- .../kotlin/com/v2ray/ang/util/MmkvManager.kt | 32 +- .../main/kotlin/com/v2ray/ang/util/Utils.kt | 29 +- .../com/v2ray/ang/util/V2rayConfigUtil.kt | 65 +- .../com/v2ray/ang/viewmodel/MainViewModel.kt | 29 +- 17 files changed, 463 insertions(+), 734 deletions(-) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt index eff2f0f8..5c2bdba4 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt @@ -1,9 +1,14 @@ package com.v2ray.ang.dto +import com.v2ray.ang.AppConfig.TAG_AGENT +import com.v2ray.ang.AppConfig.TAG_BLOCKED +import com.v2ray.ang.AppConfig.TAG_DIRECT +import com.v2ray.ang.util.Utils + data class ServerConfig( val configVersion: Int = 3, val configType: EConfigType, - val subscriptionId: String = "", + var subscriptionId: String = "", val addedTime: Long = System.currentTimeMillis(), var remarks: String = "", val outboundBean: V2rayConfig.OutboundBean? = null, @@ -48,4 +53,24 @@ data class ServerConfig( } return fullConfig?.getProxyOutbound() } + + fun getAllOutboundTags(): MutableList { + if (configType != EConfigType.CUSTOM) { + return mutableListOf(TAG_AGENT, TAG_DIRECT, TAG_BLOCKED) + } + fullConfig?.let { config -> + return config.outbounds.map { it.tag }.toMutableList() + } + return mutableListOf() + } + + fun getV2rayPointDomainAndPort(): String { + val address = getProxyOutbound()?.getServerAddress().orEmpty() + val port = getProxyOutbound()?.getServerPort() + return if (Utils.isIpv6Address(address)) { + String.format("[%s]:%s", address, port) + } else { + String.format("%s:%s", address, port) + } + } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt index bd37b416..e49dc15f 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt @@ -1,5 +1,7 @@ package com.v2ray.ang.dto +import android.text.TextUtils + data class V2rayConfig( val stats: Any? = null, val log: LogBean, @@ -112,7 +114,7 @@ data class V2rayConfig( var readBufferSize: Int = 1, var writeBufferSize: Int = 1, var header: HeaderBean = HeaderBean(), - var seed: String? = "") { + var seed: String? = null) { data class HeaderBean(var type: String = "none") } @@ -132,6 +134,72 @@ data class V2rayConfig( var header: HeaderBean = HeaderBean()) { data class HeaderBean(var type: String = "none") } + + fun populateTransportSettings(transport: String, headerType: String?, host: String?, path: String?, seed: String?, + quicSecurity: String?, key: String?): String { + var sni = "" + network = transport + when (network) { + "tcp" -> if (headerType == HTTP) { + val tcpSetting = TcpSettingsBean() + tcpSetting.header.type = HTTP + if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(path)) { + val requestObj = TcpSettingsBean.HeaderBean.RequestBean() + requestObj.headers.Host = (host ?: "").split(",").map { it.trim() } + requestObj.path = (path ?: "").split(",").map { it.trim() } + tcpSetting.header.request = requestObj + sni = requestObj.headers.Host.getOrNull(0) ?: sni + } + tcpSettings = tcpSetting + } + "kcp" -> { + val kcpsetting = KcpSettingsBean() + kcpsetting.header.type = headerType ?: "none" + if (seed.isNullOrEmpty()) { + kcpsetting.seed = null + } else { + kcpsetting.seed = seed + } + kcpSettings = kcpsetting + } + "ws" -> { + val wssetting = WsSettingsBean() + wssetting.headers.Host = host ?: "" + sni = wssetting.headers.Host + wssetting.path = path ?: "/" + wsSettings = wssetting + } + "h2", "http" -> { + network = "h2" + val h2Setting = HttpSettingsBean() + h2Setting.host = (host ?: "").split(",").map { it.trim() } + sni = h2Setting.host.getOrNull(0) ?: sni + h2Setting.path = path ?: "/" + httpSettings = h2Setting + } + "quic" -> { + val quicsetting = QuicSettingBean() + quicsetting.security = quicSecurity ?: "none" + quicsetting.key = key ?: "" + quicsetting.header.type = headerType ?: "none" + quicSettings = quicsetting + } + } + return sni + } + + fun populateTlsSettings(streamSecurity: String, allowInsecure: Boolean, sni: String) { + security = streamSecurity + val tlsSetting = TlsSettingsBean( + allowInsecure = allowInsecure, + serverName = sni + ) + if (security == TLS) { + tlsSettings = tlsSetting + } else if (security == XTLS) { + xtlsSettings = tlsSetting + } + } } data class MuxBean(var enabled: Boolean, var concurrency: Int = 8) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/receiver/TaskerReceiver.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/receiver/TaskerReceiver.kt index 74f69416..08a3184a 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/receiver/TaskerReceiver.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/receiver/TaskerReceiver.kt @@ -5,11 +5,16 @@ import android.content.Context import android.content.Intent import android.text.TextUtils import com.google.zxing.WriterException +import com.tencent.mmkv.MMKV import com.v2ray.ang.AppConfig +import com.v2ray.ang.service.V2RayServiceManager +import com.v2ray.ang.util.MmkvManager import com.v2ray.ang.util.Utils class TaskerReceiver : BroadcastReceiver() { + private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } + override fun onReceive(context: Context, intent: Intent?) { try { @@ -23,7 +28,8 @@ class TaskerReceiver : BroadcastReceiver() { if (guid == AppConfig.TASKER_DEFAULT_GUID) { Utils.startVServiceFromToggle(context) } else { - Utils.startVService(context, guid) + mainStorage?.encode(MmkvManager.KEY_SELECTED_SERVER, guid) + V2RayServiceManager.startV2Ray(context) } } else { Utils.stopVService(context) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt index 72994f10..b7e07e91 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt @@ -25,7 +25,7 @@ class QSTileService : TileService() { qsTile?.icon = Icon.createWithResource(applicationContext, R.drawable.ic_v_idle) } else if (state == Tile.STATE_ACTIVE) { qsTile?.state = Tile.STATE_ACTIVE - qsTile?.label = V2RayServiceManager.currentConfigName + qsTile?.label = V2RayServiceManager.currentConfig?.remarks qsTile?.icon = Icon.createWithResource(applicationContext, R.drawable.ic_v) } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt index 0f8b05fb..b5fce5ce 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt @@ -13,16 +13,20 @@ import android.os.Build import android.support.annotation.RequiresApi import android.support.v4.app.NotificationCompat import android.util.Log +import com.tencent.mmkv.MMKV import com.v2ray.ang.AppConfig import com.v2ray.ang.AppConfig.TAG_DIRECT import com.v2ray.ang.R +import com.v2ray.ang.dto.ServerConfig import com.v2ray.ang.extension.defaultDPreference import com.v2ray.ang.extension.toSpeedString import com.v2ray.ang.extension.toast import com.v2ray.ang.extension.v2RayApplication import com.v2ray.ang.ui.MainActivity import com.v2ray.ang.util.MessageUtil +import com.v2ray.ang.util.MmkvManager import com.v2ray.ang.util.Utils +import com.v2ray.ang.util.V2rayConfigUtil import go.Seq import libv2ray.Libv2ray import libv2ray.V2RayPoint @@ -40,6 +44,7 @@ object V2RayServiceManager { val v2rayPoint: V2RayPoint = Libv2ray.newV2RayPoint(V2RayCallback()) private val mMsgReceive = ReceiveMessageHandler() + private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } var serviceControl: SoftReference? = null set(value) { @@ -51,7 +56,7 @@ object V2RayServiceManager { Seq.setContext(context) } } - var currentConfigName = "NG" + var currentConfig: ServerConfig? = null private var lastQueryTime = 0L private var mBuilder: NotificationCompat.Builder? = null @@ -122,7 +127,12 @@ object V2RayServiceManager { fun startV2rayPoint() { val service = serviceControl?.get()?.getService() ?: return + val guid = mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER) ?: return + val config = MmkvManager.decodeServerConfig(guid) ?: return if (!v2rayPoint.isRunning) { + val result = V2rayConfigUtil.getV2rayConfig(service, guid) + if (!result.status) + return try { val mFilter = IntentFilter(AppConfig.BROADCAST_ACTION_SERVICE) @@ -134,12 +144,12 @@ object V2RayServiceManager { Log.d(service.packageName, e.toString()) } - v2rayPoint.configureFileContent = service.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG, "") + v2rayPoint.configureFileContent = result.content + v2rayPoint.domainName = config.getV2rayPointDomainAndPort() + currentConfig = config v2rayPoint.enableLocalDNS = service.defaultDPreference.getPrefBoolean(AppConfig.PREF_LOCAL_DNS_ENABLED, false) v2rayPoint.forwardIpv6 = service.defaultDPreference.getPrefBoolean(AppConfig.PREF_FORWARD_IPV6, false) - v2rayPoint.domainName = service.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG_DOMAIN, "") v2rayPoint.proxyOnly = service.defaultDPreference.getPrefString(AppConfig.PREF_MODE, "VPN") != "VPN" - currentConfigName = service.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG_NAME, "NG") try { v2rayPoint.runLoop() @@ -243,7 +253,7 @@ object V2RayServiceManager { mBuilder = NotificationCompat.Builder(service, channelId) .setSmallIcon(R.drawable.ic_v) - .setContentTitle(currentConfigName) + .setContentTitle(currentConfig?.remarks) .setPriority(NotificationCompat.PRIORITY_MIN) .setOngoing(true) .setShowWhen(false) @@ -280,7 +290,7 @@ object V2RayServiceManager { mSubscription = null } - private fun updateNotification(contentText: String, proxyTraffic: Long, directTraffic: Long) { + private fun updateNotification(contentText: String?, proxyTraffic: Long, directTraffic: Long) { if (mBuilder != null) { if (proxyTraffic < NOTIFICATION_ICON_THRESHOLD && directTraffic < NOTIFICATION_ICON_THRESHOLD) { mBuilder?.setSmallIcon(R.drawable.ic_v) @@ -309,8 +319,8 @@ object V2RayServiceManager { v2rayPoint.isRunning && service.defaultDPreference.getPrefBoolean(AppConfig.PREF_SPEED_ENABLED, false)) { var lastZeroSpeed = false - val outboundTags = service.defaultDPreference.getPrefStringOrderedSet(AppConfig.PREF_CURR_CONFIG_OUTBOUND_TAGS, LinkedHashSet()) - outboundTags.remove(TAG_DIRECT) + val outboundTags = currentConfig?.getAllOutboundTags() + outboundTags?.remove(TAG_DIRECT) mSubscription = Observable.interval(3, java.util.concurrent.TimeUnit.SECONDS) .subscribe { @@ -318,7 +328,7 @@ object V2RayServiceManager { val sinceLastQueryInSeconds = (queryTime - lastQueryTime) / 1000.0 var proxyTotal = 0L val text = StringBuilder() - outboundTags.forEach { + outboundTags?.forEach { val up = v2rayPoint.queryStats(it, "uplink") val down = v2rayPoint.queryStats(it, "downlink") if (up + down > 0) { @@ -331,7 +341,7 @@ object V2RayServiceManager { val zeroSpeed = (proxyTotal == 0L && directUplink == 0L && directDownlink == 0L) if (!zeroSpeed || !lastZeroSpeed) { if (proxyTotal == 0L) { - appendSpeedString(text, outboundTags.firstOrNull(), 0.0, 0.0) + appendSpeedString(text, outboundTags?.firstOrNull(), 0.0, 0.0) } appendSpeedString(text, TAG_DIRECT, directUplink / sinceLastQueryInSeconds, directDownlink / sinceLastQueryInSeconds) @@ -357,7 +367,7 @@ object V2RayServiceManager { if (mSubscription != null) { mSubscription?.unsubscribe() //stop queryStats mSubscription = null - updateNotification(currentConfigName, 0, 0) + updateNotification(currentConfig?.remarks, 0, 0) } } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt index 181b6c43..dc92d15f 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt @@ -126,7 +126,7 @@ class V2RayVpnService : VpnService(), ServiceControl { } } - builder.setSession(V2RayServiceManager.currentConfigName) + builder.setSession(V2RayServiceManager.currentConfig?.remarks.orEmpty()) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && defaultDPreference.getPrefBoolean(AppConfig.PREF_PER_APP_PROXY, false)) { diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt index db93eae4..54ae616c 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt @@ -17,6 +17,7 @@ import android.view.KeyEvent import android.view.Menu import android.view.MenuItem import com.tbruyelle.rxpermissions.RxPermissions +import com.tencent.mmkv.MMKV import com.v2ray.ang.AppConfig import com.v2ray.ang.BuildConfig import com.v2ray.ang.R @@ -24,7 +25,9 @@ import com.v2ray.ang.dto.EConfigType import com.v2ray.ang.extension.defaultDPreference import com.v2ray.ang.extension.toast import com.v2ray.ang.helper.SimpleItemTouchHelperCallback +import com.v2ray.ang.service.V2RayServiceManager import com.v2ray.ang.util.AngConfigManager +import com.v2ray.ang.util.MmkvManager import com.v2ray.ang.util.Utils import com.v2ray.ang.util.V2rayConfigUtil import com.v2ray.ang.viewmodel.MainViewModel @@ -47,6 +50,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList } private val adapter by lazy { MainRecyclerAdapter(this) } + private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } private var mItemTouchHelper: ItemTouchHelper? = null val mainViewModel: MainViewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) } @@ -110,7 +114,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList mainViewModel.updateTestResultAction.observe(this, { tv_test_state.text = it }) mainViewModel.isRunning.observe(this, { val isRunning = it ?: return@observe - adapter.changeable = !isRunning + adapter.isRunning = isRunning if (isRunning) { fab.setImageResource(R.drawable.ic_v) tv_test_state.text = getString(R.string.connection_connected) @@ -126,19 +130,18 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList } fun startV2Ray() { - if (AngConfigManager.configs.index < 0) { + if (mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER).isNullOrEmpty()) { return } showCircle() // toast(R.string.toast_services_start) - if (!Utils.startVService(this, AngConfigManager.configs.index)) { - hideCircle() - } + V2RayServiceManager.startV2Ray(this) + hideCircle() } public override fun onResume() { super.onResume() - adapter.notifyDataSetChanged() + mainViewModel.reloadServerList() } public override fun onPause() { @@ -437,9 +440,8 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList .subscribe { if (it) { try { - contentResolver.openInputStream(uri).use { - val configText = it?.bufferedReader()?.readText() - importCustomizeConfig(configText) + contentResolver.openInputStream(uri).use { input -> + importCustomizeConfig(input?.bufferedReader()?.readText()) } } catch (e: Exception) { e.printStackTrace() @@ -453,19 +455,21 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList * import customize config */ fun importCustomizeConfig(server: String?) { - if (server == null) { - return - } - if (!V2rayConfigUtil.isValidConfig(server)) { - toast(R.string.toast_config_file_invalid) - return - } - val resId = AngConfigManager.importCustomizeConfig(server) - if (resId > 0) { - toast(resId) - } else { + try { + if (server == null || TextUtils.isEmpty(server)) { + toast(R.string.toast_none_data) + return + } + if (!V2rayConfigUtil.isValidConfig(server)) { + toast(R.string.toast_config_file_invalid) + return + } + mainViewModel.appendCustomConfigServer(server) toast(R.string.toast_success) - adapter.notifyDataSetChanged() + adapter.notifyItemInserted(mainViewModel.serverList.lastIndex) + } catch (e: Exception) { + e.printStackTrace() + return } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt index 55f3cb3a..8b780206 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt @@ -15,6 +15,7 @@ import com.v2ray.ang.dto.EConfigType import com.v2ray.ang.extension.toast import com.v2ray.ang.helper.ItemTouchHelperAdapter import com.v2ray.ang.helper.ItemTouchHelperViewHolder +import com.v2ray.ang.service.V2RayServiceManager import com.v2ray.ang.util.AngConfigManager import com.v2ray.ang.util.MmkvManager import com.v2ray.ang.util.Utils @@ -36,20 +37,13 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter by lazy { mActivity.resources.getStringArray(R.array.share_method) } - - var changeable: Boolean = true - set(value) { - if (field == value) - return - field = value - notifyDataSetChanged() - } + var isRunning = false override fun getItemCount() = mActivity.mainViewModel.serverList.size override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { if (holder is MainViewHolder) { - val guid = mActivity.mainViewModel.getGuid(position) ?: return + val guid = mActivity.mainViewModel.serverList.getOrNull(position) ?: return val config = MmkvManager.decodeServerConfig(guid) ?: return val outbound = config.getProxyOutbound() ?: return val aff = MmkvManager.decodeServerAffiliationInfo(guid) @@ -59,7 +53,7 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter { if (config.configType == EConfigType.CUSTOM) { - shareFullContent(position) + shareFullContent(guid) } else { val iv = LayoutInflater.from(mActivity).inflate(R.layout.item_qrcode, null) iv.iv_qcode.setImageBitmap(AngConfigManager.share2QRCode(guid)) @@ -97,7 +91,7 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter shareFullContent(position) + 2 -> shareFullContent(guid) else -> mActivity.toast("else") } } catch (e: Exception) { @@ -108,6 +102,7 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter if (headerType == HTTP) { - val tcpSetting = V2rayConfig.OutboundBean.StreamSettingsBean.TcpSettingsBean() - tcpSetting.header.type = headerType - if (!TextUtils.isEmpty(requestHost) || !TextUtils.isEmpty(path)) { - val requestObj = V2rayConfig.OutboundBean.StreamSettingsBean.TcpSettingsBean.HeaderBean.RequestBean() - requestObj.headers.Host = requestHost.split(",").map { it.trim() } - requestObj.path = path.split(",").map { it.trim() } - tcpSetting.header.request = requestObj - sni = requestObj.headers.Host.getOrNull(0) ?: sni - } - streamSetting.tcpSettings = tcpSetting - } - "kcp" -> { - val kcpsetting = V2rayConfig.OutboundBean.StreamSettingsBean.KcpSettingsBean() - kcpsetting.header.type = headerType - if (TextUtils.isEmpty(path)) { - kcpsetting.seed = null - } else { - kcpsetting.seed = path - } - streamSetting.kcpSettings = kcpsetting - } - "ws" -> { - val wssetting = V2rayConfig.OutboundBean.StreamSettingsBean.WsSettingsBean() - if (!TextUtils.isEmpty(requestHost)) { - wssetting.headers.Host = requestHost - sni = requestHost - } - if (!TextUtils.isEmpty(path)) { - wssetting.path = path - } - streamSetting.wsSettings = wssetting - } - "h2" -> { - val h2Setting = V2rayConfig.OutboundBean.StreamSettingsBean.HttpSettingsBean() - if (!TextUtils.isEmpty(requestHost)) { - h2Setting.host = requestHost.split(",").map { it.trim() } - sni = h2Setting.host.getOrNull(0) ?: sni - } - h2Setting.path = path - streamSetting.httpSettings = h2Setting - } - "quic" -> { - val quicsetting = V2rayConfig.OutboundBean.StreamSettingsBean.QuicSettingBean() - quicsetting.security = requestHost - quicsetting.key = path - quicsetting.header.type = headerType - streamSetting.quicSettings = quicsetting - } - } - - streamSetting.security = if (sp_stream_security != null) streamSecuritys[sp_stream_security.selectedItemPosition] else TLS - val tlsSetting = V2rayConfig.OutboundBean.StreamSettingsBean.TlsSettingsBean( - allowInsecure = if (sp_allow_insecure != null) allowinsecures[sp_allow_insecure.selectedItemPosition].toBoolean() else false, - serverName = sni + var sni = streamSetting.populateTransportSettings( + if (sp_network != null) networks[sp_network.selectedItemPosition] else DEFAULT_NETWORK, + if (sp_header_type != null) headertypes[sp_header_type.selectedItemPosition] else "", + requestHost, + path, + path, + requestHost, + path ) - if (streamSetting.security == TLS) { - streamSetting.tlsSettings = tlsSetting - } else if (streamSetting.security == XTLS) { - streamSetting.xtlsSettings = tlsSetting + if (sni.isEmpty()) { + sni = requestHost } + streamSetting.populateTlsSettings( + if (sp_stream_security != null) streamSecuritys[sp_stream_security.selectedItemPosition] else TLS, + if (sp_allow_insecure != null) allowinsecures[sp_allow_insecure.selectedItemPosition].toBoolean() else false, + sni + ) } /** diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt index a5c604c5..7205bedd 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt @@ -21,7 +21,11 @@ class ServerCustomConfigActivity : BaseActivity() { private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } private val editGuid by lazy { intent.getStringExtra("guid").orEmpty() } - private val isRunning by lazy { editGuid.isNotEmpty() && editGuid == mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER) } + private val isRunning by lazy { + intent.getBooleanExtra("isRunning", false) + && editGuid.isNotEmpty() + && editGuid == mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER) + } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SettingsActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SettingsActivity.kt index 39dd03a8..c374b3b8 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SettingsActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SettingsActivity.kt @@ -8,7 +8,7 @@ import android.view.View import com.v2ray.ang.R import com.v2ray.ang.AppConfig import com.v2ray.ang.extension.toast -import com.v2ray.ang.util.AngConfigManager +import com.v2ray.ang.service.V2RayServiceManager import com.v2ray.ang.util.Utils import com.v2ray.ang.viewmodel.SettingsViewModel @@ -56,7 +56,7 @@ class SettingsActivity : BaseActivity() { private fun restartProxy() { Utils.stopVService(requireContext()) - Utils.startVService(requireContext(), AngConfigManager.configs.index) + V2RayServiceManager.startV2Ray(requireContext()) } private fun isRunning(): Boolean { diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/TaskerActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/TaskerActivity.kt index fac81876..b27f047b 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/TaskerActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/TaskerActivity.kt @@ -7,21 +7,23 @@ import android.widget.ArrayAdapter import android.widget.ListView import java.util.ArrayList import com.v2ray.ang.R -import com.v2ray.ang.util.AngConfigManager import android.content.Intent import android.text.TextUtils import android.view.Menu import android.view.MenuItem import com.google.zxing.WriterException +import com.tencent.mmkv.MMKV import com.v2ray.ang.AppConfig +import com.v2ray.ang.util.MmkvManager import kotlinx.android.synthetic.main.activity_tasker.* - class TaskerActivity : BaseActivity() { private var listview: ListView? = null private var lstData: ArrayList = ArrayList() private var lstGuid: ArrayList = ArrayList() + private val serverStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SERVER_CONFIG, MMKV.MULTI_PROCESS_MODE) } + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tasker) @@ -30,9 +32,11 @@ class TaskerActivity : BaseActivity() { lstData.add("Default") lstGuid.add(AppConfig.TASKER_DEFAULT_GUID) - AngConfigManager.configs.vmess.forEach { - lstData.add(it.remarks) - lstGuid.add(it.guid) + serverStorage?.allKeys()?.forEach { key -> + MmkvManager.decodeServerConfig(key)?.let { config -> + lstData.add(config.remarks) + lstGuid.add(key) + } } val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_single_choice, lstData) @@ -108,4 +112,3 @@ class TaskerActivity : BaseActivity() { } } - diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt index b4818f81..4e46a307 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt @@ -3,13 +3,16 @@ package com.v2ray.ang.util import android.graphics.Bitmap import android.text.TextUtils import com.google.gson.Gson +import com.tencent.mmkv.MMKV import com.v2ray.ang.AngApplication import com.v2ray.ang.AppConfig.ANG_CONFIG import com.v2ray.ang.AppConfig.HTTPS_PROTOCOL import com.v2ray.ang.AppConfig.HTTP_PROTOCOL import com.v2ray.ang.R import com.v2ray.ang.dto.* +import com.v2ray.ang.dto.V2rayConfig.Companion.DEFAULT_SECURITY import com.v2ray.ang.dto.V2rayConfig.Companion.TLS +import com.v2ray.ang.util.MmkvManager.KEY_SELECTED_SERVER import java.net.URI import java.net.URLDecoder import java.util.* @@ -18,18 +21,17 @@ object AngConfigManager { private lateinit var app: AngApplication private lateinit var angConfig: AngConfig val configs: AngConfig get() = angConfig + private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } fun inject(app: AngApplication) { this.app = app - if (app.firstRun) { - } loadConfig() } /** * loading config */ - fun loadConfig() { + private fun loadConfig() { try { val context = app.defaultDPreference.getPrefString(ANG_CONFIG, "") if (!TextUtils.isEmpty(context)) { @@ -54,115 +56,6 @@ object AngConfigManager { } } - /** - * add or edit server - */ - fun addServer(vmess: AngConfig.VmessBean, index: Int): Int { - try { - vmess.configVersion = 2 - vmess.configType = EConfigType.VMESS.value - - vmess.address = vmess.address.trim() - vmess.id = vmess.id.trim() - vmess.security = vmess.security.trim() - vmess.network = vmess.network.trim() - vmess.headerType = vmess.headerType.trim() - vmess.requestHost = vmess.requestHost.trim() - vmess.path = vmess.path.trim() - vmess.streamSecurity = vmess.streamSecurity.trim() - - if (index >= 0) { - //edit - angConfig.vmess[index] = vmess - } else { - //add - vmess.guid = Utils.getUuid() - angConfig.vmess.add(vmess) - if (angConfig.vmess.count() == 1) { - angConfig.index = 0 - } - } - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - - /** - * 移除服务器 - */ - fun removeServer(index: Int): Int { - try { - if (index < 0 || index > angConfig.vmess.count() - 1) { - return -1 - } - - //删除 - angConfig.vmess.removeAt(index) - - //移除的是活动的 - adjustIndexForRemovalAt(index) - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - - private fun adjustIndexForRemovalAt(index: Int) { - if (angConfig.index == index) { - if (angConfig.vmess.count() > 0) { - angConfig.index = 0 - } else { - angConfig.index = -1 - } - } else if (index < angConfig.index)//移除活动之前的 - { - angConfig.index-- - } - } - - fun swapServer(fromPosition: Int, toPosition: Int): Int { - try { - Collections.swap(angConfig.vmess, fromPosition, toPosition) - - val index = angConfig.index - if (index == fromPosition) { - angConfig.index = toPosition - } else if (index == toPosition) { - angConfig.index = fromPosition - } - //storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - - /** - * set active server - */ - fun setActiveServer(index: Int): Int { - try { - if (index < 0 || index > angConfig.vmess.count() - 1) { - return -1 - } - angConfig.index = index - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - /** * store config to file */ @@ -178,73 +71,65 @@ object AngConfigManager { /** * import config form qrcode or... */ - fun importConfig(server: String?, subid: String, removedSelectedServer: AngConfig.VmessBean?): Int { + private fun importConfig(str: String?, subid: String, removedSelectedServer: ServerConfig?): Int { try { - if (server == null || TextUtils.isEmpty(server)) { + if (str == null || TextUtils.isEmpty(str)) { return R.string.toast_none_data } //maybe sub - if (server.startsWith(HTTP_PROTOCOL) || server.startsWith(HTTPS_PROTOCOL)) { - addSubItem(server) + if (str.startsWith(HTTP_PROTOCOL) || str.startsWith(HTTPS_PROTOCOL)) { + addSubItem(str) return 0 } - var vmess = AngConfig.VmessBean() + var config: ServerConfig? = null + val allowInsecure = false//app.defaultDPreference.getPrefBoolean(AppConfig.PREF_ALLOW_INSECURE, false) + if (str.startsWith(EConfigType.VMESS.protocolScheme)) { + config = ServerConfig.create(EConfigType.VMESS) + val streamSetting = config.outboundBean?.streamSettings ?: return -1 - if (server.startsWith(EConfigType.VMESS.protocolScheme)) { + if (!tryParseNewVmess(str, config, allowInsecure)) { + if (str.indexOf("?") > 0) { + if (!tryResolveVmess4Kitsunebi(str, config)) { + return R.string.toast_incorrect_protocol + } + } else { + var result = str.replace(EConfigType.VMESS.protocolScheme, "") + result = Utils.decode(result) + if (TextUtils.isEmpty(result)) { + return R.string.toast_decoding_failed + } + val vmessQRCode = Gson().fromJson(result, VmessQRCode::class.java) + if (TextUtils.isEmpty(vmessQRCode.add) + || TextUtils.isEmpty(vmessQRCode.port) + || TextUtils.isEmpty(vmessQRCode.id) + || TextUtils.isEmpty(vmessQRCode.aid) + || TextUtils.isEmpty(vmessQRCode.net) + ) { + return R.string.toast_incorrect_protocol + } - val indexSplit = server.indexOf("?") - val newVmess = tryParseNewVmess(server) - if (newVmess != null) { - vmess = newVmess - vmess.subid = subid - } else if (indexSplit > 0) { - vmess = ResolveVmess4Kitsunebi(server) - } else { - - var result = server.replace(EConfigType.VMESS.protocolScheme, "") - result = Utils.decode(result) - if (TextUtils.isEmpty(result)) { - return R.string.toast_decoding_failed + config.remarks = vmessQRCode.ps + config.outboundBean?.settings?.vnext?.get(0)?.let { vnext -> + vnext.address = vmessQRCode.add + vnext.port = Utils.parseInt(vmessQRCode.port) + vnext.users[0].id = vmessQRCode.id + vnext.users[0].encryption = DEFAULT_SECURITY + vnext.users[0].alterId = Utils.parseInt(vmessQRCode.aid) + } + val sni = streamSetting.populateTransportSettings(vmessQRCode.net, vmessQRCode.type, vmessQRCode.host, + vmessQRCode.path, vmessQRCode.path, vmessQRCode.host, vmessQRCode.path) + streamSetting.populateTlsSettings(vmessQRCode.tls, allowInsecure, sni) } - val vmessQRCode = Gson().fromJson(result, VmessQRCode::class.java) - if (TextUtils.isEmpty(vmessQRCode.add) - || TextUtils.isEmpty(vmessQRCode.port) - || TextUtils.isEmpty(vmessQRCode.id) - || TextUtils.isEmpty(vmessQRCode.aid) - || TextUtils.isEmpty(vmessQRCode.net) - ) { - return R.string.toast_incorrect_protocol - } - - vmess.configType = EConfigType.VMESS.value - vmess.security = "auto" - vmess.network = "tcp" - vmess.headerType = "none" - - vmess.configVersion = Utils.parseInt(vmessQRCode.v) - vmess.remarks = vmessQRCode.ps - vmess.address = vmessQRCode.add - vmess.port = Utils.parseInt(vmessQRCode.port) - vmess.id = vmessQRCode.id - vmess.alterId = Utils.parseInt(vmessQRCode.aid) - vmess.network = vmessQRCode.net - vmess.headerType = vmessQRCode.type - vmess.requestHost = vmessQRCode.host - vmess.path = vmessQRCode.path - vmess.streamSecurity = vmessQRCode.tls - vmess.subid = subid } - upgradeServerVersion(vmess) - addServer(vmess, -1) - - } else if (server.startsWith(EConfigType.SHADOWSOCKS.protocolScheme)) { - var result = server.replace(EConfigType.SHADOWSOCKS.protocolScheme, "") + } else if (str.startsWith(EConfigType.SHADOWSOCKS.protocolScheme)) { + var result = str.replace(EConfigType.SHADOWSOCKS.protocolScheme, "") val indexSplit = result.indexOf("#") + config = ServerConfig.create(EConfigType.SHADOWSOCKS) if (indexSplit > 0) { try { - vmess.remarks = Utils.urlDecode(result.substring(indexSplit + 1, result.length)) + config.remarks = Utils.urlDecode(result.substring(indexSplit + 1, result.length)) } catch (e: Exception) { e.printStackTrace() } @@ -254,32 +139,28 @@ object AngConfigManager { //part decode val indexS = result.indexOf("@") - if (indexS > 0) { - result = Utils.decode(result.substring(0, indexS)) + result.substring(indexS, result.length) + result = if (indexS > 0) { + Utils.decode(result.substring(0, indexS)) + result.substring(indexS, result.length) } else { - result = Utils.decode(result) + Utils.decode(result) } val legacyPattern = "^(.+?):(.*)@(.+?):(\\d+?)/?$".toRegex() - val match = legacyPattern.matchEntire(result) - if (match == null) { - return R.string.toast_incorrect_protocol - } - vmess.security = match.groupValues[1].toLowerCase() - vmess.id = match.groupValues[2] - vmess.address = match.groupValues[3] - if (vmess.address.firstOrNull() == '[' && vmess.address.lastOrNull() == ']') - vmess.address = vmess.address.substring(1, vmess.address.length - 1) - vmess.port = match.groupValues[4].toInt() - vmess.subid = subid + val match = legacyPattern.matchEntire(result) ?: return R.string.toast_incorrect_protocol - addShadowsocksServer(vmess, -1) - } else if (server.startsWith(EConfigType.SOCKS.protocolScheme)) { - var result = server.replace(EConfigType.SOCKS.protocolScheme, "") + config.outboundBean?.settings?.servers?.get(0)?.let { server -> + server.address = match.groupValues[3].removeSurrounding("[", "]") + server.port = match.groupValues[4].toInt() + server.password = match.groupValues[2] + server.method = match.groupValues[1].toLowerCase() + } + } else if (str.startsWith(EConfigType.SOCKS.protocolScheme)) { + var result = str.replace(EConfigType.SOCKS.protocolScheme, "") val indexSplit = result.indexOf("#") + config = ServerConfig.create(EConfigType.SOCKS) if (indexSplit > 0) { try { - vmess.remarks = Utils.urlDecode(result.substring(indexSplit + 1, result.length)) + config.remarks = Utils.urlDecode(result.substring(indexSplit + 1, result.length)) } catch (e: Exception) { e.printStackTrace() } @@ -296,88 +177,58 @@ object AngConfigManager { } val legacyPattern = "^(.*):(.*)@(.+?):(\\d+?)$".toRegex() - val match = legacyPattern.matchEntire(result) - if (match == null) { - return R.string.toast_incorrect_protocol + val match = legacyPattern.matchEntire(result) ?: return R.string.toast_incorrect_protocol + + config.outboundBean?.settings?.servers?.get(0)?.let { server -> + server.address = match.groupValues[3].removeSurrounding("[", "]") + server.port = match.groupValues[4].toInt() + val socksUsersBean = V2rayConfig.OutboundBean.OutSettingsBean.ServersBean.SocksUsersBean() + socksUsersBean.user = match.groupValues[1].toLowerCase() + socksUsersBean.pass = match.groupValues[2] + server.users = listOf(socksUsersBean) } - vmess.security = match.groupValues[1].toLowerCase() - vmess.id = match.groupValues[2] - vmess.address = match.groupValues[3] - if (vmess.address.firstOrNull() == '[' && vmess.address.lastOrNull() == ']') - vmess.address = vmess.address.substring(1, vmess.address.length - 1) - vmess.port = match.groupValues[4].toInt() - vmess.subid = subid - - addSocksServer(vmess, -1) - - } else if (server.startsWith(EConfigType.TROJAN.protocolScheme)) { - val uri = URI(server) - - vmess.address = uri.host - vmess.port = uri.port - vmess.id = uri.userInfo - vmess.remarks = uri.fragment ?: "" - vmess.subid = subid - if (!TextUtils.isEmpty((uri.rawQuery))) { - val queryParam = uri.rawQuery.split("&") - .map { it.split("=").let { (k, v) -> k to URLDecoder.decode(v, "utf-8")!! } } - .toMap() - vmess.requestHost = queryParam["sni"] ?: "" + } else if (str.startsWith(EConfigType.TROJAN.protocolScheme)) { + val uri = URI(str) + config = ServerConfig.create(EConfigType.TROJAN) + config.remarks = uri.fragment ?: "" + config.outboundBean?.settings?.servers?.get(0)?.let { server -> + server.address = uri.host + server.port = uri.port + server.password = uri.userInfo } - - addTrojanServer(vmess, -1) - - } else if (server.startsWith(EConfigType.VLESS.protocolScheme)) { - val uri = URI(server) - - vmess.address = uri.host - vmess.port = uri.port - vmess.id = uri.userInfo - vmess.remarks = uri.fragment ?: "" - vmess.subid = subid - val queryParam = uri.rawQuery.split("&") .map { it.split("=").let { (k, v) -> k to URLDecoder.decode(v, "utf-8")!! } } .toMap() - - //vmess.flow = queryParam["flow"] ?: "" - vmess.security = queryParam["encryption"] ?: "none" - vmess.streamSecurity = queryParam["security"] ?: "" - vmess.network = queryParam["type"] ?: "tcp" - when (vmess.network) { - "tcp" -> { - vmess.headerType = queryParam["headerType"] ?: "none" - vmess.requestHost = queryParam["host"] ?: "" - } - "h2", - "http" -> { - vmess.network = "h2" - vmess.requestHost = queryParam["host"] ?: "" - vmess.path = queryParam["path"] ?: "/" - } - "ws" -> { - vmess.requestHost = queryParam["host"] ?: "" - vmess.path = queryParam["path"] ?: "/" - } - "kcp" -> { - vmess.headerType = queryParam["headerType"] ?: "none" - vmess.path = queryParam["seed"] ?: "" - } - "quic" -> { - vmess.headerType = queryParam["headerType"] ?: "none" - vmess.requestHost = queryParam["quicSecurity"] ?: "none" - vmess.path = queryParam["key"] ?: "" - } + config.outboundBean?.streamSettings?.populateTlsSettings(TLS, allowInsecure, queryParam["sni"] ?: "") + } else if (str.startsWith(EConfigType.VLESS.protocolScheme)) { + val uri = URI(str) + val queryParam = uri.rawQuery.split("&") + .map { it.split("=").let { (k, v) -> k to URLDecoder.decode(v, "utf-8")!! } } + .toMap() + config = ServerConfig.create(EConfigType.VLESS) + val streamSetting = config.outboundBean?.streamSettings ?: return -1 + config.remarks = uri.fragment ?: "" + config.outboundBean?.settings?.vnext?.get(0)?.let { vnext -> + vnext.address = uri.host + vnext.port = uri.port + vnext.users[0].id = uri.userInfo + vnext.users[0].encryption = queryParam["encryption"] ?: "none" + vnext.users[0].flow =queryParam["flow"] ?: "" } - addVlessServer(vmess, -1) - } else { + + val sni = streamSetting.populateTransportSettings(queryParam["type"] ?: "tcp", queryParam["headerType"], + queryParam["host"], queryParam["path"], queryParam["seed"], queryParam["quicSecurity"], queryParam["key"]) + streamSetting.populateTlsSettings(queryParam["security"] ?: "", allowInsecure, sni) + } + if (config == null){ return R.string.toast_incorrect_protocol } + config.subscriptionId = subid + val guid = MmkvManager.encodeServerConfig("", config) if (removedSelectedServer != null && - vmess.subid.equals(removedSelectedServer.subid) && - vmess.address.equals(removedSelectedServer.address) && - vmess.port.equals(removedSelectedServer.port)) { - setActiveServer(configs.vmess.count() - 1) + config.getProxyOutbound()?.getServerAddress() == removedSelectedServer.getProxyOutbound()?.getServerAddress() && + config.getProxyOutbound()?.getServerPort() == removedSelectedServer.getProxyOutbound()?.getServerPort()) { + mainStorage?.encode(KEY_SELECTED_SERVER, guid) } } catch (e: Exception) { e.printStackTrace() @@ -386,9 +237,9 @@ object AngConfigManager { return 0 } - fun tryParseNewVmess(uri: String): AngConfig.VmessBean? { + private fun tryParseNewVmess(uriString: String, config: ServerConfig, allowInsecure: Boolean): Boolean { return runCatching { - val uri = URI(uri) + val uri = URI(uriString) check(uri.scheme == "vmess") val (_, protocol, tlsStr, uuid, alterId) = Regex("(tcp|http|ws|kcp|quic)(\\+tls)?:([0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12})-([0-9]+)") @@ -398,52 +249,27 @@ object AngConfigManager { val queryParam = uri.rawQuery.split("&") .map { it.split("=").let { (k, v) -> k to URLDecoder.decode(v, "utf-8")!! } } .toMap() - val vmess = AngConfig.VmessBean() - vmess.address = uri.host - vmess.port = uri.port - vmess.id = uuid - vmess.alterId = alterId.toInt() - vmess.streamSecurity = if (tls) TLS else "" - vmess.remarks = uri.fragment - vmess.security = "auto" - // TODO: allowInsecure not supported - - when (protocol) { - "tcp" -> { - vmess.network = "tcp" - vmess.headerType = queryParam["type"] ?: "none" - vmess.requestHost = queryParam["host"] ?: "" - } - "http" -> { - vmess.network = "h2" - vmess.path = queryParam["path"]?.takeIf { it.trim() != "/" } ?: "" - vmess.requestHost = queryParam["host"]?.split("|")?.get(0) ?: "" - } - "ws" -> { - vmess.network = "ws" - vmess.path = queryParam["path"]?.takeIf { it.trim() != "/" } ?: "" - vmess.requestHost = queryParam["host"]?.split("|")?.get(0) ?: "" - } - "kcp" -> { - vmess.network = "kcp" - vmess.headerType = queryParam["type"] ?: "none" - vmess.path = queryParam["seed"] ?: "" - } - "quic" -> { - vmess.network = "quic" - vmess.requestHost = queryParam["security"] ?: "none" - vmess.headerType = queryParam["type"] ?: "none" - vmess.path = queryParam["key"] ?: "" - } + val streamSetting = config.outboundBean?.streamSettings ?: return false + config.remarks = uri.fragment + config.outboundBean.settings?.vnext?.get(0)?.let { vnext -> + vnext.address = uri.host + vnext.port = uri.port + vnext.users[0].id = uuid + vnext.users[0].encryption = DEFAULT_SECURITY + vnext.users[0].alterId = alterId.toInt() } - vmess - }.getOrNull() + + val sni = streamSetting.populateTransportSettings(protocol, queryParam["type"], + queryParam["host"]?.split("|")?.get(0) ?: "", + queryParam["path"]?.takeIf { it.trim() != "/" } ?: "", + queryParam["seed"], queryParam["security"], queryParam["key"]) + streamSetting.populateTlsSettings(if (tls) TLS else "", allowInsecure, sni) + true + }.getOrElse { false } } - private fun ResolveVmess4Kitsunebi(server: String): AngConfig.VmessBean { - - val vmess = AngConfig.VmessBean() + private fun tryResolveVmess4Kitsunebi(server: String, config: ServerConfig): Boolean { var result = server.replace(EConfigType.VMESS.protocolScheme, "") val indexSplit = result.indexOf("?") @@ -454,32 +280,29 @@ object AngConfigManager { val arr1 = result.split('@') if (arr1.count() != 2) { - return vmess + return false } val arr21 = arr1[0].split(':') val arr22 = arr1[1].split(':') - if (arr21.count() != 2 || arr21.count() != 2) { - return vmess + if (arr21.count() != 2) { + return false } - vmess.address = arr22[0] - vmess.port = Utils.parseInt(arr22[1]) - vmess.security = arr21[0] - vmess.id = arr21[1] - - vmess.security = "chacha20-poly1305" - vmess.network = "tcp" - vmess.headerType = "none" - vmess.remarks = "Alien" - vmess.alterId = 0 - - return vmess + config.remarks = "Alien" + config.outboundBean?.settings?.vnext?.get(0)?.let { vnext -> + vnext.address = arr22[0] + vnext.port = Utils.parseInt(arr22[1]) + vnext.users[0].id = arr21[1] + vnext.users[0].encryption = arr21[0] + vnext.users[0].alterId = 0 + } + return true } /** * share config */ - fun shareConfig(guid: String): String { + private fun shareConfig(guid: String): String { try { val config = MmkvManager.decodeServerConfig(guid) ?: return "" val outbound = config.getProxyOutbound() ?: return "" @@ -632,7 +455,7 @@ object AngConfigManager { continue } sb.append(url) - sb.appendln() + sb.appendLine() } if (sb.count() > 0) { Utils.setClipboard(app.applicationContext, sb.toString()) @@ -653,8 +476,7 @@ object AngConfigManager { if (TextUtils.isEmpty(conf)) { return null } - val bitmap = Utils.createQRCode(conf) - return bitmap + return Utils.createQRCode(conf) } catch (e: Exception) { e.printStackTrace() @@ -681,87 +503,30 @@ object AngConfigManager { return 0 } - /** - * import customize config - */ - fun importCustomizeConfig(server: String?): Int { - try { - if (server == null || TextUtils.isEmpty(server)) { - return R.string.toast_none_data - } - val config = ServerConfig.create(EConfigType.CUSTOM) - config.remarks = System.currentTimeMillis().toString() - config.fullConfig = Gson().fromJson(server, V2rayConfig::class.java) - MmkvManager.encodeServerConfig("", config) - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - - /** - * getIndexViaGuid - */ - fun getIndexViaGuid(guid: String): Int { - try { - if (TextUtils.isEmpty(guid)) { - return -1 - } - for (i in angConfig.vmess.indices) { - if (angConfig.vmess[i].guid == guid) { - return i - } - } - return -1 - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - } - /** * upgrade */ - fun upgradeServerVersion(vmess: AngConfig.VmessBean): Int { + private fun upgradeServerVersion(vmess: AngConfig.VmessBean): Int { try { if (vmess.configVersion == 2) { return 0 } when (vmess.network) { - "kcp" -> { - } - "ws" -> { + "ws", "h2" -> { var path = "" var host = "" val lstParameter = vmess.requestHost.split(";") - if (lstParameter.size > 0) { - path = lstParameter.get(0).trim() + if (lstParameter.isNotEmpty()) { + path = lstParameter[0].trim() } if (lstParameter.size > 1) { - path = lstParameter.get(0).trim() - host = lstParameter.get(1).trim() + path = lstParameter[0].trim() + host = lstParameter[1].trim() } vmess.path = path vmess.requestHost = host } - "h2" -> { - var path = "" - var host = "" - val lstParameter = vmess.requestHost.split(";") - if (lstParameter.size > 0) { - path = lstParameter.get(0).trim() - } - if (lstParameter.size > 1) { - path = lstParameter.get(0).trim() - host = lstParameter.get(1).trim() - } - vmess.path = path - vmess.requestHost = host - } - else -> { - } } vmess.configVersion = 2 return 0 @@ -771,62 +536,6 @@ object AngConfigManager { } } - fun addShadowsocksServer(vmess: AngConfig.VmessBean, index: Int): Int { - try { - vmess.configVersion = 2 - vmess.configType = EConfigType.SHADOWSOCKS.value - - vmess.address = vmess.address.trim() - vmess.id = vmess.id.trim() - vmess.security = vmess.security.trim() - - if (index >= 0) { - //edit - angConfig.vmess[index] = vmess - } else { - //add - vmess.guid = System.currentTimeMillis().toString() - angConfig.vmess.add(vmess) - if (angConfig.vmess.count() == 1) { - angConfig.index = 0 - } - } - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - - fun addSocksServer(vmess: AngConfig.VmessBean, index: Int): Int { - try { - vmess.configVersion = 2 - vmess.configType = EConfigType.SOCKS.value - - vmess.address = vmess.address.trim() - - if (index >= 0) { - //edit - angConfig.vmess[index] = vmess - } else { - //add - vmess.guid = System.currentTimeMillis().toString() - angConfig.vmess.add(vmess) - if (angConfig.vmess.count() == 1) { - angConfig.index = 0 - } - } - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - fun importBatchConfig(servers: String?, subid: String): Int { try { if (servers == null) { @@ -834,8 +543,8 @@ object AngConfigManager { } val removedSelectedServer = if (!TextUtils.isEmpty(subid)) { - configs.vmess.getOrNull(configs.index)?.let { - if (it.subid == subid) { + MmkvManager.decodeServerConfig(mainStorage?.decodeString(KEY_SELECTED_SERVER) ?: "")?.let { + if (it.subscriptionId == subid) { return@let it } return@let null @@ -843,7 +552,7 @@ object AngConfigManager { } else { null } - removeServerViaSubid(subid) + MmkvManager.removeServerViaSubid(subid) // var servers = server // if (server.indexOf("vmess") >= 0 && server.indexOf("vmess") == server.lastIndexOf("vmess")) { @@ -866,7 +575,7 @@ object AngConfigManager { } - fun saveSubItem(subItem: ArrayList): Int { + private fun saveSubItem(subItem: ArrayList): Int { try { if (subItem.count() <= 0) { return -1 @@ -886,22 +595,6 @@ object AngConfigManager { return 0 } - fun removeServerViaSubid(subid: String): Int { - if (TextUtils.isEmpty(subid) || configs.vmess.count() <= 0) { - return -1 - } - - for (k in configs.vmess.count() - 1 downTo 0) { - if (configs.vmess[k].subid.equals(subid)) { - angConfig.vmess.removeAt(k) - adjustIndexForRemovalAt(k) - } - } - - storeConfigFile() - return 0 - } - fun addSubItem(subItem: AngConfig.SubItemBean, index: Int): Int { try { if (index >= 0) { @@ -942,7 +635,7 @@ object AngConfigManager { return -1 } val subid = angConfig.subItem[index].id - removeServerViaSubid(subid) + MmkvManager.removeServerViaSubid(subid) angConfig.subItem.removeAt(index) @@ -953,74 +646,4 @@ object AngConfigManager { } return 0 } - - /** - * add or edit server - */ - fun addVlessServer(vmess: AngConfig.VmessBean, index: Int): Int { - try { - vmess.configVersion = 2 - vmess.configType = EConfigType.VLESS.value - - vmess.address = vmess.address.trim() - vmess.id = vmess.id.trim() - vmess.alterId = 0 - //vmess.flow = vmess.flow.trim() - vmess.security = vmess.security.trim() - vmess.network = vmess.network.trim() - vmess.headerType = vmess.headerType.trim() - vmess.requestHost = vmess.requestHost.trim() - vmess.path = vmess.path.trim() - vmess.streamSecurity = vmess.streamSecurity.trim() - - if (index >= 0) { - //edit - angConfig.vmess[index] = vmess - } else { - //add - vmess.guid = Utils.getUuid() - angConfig.vmess.add(vmess) - if (angConfig.vmess.count() == 1) { - angConfig.index = 0 - } - } - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - - fun addTrojanServer(vmess: AngConfig.VmessBean, index: Int): Int { - try { - vmess.configVersion = 2 - vmess.configType = EConfigType.TROJAN.value - - vmess.address = vmess.address.trim() - vmess.id = vmess.id.trim() - - vmess.streamSecurity = TLS; - - if (index >= 0) { - //edit - angConfig.vmess[index] = vmess - } else { - //add - vmess.guid = System.currentTimeMillis().toString() - angConfig.vmess.add(vmess) - if (angConfig.vmess.count() == 1) { - angConfig.index = 0 - } - } - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt index 45f5ed63..087c346a 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt @@ -14,6 +14,7 @@ object MmkvManager { const val KEY_SELECTED_SERVER = "SELECTED_SERVER" const val KEY_ANG_CONFIGS = "ANG_CONFIGS" + private val mainStorage by lazy { MMKV.mmkvWithID(ID_MAIN, MMKV.MULTI_PROCESS_MODE) } private val serverStorage by lazy { MMKV.mmkvWithID(ID_SERVER_CONFIG, MMKV.MULTI_PROCESS_MODE) } private val serverAffStorage by lazy { MMKV.mmkvWithID(ID_SERVER_AFF, MMKV.MULTI_PROCESS_MODE) } @@ -28,20 +29,49 @@ object MmkvManager { return Gson().fromJson(json, ServerConfig::class.java) } - fun encodeServerConfig(guid: String, config: ServerConfig) { + fun encodeServerConfig(guid: String, config: ServerConfig): String { val key = if (guid.isBlank()) { Utils.getUuid() } else { guid } serverStorage?.encode(key, Gson().toJson(config)) + val serverList= Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toMutableList() + serverList.add(guid) + mainStorage?.encode(KEY_ANG_CONFIGS, Gson().toJson(serverList)) + if (mainStorage?.decodeString(KEY_SELECTED_SERVER).isNullOrBlank()) { + mainStorage?.encode(KEY_SELECTED_SERVER, guid) + } + return key } fun removeServer(guid: String) { + if (guid.isBlank()) { + return + } + if (mainStorage?.decodeString(KEY_SELECTED_SERVER) == guid) { + mainStorage?.remove(KEY_SELECTED_SERVER) + } + val serverList= Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toMutableList() + serverList.remove(guid) + mainStorage?.encode(KEY_ANG_CONFIGS, Gson().toJson(serverList)) serverStorage?.remove(guid) serverAffStorage?.remove(guid) } + fun removeServerViaSubid(subid: String) { + if (subid.isBlank()) { + return + } + serverStorage?.allKeys()?.forEach { key -> + decodeServerConfig(key)?.let { config -> + if (config.subscriptionId == subid) { + removeServer(key) + } + } + } + } + fun decodeServerAffiliationInfo(guid: String): ServerAffiliationInfo? { if (guid.isBlank()) { return null diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt index ee751ad5..05aefe3e 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt @@ -19,6 +19,7 @@ import android.text.TextUtils import android.util.Log import android.util.Patterns import android.webkit.URLUtil +import com.tencent.mmkv.MMKV import com.v2ray.ang.AngApplication import com.v2ray.ang.AppConfig import com.v2ray.ang.R @@ -35,6 +36,7 @@ import kotlin.coroutines.coroutineContext object Utils { + private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } private val tcpTestingSockets = ArrayList() /** @@ -270,8 +272,7 @@ object Utils { } fun startVServiceFromToggle(context: Context): Boolean { - val result = context.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG, "") - if (result.isBlank()) { + if (mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER).isNullOrEmpty()) { context.toast(R.string.app_tile_first_use) return false } @@ -279,26 +280,6 @@ object Utils { return true } - /** - * startVService - */ - fun startVService(context: Context, guid: String): Boolean { - val index = AngConfigManager.getIndexViaGuid(guid) - context.v2RayApplication.curIndex=index - return startVService(context, index) - } - - /** - * startVService - */ - fun startVService(context: Context, index: Int): Boolean { - if (AngConfigManager.setActiveServer(index) < 0) { - return false - } - V2RayServiceManager.startV2Ray(context) - return true - } - /** * stopVService */ @@ -398,8 +379,8 @@ object Utils { /** * readTextFromAssets */ - fun readTextFromAssets(app: AngApplication, fileName: String): String { - val content = app.assets.open(fileName).bufferedReader().use { + fun readTextFromAssets(context: Context, fileName: String): String { + val content = context.assets.open(fileName).bufferedReader().use { it.readText() } return content diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt index cb4cd815..610c7476 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt @@ -1,14 +1,15 @@ package com.v2ray.ang.util +import android.content.Context import android.text.TextUtils import android.util.Log import com.google.gson.* -import com.v2ray.ang.AngApplication import com.v2ray.ang.AppConfig import com.v2ray.ang.dto.V2rayConfig import org.json.JSONException import org.json.JSONObject import com.v2ray.ang.dto.EConfigType +import com.v2ray.ang.extension.defaultDPreference object V2rayConfigUtil { // private val requestObj: JsonObject by lazy { @@ -23,7 +24,7 @@ object V2rayConfigUtil { /** * 生成v2ray的客户端配置文件 */ - fun getV2rayConfig(app: AngApplication, guid: String): Result { + fun getV2rayConfig(context: Context, guid: String): Result { try { val config = MmkvManager.decodeServerConfig(guid) ?: return Result(false, "") if (config.configType == EConfigType.CUSTOM) { @@ -32,7 +33,7 @@ object V2rayConfigUtil { return Result(true, customConfig) } val outbound = config.getProxyOutbound() ?: return Result(false, "") - val result = getV2rayNonCustomConfig(app, outbound) + val result = getV2rayNonCustomConfig(context, outbound) Log.d("V2rayConfigUtilGoLog", result.content) return result } catch (e: Exception) { @@ -44,10 +45,10 @@ object V2rayConfigUtil { /** * 生成v2ray的客户端配置文件 */ - private fun getV2rayNonCustomConfig(app: AngApplication, outbound: V2rayConfig.OutboundBean): Result { + private fun getV2rayNonCustomConfig(context: Context, outbound: V2rayConfig.OutboundBean): Result { val result = Result(false, "") //取得默认配置 - val assets = Utils.readTextFromAssets(app, "v2ray_config.json") + val assets = Utils.readTextFromAssets(context, "v2ray_config.json") if (TextUtils.isEmpty(assets)) { return result } @@ -55,18 +56,18 @@ object V2rayConfigUtil { //转成Json val v2rayConfig = Gson().fromJson(assets, V2rayConfig::class.java) ?: return result - //v2rayConfig.log.loglevel = app.defaultDPreference.getPrefString(AppConfig.PREF_LOGLEVEL, "warning") + //v2rayConfig.log.loglevel = context.defaultDPreference.getPrefString(AppConfig.PREF_LOGLEVEL, "warning") - inbounds(v2rayConfig, app) + inbounds(v2rayConfig, context) v2rayConfig.outbounds[0] = outbound - routing(v2rayConfig, app) + routing(v2rayConfig, context) - if (app.defaultDPreference.getPrefBoolean(AppConfig.PREF_LOCAL_DNS_ENABLED, false)) { - customLocalDns(v2rayConfig, app) + if (context.defaultDPreference.getPrefBoolean(AppConfig.PREF_LOCAL_DNS_ENABLED, false)) { + customLocalDns(v2rayConfig, context) } else { - customRemoteDns(v2rayConfig, app) + customRemoteDns(v2rayConfig, context) } val finalConfig = GsonBuilder().setPrettyPrinting().create().toJson(v2rayConfig) @@ -79,19 +80,19 @@ object V2rayConfigUtil { /** * */ - private fun inbounds(v2rayConfig: V2rayConfig, app: AngApplication): Boolean { + private fun inbounds(v2rayConfig: V2rayConfig, context: Context): Boolean { try { - //val socksPort = Utils.parseInt(app.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_SOCKS_PORT, AppConfig.PORT_SOCKS)) - //val httpPort = Utils.parseInt(app.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_HTTP_PORT, AppConfig.PORT_HTTP)) + //val socksPort = Utils.parseInt(context.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_SOCKS_PORT, AppConfig .PORT_SOCKS)) + //val httpPort = Utils.parseInt(context.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_HTTP_PORT, AppConfig.PORT_HTTP)) v2rayConfig.inbounds.forEach { curInbound -> - if (!app.defaultDPreference.getPrefBoolean(AppConfig.PREF_PROXY_SHARING, false)) { + if (!context.defaultDPreference.getPrefBoolean(AppConfig.PREF_PROXY_SHARING, false)) { //bind all inbounds to localhost if the user requests curInbound.listen = "127.0.0.1" } } v2rayConfig.inbounds[0].port = 10808 - v2rayConfig.inbounds[0].sniffing?.enabled = app.defaultDPreference.getPrefBoolean(AppConfig.PREF_SNIFFING_ENABLED, true) + v2rayConfig.inbounds[0].sniffing?.enabled = context.defaultDPreference.getPrefBoolean(AppConfig.PREF_SNIFFING_ENABLED, true) //v2rayConfig.inbounds[1].port = httpPort @@ -111,14 +112,14 @@ object V2rayConfigUtil { /** * routing */ - private fun routing(v2rayConfig: V2rayConfig, app: AngApplication): Boolean { + private fun routing(v2rayConfig: V2rayConfig, context: Context): Boolean { try { - routingUserRule(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_AGENT, ""), AppConfig.TAG_AGENT, v2rayConfig) - routingUserRule(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_DIRECT, ""), AppConfig.TAG_DIRECT, v2rayConfig) - routingUserRule(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED, ""), AppConfig.TAG_BLOCKED, v2rayConfig) + routingUserRule(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_AGENT, ""), AppConfig.TAG_AGENT, v2rayConfig) + routingUserRule(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_DIRECT, ""), AppConfig.TAG_DIRECT, v2rayConfig) + routingUserRule(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED, ""), AppConfig.TAG_BLOCKED, v2rayConfig) - v2rayConfig.routing.domainStrategy = app.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_DOMAIN_STRATEGY, "IPIfNonMatch") - val routingMode = app.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") + v2rayConfig.routing.domainStrategy = context.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_DOMAIN_STRATEGY, "IPIfNonMatch") + val routingMode = context.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") // Hardcode googleapis.cn val googleapisRoute = V2rayConfig.RoutingBean.RulesBean( @@ -229,36 +230,36 @@ object V2rayConfigUtil { /** * Custom Dns */ - private fun customLocalDns(v2rayConfig: V2rayConfig, app: AngApplication): Boolean { + private fun customLocalDns(v2rayConfig: V2rayConfig, context: Context): Boolean { try { val hosts = mutableMapOf() val servers = ArrayList() - val remoteDns = Utils.getRemoteDnsServers(app.defaultDPreference) + val remoteDns = Utils.getRemoteDnsServers(context.defaultDPreference) remoteDns.forEach { servers.add(it) } - val domesticDns = Utils.getDomesticDnsServers(app.defaultDPreference) + val domesticDns = Utils.getDomesticDnsServers(context.defaultDPreference) val geositeCn = arrayListOf("geosite:cn") val geoipCn = arrayListOf("geoip:cn") - val agDomain = userRule2Domian(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_AGENT, "")) + val agDomain = userRule2Domian(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_AGENT, "")) if (agDomain.size > 0) { servers.add(V2rayConfig.DnsBean.ServersBean(remoteDns.first(), 53, agDomain, null)) } - val dirDomain = userRule2Domian(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_DIRECT, "")) + val dirDomain = userRule2Domian(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_DIRECT, "")) if (dirDomain.size > 0) { servers.add(V2rayConfig.DnsBean.ServersBean(domesticDns.first(), 53, dirDomain, geoipCn)) } - val routingMode = app.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") + val routingMode = context.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") if (routingMode == "2" || routingMode == "3") { servers.add(V2rayConfig.DnsBean.ServersBean(domesticDns.first(), 53, geositeCn, geoipCn)) } - val blkDomain = userRule2Domian(app.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED, "")) + val blkDomain = userRule2Domian(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED, "")) if (blkDomain.size > 0) { hosts.putAll(blkDomain.map { it to "127.0.0.1" }) } @@ -278,7 +279,7 @@ object V2rayConfigUtil { port = 53, network = "tcp,udp") - //val localDnsPort = Utils.parseInt(app.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_LOCAL_DNS_PORT, AppConfig.PORT_LOCAL_DNS)) + //val localDnsPort = Utils.parseInt(context.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_LOCAL_DNS_PORT, AppConfig.PORT_LOCAL_DNS)) v2rayConfig.inbounds.add( V2rayConfig.InboundBean( tag = "dns-in", @@ -338,12 +339,12 @@ object V2rayConfigUtil { /** * Custom Remote Dns */ - private fun customRemoteDns(v2rayConfig: V2rayConfig, app: AngApplication): Boolean { + private fun customRemoteDns(v2rayConfig: V2rayConfig, context: Context): Boolean { try { val servers = ArrayList() val hosts = mutableMapOf() - Utils.getRemoteDnsServers(app.defaultDPreference).forEach { + Utils.getRemoteDnsServers(context.defaultDPreference).forEach { servers.add(it) } // hardcode googleapi rule to fix play store problems diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt index 605cc15c..c510d8d0 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt @@ -13,16 +13,21 @@ import com.tencent.mmkv.MMKV import com.v2ray.ang.AngApplication import com.v2ray.ang.AppConfig import com.v2ray.ang.R +import com.v2ray.ang.dto.EConfigType +import com.v2ray.ang.dto.ServerConfig +import com.v2ray.ang.dto.V2rayConfig import com.v2ray.ang.extension.toast import com.v2ray.ang.util.* import com.v2ray.ang.util.MmkvManager.KEY_ANG_CONFIGS import kotlinx.coroutines.* +import java.util.* class MainViewModel(application: Application) : AndroidViewModel(application) { private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } private val serverAffStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SERVER_AFF, MMKV.MULTI_PROCESS_MODE) } - val serverList by lazy { Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toList() } + var serverList= Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toMutableList() + private set val isRunning by lazy { MutableLiveData() } val updateListAction by lazy { MutableLiveData() } val updateTestResultAction by lazy { MutableLiveData() } @@ -43,8 +48,26 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { super.onCleared() } - fun getGuid(index: Int): String? { - return serverList.getOrNull(index) + fun reloadServerList() { + serverList = Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toMutableList() + updateListAction.value = -1 + } + + fun removeServer(guid: String) { + serverList.remove(guid) + MmkvManager.removeServer(guid) + } + + fun appendCustomConfigServer(server: String) { + val config = ServerConfig.create(EConfigType.CUSTOM) + config.remarks = System.currentTimeMillis().toString() + config.fullConfig = Gson().fromJson(server, V2rayConfig::class.java) + serverList.add(MmkvManager.encodeServerConfig("", config)) + } + + fun swapServer(fromPosition: Int, toPosition: Int) { + Collections.swap(serverList, fromPosition, toPosition) + mainStorage?.encode(KEY_ANG_CONFIGS, Gson().toJson(serverList)) } fun testAllTcping() { From 572955dd1ee6713b9d906550c82e9ca5b4fa8128 Mon Sep 17 00:00:00 2001 From: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Date: Sat, 20 Mar 2021 01:00:12 -0400 Subject: [PATCH 3/6] Move everything else to MMKV - Exclude old armv5 so lib from MMKV - Move subscription to MMKV - Clean up settings key - Map settings to MMKV - Say goodbye to DPreference Fix some bugs: - null pointer check - server list refresh - show test result - custom config display - fix port number in DNS object shown as Double - shadowsocks, socks streamsettings - quic settings with wrong security - main list footer --- V2rayNG/app/build.gradle | 3 +- .../kotlin/com/v2ray/ang/AngApplication.kt | 3 - .../main/kotlin/com/v2ray/ang/AppConfig.kt | 36 +-- .../v2ray/ang/dto/ServerAffiliationInfo.kt | 2 +- .../kotlin/com/v2ray/ang/dto/ServerConfig.kt | 9 +- .../com/v2ray/ang/dto/SubscriptionItem.kt | 8 + .../kotlin/com/v2ray/ang/dto/V2rayConfig.kt | 19 +- .../kotlin/com/v2ray/ang/extension/_Ext.kt | 8 - .../com/v2ray/ang/extension/_Preference.kt | 10 - .../v2ray/ang/service/V2RayServiceManager.kt | 16 +- .../com/v2ray/ang/service/V2RayVpnService.kt | 18 +- .../kotlin/com/v2ray/ang/ui/MainActivity.kt | 24 +- .../com/v2ray/ang/ui/MainRecyclerAdapter.kt | 2 +- .../com/v2ray/ang/ui/PerAppProxyActivity.kt | 19 +- .../v2ray/ang/ui/RoutingSettingsFragment.kt | 8 +- .../kotlin/com/v2ray/ang/ui/ServerActivity.kt | 33 ++- .../ang/ui/ServerCustomConfigActivity.kt | 3 +- .../com/v2ray/ang/ui/SubEditActivity.kt | 64 ++--- .../com/v2ray/ang/ui/SubSettingActivity.kt | 15 +- .../v2ray/ang/ui/SubSettingRecyclerAdapter.kt | 30 +- .../com/v2ray/ang/util/AngConfigManager.kt | 95 +------ .../kotlin/com/v2ray/ang/util/MmkvManager.kt | 65 ++++- .../main/kotlin/com/v2ray/ang/util/Utils.kt | 13 +- .../com/v2ray/ang/util/V2rayConfigUtil.kt | 49 ++-- .../com/v2ray/ang/viewmodel/MainViewModel.kt | 12 +- .../v2ray/ang/viewmodel/SettingsViewModel.kt | 28 +- V2rayNG/dpreference/.gitignore | 1 - V2rayNG/dpreference/build.gradle | 25 -- V2rayNG/dpreference/proguard-rules.pro | 17 -- .../dpreference/src/main/AndroidManifest.xml | 16 -- .../me/dozen/dpreference/DPreference.java | 86 ------ .../java/me/dozen/dpreference/IOUtils.java | 61 ---- .../java/me/dozen/dpreference/IPrefImpl.java | 39 --- .../me/dozen/dpreference/PrefAccessor.java | 116 -------- .../me/dozen/dpreference/PreferenceImpl.java | 133 --------- .../dozen/dpreference/PreferenceProvider.java | 267 ------------------ .../dozen/dpreference/StringSetConverter.java | 22 -- V2rayNG/settings.gradle | 2 +- 38 files changed, 274 insertions(+), 1103 deletions(-) create mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/SubscriptionItem.kt delete mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Preference.kt delete mode 100644 V2rayNG/dpreference/.gitignore delete mode 100644 V2rayNG/dpreference/build.gradle delete mode 100644 V2rayNG/dpreference/proguard-rules.pro delete mode 100644 V2rayNG/dpreference/src/main/AndroidManifest.xml delete mode 100644 V2rayNG/dpreference/src/main/java/me/dozen/dpreference/DPreference.java delete mode 100644 V2rayNG/dpreference/src/main/java/me/dozen/dpreference/IOUtils.java delete mode 100644 V2rayNG/dpreference/src/main/java/me/dozen/dpreference/IPrefImpl.java delete mode 100644 V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PrefAccessor.java delete mode 100644 V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PreferenceImpl.java delete mode 100644 V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PreferenceProvider.java delete mode 100644 V2rayNG/dpreference/src/main/java/me/dozen/dpreference/StringSetConverter.java diff --git a/V2rayNG/app/build.gradle b/V2rayNG/app/build.gradle index 3288a1d3..1f5dbeb8 100644 --- a/V2rayNG/app/build.gradle +++ b/V2rayNG/app/build.gradle @@ -25,12 +25,14 @@ android { minifyEnabled false zipAlignEnabled false shrinkResources false + ndk.abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' // proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } debug { minifyEnabled false zipAlignEnabled false shrinkResources false + ndk.abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' } } @@ -67,7 +69,6 @@ android { dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') testImplementation 'junit:junit:4.13' - implementation project(':dpreference') implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion" diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt index 320c98b8..420a6827 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt @@ -4,7 +4,6 @@ import android.support.multidex.MultiDexApplication import android.support.v7.preference.PreferenceManager import com.tencent.mmkv.MMKV import com.v2ray.ang.util.AngConfigManager -import me.dozen.dpreference.DPreference class AngApplication : MultiDexApplication() { companion object { @@ -15,8 +14,6 @@ class AngApplication : MultiDexApplication() { var firstRun = false private set - val defaultDPreference by lazy { DPreference(this, packageName + "_preferences") } - override fun onCreate() { super.onCreate() diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt index 4eee79da..8fd58789 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt @@ -6,36 +6,39 @@ package com.v2ray.ang */ object AppConfig { const val ANG_PACKAGE = "com.v2ray.ang" - const val ANG_CONFIG = "ang_config" - const val PREF_CURR_CONFIG = "pref_v2ray_config" - const val PREF_CURR_CONFIG_GUID = "pref_v2ray_config_guid" - const val PREF_CURR_CONFIG_NAME = "pref_v2ray_config_name" - const val PREF_CURR_CONFIG_DOMAIN = "pref_v2ray_config_domain" - const val PREF_CURR_CONFIG_OUTBOUND_TAGS = "pref_v2ray_config_outbound_tags" - const val PREF_INAPP_BUY_IS_PREMIUM = "pref_inapp_buy_is_premium" + // legacy + const val ANG_CONFIG = "ang_config" + const val PREF_INAPP_BUY_IS_PREMIUM = "pref_inapp_buy_is_premium" + const val PREF_ROUTING_CUSTOM = "pref_routing_custom" + + // Preferences mapped to MMKV const val PREF_MODE = "pref_mode" - // const val PREF_BYPASS_MAINLAND = "pref_bypass_mainland" - // const val PREF_START_ON_BOOT = "pref_start_on_boot" - const val PREF_PER_APP_PROXY = "pref_per_app_proxy" - // const val PREF_MUX_ENAimport libv2ray.Libv2rayBLED = "pref_mux_enabled" const val PREF_SPEED_ENABLED = "pref_speed_enabled" const val PREF_SNIFFING_ENABLED = "pref_sniffing_enabled" const val PREF_PROXY_SHARING = "pref_proxy_sharing_enabled" const val PREF_LOCAL_DNS_ENABLED = "pref_local_dns_enabled" const val PREF_REMOTE_DNS = "pref_remote_dns" const val PREF_DOMESTIC_DNS = "pref_domestic_dns" - // const val PREF_SOCKS_PORT = "pref_socks_port" -// const val PREF_HTTP_PORT = "pref_http_port" + const val PREF_FORWARD_IPV6 = "pref_forward_ipv6" const val PREF_ROUTING_DOMAIN_STRATEGY = "pref_routing_domain_strategy" const val PREF_ROUTING_MODE = "pref_routing_mode" - const val PREF_ROUTING_CUSTOM = "pref_routing_custom" + const val PREF_V2RAY_ROUTING_AGENT = "pref_v2ray_routing_agent" + const val PREF_V2RAY_ROUTING_DIRECT = "pref_v2ray_routing_direct" + const val PREF_V2RAY_ROUTING_BLOCKED = "pref_v2ray_routing_blocked" + const val PREF_PER_APP_PROXY = "pref_per_app_proxy" + const val PREF_PER_APP_PROXY_SET = "pref_per_app_proxy_set" + const val PREF_BYPASS_APPS = "pref_bypass_apps" + // const val PREF_BYPASS_MAINLAND = "pref_bypass_mainland" + // const val PREF_START_ON_BOOT = "pref_start_on_boot" + // const val PREF_MUX_ENAimport libv2ray.Libv2rayBLED = "pref_mux_enabled" + // const val PREF_SOCKS_PORT = "pref_socks_port" +// const val PREF_HTTP_PORT = "pref_http_port" // const val PREF_DONATE = "pref_donate" // const val PREF_LICENSES = "pref_licenses" // const val PREF_FEEDBACK = "pref_feedback" // const val PREF_TG_GROUP = "pref_tg_group" // const val PREF_AUTO_RESTART = "pref_auto_restart" - const val PREF_FORWARD_IPV6 = "pref_forward_ipv6" const val HTTP_PROTOCOL: String = "http://" const val HTTPS_PROTOCOL: String = "https://" @@ -50,9 +53,6 @@ object AppConfig { const val TASKER_EXTRA_BUNDLE_GUID = "tasker_extra_bundle_guid" const val TASKER_DEFAULT_GUID = "Default" - const val PREF_V2RAY_ROUTING_AGENT = "pref_v2ray_routing_agent" - const val PREF_V2RAY_ROUTING_DIRECT = "pref_v2ray_routing_direct" - const val PREF_V2RAY_ROUTING_BLOCKED = "pref_v2ray_routing_blocked" const val TAG_AGENT = "proxy" const val TAG_DIRECT = "direct" const val TAG_BLOCKED = "block" diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt index 100044d2..bb4d20be 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt @@ -1,6 +1,6 @@ package com.v2ray.ang.dto -data class ServerAffiliationInfo(var testDelayMillis: Long) { +data class ServerAffiliationInfo(var testDelayMillis: Long = 0L) { fun getTestDelayString(): String { if (testDelayMillis == 0L) { return "" diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt index 5c2bdba4..977be96f 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt @@ -28,14 +28,7 @@ data class ServerConfig( streamSettings = V2rayConfig.OutboundBean.StreamSettingsBean())) EConfigType.CUSTOM -> return ServerConfig(configType = configType) - EConfigType.SHADOWSOCKS, EConfigType.SOCKS -> - return ServerConfig( - configType = configType, - outboundBean = V2rayConfig.OutboundBean( - protocol = configType.name.toLowerCase(), - settings = V2rayConfig.OutboundBean.OutSettingsBean( - servers = listOf(V2rayConfig.OutboundBean.OutSettingsBean.ServersBean())))) - EConfigType.TROJAN -> + EConfigType.SHADOWSOCKS, EConfigType.SOCKS, EConfigType.TROJAN -> return ServerConfig( configType = configType, outboundBean = V2rayConfig.OutboundBean( diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/SubscriptionItem.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/SubscriptionItem.kt new file mode 100644 index 00000000..b2195148 --- /dev/null +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/SubscriptionItem.kt @@ -0,0 +1,8 @@ +package com.v2ray.ang.dto + +data class SubscriptionItem( + var remarks: String = "", + var url: String = "", + var enabled: Boolean = true, + val addedTime: Long = System.currentTimeMillis()) { +} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt index e49dc15f..4cb83de7 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt @@ -1,6 +1,12 @@ package com.v2ray.ang.dto import android.text.TextUtils +import com.google.gson.GsonBuilder +import com.google.gson.JsonPrimitive +import com.google.gson.JsonSerializationContext +import com.google.gson.JsonSerializer +import com.google.gson.reflect.TypeToken +import java.lang.reflect.Type data class V2rayConfig( val stats: Any? = null, @@ -284,7 +290,7 @@ data class V2rayConfig( "quic" -> { val quicSetting = streamSettings?.quicSettings ?: return null listOf(quicSetting.header.type, - quicSetting.key, + quicSetting.security, quicSetting.key) } else -> null @@ -336,4 +342,15 @@ data class V2rayConfig( } return null } + + fun toPrettyPrinting(): String { + return GsonBuilder() + .setPrettyPrinting() + .registerTypeAdapter( // custom serialiser is needed here since JSON by default parse number as Double, core will fail to start + object: TypeToken() {}.type, + JsonSerializer { src: Double?, _: Type?, _: JsonSerializationContext? -> JsonPrimitive(src?.toInt()) } + ) + .create() + .toJson(this) + } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt index 73a400cd..b0e74368 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt @@ -4,7 +4,6 @@ import android.content.Context import android.os.Build import android.widget.Toast import com.v2ray.ang.AngApplication -import me.dozen.dpreference.DPreference import me.drakeet.support.toast.ToastCompat import org.json.JSONObject import java.net.URLConnection @@ -16,13 +15,6 @@ import java.net.URLConnection val Context.v2RayApplication: AngApplication get() = applicationContext as AngApplication -// Usage note: DPreference use Android ContentProvider to redirect multi process access to main process. -// Currently, RunSoLibV2RayDaemon process will run proxy core, keep minimum configuration and long running -// in the background, support toggle on/off. That means it should NOT use DPreference after the initial -// creation and setup of the service -val Context.defaultDPreference: DPreference - get() = v2RayApplication.defaultDPreference - inline fun Context.toast(message: Int): Toast = ToastCompat .makeText(this, message, Toast.LENGTH_SHORT) .apply { diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Preference.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Preference.kt deleted file mode 100644 index dcfa4671..00000000 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Preference.kt +++ /dev/null @@ -1,10 +0,0 @@ -package com.v2ray.ang.extension - -import android.preference.Preference - -fun Preference.onClick(listener: () -> Unit) { - setOnPreferenceClickListener { - listener() - true - } -} \ No newline at end of file diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt index b5fce5ce..adcb2c5b 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt @@ -18,10 +18,8 @@ import com.v2ray.ang.AppConfig import com.v2ray.ang.AppConfig.TAG_DIRECT import com.v2ray.ang.R import com.v2ray.ang.dto.ServerConfig -import com.v2ray.ang.extension.defaultDPreference import com.v2ray.ang.extension.toSpeedString import com.v2ray.ang.extension.toast -import com.v2ray.ang.extension.v2RayApplication import com.v2ray.ang.ui.MainActivity import com.v2ray.ang.util.MessageUtil import com.v2ray.ang.util.MmkvManager @@ -45,6 +43,7 @@ object V2RayServiceManager { val v2rayPoint: V2RayPoint = Libv2ray.newV2RayPoint(V2RayCallback()) private val mMsgReceive = ReceiveMessageHandler() private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } + private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) } var serviceControl: SoftReference? = null set(value) { @@ -64,12 +63,12 @@ object V2RayServiceManager { private var mNotificationManager: NotificationManager? = null fun startV2Ray(context: Context) { - if (context.v2RayApplication.defaultDPreference.getPrefBoolean(AppConfig.PREF_PROXY_SHARING, false)) { + if (settingsStorage?.decodeBool(AppConfig.PREF_PROXY_SHARING) == true) { context.toast(R.string.toast_warning_pref_proxysharing_short) }else{ context.toast(R.string.toast_services_start) } - val intent = if (context.v2RayApplication.defaultDPreference.getPrefString(AppConfig.PREF_MODE, "VPN") == "VPN") { + val intent = if (settingsStorage?.decodeString(AppConfig.PREF_MODE) ?: "VPN" == "VPN") { Intent(context.applicationContext, V2RayVpnService::class.java) } else { Intent(context.applicationContext, V2RayProxyOnlyService::class.java) @@ -147,9 +146,9 @@ object V2RayServiceManager { v2rayPoint.configureFileContent = result.content v2rayPoint.domainName = config.getV2rayPointDomainAndPort() currentConfig = config - v2rayPoint.enableLocalDNS = service.defaultDPreference.getPrefBoolean(AppConfig.PREF_LOCAL_DNS_ENABLED, false) - v2rayPoint.forwardIpv6 = service.defaultDPreference.getPrefBoolean(AppConfig.PREF_FORWARD_IPV6, false) - v2rayPoint.proxyOnly = service.defaultDPreference.getPrefString(AppConfig.PREF_MODE, "VPN") != "VPN" + v2rayPoint.enableLocalDNS = settingsStorage?.decodeBool(AppConfig.PREF_LOCAL_DNS_ENABLED) ?: false + v2rayPoint.forwardIpv6 = settingsStorage?.decodeBool(AppConfig.PREF_FORWARD_IPV6) ?: false + v2rayPoint.proxyOnly = settingsStorage?.decodeString(AppConfig.PREF_MODE) ?: "VPN" == "VPN" try { v2rayPoint.runLoop() @@ -314,10 +313,9 @@ object V2RayServiceManager { } fun startSpeedNotification() { - val service = serviceControl?.get()?.getService() ?: return if (mSubscription == null && v2rayPoint.isRunning && - service.defaultDPreference.getPrefBoolean(AppConfig.PREF_SPEED_ENABLED, false)) { + settingsStorage?.decodeBool(AppConfig.PREF_SPEED_ENABLED) == true) { var lastZeroSpeed = false val outboundTags = currentConfig?.getAllOutboundTags() outboundTags?.remove(TAG_DIRECT) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt index dc92d15f..efc410ff 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt @@ -10,10 +10,10 @@ import android.os.ParcelFileDescriptor import android.os.StrictMode import android.support.annotation.RequiresApi import android.util.Log +import com.tencent.mmkv.MMKV import com.v2ray.ang.AppConfig import com.v2ray.ang.R -import com.v2ray.ang.extension.defaultDPreference -import com.v2ray.ang.ui.PerAppProxyActivity +import com.v2ray.ang.util.MmkvManager import com.v2ray.ang.util.Utils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope @@ -22,6 +22,8 @@ import java.io.File import java.lang.ref.SoftReference class V2RayVpnService : VpnService(), ServiceControl { + private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) } + private lateinit var mInterface: ParcelFileDescriptor /** @@ -91,8 +93,8 @@ class V2RayVpnService : VpnService(), ServiceControl { // If the old interface has exactly the same parameters, use it! // Configure a builder while parsing the parameters. val builder = Builder() - val enableLocalDns = defaultDPreference.getPrefBoolean(AppConfig.PREF_LOCAL_DNS_ENABLED, false) - val routingMode = defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") + val enableLocalDns = settingsStorage?.decodeBool(AppConfig.PREF_LOCAL_DNS_ENABLED) ?: false + val routingMode = settingsStorage?.decodeString(AppConfig.PREF_ROUTING_MODE) ?: "0" parameters.split(" ") .map { it.split(",") } @@ -120,7 +122,7 @@ class V2RayVpnService : VpnService(), ServiceControl { } if(!enableLocalDns) { - Utils.getRemoteDnsServers(defaultDPreference) + Utils.getRemoteDnsServers() .forEach { builder.addDnsServer(it) } @@ -129,9 +131,9 @@ class V2RayVpnService : VpnService(), ServiceControl { builder.setSession(V2RayServiceManager.currentConfig?.remarks.orEmpty()) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && - defaultDPreference.getPrefBoolean(AppConfig.PREF_PER_APP_PROXY, false)) { - val apps = defaultDPreference.getPrefStringSet(PerAppProxyActivity.PREF_PER_APP_PROXY_SET, null) - val bypassApps = defaultDPreference.getPrefBoolean(PerAppProxyActivity.PREF_BYPASS_APPS, false) + settingsStorage?.decodeBool(AppConfig.PREF_PER_APP_PROXY) == true) { + val apps = settingsStorage?.decodeStringSet(AppConfig.PREF_PER_APP_PROXY_SET) + val bypassApps = settingsStorage?.decodeBool(AppConfig.PREF_BYPASS_APPS) ?: false apps?.forEach { try { if (bypassApps) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt index 54ae616c..5c269dab 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt @@ -22,7 +22,6 @@ import com.v2ray.ang.AppConfig import com.v2ray.ang.BuildConfig import com.v2ray.ang.R import com.v2ray.ang.dto.EConfigType -import com.v2ray.ang.extension.defaultDPreference import com.v2ray.ang.extension.toast import com.v2ray.ang.helper.SimpleItemTouchHelperCallback import com.v2ray.ang.service.V2RayServiceManager @@ -51,6 +50,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList private val adapter by lazy { MainRecyclerAdapter(this) } private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } + private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) } private var mItemTouchHelper: ItemTouchHelper? = null val mainViewModel: MainViewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) } @@ -63,7 +63,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList fab.setOnClickListener { if (mainViewModel.isRunning.value == true) { Utils.stopVService(this) - } else if (defaultDPreference.getPrefString(AppConfig.PREF_MODE, "VPN") == "VPN") { + } else if (settingsStorage?.decodeString(AppConfig.PREF_MODE) ?: "VPN" == "VPN") { val intent = VpnService.prepare(this) if (intent == null) { startV2Ray() @@ -297,7 +297,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList } if (count > 0) { toast(R.string.toast_success) - adapter.notifyDataSetChanged() + mainViewModel.reloadServerList() } else { toast(R.string.toast_failure) } @@ -381,18 +381,16 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList : Boolean { try { toast(R.string.title_sub_update) - val subItem = AngConfigManager.configs.subItem - for (k in 0 until subItem.count()) { - if (TextUtils.isEmpty(subItem[k].id) - || TextUtils.isEmpty(subItem[k].remarks) - || TextUtils.isEmpty(subItem[k].url) + MmkvManager.decodeSubscriptions().forEach { + if (TextUtils.isEmpty(it.first) + || TextUtils.isEmpty(it.second.remarks) + || TextUtils.isEmpty(it.second.url) ) { - continue + return@forEach } - val id = subItem[k].id - val url = subItem[k].url + val url = it.second.url if (!Utils.isValidUrl(url)) { - continue + return@forEach } Log.d("Main", url) GlobalScope.launch(Dispatchers.IO) { @@ -403,7 +401,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList "" } launch(Dispatchers.Main) { - importBatchConfig(Utils.decode(configText), id) + importBatchConfig(Utils.decode(configText), it.first) } } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt index 8b780206..0fe9fbd2 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt @@ -39,7 +39,7 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter? = null + private val defaultSharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -52,7 +49,7 @@ class PerAppProxyActivity : BaseActivity() { val dividerItemDecoration = DividerItemDecoration(this, LinearLayoutManager.VERTICAL) recycler_view.addItemDecoration(dividerItemDecoration) - val blacklist = defaultDPreference.getPrefStringSet(PREF_PER_APP_PROXY_SET, null) + val blacklist = defaultSharedPreferences.getStringSet(AppConfig.PREF_PER_APP_PROXY_SET, null) AppManagerUtil.rxLoadNetworkAppList(this) .subscribeOn(Schedulers.io()) @@ -142,14 +139,14 @@ class PerAppProxyActivity : BaseActivity() { }) switch_per_app_proxy.setOnCheckedChangeListener { buttonView, isChecked -> - defaultDPreference.setPrefBoolean(AppConfig.PREF_PER_APP_PROXY, isChecked) + defaultSharedPreferences.edit().putBoolean(AppConfig.PREF_PER_APP_PROXY, isChecked).apply() } - switch_per_app_proxy.isChecked = defaultDPreference.getPrefBoolean(AppConfig.PREF_PER_APP_PROXY, false) + switch_per_app_proxy.isChecked = defaultSharedPreferences.getBoolean(AppConfig.PREF_PER_APP_PROXY, false) switch_bypass_apps.setOnCheckedChangeListener { buttonView, isChecked -> - defaultDPreference.setPrefBoolean(PREF_BYPASS_APPS, isChecked) + defaultSharedPreferences.edit().putBoolean(AppConfig.PREF_BYPASS_APPS, isChecked).apply() } - switch_bypass_apps.isChecked = defaultDPreference.getPrefBoolean(PREF_BYPASS_APPS, false) + switch_bypass_apps.isChecked = defaultSharedPreferences.getBoolean(AppConfig.PREF_BYPASS_APPS, false) et_search.setOnEditorActionListener { v, actionId, event -> if (actionId == EditorInfo.IME_ACTION_SEARCH) { @@ -183,7 +180,7 @@ class PerAppProxyActivity : BaseActivity() { override fun onPause() { super.onPause() adapter?.let { - defaultDPreference.setPrefStringSet(PREF_PER_APP_PROXY_SET, it.blacklist) + defaultSharedPreferences.edit().putStringSet(AppConfig.PREF_PER_APP_PROXY_SET, it.blacklist).apply() } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt index 97917148..a32c2223 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt @@ -5,9 +5,9 @@ import android.app.Activity.RESULT_OK import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment +import android.support.v7.preference.PreferenceManager import android.view.* import com.v2ray.ang.R -import com.v2ray.ang.extension.defaultDPreference import com.v2ray.ang.util.Utils import kotlinx.android.synthetic.main.fragment_routing_settings.* import android.view.MenuInflater @@ -26,6 +26,8 @@ class RoutingSettingsFragment : Fragment() { private const val REQUEST_SCAN_APPEND = 12 } + val defaultSharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) } + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment @@ -43,7 +45,7 @@ class RoutingSettingsFragment : Fragment() { override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) - val content = activity?.defaultDPreference?.getPrefString(arguments!!.getString(routing_arg), "") + val content = defaultSharedPreferences.getString(arguments!!.getString(routing_arg), "") et_routing_content.text = Utils.getEditable(content!!) setHasOptionsMenu(true) @@ -57,7 +59,7 @@ class RoutingSettingsFragment : Fragment() { override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.save_routing -> { val content = et_routing_content.text.toString() - activity?.defaultDPreference?.setPrefString(arguments!!.getString(routing_arg), content) + defaultSharedPreferences.edit().putString(arguments!!.getString(routing_arg), content).apply() activity?.toast(R.string.toast_success) true } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt index d4820350..c886c8f7 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt @@ -12,7 +12,6 @@ import com.v2ray.ang.dto.ServerConfig import com.v2ray.ang.dto.V2rayConfig import com.v2ray.ang.dto.V2rayConfig.Companion.DEFAULT_NETWORK import com.v2ray.ang.dto.V2rayConfig.Companion.DEFAULT_PORT -import com.v2ray.ang.dto.V2rayConfig.Companion.TLS import com.v2ray.ang.dto.V2rayConfig.Companion.XTLS import com.v2ray.ang.extension.toast import com.v2ray.ang.util.MmkvManager @@ -35,6 +34,7 @@ import kotlinx.android.synthetic.main.activity_server_vmess.sp_stream_security class ServerActivity : BaseActivity() { private val mainStorage by lazy { MMKV.mmkvWithID(ID_MAIN, MMKV.MULTI_PROCESS_MODE) } + private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) } private val editGuid by lazy { intent.getStringExtra("guid").orEmpty() } private val isRunning by lazy { intent.getBooleanExtra("isRunning", false) @@ -96,7 +96,7 @@ class ServerActivity : BaseActivity() { et_remarks.text = Utils.getEditable(config.remarks) et_address.text = Utils.getEditable(outbound.getServerAddress().orEmpty()) - et_port.text = Utils.getEditable(outbound.getServerPort()?.or(DEFAULT_PORT).toString()) + et_port.text = Utils.getEditable(outbound.getServerPort()?.toString() ?: DEFAULT_PORT.toString()) et_id.text = Utils.getEditable(outbound.getPassword().orEmpty()) et_alterId?.text = Utils.getEditable(outbound.settings?.vnext?.get(0)?.users?.get(0)?.alterId.toString()) if (config.configType == EConfigType.SOCKS) { @@ -229,18 +229,22 @@ class ServerActivity : BaseActivity() { if (config.configType == EConfigType.SHADOWSOCKS) { server.password = et_id.text.toString().trim() server.method = shadowsocksSecuritys[sp_security.selectedItemPosition] - } else if (config.configType == EConfigType.SOCKS && !TextUtils.isEmpty(et_security.text) && !TextUtils.isEmpty(et_id.text)) { - val socksUsersBean = V2rayConfig.OutboundBean.OutSettingsBean.ServersBean.SocksUsersBean() - socksUsersBean.user = et_security.text.toString().trim() - socksUsersBean.pass = et_id.text.toString().trim() - server.users = listOf(socksUsersBean) + } else if (config.configType == EConfigType.SOCKS) { + if (TextUtils.isEmpty(et_security.text) && TextUtils.isEmpty(et_id.text)) { + server.users = null + } else { + val socksUsersBean = V2rayConfig.OutboundBean.OutSettingsBean.ServersBean.SocksUsersBean() + socksUsersBean.user = et_security.text.toString().trim() + socksUsersBean.pass = et_id.text.toString().trim() + server.users = listOf(socksUsersBean) + } } else if (config.configType == EConfigType.TROJAN) { server.password = et_id.text.toString().trim() } } private fun saveStreamSettings(streamSetting: V2rayConfig.OutboundBean.StreamSettingsBean) { - val requestHost = et_request_host.text.toString().trim() + val requestHost = et_request_host?.text.toString().trim() val path = et_path?.text.toString().trim() var sni = streamSetting.populateTransportSettings( if (sp_network != null) networks[sp_network.selectedItemPosition] else DEFAULT_NETWORK, @@ -254,9 +258,18 @@ class ServerActivity : BaseActivity() { if (sni.isEmpty()) { sni = requestHost } + val allowInsecure = if (sp_allow_insecure != null) { + if (allowinsecures[sp_allow_insecure.selectedItemPosition].isBlank()) { + false//settingsStorage?.decodeBool(PREF_ALLOW_INSECURE) ?: false + } else { + allowinsecures[sp_allow_insecure.selectedItemPosition].toBoolean() + } + } else { + false + } streamSetting.populateTlsSettings( - if (sp_stream_security != null) streamSecuritys[sp_stream_security.selectedItemPosition] else TLS, - if (sp_allow_insecure != null) allowinsecures[sp_allow_insecure.selectedItemPosition].toBoolean() else false, + if (sp_stream_security != null) streamSecuritys[sp_stream_security.selectedItemPosition] else "", + allowInsecure, sni ) } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt index 7205bedd..8db9793f 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerCustomConfigActivity.kt @@ -15,7 +15,6 @@ import com.v2ray.ang.extension.toast import com.v2ray.ang.util.MmkvManager import com.v2ray.ang.util.Utils import kotlinx.android.synthetic.main.activity_server_custom_config.* -import java.lang.Exception class ServerCustomConfigActivity : BaseActivity() { @@ -46,7 +45,7 @@ class ServerCustomConfigActivity : BaseActivity() { */ private fun bindingServer(config: ServerConfig): Boolean { et_remarks.text = Utils.getEditable(config.remarks) - tv_content.text = Utils.getEditable(Gson().toJson(config.fullConfig)) + tv_content.text = Utils.getEditable(config.fullConfig?.toPrettyPrinting().orEmpty()) return true } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubEditActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubEditActivity.kt index 1d60a327..f35cdff6 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubEditActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubEditActivity.kt @@ -5,10 +5,12 @@ import android.support.v7.app.AlertDialog import android.text.TextUtils import android.view.Menu import android.view.MenuItem +import com.google.gson.Gson +import com.tencent.mmkv.MMKV import com.v2ray.ang.R -import com.v2ray.ang.dto.AngConfig +import com.v2ray.ang.dto.SubscriptionItem import com.v2ray.ang.extension.toast -import com.v2ray.ang.util.AngConfigManager +import com.v2ray.ang.util.MmkvManager import com.v2ray.ang.util.Utils import kotlinx.android.synthetic.main.activity_sub_edit.* @@ -17,20 +19,17 @@ class SubEditActivity : BaseActivity() { var del_config: MenuItem? = null var save_config: MenuItem? = null - private lateinit var configs: AngConfig - private var edit_index: Int = -1 //当前编辑的 + private val subStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SUB, MMKV.MULTI_PROCESS_MODE) } + private val editSubId by lazy { intent.getStringExtra("subId").orEmpty() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sub_edit) - - configs = AngConfigManager.configs - edit_index = intent.getIntExtra("position", -1) - title = getString(R.string.title_sub_setting) - if (edit_index >= 0) { - bindingServer(configs.subItem[edit_index]) + val json = subStorage?.decodeString(editSubId) + if (!json.isNullOrBlank()) { + bindingServer(Gson().fromJson(json, SubscriptionItem::class.java)) } else { clearServer() } @@ -40,7 +39,7 @@ class SubEditActivity : BaseActivity() { /** * bingding seleced server config */ - fun bindingServer(subItem: AngConfig.SubItemBean): Boolean { + private fun bindingServer(subItem: SubscriptionItem): Boolean { et_remarks.text = Utils.getEditable(subItem.remarks) et_url.text = Utils.getEditable(subItem.url) @@ -50,7 +49,7 @@ class SubEditActivity : BaseActivity() { /** * clear or init server config */ - fun clearServer(): Boolean { + private fun clearServer(): Boolean { et_remarks.text = null et_url.text = null @@ -60,12 +59,15 @@ class SubEditActivity : BaseActivity() { /** * save server config */ - fun saveServer(): Boolean { - val subItem: AngConfig.SubItemBean - if (edit_index >= 0) { - subItem = configs.subItem[edit_index] + private fun saveServer(): Boolean { + val subItem: SubscriptionItem + val json = subStorage?.decodeString(editSubId) + var subId = editSubId + if (!json.isNullOrBlank()) { + subItem = Gson().fromJson(json, SubscriptionItem::class.java) } else { - subItem = AngConfig.SubItemBean() + subId = Utils.getUuid() + subItem = SubscriptionItem() } subItem.remarks = et_remarks.text.toString() @@ -80,32 +82,23 @@ class SubEditActivity : BaseActivity() { return false } - if (AngConfigManager.addSubItem(subItem, edit_index) == 0) { - toast(R.string.toast_success) - finish() - return true - } else { - toast(R.string.toast_failure) - return false - } + subStorage?.encode(subId, Gson().toJson(subItem)) + toast(R.string.toast_success) + finish() + return true } /** * save server config */ - fun deleteServer(): Boolean { - if (edit_index >= 0) { + private fun deleteServer(): Boolean { + if (editSubId.isNotEmpty()) { AlertDialog.Builder(this).setMessage(R.string.del_config_comfirm) .setPositiveButton(android.R.string.ok) { _, _ -> - if (AngConfigManager.removeSubItem(edit_index) == 0) { - toast(R.string.toast_success) - finish() - } else { - toast(R.string.toast_failure) - } + MmkvManager.removeSubscription(editSubId) + finish() } .show() - } else { } return true } @@ -115,8 +108,7 @@ class SubEditActivity : BaseActivity() { del_config = menu?.findItem(R.id.del_config) save_config = menu?.findItem(R.id.save_config) - if (edit_index >= 0) { - } else { + if (editSubId.isEmpty()) { del_config?.isVisible = false } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubSettingActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubSettingActivity.kt index e8a6b449..5cc99703 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubSettingActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubSettingActivity.kt @@ -1,15 +1,18 @@ package com.v2ray.ang.ui import android.content.Intent -import android.support.v7.widget.LinearLayoutManager import android.view.Menu import android.view.MenuItem import com.v2ray.ang.R import kotlinx.android.synthetic.main.activity_sub_setting.* import android.os.Bundle +import android.support.v7.widget.LinearLayoutManager +import com.v2ray.ang.dto.SubscriptionItem +import com.v2ray.ang.util.MmkvManager class SubSettingActivity : BaseActivity() { + var subscriptions:List> = listOf() private val adapter by lazy { SubSettingRecyclerAdapter(this) } override fun onCreate(savedInstanceState: Bundle?) { @@ -27,7 +30,8 @@ class SubSettingActivity : BaseActivity() { override fun onResume() { super.onResume() - adapter.updateConfigList() + subscriptions = MmkvManager.decodeSubscriptions() + adapter.notifyDataSetChanged() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { @@ -40,14 +44,9 @@ class SubSettingActivity : BaseActivity() { override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.add_config -> { - startActivity(Intent(this, SubEditActivity::class.java) - .putExtra("position", -1) - ) - adapter.updateConfigList() + startActivity(Intent(this, SubEditActivity::class.java)) true } else -> super.onOptionsItemSelected(item) } - - } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubSettingRecyclerAdapter.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubSettingRecyclerAdapter.kt index 50c89d5b..56998f63 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubSettingRecyclerAdapter.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/SubSettingRecyclerAdapter.kt @@ -7,36 +7,27 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.v2ray.ang.R -import com.v2ray.ang.dto.AngConfig -import com.v2ray.ang.util.AngConfigManager import kotlinx.android.synthetic.main.item_recycler_sub_setting.view.* class SubSettingRecyclerAdapter(val activity: SubSettingActivity) : RecyclerView.Adapter() { private var mActivity: SubSettingActivity = activity - private lateinit var configs: AngConfig - init { - updateConfigList() - } - - override fun getItemCount() = configs.subItem.count() + override fun getItemCount() = mActivity.subscriptions.size override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { if (holder is MainViewHolder) { - val remarks = configs.subItem[position].remarks - val url = configs.subItem[position].url - - holder.name.text = remarks - holder.url.text = url + val subId = mActivity.subscriptions[position].first + val subItem = mActivity.subscriptions[position].second + holder.name.text = subItem.remarks + holder.url.text = subItem.url holder.itemView.setBackgroundColor(Color.TRANSPARENT) holder.layout_edit.setOnClickListener { mActivity.startActivity(Intent(mActivity, SubEditActivity::class.java) - .putExtra("position", position) + .putExtra("subId", subId) ) } - } else { } } @@ -45,15 +36,6 @@ class SubSettingRecyclerAdapter(val activity: SubSettingActivity) : RecyclerView .inflate(R.layout.item_recycler_sub_setting, parent, false)) } - fun updateConfigList() { - configs = AngConfigManager.configs - notifyDataSetChanged() - } - -// fun updateSelectedItem() { -// notifyItemChanged(configs.index) -// } - open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) class MainViewHolder(itemView: View) : BaseViewHolder(itemView) { diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt index 4e46a307..9b92aa24 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt @@ -1,6 +1,7 @@ package com.v2ray.ang.util import android.graphics.Bitmap +import android.support.v7.preference.PreferenceManager import android.text.TextUtils import com.google.gson.Gson import com.tencent.mmkv.MMKV @@ -20,8 +21,8 @@ import java.util.* object AngConfigManager { private lateinit var app: AngApplication private lateinit var angConfig: AngConfig - val configs: AngConfig get() = angConfig private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } + private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) } fun inject(app: AngApplication) { this.app = app @@ -33,7 +34,8 @@ object AngConfigManager { */ private fun loadConfig() { try { - val context = app.defaultDPreference.getPrefString(ANG_CONFIG, "") + val defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(app) + val context = defaultSharedPreferences.getString(ANG_CONFIG, "") if (!TextUtils.isEmpty(context)) { angConfig = Gson().fromJson(context, AngConfig::class.java) } else { @@ -56,18 +58,6 @@ object AngConfigManager { } } - /** - * store config to file - */ - fun storeConfigFile() { - try { - val conf = Gson().toJson(angConfig) - app.defaultDPreference.setPrefString(ANG_CONFIG, conf) - } catch (e: Exception) { - e.printStackTrace() - } - } - /** * import config form qrcode or... */ @@ -79,12 +69,12 @@ object AngConfigManager { //maybe sub if (str.startsWith(HTTP_PROTOCOL) || str.startsWith(HTTPS_PROTOCOL)) { - addSubItem(str) + MmkvManager.importUrlAsSubscription(str) return 0 } var config: ServerConfig? = null - val allowInsecure = false//app.defaultDPreference.getPrefBoolean(AppConfig.PREF_ALLOW_INSECURE, false) + val allowInsecure = false//settingsStorage?.decodeBool(AppConfig.PREF_ALLOW_INSECURE) ?: false if (str.startsWith(EConfigType.VMESS.protocolScheme)) { config = ServerConfig.create(EConfigType.VMESS) val streamSetting = config.outboundBean?.streamSettings ?: return -1 @@ -573,77 +563,4 @@ object AngConfigManager { } return 0 } - - - private fun saveSubItem(subItem: ArrayList): Int { - try { - if (subItem.count() <= 0) { - return -1 - } - for (k in 0 until subItem.count()) { - if (TextUtils.isEmpty(subItem[k].id)) { - subItem[k].id = Utils.getUuid() - } - } - angConfig.subItem = subItem - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - - fun addSubItem(subItem: AngConfig.SubItemBean, index: Int): Int { - try { - if (index >= 0) { - //edit - angConfig.subItem[index] = subItem - } else { - //add - angConfig.subItem.add(subItem) - } - - saveSubItem(angConfig.subItem) - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } - - private fun addSubItem(url: String): Int { - //already exists - angConfig.subItem.forEach { - if (it.url == url) { - return 0 - } - } - val subItem = AngConfig.SubItemBean() - subItem.remarks = "import sub" - subItem.url = url - return addSubItem(subItem, -1) - } - - /** - * - */ - fun removeSubItem(index: Int): Int { - try { - if (index < 0 || index > angConfig.subItem.count() - 1) { - return -1 - } - val subid = angConfig.subItem[index].id - MmkvManager.removeServerViaSubid(subid) - - angConfig.subItem.removeAt(index) - - storeConfigFile() - } catch (e: Exception) { - e.printStackTrace() - return -1 - } - return 0 - } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt index 087c346a..220d1438 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/MmkvManager.kt @@ -4,6 +4,7 @@ import com.google.gson.Gson import com.tencent.mmkv.MMKV import com.v2ray.ang.dto.ServerAffiliationInfo import com.v2ray.ang.dto.ServerConfig +import com.v2ray.ang.dto.SubscriptionItem object MmkvManager { const val ID_MAIN = "MAIN" @@ -17,6 +18,16 @@ object MmkvManager { private val mainStorage by lazy { MMKV.mmkvWithID(ID_MAIN, MMKV.MULTI_PROCESS_MODE) } private val serverStorage by lazy { MMKV.mmkvWithID(ID_SERVER_CONFIG, MMKV.MULTI_PROCESS_MODE) } private val serverAffStorage by lazy { MMKV.mmkvWithID(ID_SERVER_AFF, MMKV.MULTI_PROCESS_MODE) } + private val subStorage by lazy { MMKV.mmkvWithID(ID_SUB, MMKV.MULTI_PROCESS_MODE) } + + fun decodeServerList(): MutableList { + val json = mainStorage?.decodeString(KEY_ANG_CONFIGS) + return if (json.isNullOrBlank()) { + mutableListOf() + } else { + Gson().fromJson(json, Array::class.java).toMutableList() + } + } fun decodeServerConfig(guid: String): ServerConfig? { if (guid.isBlank()) { @@ -36,11 +47,13 @@ object MmkvManager { guid } serverStorage?.encode(key, Gson().toJson(config)) - val serverList= Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toMutableList() - serverList.add(guid) - mainStorage?.encode(KEY_ANG_CONFIGS, Gson().toJson(serverList)) - if (mainStorage?.decodeString(KEY_SELECTED_SERVER).isNullOrBlank()) { - mainStorage?.encode(KEY_SELECTED_SERVER, guid) + val serverList= decodeServerList() + if (!serverList.contains(key)) { + serverList.add(key) + mainStorage?.encode(KEY_ANG_CONFIGS, Gson().toJson(serverList)) + if (mainStorage?.decodeString(KEY_SELECTED_SERVER).isNullOrBlank()) { + mainStorage?.encode(KEY_SELECTED_SERVER, key) + } } return key } @@ -52,7 +65,7 @@ object MmkvManager { if (mainStorage?.decodeString(KEY_SELECTED_SERVER) == guid) { mainStorage?.remove(KEY_SELECTED_SERVER) } - val serverList= Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toMutableList() + val serverList= decodeServerList() serverList.remove(guid) mainStorage?.encode(KEY_ANG_CONFIGS, Gson().toJson(serverList)) serverStorage?.remove(guid) @@ -83,6 +96,15 @@ object MmkvManager { return Gson().fromJson(json, ServerAffiliationInfo::class.java) } + fun encodeServerTestDelayMillis(guid: String, testResult: Long) { + if (guid.isBlank()) { + return + } + val aff = decodeServerAffiliationInfo(guid) ?: ServerAffiliationInfo() + aff.testDelayMillis = testResult + serverAffStorage?.encode(guid, Gson().toJson(aff)) + } + fun clearAllTestDelayResults() { serverAffStorage?.allKeys()?.forEach { key -> decodeServerAffiliationInfo(key)?.let { aff -> @@ -91,4 +113,35 @@ object MmkvManager { } } } + + fun importUrlAsSubscription(url: String): Int { + val subscriptions = decodeSubscriptions() + subscriptions.forEach { + if (it.second.url == url) { + return 0 + } + } + val subItem = SubscriptionItem() + subItem.remarks = "import sub" + subItem.url = url + subStorage?.encode(Utils.getUuid(), Gson().toJson(subItem)) + return 1 + } + + fun decodeSubscriptions(): List> { + val subscriptions = mutableListOf>() + subStorage?.allKeys()?.forEach { key -> + val json = subStorage?.decodeString(key) + if (!json.isNullOrBlank()) { + subscriptions.add(Pair(key, Gson().fromJson(json, SubscriptionItem::class.java))) + } + } + subscriptions.sortedBy { (_, value) -> value.addedTime } + return subscriptions + } + + fun removeSubscription(subid: String) { + subStorage?.remove(subid) + removeServerViaSubid(subid) + } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt index 05aefe3e..66845af2 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt @@ -20,16 +20,12 @@ import android.util.Log import android.util.Patterns import android.webkit.URLUtil import com.tencent.mmkv.MMKV -import com.v2ray.ang.AngApplication import com.v2ray.ang.AppConfig import com.v2ray.ang.R -import com.v2ray.ang.extension.defaultDPreference import com.v2ray.ang.extension.responseLength import com.v2ray.ang.extension.toast -import com.v2ray.ang.extension.v2RayApplication import com.v2ray.ang.service.V2RayServiceManager import kotlinx.coroutines.isActive -import me.dozen.dpreference.DPreference import java.io.IOException import java.net.* import kotlin.coroutines.coroutineContext @@ -37,6 +33,7 @@ import kotlin.coroutines.coroutineContext object Utils { private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } + private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) } private val tcpTestingSockets = ArrayList() /** @@ -126,8 +123,8 @@ object Utils { /** * get remote dns servers from preference */ - fun getRemoteDnsServers(defaultDPreference: DPreference): ArrayList { - val remoteDns = defaultDPreference.getPrefString(AppConfig.PREF_REMOTE_DNS, AppConfig.DNS_AGENT) + fun getRemoteDnsServers(): ArrayList { + val remoteDns = settingsStorage?.decodeString(AppConfig.PREF_REMOTE_DNS) ?: AppConfig.DNS_AGENT val ret = ArrayList() if (!TextUtils.isEmpty(remoteDns)) { remoteDns @@ -147,8 +144,8 @@ object Utils { /** * get remote dns servers from preference */ - fun getDomesticDnsServers(defaultDPreference: DPreference): ArrayList { - val domesticDns = defaultDPreference.getPrefString(AppConfig.PREF_DOMESTIC_DNS, AppConfig.DNS_DIRECT) + fun getDomesticDnsServers(): ArrayList { + val domesticDns = settingsStorage?.decodeString(AppConfig.PREF_DOMESTIC_DNS) ?: AppConfig.DNS_DIRECT val ret = ArrayList() if (!TextUtils.isEmpty(domesticDns)) { domesticDns diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt index 610c7476..ce260012 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt @@ -4,12 +4,12 @@ import android.content.Context import android.text.TextUtils import android.util.Log import com.google.gson.* +import com.tencent.mmkv.MMKV import com.v2ray.ang.AppConfig import com.v2ray.ang.dto.V2rayConfig import org.json.JSONException import org.json.JSONObject import com.v2ray.ang.dto.EConfigType -import com.v2ray.ang.extension.defaultDPreference object V2rayConfigUtil { // private val requestObj: JsonObject by lazy { @@ -19,6 +19,8 @@ object V2rayConfigUtil { // JSONObject("""{"version":"1.1","status":"200","reason":"OK","headers":{"Content-Type":["application/octet-stream","video/mpeg"],"Transfer-Encoding":["chunked"],"Connection":["keep-alive"],"Pragma":"no-cache"}}""") // } + private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) } + data class Result(var status: Boolean, var content: String) /** @@ -28,7 +30,7 @@ object V2rayConfigUtil { try { val config = MmkvManager.decodeServerConfig(guid) ?: return Result(false, "") if (config.configType == EConfigType.CUSTOM) { - val customConfig = Gson().toJson(config.fullConfig) + val customConfig = config.fullConfig?.toPrettyPrinting() ?: return Result(false, "") Log.d("V2rayConfigUtilGoLog", customConfig) return Result(true, customConfig) } @@ -56,7 +58,7 @@ object V2rayConfigUtil { //转成Json val v2rayConfig = Gson().fromJson(assets, V2rayConfig::class.java) ?: return result - //v2rayConfig.log.loglevel = context.defaultDPreference.getPrefString(AppConfig.PREF_LOGLEVEL, "warning") + //v2rayConfig.log.loglevel = settingsStorage?.decodeString(AppConfig.PREF_LOGLEVEL) ?: "warning" inbounds(v2rayConfig, context) @@ -64,16 +66,13 @@ object V2rayConfigUtil { routing(v2rayConfig, context) - if (context.defaultDPreference.getPrefBoolean(AppConfig.PREF_LOCAL_DNS_ENABLED, false)) { + if (settingsStorage?.decodeBool(AppConfig.PREF_LOCAL_DNS_ENABLED) == true) { customLocalDns(v2rayConfig, context) } else { customRemoteDns(v2rayConfig, context) } - - val finalConfig = GsonBuilder().setPrettyPrinting().create().toJson(v2rayConfig) - result.status = true - result.content = finalConfig + result.content = v2rayConfig.toPrettyPrinting() return result } @@ -82,17 +81,17 @@ object V2rayConfigUtil { */ private fun inbounds(v2rayConfig: V2rayConfig, context: Context): Boolean { try { - //val socksPort = Utils.parseInt(context.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_SOCKS_PORT, AppConfig .PORT_SOCKS)) - //val httpPort = Utils.parseInt(context.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_HTTP_PORT, AppConfig.PORT_HTTP)) + //val socksPort = Utils.parseInt(settingsStorage?.decodeString(AppConfig.PREF_SOCKS_PORT) ?: AppConfig.PORT_SOCKS) + //val httpPort = Utils.parseInt(settingsStorage?.decodeString(AppConfig.PREF_HTTP_PORT) ?: AppConfig.PORT_HTTP) v2rayConfig.inbounds.forEach { curInbound -> - if (!context.defaultDPreference.getPrefBoolean(AppConfig.PREF_PROXY_SHARING, false)) { + if (!(settingsStorage?.decodeBool(AppConfig.PREF_PROXY_SHARING) ?: false)) { //bind all inbounds to localhost if the user requests curInbound.listen = "127.0.0.1" } } v2rayConfig.inbounds[0].port = 10808 - v2rayConfig.inbounds[0].sniffing?.enabled = context.defaultDPreference.getPrefBoolean(AppConfig.PREF_SNIFFING_ENABLED, true) + v2rayConfig.inbounds[0].sniffing?.enabled = settingsStorage?.decodeBool(AppConfig.PREF_SNIFFING_ENABLED) ?: true //v2rayConfig.inbounds[1].port = httpPort @@ -114,12 +113,12 @@ object V2rayConfigUtil { */ private fun routing(v2rayConfig: V2rayConfig, context: Context): Boolean { try { - routingUserRule(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_AGENT, ""), AppConfig.TAG_AGENT, v2rayConfig) - routingUserRule(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_DIRECT, ""), AppConfig.TAG_DIRECT, v2rayConfig) - routingUserRule(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED, ""), AppConfig.TAG_BLOCKED, v2rayConfig) + routingUserRule(settingsStorage?.decodeString(AppConfig.PREF_V2RAY_ROUTING_AGENT) ?: "", AppConfig.TAG_AGENT, v2rayConfig) + routingUserRule(settingsStorage?.decodeString(AppConfig.PREF_V2RAY_ROUTING_DIRECT) ?: "", AppConfig.TAG_DIRECT, v2rayConfig) + routingUserRule(settingsStorage?.decodeString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED) ?: "", AppConfig.TAG_BLOCKED, v2rayConfig) - v2rayConfig.routing.domainStrategy = context.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_DOMAIN_STRATEGY, "IPIfNonMatch") - val routingMode = context.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") + v2rayConfig.routing.domainStrategy = settingsStorage?.decodeString(AppConfig.PREF_ROUTING_DOMAIN_STRATEGY) ?: "IPIfNonMatch" + val routingMode = settingsStorage?.decodeString(AppConfig.PREF_ROUTING_MODE) ?: "0" // Hardcode googleapis.cn val googleapisRoute = V2rayConfig.RoutingBean.RulesBean( @@ -234,32 +233,32 @@ object V2rayConfigUtil { try { val hosts = mutableMapOf() val servers = ArrayList() - val remoteDns = Utils.getRemoteDnsServers(context.defaultDPreference) + val remoteDns = Utils.getRemoteDnsServers() remoteDns.forEach { servers.add(it) } - val domesticDns = Utils.getDomesticDnsServers(context.defaultDPreference) + val domesticDns = Utils.getDomesticDnsServers() val geositeCn = arrayListOf("geosite:cn") val geoipCn = arrayListOf("geoip:cn") - val agDomain = userRule2Domian(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_AGENT, "")) + val agDomain = userRule2Domian(settingsStorage?.decodeString(AppConfig.PREF_V2RAY_ROUTING_AGENT) ?: "") if (agDomain.size > 0) { servers.add(V2rayConfig.DnsBean.ServersBean(remoteDns.first(), 53, agDomain, null)) } - val dirDomain = userRule2Domian(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_DIRECT, "")) + val dirDomain = userRule2Domian(settingsStorage?.decodeString(AppConfig.PREF_V2RAY_ROUTING_DIRECT) ?: "") if (dirDomain.size > 0) { servers.add(V2rayConfig.DnsBean.ServersBean(domesticDns.first(), 53, dirDomain, geoipCn)) } - val routingMode = context.defaultDPreference.getPrefString(AppConfig.PREF_ROUTING_MODE, "0") + val routingMode = settingsStorage?.decodeString(AppConfig.PREF_ROUTING_MODE) ?: "0" if (routingMode == "2" || routingMode == "3") { servers.add(V2rayConfig.DnsBean.ServersBean(domesticDns.first(), 53, geositeCn, geoipCn)) } - val blkDomain = userRule2Domian(context.defaultDPreference.getPrefString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED, "")) + val blkDomain = userRule2Domian(settingsStorage?.decodeString(AppConfig.PREF_V2RAY_ROUTING_BLOCKED) ?: "") if (blkDomain.size > 0) { hosts.putAll(blkDomain.map { it to "127.0.0.1" }) } @@ -279,7 +278,7 @@ object V2rayConfigUtil { port = 53, network = "tcp,udp") - //val localDnsPort = Utils.parseInt(context.defaultDPreference.getPrefStringNonEmpty(AppConfig.PREF_LOCAL_DNS_PORT, AppConfig.PORT_LOCAL_DNS)) + //val localDnsPort = Utils.parseInt(settingsStorage?.decodeString(AppConfig.PREF_LOCAL_DNS_PORT) ?: AppConfig.PORT_LOCAL_DNS) v2rayConfig.inbounds.add( V2rayConfig.InboundBean( tag = "dns-in", @@ -344,7 +343,7 @@ object V2rayConfigUtil { val servers = ArrayList() val hosts = mutableMapOf() - Utils.getRemoteDnsServers(context.defaultDPreference).forEach { + Utils.getRemoteDnsServers().forEach { servers.add(it) } // hardcode googleapi rule to fix play store problems diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt index c510d8d0..3e076cdc 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/MainViewModel.kt @@ -24,9 +24,8 @@ import java.util.* class MainViewModel(application: Application) : AndroidViewModel(application) { private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } - private val serverAffStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SERVER_AFF, MMKV.MULTI_PROCESS_MODE) } - var serverList= Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toMutableList() + var serverList= MmkvManager.decodeServerList() private set val isRunning by lazy { MutableLiveData() } val updateListAction by lazy { MutableLiveData() } @@ -49,7 +48,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { } fun reloadServerList() { - serverList = Gson().fromJson(mainStorage?.decodeString(KEY_ANG_CONFIGS), Array::class.java).toMutableList() + serverList = MmkvManager.decodeServerList() updateListAction.value = -1 } @@ -85,11 +84,8 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { tcpingTestScope.launch { val testResult = Utils.tcping(serverAddress, serverPort) launch(Dispatchers.Main) { - MmkvManager.decodeServerAffiliationInfo(guid)?.let { aff -> - aff.testDelayMillis = testResult - serverAffStorage?.encode(guid, Gson().toJson(aff)) - updateListAction.value = serverList.indexOf(guid) - } + MmkvManager.encodeServerTestDelayMillis(guid, testResult) + updateListAction.value = serverList.indexOf(guid) } } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/SettingsViewModel.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/SettingsViewModel.kt index b2886046..d117ef2c 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/SettingsViewModel.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/viewmodel/SettingsViewModel.kt @@ -5,11 +5,14 @@ import android.arch.lifecycle.AndroidViewModel import android.content.SharedPreferences import android.support.v7.preference.PreferenceManager import android.util.Log +import com.tencent.mmkv.MMKV import com.v2ray.ang.AppConfig -import kotlinx.coroutines.GlobalScope -import kotlinx.coroutines.launch +import com.v2ray.ang.util.MmkvManager class SettingsViewModel(application: Application) : AndroidViewModel(application), SharedPreferences.OnSharedPreferenceChangeListener { + + private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) } + fun startListenPreferenceChange() { PreferenceManager.getDefaultSharedPreferences(getApplication()).registerOnSharedPreferenceChangeListener(this) } @@ -23,18 +26,27 @@ class SettingsViewModel(application: Application) : AndroidViewModel(application override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) { Log.d(AppConfig.ANG_PACKAGE, "Observe settings changed: $key") when(key) { - AppConfig.PREF_SNIFFING_ENABLED, - AppConfig.PREF_PROXY_SHARING, - AppConfig.PREF_LOCAL_DNS_ENABLED, + AppConfig.PREF_MODE, AppConfig.PREF_REMOTE_DNS, AppConfig.PREF_DOMESTIC_DNS, AppConfig.PREF_ROUTING_DOMAIN_STRATEGY, AppConfig.PREF_ROUTING_MODE, AppConfig.PREF_V2RAY_ROUTING_AGENT, AppConfig.PREF_V2RAY_ROUTING_BLOCKED, - AppConfig.PREF_V2RAY_ROUTING_DIRECT -> { - GlobalScope.launch { - } + AppConfig.PREF_V2RAY_ROUTING_DIRECT, -> { + settingsStorage?.encode(key, sharedPreferences.getString(key, "")) + } + AppConfig.PREF_SPEED_ENABLED, + AppConfig.PREF_SNIFFING_ENABLED, + AppConfig.PREF_PROXY_SHARING, + AppConfig.PREF_LOCAL_DNS_ENABLED, + AppConfig.PREF_FORWARD_IPV6, + AppConfig.PREF_PER_APP_PROXY, + AppConfig.PREF_BYPASS_APPS, -> { + settingsStorage?.encode(key, sharedPreferences.getBoolean(key, false)) + } + AppConfig.PREF_PER_APP_PROXY_SET -> { + settingsStorage?.encode(key, sharedPreferences.getStringSet(key, setOf())) } } } diff --git a/V2rayNG/dpreference/.gitignore b/V2rayNG/dpreference/.gitignore deleted file mode 100644 index 796b96d1..00000000 --- a/V2rayNG/dpreference/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/V2rayNG/dpreference/build.gradle b/V2rayNG/dpreference/build.gradle deleted file mode 100644 index 36a9e314..00000000 --- a/V2rayNG/dpreference/build.gradle +++ /dev/null @@ -1,25 +0,0 @@ -apply plugin: 'com.android.library' - -android { - compileSdkVersion Integer.parseInt("$compileSdkVer") - buildToolsVersion buildToolsVer - - defaultConfig { - minSdkVersion 17 - targetSdkVersion Integer.parseInt("$targetSdkVer") - versionCode 1 - versionName "1.0" - } - buildTypes { - release { - minifyEnabled false - } - } -} - -dependencies { - implementation fileTree(include: ['*.jar'], dir: 'libs') - testImplementation 'junit:junit:4.13' - implementation "com.android.support:support-annotations:$supportLibVersion" - implementation 'com.google.code.gson:gson:2.8.6' -} diff --git a/V2rayNG/dpreference/proguard-rules.pro b/V2rayNG/dpreference/proguard-rules.pro deleted file mode 100644 index c233c4c9..00000000 --- a/V2rayNG/dpreference/proguard-rules.pro +++ /dev/null @@ -1,17 +0,0 @@ -# Add project specific ProGuard rules here. -# By default, the flags in this file are appended to flags specified -# in /Users/wangyida/Library/Android/sdk/tools/proguard/proguard-android.txt -# You can edit the include path and order by changing the proguardFiles -# directive in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# Add any project specific keep options here: - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} diff --git a/V2rayNG/dpreference/src/main/AndroidManifest.xml b/V2rayNG/dpreference/src/main/AndroidManifest.xml deleted file mode 100644 index 8ca57060..00000000 --- a/V2rayNG/dpreference/src/main/AndroidManifest.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - diff --git a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/DPreference.java b/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/DPreference.java deleted file mode 100644 index fdc7eafe..00000000 --- a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/DPreference.java +++ /dev/null @@ -1,86 +0,0 @@ -package me.dozen.dpreference; - - -import android.content.Context; -import android.text.TextUtils; - -import java.util.LinkedHashSet; -import java.util.Set; - -/** - * Created by wangyida on 15-4-9. - */ -public class DPreference { - - Context mContext; - - /** - * preference file name - */ - String mName; - - private DPreference() { - } - - public DPreference(Context context, String name) { - this.mContext = context; - this.mName = name; - } - - public String getPrefString(final String key, final String defaultValue) { - return PrefAccessor.getString(mContext, mName, key, defaultValue); - } - - public void setPrefString(final String key, final String value) { - PrefAccessor.setString(mContext, mName, key, value); - } - - public boolean getPrefBoolean(final String key, final boolean defaultValue) { - return PrefAccessor.getBoolean(mContext, mName, key, defaultValue); - } - - public void setPrefBoolean(final String key, final boolean value) { - PrefAccessor.setBoolean(mContext, mName, key, value); - } - - public void setPrefInt(final String key, final int value) { - PrefAccessor.setInt(mContext, mName, key, value); - } - - public int getPrefInt(final String key, final int defaultValue) { - return PrefAccessor.getInt(mContext, mName, key, defaultValue); - } - - public void setPrefLong(final String key, final long value) { - PrefAccessor.setLong(mContext, mName, key, value); - } - - public long getPrefLong(final String key, final long defaultValue) { - return PrefAccessor.getLong(mContext, mName, key, defaultValue); - } - - public void setPrefStringSet(final String key, final Set value) { - PrefAccessor.setStringSet(mContext, mName, key, value); - } - - public Set getPrefStringSet(final String key, final Set defaultValue) { - return PrefAccessor.getStringSet(mContext, mName, key, defaultValue); - } - - public void setPrefStringOrderedSet(final String key, final LinkedHashSet value) { - PrefAccessor.setString(mContext, mName, key, StringSetConverter.encode(value)); - } - - public LinkedHashSet getPrefStringOrderedSet(final String key, final LinkedHashSet defaultValue) { - String value = PrefAccessor.getString(mContext, mName, key, ""); - if (TextUtils.isEmpty(value)) { - return defaultValue; - } - return StringSetConverter.decode(value); - } - - public void removePreference(final String key) { - PrefAccessor.remove(mContext, mName, key); - } - -} diff --git a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/IOUtils.java b/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/IOUtils.java deleted file mode 100644 index f8b8b961..00000000 --- a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/IOUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -package me.dozen.dpreference; - - -import android.database.Cursor; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; - -final class IOUtils { - - // NOTE: This class is focussed on InputStream, OutputStream, Reader and - // Writer. Each method should take at least one of these as a parameter, - // or return one of them. - - private static final int EOF = -1; - - /** - * The default buffer size ({@value}) to use for {@link - */ - private static final int DEFAULT_BUFFER_SIZE = 1024; - - public static void closeQuietly(InputStream is) { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - // ignore - } - } - } - - public static void closeQuietly(OutputStream os) { - if (os != null) { - try { - os.close(); - } catch (IOException e) { - // ignore - } - } - } - - public static void closeQuietly(Reader r) { - if (r != null) { - try { - r.close(); - } catch (IOException e) { - // ignore - } - } - } - - public static void closeQuietly(Cursor cursor) { - if (cursor != null && !cursor.isClosed()) { - cursor.close(); - } - } - - -} diff --git a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/IPrefImpl.java b/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/IPrefImpl.java deleted file mode 100644 index 1e05769d..00000000 --- a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/IPrefImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.dozen.dpreference; - - -import java.util.Set; - -/** - * Created by wangyida on 15/12/18. - */ -interface IPrefImpl { - - String getPrefString(String key, String defaultValue); - - void setPrefString(String key, String value); - - boolean getPrefBoolean(String key, boolean defaultValue); - - void setPrefBoolean(final String key, final boolean value); - - void setPrefInt(final String key, final int value); - - int getPrefInt(final String key, final int defaultValue); - - void setPrefFloat(final String key, final float value); - - float getPrefFloat(final String key, final float defaultValue); - - void setPrefLong(final String key, final long value); - - long getPrefLong(final String key, final long defaultValue); - - Set getPrefStringSet(String key, Set defaultValue); - - void setPrefStringSet(String key, Set value); - - void removePreference(final String key); - - boolean hasKey(String key); - -} diff --git a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PrefAccessor.java b/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PrefAccessor.java deleted file mode 100644 index 5986928d..00000000 --- a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PrefAccessor.java +++ /dev/null @@ -1,116 +0,0 @@ -package me.dozen.dpreference; - -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; - -import java.util.Set; - -/** - * Created by wangyida on 15/12/18. - */ -class PrefAccessor { - - public static String getString(Context context, String name, String key, String defaultValue) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_STRING); - String value = defaultValue; - Cursor cursor = context.getContentResolver().query(URI, null, null, null, null); - if (cursor != null && cursor.moveToFirst()) { - value = cursor.getString(cursor.getColumnIndex(PreferenceProvider.PREF_VALUE)); - } - IOUtils.closeQuietly(cursor); - return value; - } - - public static int getInt(Context context, String name, String key, int defaultValue) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_INT); - int value = defaultValue; - Cursor cursor = context.getContentResolver().query(URI, null, null, null, null); - if (cursor != null && cursor.moveToFirst()) { - value = cursor.getInt(cursor.getColumnIndex(PreferenceProvider.PREF_VALUE)); - } - IOUtils.closeQuietly(cursor); - return value; - } - - public static long getLong(Context context, String name, String key, long defaultValue) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_LONG); - long value = defaultValue; - Cursor cursor = context.getContentResolver().query(URI, null, null, null, null); - if (cursor != null && cursor.moveToFirst()) { - value = cursor.getLong(cursor.getColumnIndex(PreferenceProvider.PREF_VALUE)); - } - IOUtils.closeQuietly(cursor); - return value; - } - - public static boolean getBoolean(Context context, String name, String key, boolean defaultValue) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_BOOLEAN); - int value = defaultValue ? 1 : 0; - Cursor cursor = context.getContentResolver().query(URI, null, null, null, null); - if (cursor != null && cursor.moveToFirst()) { - value = cursor.getInt(cursor.getColumnIndex(PreferenceProvider.PREF_VALUE)); - } - IOUtils.closeQuietly(cursor); - return value == 1; - } - - public static Set getStringSet(Context context, String name, String key, Set defaultValue) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_STRING_SET); - Set value = defaultValue; - Cursor cursor = context.getContentResolver().query(URI, null, null, null, null); - if (cursor != null && cursor.moveToFirst()) { - String cursorString = cursor.getString(cursor.getColumnIndex(PreferenceProvider.PREF_VALUE)); - value = StringSetConverter.decode(cursorString); - } - IOUtils.closeQuietly(cursor); - return value; - } - - public static void remove(Context context, String name, String key) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_STRING); - context.getContentResolver().delete(URI, null, null); - } - - public static void setString(Context context, String name, String key, String value) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_STRING); - ContentValues cv = new ContentValues(); - cv.put(PreferenceProvider.PREF_KEY, key); - cv.put(PreferenceProvider.PREF_VALUE, value); - context.getContentResolver().update(URI, cv, null, null); - } - - public static void setBoolean(Context context, String name, String key, boolean value) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_BOOLEAN); - ContentValues cv = new ContentValues(); - cv.put(PreferenceProvider.PREF_KEY, key); - cv.put(PreferenceProvider.PREF_VALUE, value); - context.getContentResolver().update(URI, cv, null, null); - } - - public static void setInt(Context context, String name, String key, int value) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_INT); - ContentValues cv = new ContentValues(); - cv.put(PreferenceProvider.PREF_KEY, key); - cv.put(PreferenceProvider.PREF_VALUE, value); - context.getContentResolver().update(URI, cv, null, null); - } - - public static void setLong(Context context, String name, String key, long value) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_LONG); - ContentValues cv = new ContentValues(); - cv.put(PreferenceProvider.PREF_KEY, key); - cv.put(PreferenceProvider.PREF_VALUE, value); - context.getContentResolver().update(URI, cv, null, null); - } - - public static void setStringSet(Context context, String name, String key, Set value) { - Uri URI = PreferenceProvider.buildUri(name, key, PreferenceProvider.PREF_STRING_SET); - ContentValues cv = new ContentValues(); - cv.put(PreferenceProvider.PREF_KEY, key); - cv.put(PreferenceProvider.PREF_VALUE, StringSetConverter.encode(value)); - context.getContentResolver().update(URI, cv, null, null); - } -} - diff --git a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PreferenceImpl.java b/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PreferenceImpl.java deleted file mode 100644 index bf36fa95..00000000 --- a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PreferenceImpl.java +++ /dev/null @@ -1,133 +0,0 @@ -package me.dozen.dpreference; - -import android.content.Context; -import android.content.SharedPreferences; - -import java.util.Set; - -/** - * Created by wangyida on 15/12/18. - */ -class PreferenceImpl implements IPrefImpl { - - private Context mContext; - - private String mPrefName; - - public PreferenceImpl(Context context, String prefName) { - mContext = context; - mPrefName = prefName; - } - - public String getPrefString(final String key, - final String defaultValue) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - return settings.getString(key, defaultValue); - } - - public void setPrefString(final String key, final String value) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - settings.edit().putString(key, value).apply(); - } - - public boolean getPrefBoolean(final String key, - final boolean defaultValue) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - return settings.getBoolean(key, defaultValue); - } - - public boolean hasKey(final String key) { - return mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE) - .contains(key); - } - - public void setPrefBoolean(final String key, final boolean value) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - settings.edit().putBoolean(key, value).apply(); - } - - public void setPrefInt(final String key, final int value) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - settings.edit().putInt(key, value).apply(); - } - - @Override - public Set getPrefStringSet(String key, Set defaultValue) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - return settings.getStringSet(key, defaultValue); - } - - @Override - public void setPrefStringSet(String key, Set value) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - settings.edit().putStringSet(key, value).apply(); - } - - public void increasePrefInt(final String key) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - increasePrefInt(settings, key); - } - - public void increasePrefInt(final SharedPreferences sp, final String key) { - final int v = sp.getInt(key, 0) + 1; - sp.edit().putInt(key, v).apply(); - } - - public void increasePrefInt(final SharedPreferences sp, final String key, - final int increment) { - final int v = sp.getInt(key, 0) + increment; - sp.edit().putInt(key, v).apply(); - } - - public int getPrefInt(final String key, final int defaultValue) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - return settings.getInt(key, defaultValue); - } - - public void setPrefFloat(final String key, final float value) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - settings.edit().putFloat(key, value).apply(); - } - - public float getPrefFloat(final String key, final float defaultValue) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - return settings.getFloat(key, defaultValue); - } - - public void setPrefLong(final String key, final long value) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - settings.edit().putLong(key, value).apply(); - } - - public long getPrefLong(final String key, final long defaultValue) { - final SharedPreferences settings = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - return settings.getLong(key, defaultValue); - } - - - public void removePreference(final String key) { - final SharedPreferences prefs = - mContext.getSharedPreferences(mPrefName, Context.MODE_PRIVATE); - prefs.edit().remove(key).apply(); - } - - public void clearPreference(final SharedPreferences p) { - final SharedPreferences.Editor editor = p.edit(); - editor.clear(); - editor.apply(); - } - -} diff --git a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PreferenceProvider.java b/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PreferenceProvider.java deleted file mode 100644 index f8bf2a94..00000000 --- a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/PreferenceProvider.java +++ /dev/null @@ -1,267 +0,0 @@ -package me.dozen.dpreference; - -import android.content.ContentProvider; -import android.content.ContentValues; -import android.content.UriMatcher; -import android.database.Cursor; -import android.database.MatrixCursor; -import android.net.Uri; -import android.support.annotation.Nullable; -import android.text.TextUtils; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by wangyida on 15/12/18. - */ -public class PreferenceProvider extends ContentProvider { - - private static final String TAG = PreferenceProvider.class.getSimpleName(); - - private static final String AUTHORITY = "com.v2ray.ang.dpreference"; - - public static final String CONTENT_PREF_BOOLEAN_URI = "content://" + AUTHORITY + "/boolean/"; - public static final String CONTENT_PREF_STRING_URI = "content://" + AUTHORITY + "/string/"; - public static final String CONTENT_PREF_INT_URI = "content://" + AUTHORITY + "/integer/"; - public static final String CONTENT_PREF_LONG_URI = "content://" + AUTHORITY + "/long/"; - public static final String CONTENT_PREF_STRING_SET_URI = "content://" + AUTHORITY + "/string_set/"; - - - public static final String PREF_KEY = "key"; - public static final String PREF_VALUE = "value"; - - public static final int PREF_BOOLEAN = 1; - public static final int PREF_STRING = 2; - public static final int PREF_INT = 3; - public static final int PREF_LONG = 4; - public static final int PREF_STRING_SET = 5; - - private static final UriMatcher sUriMatcher; - - static { - sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); - sUriMatcher.addURI(AUTHORITY, "boolean/*/*", PREF_BOOLEAN); - sUriMatcher.addURI(AUTHORITY, "string/*/*", PREF_STRING); - sUriMatcher.addURI(AUTHORITY, "integer/*/*", PREF_INT); - sUriMatcher.addURI(AUTHORITY, "long/*/*", PREF_LONG); - sUriMatcher.addURI(AUTHORITY, "string_set/*/*", PREF_STRING_SET); - - } - - @Override - public boolean onCreate() { - return true; - } - - @Nullable - @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { - MatrixCursor cursor = null; - PrefModel model = getPrefModelByUri(uri); - switch (sUriMatcher.match(uri)) { - case PREF_BOOLEAN: - if (getDPreference(model.getName()).hasKey(model.getKey())) { - cursor = preferenceToCursor(getDPreference(model.getName()).getPrefBoolean(model.getKey(), false) ? 1 : 0); - } - break; - case PREF_STRING: - if (getDPreference(model.getName()).hasKey(model.getKey())) { - cursor = preferenceToCursor(getDPreference(model.getName()).getPrefString(model.getKey(), "")); - } - break; - case PREF_INT: - if (getDPreference(model.getName()).hasKey(model.getKey())) { - cursor = preferenceToCursor(getDPreference(model.getName()).getPrefInt(model.getKey(), -1)); - } - break; - case PREF_LONG: - if (getDPreference(model.getName()).hasKey(model.getKey())) { - cursor = preferenceToCursor(getDPreference(model.getName()).getPrefLong(model.getKey(), -1)); - } - break; - case PREF_STRING_SET: - if (getDPreference(model.getName()).hasKey(model.getKey())) { - cursor = preferenceToCursor(getDPreference(model.getName()).getPrefStringSet(model.getKey(), null)); - } - break; - } - return cursor; - } - - @Nullable - @Override - public String getType(Uri uri) { - return null; - } - - @Nullable - @Override - public Uri insert(Uri uri, ContentValues values) { - throw new IllegalStateException("insert unsupport!!!"); - } - - @Override - public int delete(Uri uri, String selection, String[] selectionArgs) { - switch (sUriMatcher.match(uri)) { - case PREF_BOOLEAN: - case PREF_LONG: - case PREF_STRING: - case PREF_INT: - case PREF_STRING_SET: - PrefModel model = getPrefModelByUri(uri); - if (model != null) { - getDPreference(model.getName()).removePreference(model.getKey()); - } - break; - default: - throw new IllegalStateException(" unsupported uri : " + uri); - } - return 0; - } - - @Override - public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { - PrefModel model = getPrefModelByUri(uri); - if (model == null) { - throw new IllegalArgumentException("update prefModel is null"); - } - switch (sUriMatcher.match(uri)) { - case PREF_BOOLEAN: - persistBoolean(model.getName(), values); - break; - case PREF_LONG: - persistLong(model.getName(), values); - break; - case PREF_STRING: - persistString(model.getName(), values); - break; - case PREF_INT: - persistInt(model.getName(), values); - break; - case PREF_STRING_SET: - persistStringSet(model.getName(), values); - break; - default: - throw new IllegalStateException("update unsupported uri : " + uri); - } - return 0; - } - - private static String[] PREFERENCE_COLUMNS = {PREF_VALUE}; - - private MatrixCursor preferenceToCursor(T value) { - MatrixCursor matrixCursor = new MatrixCursor(PREFERENCE_COLUMNS, 1); - MatrixCursor.RowBuilder builder = matrixCursor.newRow(); - builder.add(value); - return matrixCursor; - } - - private void persistInt(String name, ContentValues values) { - if (values == null) { - throw new IllegalArgumentException(" values is null!!!"); - } - String kInteger = values.getAsString(PREF_KEY); - int vInteger = values.getAsInteger(PREF_VALUE); - getDPreference(name).setPrefInt(kInteger, vInteger); - } - - private void persistBoolean(String name, ContentValues values) { - if (values == null) { - throw new IllegalArgumentException(" values is null!!!"); - } - String kBoolean = values.getAsString(PREF_KEY); - boolean vBoolean = values.getAsBoolean(PREF_VALUE); - getDPreference(name).setPrefBoolean(kBoolean, vBoolean); - } - - private void persistLong(String name, ContentValues values) { - if (values == null) { - throw new IllegalArgumentException(" values is null!!!"); - } - String kLong = values.getAsString(PREF_KEY); - long vLong = values.getAsLong(PREF_VALUE); - getDPreference(name).setPrefLong(kLong, vLong); - } - - private void persistString(String name, ContentValues values) { - if (values == null) { - throw new IllegalArgumentException(" values is null!!!"); - } - String kString = values.getAsString(PREF_KEY); - String vString = values.getAsString(PREF_VALUE); - getDPreference(name).setPrefString(kString, vString); - } - - private void persistStringSet(String name, ContentValues values) { - if (values == null) { - throw new IllegalArgumentException(" values is null!!!"); - } - String kString = values.getAsString(PREF_KEY); - String vString = values.getAsString(PREF_VALUE); - getDPreference(name).setPrefStringSet(kString, StringSetConverter.decode(vString)); - } - - private static Map sPreferences = new HashMap<>(); - - private IPrefImpl getDPreference(String name) { - if (TextUtils.isEmpty(name)) { - throw new IllegalArgumentException("getDPreference name is null!!!"); - } - if (sPreferences.get(name) == null) { - IPrefImpl pref = new PreferenceImpl(getContext(), name); - sPreferences.put(name, pref); - } - return sPreferences.get(name); - } - - private PrefModel getPrefModelByUri(Uri uri) { - if (uri == null || uri.getPathSegments().size() != 3) { - throw new IllegalArgumentException("getPrefModelByUri uri is wrong : " + uri); - } - String name = uri.getPathSegments().get(1); - String key = uri.getPathSegments().get(2); - return new PrefModel(name, key); - } - - - public static Uri buildUri(String name, String key, int type) { - return Uri.parse(getUriByType(type) + name + "/" + key); - } - - private static String getUriByType(int type) { - switch (type) { - case PreferenceProvider.PREF_BOOLEAN: - return PreferenceProvider.CONTENT_PREF_BOOLEAN_URI; - case PreferenceProvider.PREF_INT: - return PreferenceProvider.CONTENT_PREF_INT_URI; - case PreferenceProvider.PREF_LONG: - return PreferenceProvider.CONTENT_PREF_LONG_URI; - case PreferenceProvider.PREF_STRING: - return PreferenceProvider.CONTENT_PREF_STRING_URI; - case PreferenceProvider.PREF_STRING_SET: - return PreferenceProvider.CONTENT_PREF_STRING_SET_URI; - } - throw new IllegalStateException("unsupport preftype : " + type); - } - - private static class PrefModel { - String name; - - String key; - - public PrefModel(String name, String key) { - this.name = name; - this.key = key; - } - - public String getName() { - return name; - } - - public String getKey() { - return key; - } - } - -} diff --git a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/StringSetConverter.java b/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/StringSetConverter.java deleted file mode 100644 index 8350d46b..00000000 --- a/V2rayNG/dpreference/src/main/java/me/dozen/dpreference/StringSetConverter.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.dozen.dpreference; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import java.lang.reflect.Type; -import java.util.LinkedHashSet; -import java.util.Set; - -public class StringSetConverter { - private static final Gson gson = new Gson(); - - public static String encode(Set src) { - return gson.toJson(src); - } - - public static LinkedHashSet decode(String json) { - Type setType = new TypeToken>() { - }.getType(); - return gson.fromJson(json, setType); - } -} diff --git a/V2rayNG/settings.gradle b/V2rayNG/settings.gradle index 61ddbe8d..e7b4def4 100644 --- a/V2rayNG/settings.gradle +++ b/V2rayNG/settings.gradle @@ -1 +1 @@ -include ':app', ':dpreference' +include ':app' From 463f45804f396987fb24780683dcab708d6c0725 Mon Sep 17 00:00:00 2001 From: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Date: Fri, 26 Mar 2021 20:55:00 -0400 Subject: [PATCH 4/6] Add missing data fields for config Make custom config able to parse any config Fix subscription TODO Fix some bugs - vless tls should clear out flow - trojan tls settings - import with null rawQuery link - socks share link username - remove an item in the middle of server list --- .../kotlin/com/v2ray/ang/dto/V2rayConfig.kt | 83 ++++++++++++++----- .../v2ray/ang/service/V2RayServiceManager.kt | 2 +- .../com/v2ray/ang/ui/MainRecyclerAdapter.kt | 10 ++- .../kotlin/com/v2ray/ang/ui/ServerActivity.kt | 23 +++-- .../com/v2ray/ang/util/AngConfigManager.kt | 25 ++++-- 5 files changed, 102 insertions(+), 41 deletions(-) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt index 4cb83de7..b4ce85ae 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt @@ -15,7 +15,11 @@ data class V2rayConfig( val inbounds: ArrayList, var outbounds: ArrayList, var dns: DnsBean, - val routing: RoutingBean) { + val routing: RoutingBean, + val api: Any? = null, + val transport: Any? = null, + val reverse: Any? = null, + val fakedns: Any? = null) { companion object { const val DEFAULT_PORT = 443 const val DEFAULT_SECURITY = "auto" @@ -37,8 +41,10 @@ data class V2rayConfig( var port: Int, var protocol: String, var listen: String? = null, - val settings: InSettingsBean, - val sniffing: SniffingBean?) { + val settings: Any? = null, + val sniffing: SniffingBean?, + val streamSettings: Any? = null, + val allocate: Any? = null) { data class InSettingsBean(val auth: String? = null, val udp: Boolean? = null, @@ -48,18 +54,32 @@ data class V2rayConfig( val network: String? = null) data class SniffingBean(var enabled: Boolean, - val destOverride: List) + val destOverride: List, + val metadataOnly: Boolean? = null) } data class OutboundBean(val tag: String = "proxy", var protocol: String, - var settings: OutSettingsBean?, + var settings: OutSettingsBean? = null, var streamSettings: StreamSettingsBean? = null, + val proxySettings: Any? = null, + val sendThrough: String? = null, val mux: MuxBean? = MuxBean(false)) { data class OutSettingsBean(var vnext: List? = null, var servers: List? = null, - var response: Response? = null) { + /*Blackhole*/ + var response: Response? = null, + /*DNS*/ + val network: String? = null, + val address: String? = null, + val port: Int? = null, + /*Freedom*/ + val domainStrategy: String? = null, + val redirect: String? = null, + val userLevel: Int? = null, + /*Loopback*/ + val inboundTag: String? = null) { data class VnextBean(var address: String = "", var port: Int = DEFAULT_PORT, @@ -98,7 +118,10 @@ data class V2rayConfig( var httpSettings: HttpSettingsBean? = null, var tlsSettings: TlsSettingsBean? = null, var quicSettings: QuicSettingBean? = null, - var xtlsSettings: TlsSettingsBean? = null + var xtlsSettings: TlsSettingsBean? = null, + val grpcSettings: Any? = null, + val dsSettings: Any? = null, + val sockopt: Any? = null ) { data class TcpSettingsBean(var header: HeaderBean = HeaderBean()) { @@ -133,7 +156,10 @@ data class V2rayConfig( var path: String = "") data class TlsSettingsBean(var allowInsecure: Boolean = false, - var serverName: String = "") + var serverName: String = "", + val alpn: List? = null, + val certificates: List? = null, + val disableSystemRoot: Boolean? = null) data class QuicSettingBean(var security: String = "none", var key: String = "", @@ -248,14 +274,12 @@ data class V2rayConfig( } fun getSecurityEncryption(): String? { - if (protocol.equals(EConfigType.VMESS.name, true)) { - return settings?.vnext?.get(0)?.users?.get(0)?.security - } else if (protocol.equals(EConfigType.VLESS.name, true)) { - return settings?.vnext?.get(0)?.users?.get(0)?.encryption - } else if (protocol.equals(EConfigType.SHADOWSOCKS.name, true)) { - return settings?.servers?.get(0)?.method + return when { + protocol.equals(EConfigType.VMESS.name, true) -> settings?.vnext?.get(0)?.users?.get(0)?.security + protocol.equals(EConfigType.VLESS.name, true) -> settings?.vnext?.get(0)?.users?.get(0)?.encryption + protocol.equals(EConfigType.SHADOWSOCKS.name, true) -> settings?.servers?.get(0)?.method + else -> null } - return null } fun getTransportSettingDetails(): List? { @@ -300,25 +324,39 @@ data class V2rayConfig( } } - //data class DnsBean(var servers: List) data class DnsBean(var servers: List? = null, - var hosts: Map? = null + var hosts: Map? = null, + val clientIp: String? = null, + val disableCache: Boolean? = null, + val tag: String? = null ) { data class ServersBean(var address: String = "", var port: Int = 0, var domains: List?, - var expectIPs: List?) + var expectIPs: List?, + val clientIp: String? = null) } data class RoutingBean(var domainStrategy: String, - var rules: ArrayList) { + val domainMatcher: String? = null, + var rules: ArrayList, + val balancers: List? = null) { data class RulesBean(var type: String = "", var ip: ArrayList? = null, var domain: ArrayList? = null, var outboundTag: String = "", + var balancerTag: String? = null, var port: String? = null, - var inboundTag: ArrayList? = null) + val sourcePort: String? = null, + val network: String? = null, + val source: List? = null, + val user: List? = null, + var inboundTag: List? = null, + val protocol: List? = null, + val attrs: String? = null, + val domainMatcher: String? = null + ) } data class PolicyBean(var levels: Map, @@ -327,7 +365,10 @@ data class V2rayConfig( var handshake: Int? = null, var connIdle: Int? = null, var uplinkOnly: Int? = null, - var downlinkOnly: Int? = null) + var downlinkOnly: Int? = null, + val statsUserUplink: Boolean? = null, + val statsUserDownlink: Boolean? = null, + var bufferSize: Int? = null) } fun getProxyOutbound(): OutboundBean? { diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt index adcb2c5b..1387439f 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt @@ -148,7 +148,7 @@ object V2RayServiceManager { currentConfig = config v2rayPoint.enableLocalDNS = settingsStorage?.decodeBool(AppConfig.PREF_LOCAL_DNS_ENABLED) ?: false v2rayPoint.forwardIpv6 = settingsStorage?.decodeBool(AppConfig.PREF_FORWARD_IPV6) ?: false - v2rayPoint.proxyOnly = settingsStorage?.decodeString(AppConfig.PREF_MODE) ?: "VPN" == "VPN" + v2rayPoint.proxyOnly = settingsStorage?.decodeString(AppConfig.PREF_MODE) ?: "VPN" != "VPN" try { v2rayPoint.runLoop() diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt index 0fe9fbd2..385e0842 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt @@ -8,10 +8,12 @@ import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import com.google.gson.Gson import com.tencent.mmkv.MMKV import com.v2ray.ang.AppConfig import com.v2ray.ang.R import com.v2ray.ang.dto.EConfigType +import com.v2ray.ang.dto.SubscriptionItem import com.v2ray.ang.extension.toast import com.v2ray.ang.helper.ItemTouchHelperAdapter import com.v2ray.ang.helper.ItemTouchHelperViewHolder @@ -34,6 +36,7 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter by lazy { mActivity.resources.getStringArray(R.array.share_method) } @@ -58,7 +61,11 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter= 0) { sp_stream_security?.setSelection(streamSecurity) - streamSetting.tlsSettings?: streamSetting.xtlsSettings?.let { tlsSetting -> + (streamSetting.tlsSettings?: streamSetting.xtlsSettings)?.let { tlsSetting -> val allowinsecure = Utils.arrayFind(allowinsecures, tlsSetting.allowInsecure.toString()) if (allowinsecure >= 0) { sp_allow_insecure?.setSelection(allowinsecure) @@ -198,7 +198,7 @@ class ServerActivity : BaseActivity() { saveServers(server, port, config) } config.outboundBean?.streamSettings?.let { - saveStreamSettings(it) + saveStreamSettings(it, config) } MmkvManager.encodeServerConfig(editGuid, config) @@ -217,8 +217,10 @@ class ServerActivity : BaseActivity() { } else if (config.configType == EConfigType.VLESS) { vnext.users[0].encryption = et_security.text.toString().trim() if (streamSecuritys[sp_stream_security.selectedItemPosition] == XTLS) { -// vnext.users[0].flow = if (flows[sp_flow.selectedItemPosition].isBlank()) DEFAULT_FLOW +// vnext.users[0].flow = if (flows[sp_flow.selectedItemPosition].isBlank()) V2rayConfig.DEFAULT_FLOW // else flows[sp_flow.selectedItemPosition] + } else { + vnext.users[0].flow = "" } } } @@ -243,7 +245,7 @@ class ServerActivity : BaseActivity() { } } - private fun saveStreamSettings(streamSetting: V2rayConfig.OutboundBean.StreamSettingsBean) { + private fun saveStreamSettings(streamSetting: V2rayConfig.OutboundBean.StreamSettingsBean, config: ServerConfig) { val requestHost = et_request_host?.text.toString().trim() val path = et_path?.text.toString().trim() var sni = streamSetting.populateTransportSettings( @@ -258,17 +260,14 @@ class ServerActivity : BaseActivity() { if (sni.isEmpty()) { sni = requestHost } - val allowInsecure = if (sp_allow_insecure != null) { - if (allowinsecures[sp_allow_insecure.selectedItemPosition].isBlank()) { - false//settingsStorage?.decodeBool(PREF_ALLOW_INSECURE) ?: false - } else { - allowinsecures[sp_allow_insecure.selectedItemPosition].toBoolean() - } + val allowInsecure = if (sp_allow_insecure == null || allowinsecures[sp_allow_insecure.selectedItemPosition].isBlank()) { + false//settingsStorage?.decodeBool(PREF_ALLOW_INSECURE) ?: false } else { - false + allowinsecures[sp_allow_insecure.selectedItemPosition].toBoolean() } + val defaultTls = if (config.configType == EConfigType.TROJAN) V2rayConfig.TLS else "" streamSetting.populateTlsSettings( - if (sp_stream_security != null) streamSecuritys[sp_stream_security.selectedItemPosition] else "", + if (sp_stream_security != null) streamSecuritys[sp_stream_security.selectedItemPosition] else defaultTls, allowInsecure, sni ) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt index 9b92aa24..639519e5 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt @@ -186,10 +186,14 @@ object AngConfigManager { server.port = uri.port server.password = uri.userInfo } - val queryParam = uri.rawQuery.split("&") - .map { it.split("=").let { (k, v) -> k to URLDecoder.decode(v, "utf-8")!! } } - .toMap() - config.outboundBean?.streamSettings?.populateTlsSettings(TLS, allowInsecure, queryParam["sni"] ?: "") + var sni = "" + uri.rawQuery?.let { rawQuery -> + val queryParam = rawQuery.split("&") + .map { it.split("=").let { (k, v) -> k to URLDecoder.decode(v, "utf-8")!! } } + .toMap() + sni = queryParam["sni"] ?: "" + } + config.outboundBean?.streamSettings?.populateTlsSettings(TLS, allowInsecure, sni) } else if (str.startsWith(EConfigType.VLESS.protocolScheme)) { val uri = URI(str) val queryParam = uri.rawQuery.split("&") @@ -317,7 +321,7 @@ object AngConfigManager { Utils.encode(json) } EConfigType.CUSTOM -> "" - EConfigType.SHADOWSOCKS, EConfigType.SOCKS -> { + EConfigType.SHADOWSOCKS -> { val remark = "#" + Utils.urlEncode(config.remarks) val url = String.format("%s:%s@%s:%s", outbound.getSecurityEncryption(), @@ -326,6 +330,15 @@ object AngConfigManager { outbound.getServerPort()) Utils.encode(url) + remark } + EConfigType.SOCKS -> { + val remark = "#" + Utils.urlEncode(config.remarks) + val url = String.format("%s:%s@%s:%s", + outbound.settings?.servers?.get(0)?.users?.get(0)?.user, + outbound.getPassword(), + outbound.getServerAddress(), + outbound.getServerPort()) + Utils.encode(url) + remark + } EConfigType.VLESS -> { val remark = "#" + Utils.urlEncode(config.remarks) @@ -396,7 +409,7 @@ object AngConfigManager { EConfigType.TROJAN -> { val remark = "#" + Utils.urlEncode(config.remarks) var query = "" - streamSetting.tlsSettings?: streamSetting.xtlsSettings?.let { tlsSetting -> + (streamSetting.tlsSettings?: streamSetting.xtlsSettings)?.let { tlsSetting -> if (!TextUtils.isEmpty(tlsSetting.serverName)) { query = "?sni=${tlsSetting.serverName}" } From 00e6314afe2a1f29cc8580c4d058387aa80e78bd Mon Sep 17 00:00:00 2001 From: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Date: Fri, 26 Mar 2021 20:55:00 -0400 Subject: [PATCH 5/6] Merge branch 'master' into new-storage --- .../src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt | 4 ++-- .../src/main/kotlin/com/v2ray/ang/dto/VmessQRCode.kt | 3 ++- .../main/kotlin/com/v2ray/ang/ui/ServerActivity.kt | 3 --- .../kotlin/com/v2ray/ang/util/AngConfigManager.kt | 11 +++++++++-- .../main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt | 4 ++++ 5 files changed, 17 insertions(+), 8 deletions(-) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt index b4ce85ae..76e410cb 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt @@ -9,9 +9,9 @@ import com.google.gson.reflect.TypeToken import java.lang.reflect.Type data class V2rayConfig( - val stats: Any? = null, + var stats: Any? = null, val log: LogBean, - val policy: PolicyBean, + var policy: PolicyBean?, val inbounds: ArrayList, var outbounds: ArrayList, var dns: DnsBean, diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/VmessQRCode.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/VmessQRCode.kt index 30618017..d8363ca5 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/VmessQRCode.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/VmessQRCode.kt @@ -10,4 +10,5 @@ data class VmessQRCode(var v: String = "", var type: String = "", var host: String = "", var path: String = "", - var tls: String = "") \ No newline at end of file + var tls: String = "", + var sni: String = "") diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt index 1b6499a2..7b2d11ec 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ServerActivity.kt @@ -257,9 +257,6 @@ class ServerActivity : BaseActivity() { requestHost, path ) - if (sni.isEmpty()) { - sni = requestHost - } val allowInsecure = if (sp_allow_insecure == null || allowinsecures[sp_allow_insecure.selectedItemPosition].isBlank()) { false//settingsStorage?.decodeBool(PREF_ALLOW_INSECURE) ?: false } else { diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt index 639519e5..290425c7 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt @@ -110,7 +110,8 @@ object AngConfigManager { } val sni = streamSetting.populateTransportSettings(vmessQRCode.net, vmessQRCode.type, vmessQRCode.host, vmessQRCode.path, vmessQRCode.path, vmessQRCode.host, vmessQRCode.path) - streamSetting.populateTlsSettings(vmessQRCode.tls, allowInsecure, sni) + streamSetting.populateTlsSettings(vmessQRCode.tls, allowInsecure, + if (vmessQRCode.sni.isNotBlank()) vmessQRCode.sni else sni) } } } else if (str.startsWith(EConfigType.SHADOWSOCKS.protocolScheme)) { @@ -212,7 +213,7 @@ object AngConfigManager { val sni = streamSetting.populateTransportSettings(queryParam["type"] ?: "tcp", queryParam["headerType"], queryParam["host"], queryParam["path"], queryParam["seed"], queryParam["quicSecurity"], queryParam["key"]) - streamSetting.populateTlsSettings(queryParam["security"] ?: "", allowInsecure, sni) + streamSetting.populateTlsSettings(queryParam["security"] ?: "", allowInsecure, queryParam["sni"] ?: sni) } if (config == null){ return R.string.toast_incorrect_protocol @@ -312,6 +313,7 @@ object AngConfigManager { vmessQRCode.aid = outbound.settings?.vnext?.get(0)?.users?.get(0)?.alterId.toString() vmessQRCode.net = streamSetting.network vmessQRCode.tls = streamSetting.security + vmessQRCode.sni = streamSetting.tlsSettings?.serverName.orEmpty() outbound.getTransportSettingDetails()?.let { transportDetails -> vmessQRCode.type = transportDetails[0] vmessQRCode.host = transportDetails[1] @@ -352,6 +354,11 @@ object AngConfigManager { else outbound.getSecurityEncryption().orEmpty() dicQuery["security"] = if (streamSetting.security.isEmpty()) "none" else streamSetting.security + (streamSetting.tlsSettings?: streamSetting.xtlsSettings)?.let { tlsSetting -> + if (!TextUtils.isEmpty(tlsSetting.serverName)) { + dicQuery["sni"] = tlsSetting.serverName + } + } dicQuery["type"] = if (streamSetting.network.isEmpty()) V2rayConfig.DEFAULT_NETWORK else streamSetting.network diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt index ce260012..62180964 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt @@ -71,6 +71,10 @@ object V2rayConfigUtil { } else { customRemoteDns(v2rayConfig, context) } + if (settingsStorage?.decodeBool(AppConfig.PREF_SPEED_ENABLED) != true) { + v2rayConfig.stats = null + v2rayConfig.policy = null + } result.status = true result.content = v2rayConfig.toPrettyPrinting() return result From fb017c6659f202af568035ed73144d3345cc5c20 Mon Sep 17 00:00:00 2001 From: yuhan6665 <1588741+yuhan6665@users.noreply.github.com> Date: Fri, 26 Mar 2021 20:55:00 -0400 Subject: [PATCH 6/6] Add migration - Fix some compile warnings - Add migration method - Add vmessBean migration --- .../kotlin/com/v2ray/ang/AngApplication.kt | 2 - .../kotlin/com/v2ray/ang/extension/_Ext.kt | 2 +- .../com/v2ray/ang/ui/BaseDrawerActivity.kt | 199 ------------------ .../kotlin/com/v2ray/ang/ui/MainActivity.kt | 19 +- .../com/v2ray/ang/ui/MainRecyclerAdapter.kt | 4 +- .../com/v2ray/ang/ui/PerAppProxyActivity.kt | 4 +- .../v2ray/ang/ui/RoutingSettingsFragment.kt | 4 +- .../com/v2ray/ang/ui/ScannerActivity.kt | 4 +- .../kotlin/com/v2ray/ang/ui/TaskerActivity.kt | 8 +- .../com/v2ray/ang/util/AngConfigManager.kt | 156 +++++++++++--- .../com/v2ray/ang/util/AppManagerUtil.kt | 2 +- .../main/kotlin/com/v2ray/ang/util/Utils.kt | 2 +- .../com/v2ray/ang/util/V2rayConfigUtil.kt | 16 +- .../src/main/res/values-zh-rCN/strings.xml | 2 + .../src/main/res/values-zh-rTW/strings.xml | 2 + V2rayNG/app/src/main/res/values/strings.xml | 2 + 16 files changed, 173 insertions(+), 255 deletions(-) delete mode 100644 V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/BaseDrawerActivity.kt diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt index 420a6827..38787b78 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt @@ -3,7 +3,6 @@ package com.v2ray.ang import android.support.multidex.MultiDexApplication import android.support.v7.preference.PreferenceManager import com.tencent.mmkv.MMKV -import com.v2ray.ang.util.AngConfigManager class AngApplication : MultiDexApplication() { companion object { @@ -25,7 +24,6 @@ class AngApplication : MultiDexApplication() { defaultSharedPreferences.edit().putInt(PREF_LAST_VERSION, BuildConfig.VERSION_CODE).apply() //Logger.init().logLevel(if (BuildConfig.DEBUG) LogLevel.FULL else LogLevel.NONE) - AngConfigManager.inject(this) MMKV.initialize(this) } } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt index b0e74368..4d317e67 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt @@ -27,7 +27,7 @@ inline fun Context.toast(message: CharSequence): Toast = ToastCompat show() } -fun JSONObject.putOpt(pair: Pair) = putOpt(pair.first, pair.second)!! +fun JSONObject.putOpt(pair: Pair) = putOpt(pair.first, pair.second) fun JSONObject.putOpt(pairs: Map) = pairs.forEach { putOpt(it.key to it.value) } const val threshold = 1000 diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/BaseDrawerActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/BaseDrawerActivity.kt deleted file mode 100644 index 231575bb..00000000 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/BaseDrawerActivity.kt +++ /dev/null @@ -1,199 +0,0 @@ -package com.v2ray.ang.ui - -import android.app.ActivityOptions -import android.app.FragmentManager -import android.content.Intent -import android.content.res.Configuration -import android.os.Bundle -import android.support.design.widget.NavigationView -import android.support.v4.view.GravityCompat -import android.support.v4.widget.DrawerLayout -import android.support.v7.app.ActionBarDrawerToggle -import android.support.v7.widget.Toolbar -import android.util.Log -import android.view.MenuItem -import android.view.View -import com.v2ray.ang.R - -abstract class BaseDrawerActivity : BaseActivity() { - companion object { - - private val TAG = "BaseDrawerActivity" - } - - private var mToolbar: Toolbar? = null - - private var mDrawerToggle: ActionBarDrawerToggle? = null - - private var mDrawerLayout: DrawerLayout? = null - - private var mToolbarInitialized: Boolean = false - - private var mItemToOpenWhenDrawerCloses = -1 - - private val backStackChangedListener = FragmentManager.OnBackStackChangedListener { updateDrawerToggle() } - - private val drawerListener = object : DrawerLayout.DrawerListener { - override fun onDrawerSlide(drawerView: View, slideOffset: Float) { - mDrawerToggle!!.onDrawerSlide(drawerView, slideOffset) - } - - override fun onDrawerOpened(drawerView: View) { - mDrawerToggle!!.onDrawerOpened(drawerView) - //supportActionBar!!.setTitle(R.string.app_name) - } - - override fun onDrawerClosed(drawerView: View) { - mDrawerToggle!!.onDrawerClosed(drawerView) - - if (mItemToOpenWhenDrawerCloses >= 0) { - val extras = ActivityOptions.makeCustomAnimation( - this@BaseDrawerActivity, R.anim.fade_in, R.anim.fade_out).toBundle() - var activityClass: Class<*>? = null - when (mItemToOpenWhenDrawerCloses) { - R.id.sub_setting -> activityClass = SubSettingActivity::class.java - R.id.settings -> activityClass = SettingsActivity::class.java - R.id.logcat -> { - startActivity(Intent(this@BaseDrawerActivity, LogcatActivity::class.java)) - return - } - R.id.donate -> { -// startActivity() - return - } - } - if (activityClass != null) { - startActivity(Intent(this@BaseDrawerActivity, activityClass), extras) - finish() - } - } - } - - override fun onDrawerStateChanged(newState: Int) { - mDrawerToggle!!.onDrawerStateChanged(newState) - } - } - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - Log.d(TAG, "Activity onCreate") - } - - override fun onStart() { - super.onStart() - if (!mToolbarInitialized) { - throw IllegalStateException("You must run super.initializeToolbar at " + "the end of your onCreate method") - } - } - - public override fun onResume() { - super.onResume() - // Whenever the fragment back stack changes, we may need to update the - // action bar toggle: only top level screens show the hamburger-like icon, inner - // screens - either Activities or fragments - show the "Up" icon instead. - fragmentManager.addOnBackStackChangedListener(backStackChangedListener) - } - - public override fun onPause() { - super.onPause() - fragmentManager.removeOnBackStackChangedListener(backStackChangedListener) - } - - override fun onPostCreate(savedInstanceState: Bundle?) { - super.onPostCreate(savedInstanceState) - mDrawerToggle!!.syncState() - } - - override fun onConfigurationChanged(newConfig: Configuration) { - super.onConfigurationChanged(newConfig) - mDrawerToggle!!.onConfigurationChanged(newConfig) - } - - override fun onOptionsItemSelected(item: MenuItem): Boolean { - if (mDrawerToggle != null && mDrawerToggle!!.onOptionsItemSelected(item)) { - return true - } - // If not handled by drawerToggle, home needs to be handled by returning to previous - if (item.itemId == android.R.id.home) { - onBackPressed() - return true - } - return super.onOptionsItemSelected(item) - } - - override fun onBackPressed() { - // If the drawer is open, back will close it - if (mDrawerLayout != null && mDrawerLayout!!.isDrawerOpen(GravityCompat.START)) { - mDrawerLayout!!.closeDrawers() - return - } - // Otherwise, it may return to the previous fragment stack - val fragmentManager = fragmentManager - if (fragmentManager.backStackEntryCount > 0) { - fragmentManager.popBackStack() - } else { - // Lastly, it will rely on the system behavior for back - super.onBackPressed() - } - } - - private fun updateDrawerToggle() { - if (mDrawerToggle == null) { - return - } - val isRoot = fragmentManager.backStackEntryCount == 0 - mDrawerToggle!!.isDrawerIndicatorEnabled = isRoot - - supportActionBar!!.setDisplayShowHomeEnabled(!isRoot) - supportActionBar!!.setDisplayHomeAsUpEnabled(!isRoot) - supportActionBar!!.setHomeButtonEnabled(!isRoot) - - if (isRoot) { - mDrawerToggle!!.syncState() - } - } - - protected fun initializeToolbar() { - mToolbar = findViewById(R.id.toolbar) as Toolbar - if (mToolbar == null) { - throw IllegalStateException("Layout is required to include a Toolbar with id " + "'toolbar'") - } - - // mToolbar.inflateMenu(R.menu.main); - - mDrawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout - if (mDrawerLayout != null) { - val navigationView = findViewById(R.id.nav_view) as NavigationView - ?: throw IllegalStateException("Layout requires a NavigationView " + "with id 'nav_view'") - - // Create an ActionBarDrawerToggle that will handle opening/closing of the drawer: - mDrawerToggle = ActionBarDrawerToggle(this, mDrawerLayout, - mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) - - mDrawerLayout!!.addDrawerListener(drawerListener) - - populateDrawerItems(navigationView) - setSupportActionBar(mToolbar) - updateDrawerToggle() - } else { - setSupportActionBar(mToolbar) - } - - mToolbarInitialized = true - } - - private fun populateDrawerItems(navigationView: NavigationView) { - navigationView.setNavigationItemSelectedListener { menuItem -> - menuItem.isChecked = true - mItemToOpenWhenDrawerCloses = menuItem.itemId - mDrawerLayout!!.closeDrawers() - true - } - - if (SubSettingActivity::class.java.isAssignableFrom(javaClass)) { - navigationView.setCheckedItem(R.id.sub_setting) - } else if (SettingsActivity::class.java.isAssignableFrom(javaClass)) { - navigationView.setCheckedItem(R.id.settings) - } - } -} diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt index 5c269dab..eec16e03 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt @@ -100,6 +100,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList version.text = "v${BuildConfig.VERSION_NAME} (${Libv2ray.checkVersionX()})" setupViewModelObserver() + migrateLegacy() } private fun setupViewModelObserver() { @@ -129,6 +130,22 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList mainViewModel.startListenBroadcast() } + private fun migrateLegacy() { + GlobalScope.launch(Dispatchers.IO) { + val result = AngConfigManager.migrateLegacyConfig(this@MainActivity) + if (result != null) { + launch(Dispatchers.Main) { + if (result) { + toast(getString(R.string.migration_success)) + mainViewModel.reloadServerList() + } else { + toast(getString(R.string.migration_fail)) + } + } + } + } + } + fun startV2Ray() { if (mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER).isNullOrEmpty()) { return @@ -229,7 +246,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList } R.id.export_all -> { - if (AngConfigManager.shareNonCustomConfigsToClipboard(mainViewModel.serverList) == 0) { + if (AngConfigManager.shareNonCustomConfigsToClipboard(this, mainViewModel.serverList) == 0) { toast(R.string.toast_success) } else { toast(R.string.toast_failure) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt index 385e0842..26161149 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt @@ -92,7 +92,7 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter { - if (AngConfigManager.share2Clipboard(guid) == 0) { + if (AngConfigManager.share2Clipboard(mActivity, guid) == 0) { mActivity.toast(R.string.toast_success) } else { mActivity.toast(R.string.toast_failure) @@ -156,7 +156,7 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter + switch_per_app_proxy.setOnCheckedChangeListener { _, isChecked -> defaultSharedPreferences.edit().putBoolean(AppConfig.PREF_PER_APP_PROXY, isChecked).apply() } switch_per_app_proxy.isChecked = defaultSharedPreferences.getBoolean(AppConfig.PREF_PER_APP_PROXY, false) - switch_bypass_apps.setOnCheckedChangeListener { buttonView, isChecked -> + switch_bypass_apps.setOnCheckedChangeListener { _, isChecked -> defaultSharedPreferences.edit().putBoolean(AppConfig.PREF_BYPASS_APPS, isChecked).apply() } switch_bypass_apps.isChecked = defaultSharedPreferences.getBoolean(AppConfig.PREF_BYPASS_APPS, false) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt index a32c2223..993c2d32 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt @@ -42,8 +42,8 @@ class RoutingSettingsFragment : Fragment() { return fragment } - override fun onActivityCreated(savedInstanceState: Bundle?) { - super.onActivityCreated(savedInstanceState) + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) val content = defaultSharedPreferences.getString(arguments!!.getString(routing_arg), "") et_routing_content.text = Utils.getEditable(content!!) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ScannerActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ScannerActivity.kt index 6f1dafd1..5e973cb8 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ScannerActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ScannerActivity.kt @@ -23,8 +23,8 @@ class ScannerActivity : BaseActivity(), ZXingScannerView.ResultHandler { private var mScannerView: ZXingScannerView? = null - public override fun onCreate(state: Bundle?) { - super.onCreate(state) + public override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) mScannerView = ZXingScannerView(this) // Programmatically initialize the scanner view mScannerView?.setAutoFocus(true) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/TaskerActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/TaskerActivity.kt index b27f047b..2b8c1673 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/TaskerActivity.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/TaskerActivity.kt @@ -79,12 +79,10 @@ class TaskerActivity : BaseActivity() { val intent = Intent() val remarks = lstData[position] - var blurb = "" - - if (switch_start_service.isChecked) { - blurb = "Start $remarks" + val blurb = if (switch_start_service.isChecked) { + "Start $remarks" } else { - blurb = "Stop $remarks" + "Stop $remarks" } intent.putExtra(AppConfig.TASKER_EXTRA_BUNDLE, extraBundle) diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt index 290425c7..5becce11 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AngConfigManager.kt @@ -1,11 +1,13 @@ package com.v2ray.ang.util +import android.content.Context +import android.content.SharedPreferences import android.graphics.Bitmap import android.support.v7.preference.PreferenceManager import android.text.TextUtils import com.google.gson.Gson import com.tencent.mmkv.MMKV -import com.v2ray.ang.AngApplication +import com.v2ray.ang.AppConfig import com.v2ray.ang.AppConfig.ANG_CONFIG import com.v2ray.ang.AppConfig.HTTPS_PROTOCOL import com.v2ray.ang.AppConfig.HTTP_PROTOCOL @@ -19,43 +21,139 @@ import java.net.URLDecoder import java.util.* object AngConfigManager { - private lateinit var app: AngApplication - private lateinit var angConfig: AngConfig private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) } private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) } - - fun inject(app: AngApplication) { - this.app = app - loadConfig() - } + private val subStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SUB, MMKV.MULTI_PROCESS_MODE) } /** - * loading config + * Legacy loading config */ - private fun loadConfig() { + fun migrateLegacyConfig(c: Context): Boolean? { try { - val defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(app) + val defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(c) val context = defaultSharedPreferences.getString(ANG_CONFIG, "") - if (!TextUtils.isEmpty(context)) { - angConfig = Gson().fromJson(context, AngConfig::class.java) - } else { - angConfig = AngConfig(0, vmess = arrayListOf(AngConfig.VmessBean()), subItem = arrayListOf(AngConfig.SubItemBean())) - angConfig.index = -1 - angConfig.vmess.clear() - angConfig.subItem.clear() + if (context.isNullOrBlank()) { + return null } - + val angConfig = Gson().fromJson(context, AngConfig::class.java) for (i in angConfig.vmess.indices) { upgradeServerVersion(angConfig.vmess[i]) } -// if (configs.subItem == null) { -// configs.subItem = arrayListOf(AngConfig.SubItemBean()) -// } + copyLegacySettings(defaultSharedPreferences) + migrateVmessBean(angConfig, defaultSharedPreferences) + migrateSubItemBean(angConfig) + defaultSharedPreferences.edit().remove(ANG_CONFIG).apply() + return true } catch (e: Exception) { e.printStackTrace() } + return false + } + + private fun copyLegacySettings(sharedPreferences: SharedPreferences) { + listOf(AppConfig.PREF_MODE, + AppConfig.PREF_REMOTE_DNS, + AppConfig.PREF_DOMESTIC_DNS, +// AppConfig.PREF_LOCAL_DNS_PORT, +// AppConfig.PREF_SOCKS_PORT, +// AppConfig.PREF_HTTP_PORT, +// AppConfig.PREF_LOGLEVEL, + AppConfig.PREF_ROUTING_DOMAIN_STRATEGY, + AppConfig.PREF_ROUTING_MODE, + AppConfig.PREF_V2RAY_ROUTING_AGENT, + AppConfig.PREF_V2RAY_ROUTING_BLOCKED, + AppConfig.PREF_V2RAY_ROUTING_DIRECT,).forEach { key -> + settingsStorage?.encode(key, sharedPreferences.getString(key, "")) + } + listOf(AppConfig.PREF_SPEED_ENABLED, + AppConfig.PREF_SNIFFING_ENABLED, + AppConfig.PREF_PROXY_SHARING, + AppConfig.PREF_LOCAL_DNS_ENABLED, +// AppConfig.PREF_ALLOW_INSECURE, +// AppConfig.PREF_PREFER_IPV6, + AppConfig.PREF_PER_APP_PROXY, + AppConfig.PREF_BYPASS_APPS,).forEach { key -> + settingsStorage?.encode(key, sharedPreferences.getBoolean(key, false)) + } + settingsStorage?.encode(AppConfig.PREF_PER_APP_PROXY_SET, sharedPreferences.getStringSet(AppConfig.PREF_PER_APP_PROXY_SET, setOf())) + } + + private fun migrateVmessBean(angConfig: AngConfig, sharedPreferences: SharedPreferences) { + angConfig.vmess.forEachIndexed { index, vmessBean -> + val type = EConfigType.fromInt(vmessBean.configType) ?: return@forEachIndexed + val config = ServerConfig.create(type) + config.remarks = vmessBean.remarks + config.subscriptionId = vmessBean.subid + if (type == EConfigType.CUSTOM) { + val jsonConfig = sharedPreferences.getString(ANG_CONFIG + vmessBean.guid, "") + val v2rayConfig = try { + Gson().fromJson(jsonConfig, V2rayConfig::class.java) + } catch (e: Exception) { + e.printStackTrace() + return@forEachIndexed + } + config.fullConfig = v2rayConfig + } else { + config.outboundBean?.settings?.vnext?.get(0)?.let { vnext -> + vnext.address = vmessBean.address + vnext.port = vmessBean.port + vnext.users[0].id = vmessBean.id + if (config.configType == EConfigType.VMESS) { + vnext.users[0].alterId = vmessBean.alterId + vnext.users[0].security = vmessBean.security + } else if (config.configType == EConfigType.VLESS) { + vnext.users[0].encryption = vmessBean.security +// vnext.users[0].flow = vmessBean.flow + } + } + config.outboundBean?.settings?.servers?.get(0)?.let { server -> + server.address = vmessBean.address + server.port = vmessBean.port + if (config.configType == EConfigType.SHADOWSOCKS) { + server.password = vmessBean.id + server.method = vmessBean.security + } else if (config.configType == EConfigType.SOCKS) { + if (TextUtils.isEmpty(vmessBean.security) && TextUtils.isEmpty(vmessBean.id)) { + server.users = null + } else { + val socksUsersBean = V2rayConfig.OutboundBean.OutSettingsBean.ServersBean.SocksUsersBean() + socksUsersBean.user = vmessBean.security + socksUsersBean.pass = vmessBean.id + server.users = listOf(socksUsersBean) + } + } else if (config.configType == EConfigType.TROJAN) { + server.password = vmessBean.id + } + } + config.outboundBean?.streamSettings?.let { streamSetting -> + val sni = streamSetting.populateTransportSettings(vmessBean.network, vmessBean.headerType, + vmessBean.requestHost, vmessBean.path, vmessBean.path, vmessBean.requestHost, vmessBean.path) +// val allowInsecure = if (vmessBean.allowInsecure.isBlank()) { +// settingsStorage?.decodeBool(AppConfig.PREF_ALLOW_INSECURE) ?: false +// } else { +// vmessBean.allowInsecure.toBoolean() +// } + streamSetting.populateTlsSettings(vmessBean.streamSecurity, false, + sni)//if (vmessBean.sni.isNotBlank()) vmessBean.sni else sni) + } + } + val key = MmkvManager.encodeServerConfig(vmessBean.guid, config) + if (index == angConfig.index) { + mainStorage?.encode(KEY_SELECTED_SERVER, key) + } + } + } + + private fun migrateSubItemBean(angConfig: AngConfig) { + angConfig.subItem.forEach { + val subItem = SubscriptionItem() + subItem.remarks = it.remarks + subItem.url = it.url + //subItem.enabled = it.enabled + subStorage?.encode(it.id, Gson().toJson(subItem)) + } } /** @@ -437,14 +535,14 @@ object AngConfigManager { /** * share2Clipboard */ - fun share2Clipboard(guid: String): Int { + fun share2Clipboard(context: Context, guid: String): Int { try { val conf = shareConfig(guid) if (TextUtils.isEmpty(conf)) { return -1 } - Utils.setClipboard(app.applicationContext, conf) + Utils.setClipboard(context, conf) } catch (e: Exception) { e.printStackTrace() @@ -456,7 +554,7 @@ object AngConfigManager { /** * share2Clipboard */ - fun shareNonCustomConfigsToClipboard(serverList: List): Int { + fun shareNonCustomConfigsToClipboard(context: Context, serverList: List): Int { try { val sb = StringBuilder() for (guid in serverList) { @@ -468,7 +566,7 @@ object AngConfigManager { sb.appendLine() } if (sb.count() > 0) { - Utils.setClipboard(app.applicationContext, sb.toString()) + Utils.setClipboard(context, sb.toString()) } } catch (e: Exception) { e.printStackTrace() @@ -497,12 +595,12 @@ object AngConfigManager { /** * shareFullContent2Clipboard */ - fun shareFullContent2Clipboard(guid: String?): Int { + fun shareFullContent2Clipboard(context: Context, guid: String?): Int { try { if (guid == null) return -1 - val result = V2rayConfigUtil.getV2rayConfig(app, guid) + val result = V2rayConfigUtil.getV2rayConfig(context, guid) if (result.status) { - Utils.setClipboard(app.applicationContext, result.content) + Utils.setClipboard(context, result.content) } else { return -1 } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AppManagerUtil.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AppManagerUtil.kt index 91ef1796..b95b408b 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AppManagerUtil.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/AppManagerUtil.kt @@ -31,7 +31,7 @@ object AppManagerUtil { return apps } - fun rxLoadNetworkAppList(ctx: Context): Observable> = Observable.create { + fun rxLoadNetworkAppList(ctx: Context): Observable> = Observable.unsafeCreate { it.onNext(loadNetworkAppList(ctx)) } diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt index 66845af2..a619d7bf 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/Utils.kt @@ -258,7 +258,7 @@ object Utils { */ fun isValidUrl(value: String?): Boolean { try { - if (Patterns.WEB_URL.matcher(value).matches() || URLUtil.isValidUrl(value)) { + if (value != null && Patterns.WEB_URL.matcher(value).matches() || URLUtil.isValidUrl(value)) { return true } } catch (e: WriterException) { diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt index 62180964..7dc3aefb 100644 --- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt +++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/util/V2rayConfigUtil.kt @@ -60,16 +60,16 @@ object V2rayConfigUtil { //v2rayConfig.log.loglevel = settingsStorage?.decodeString(AppConfig.PREF_LOGLEVEL) ?: "warning" - inbounds(v2rayConfig, context) + inbounds(v2rayConfig) v2rayConfig.outbounds[0] = outbound - routing(v2rayConfig, context) + routing(v2rayConfig) if (settingsStorage?.decodeBool(AppConfig.PREF_LOCAL_DNS_ENABLED) == true) { - customLocalDns(v2rayConfig, context) + customLocalDns(v2rayConfig) } else { - customRemoteDns(v2rayConfig, context) + customRemoteDns(v2rayConfig) } if (settingsStorage?.decodeBool(AppConfig.PREF_SPEED_ENABLED) != true) { v2rayConfig.stats = null @@ -83,7 +83,7 @@ object V2rayConfigUtil { /** * */ - private fun inbounds(v2rayConfig: V2rayConfig, context: Context): Boolean { + private fun inbounds(v2rayConfig: V2rayConfig): Boolean { try { //val socksPort = Utils.parseInt(settingsStorage?.decodeString(AppConfig.PREF_SOCKS_PORT) ?: AppConfig.PORT_SOCKS) //val httpPort = Utils.parseInt(settingsStorage?.decodeString(AppConfig.PREF_HTTP_PORT) ?: AppConfig.PORT_HTTP) @@ -115,7 +115,7 @@ object V2rayConfigUtil { /** * routing */ - private fun routing(v2rayConfig: V2rayConfig, context: Context): Boolean { + private fun routing(v2rayConfig: V2rayConfig): Boolean { try { routingUserRule(settingsStorage?.decodeString(AppConfig.PREF_V2RAY_ROUTING_AGENT) ?: "", AppConfig.TAG_AGENT, v2rayConfig) routingUserRule(settingsStorage?.decodeString(AppConfig.PREF_V2RAY_ROUTING_DIRECT) ?: "", AppConfig.TAG_DIRECT, v2rayConfig) @@ -233,7 +233,7 @@ object V2rayConfigUtil { /** * Custom Dns */ - private fun customLocalDns(v2rayConfig: V2rayConfig, context: Context): Boolean { + private fun customLocalDns(v2rayConfig: V2rayConfig): Boolean { try { val hosts = mutableMapOf() val servers = ArrayList() @@ -342,7 +342,7 @@ object V2rayConfigUtil { /** * Custom Remote Dns */ - private fun customRemoteDns(v2rayConfig: V2rayConfig, context: Context): Boolean { + private fun customRemoteDns(v2rayConfig: V2rayConfig): Boolean { try { val servers = ArrayList() val hosts = mutableMapOf() diff --git a/V2rayNG/app/src/main/res/values-zh-rCN/strings.xml b/V2rayNG/app/src/main/res/values-zh-rCN/strings.xml index 44675d2d..9a91f38a 100644 --- a/V2rayNG/app/src/main/res/values-zh-rCN/strings.xml +++ b/V2rayNG/app/src/main/res/values-zh-rCN/strings.xml @@ -6,6 +6,8 @@ 初次使用此功能请先用APP添加配置 Open navigation drawer Close navigation drawer + 数据迁移成功! + 数据迁移失败啦! 停止 diff --git a/V2rayNG/app/src/main/res/values-zh-rTW/strings.xml b/V2rayNG/app/src/main/res/values-zh-rTW/strings.xml index db86bbc1..5303fdbb 100644 --- a/V2rayNG/app/src/main/res/values-zh-rTW/strings.xml +++ b/V2rayNG/app/src/main/res/values-zh-rTW/strings.xml @@ -6,6 +6,8 @@ 首次使用此功能,請使用此應用程式新增組態 Open navigation drawer Close navigation drawer + 數據遷移成功! + 數據遷移失敗啦! 停止 diff --git a/V2rayNG/app/src/main/res/values/strings.xml b/V2rayNG/app/src/main/res/values/strings.xml index 1d4944a4..b45ed29b 100644 --- a/V2rayNG/app/src/main/res/values/strings.xml +++ b/V2rayNG/app/src/main/res/values/strings.xml @@ -6,6 +6,8 @@ First use of this feature, please use the app to add server Open navigation drawer Close navigation drawer + Data migration success! + Data migration failed! Stop