This commit is contained in:
MYSOREZ committed 2026-04-10 11:58:29 +03:00
1 parent 88d26c21f8
commit 50e3c153da
5 files changed
+166 -86

No files matched your search

+6 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId = "com.vkturn.proxy"
minSdk = 23
targetSdk = 28
versionCode = 7
versionName = "2.0.0"
versionCode = 8
versionName = "2.0.1"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
@@ -74,6 +74,7 @@ android {
compose = true
}
compileOptions {
isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
@@ -83,6 +84,9 @@ android {
}
dependencies {
// Core Library Desugaring (поддержка новых Java/Android API на старых устройствах)
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
// SSH и Корутины
implementation("com.github.mwiede:jsch:0.2.17")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
@@ -11,74 +11,86 @@ import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import com.vkturn.proxy.models.*
class AppPreferences(context: Context) {
class AppPreferences(private val context: Context) {
private val gson = Gson()
private val proxyPrefs: SharedPreferences = context.getSharedPreferences("ProxyPrefs", Context.MODE_PRIVATE)
private val sshPrefs: SharedPreferences = context.getSharedPreferences("SshPrefs", Context.MODE_PRIVATE)
private val _selectedProfileIdFlow = MutableStateFlow(proxyPrefs.getString("selectedProfileId", "") ?: "")
val selectedProfileIdFlow: StateFlow<String> = _selectedProfileIdFlow.asStateFlow()
private val _clientConfigFlow = MutableStateFlow(loadClientConfig())
val clientConfigFlow: StateFlow<ClientConfig> = _clientConfigFlow.asStateFlow()
private val _sshConfigFlow = MutableStateFlow(loadSshConfig())
val sshConfigFlow: StateFlow<SshConfig> = _sshConfigFlow.asStateFlow()
private val gson = Gson()
private val _selectedProfileIdFlow = MutableStateFlow(proxyPrefs.getString("selectedProfileId", "") ?: "")
val selectedProfileIdFlow: StateFlow<String> = _selectedProfileIdFlow.asStateFlow()
private val _profilesFlow = MutableStateFlow(loadProfiles())
val profilesFlow: StateFlow<List<ProxyProfile>> = _profilesFlow.asStateFlow()
companion object {
fun migrateConfig(config: ClientConfig): ClientConfig {
fun migrateConfig(config: ClientConfig, context: android.content.Context? = null): ClientConfig {
var currentFlags = (config.customFlags ?: emptyList()).toMutableList()
var changed = false
if (currentFlags.isEmpty()) {
// IMPORTANT: Only treat as "empty" if we have no legacy indicators that this is an existing config.
// If the user has a peer set, it means it's NOT a fresh install, so we shouldn't force defaults.
val isFreshInstall = if (context != null) {
val p = context.getSharedPreferences("ProxyPrefs", android.content.Context.MODE_PRIVATE)
p.getString("peer", "").isNullOrEmpty() && p.getString("currentConfigJson", null) == null
} else false
if (currentFlags.isEmpty() && isFreshInstall) {
currentFlags = mutableListOf(
ProxyFlag(label = "UDP", argument = "-udp", enabled = true, deletable = false),
ProxyFlag(label = "VLESS", argument = "-vless", enabled = false, deletable = false),
ProxyFlag(label = "Manual Captcha", argument = "--manual-captcha", enabled = false, deletable = false),
ProxyFlag(label = "Disable DTLS", argument = "-no-dtls", enabled = false, deletable = false),
ProxyFlag(label = "Debug", argument = "-debug", enabled = false, deletable = false)
ProxyFlag(id = FLAG_ID_UDP, label = "UDP", argument = "-udp", enabled = true, deletable = false),
ProxyFlag(id = FLAG_ID_VLESS, label = "VLESS", argument = "-vless", enabled = false, deletable = false),
ProxyFlag(id = FLAG_ID_CAPTCHA, label = "Manual Captcha", argument = "--manual-captcha", enabled = false, deletable = false),
ProxyFlag(id = FLAG_ID_DTLS, label = "Disable DTLS", argument = "-no-dtls", enabled = false, deletable = false),
ProxyFlag(id = FLAG_ID_DEBUG, label = "Debug", argument = "-debug", enabled = false, deletable = false)
)
changed = true
} else {
val mandatoryArgs = listOf("-udp", "-vless", "--manual-captcha", "-no-dtls", "-debug")
val mandatoryLabels = mapOf(
"-udp" to "UDP",
"-vless" to "VLESS",
"--manual-captcha" to "Manual Captcha",
"-no-dtls" to "Disable DTLS",
"-debug" to "Debug"
val mandatory: List<Triple<String, String, String>> = listOf(
Triple(FLAG_ID_UDP, "-udp", "UDP"),
Triple(FLAG_ID_VLESS, "-vless", "VLESS"),
Triple(FLAG_ID_CAPTCHA, "--manual-captcha", "Manual Captcha"),
Triple(FLAG_ID_DTLS, "-no-dtls", "Disable DTLS"),
Triple(FLAG_ID_DEBUG, "-debug", "Debug")
)
// 1. Update labels and identify present mandatory flags
mandatoryArgs.forEach { arg ->
val label = mandatoryLabels[arg]!!
val existing = currentFlags.find { it.argument == arg }
// 1. Update labels and ensure mandatory flags exist with stable IDs
mandatory.forEach { (id: String, arg: String, label: String) ->
// Try to find by ID first, then by argument
val existing = currentFlags.find { it.id == id } ?: currentFlags.find { it.argument == arg }
if (existing == null) {
currentFlags.add(ProxyFlag(label = label, argument = arg, enabled = false, deletable = false))
changed = true
} else if (existing.label != label) {
val idx = currentFlags.indexOf(existing)
currentFlags[idx] = existing.copy(label = label)
currentFlags.add(ProxyFlag(id = id, label = label, argument = arg, enabled = false, deletable = false))
changed = true
} else {
// Found existing, ensure it has stable ID and fresh label
// BUT: don't touch 'enabled'!
if (existing.id != id || existing.label != label || (existing.argument != arg && !existing.deletable)) {
val idx = currentFlags.indexOf(existing)
currentFlags[idx] = existing.copy(id = id, label = label, argument = arg)
changed = true
}
}
}
// 2. Reorder: Mandatory flags first in the specified order, then the rest
val orderedFlags = mutableListOf<ProxyFlag>()
mandatoryArgs.forEach { arg ->
currentFlags.find { it.argument == arg }?.let { orderedFlags.add(it) }
mandatory.forEach { (id: String, _: String, _: String) ->
currentFlags.find { it.id == id }?.let { orderedFlags.add(it) }
}
val otherFlags = currentFlags.filter { it.argument !in mandatoryArgs }
val otherFlags = currentFlags.filter { f -> mandatory.none { it.component1() == f.id } }
if (currentFlags != (orderedFlags + otherFlags)) {
// Compare contents carefully to avoid unnecessary 'changed' triggers
val newOrder = orderedFlags + otherFlags
if (currentFlags != newOrder) {
currentFlags.clear()
currentFlags.addAll(orderedFlags)
currentFlags.addAll(otherFlags)
currentFlags.addAll(newOrder)
changed = true
}
}
@@ -90,6 +102,7 @@ class AppPreferences(context: Context) {
changed = true
}
// Ensure isRawMode is false if rawCommand is empty (safety for legacy profiles)
if (config.isRawMode && config.rawCommand.isBlank()) {
return config.copy(
@@ -108,7 +121,8 @@ class AppPreferences(context: Context) {
if (json != null) {
return try {
val config = gson.fromJson(json, ClientConfig::class.java)
migrateConfig(config)
val migrated = migrateConfig(config, context)
migrated
} catch (e: Exception) {
createDefaultConfig()
}
@@ -117,27 +131,21 @@ class AppPreferences(context: Context) {
}
fun createDefaultConfig(): ClientConfig {
val udp = proxyPrefs.getBoolean("udp", true)
val noDtls = proxyPrefs.getBoolean("noDtls", false)
val captcha = proxyPrefs.getBoolean("useManualCaptcha", false)
val link = proxyPrefs.getString("link", "") ?: ""
val linkArg = proxyPrefs.getString("linkArg", "") ?: ""
val flags = listOf(
ProxyFlag(label = "UDP", argument = "-udp", enabled = udp, deletable = false),
ProxyFlag(label = "VLESS", argument = "-vless", enabled = false, deletable = false),
ProxyFlag(label = "Manual Captcha", argument = "--manual-captcha", enabled = false, deletable = false),
ProxyFlag(label = "Disable DTLS", argument = "-no-dtls", enabled = noDtls, deletable = false),
ProxyFlag(label = "Debug", argument = "-debug", enabled = false, deletable = false)
ProxyFlag(id = FLAG_ID_UDP, label = "UDP", argument = "-udp", enabled = true, deletable = false),
ProxyFlag(id = FLAG_ID_VLESS, label = "VLESS", argument = "-vless", enabled = false, deletable = false),
ProxyFlag(id = FLAG_ID_CAPTCHA, label = "Manual Captcha", argument = "--manual-captcha", enabled = false, deletable = false),
ProxyFlag(id = FLAG_ID_DTLS, label = "Disable DTLS", argument = "-no-dtls", enabled = false, deletable = false),
ProxyFlag(id = FLAG_ID_DEBUG, label = "Debug", argument = "-debug", enabled = false, deletable = false)
)
return ClientConfig(
serverAddress = proxyPrefs.getString("peer", "") ?: "",
vkLink = link,
linkArgument = linkArg,
vkLink = proxyPrefs.getString("link", "") ?: "",
linkArgument = proxyPrefs.getString("linkArg", "") ?: "",
threads = proxyPrefs.getString("n", "8")?.toIntOrNull() ?: 8,
localPort = proxyPrefs.getString("listen", "127.0.0.1:9000") ?: "127.0.0.1:9000",
isRawMode = false, // Always default to false for new/default configs
isRawMode = false,
rawCommand = "",
customFlags = flags
)
@@ -155,6 +163,7 @@ class AppPreferences(context: Context) {
}
fun saveClientConfig(config: ClientConfig) {
proxyPrefs.edit().apply {
putString("peer", config.serverAddress)
putString("link", config.vkLink)
@@ -163,6 +172,17 @@ class AppPreferences(context: Context) {
putString("listen", config.localPort)
putBoolean("isRaw", config.isRawMode)
putString("rawCmd", config.rawCommand)
// Sync legacy boolean keys for extra safety
val udpFlag = config.customFlags.find { it.id == FLAG_ID_UDP }
if (udpFlag != null) putBoolean("udp", udpFlag.enabled)
val dtlsFlag = config.customFlags.find { it.id == FLAG_ID_DTLS }
if (dtlsFlag != null) putBoolean("noDtls", dtlsFlag.enabled)
val captchaFlag = config.customFlags.find { it.id == FLAG_ID_CAPTCHA }
if (captchaFlag != null) putBoolean("useManualCaptcha", captchaFlag.enabled)
putString("currentConfigJson", gson.toJson(config))
}.apply()
_clientConfigFlow.value = config
@@ -188,16 +208,26 @@ class AppPreferences(context: Context) {
proxyPrefs.edit().putString("profilesJson", gson.toJson(profiles)).apply()
if (proxyPrefs.getString("selectedProfileId", "").isNullOrEmpty()) {
proxyPrefs.edit().putString("selectedProfileId", initialProfile.id).apply()
_selectedProfileIdFlow.value = initialProfile.id
}
return profiles
}
val type = object : TypeToken<List<ProxyProfile>>() {}.type
val rawProfiles: List<ProxyProfile> = gson.fromJson(json, type) ?: emptyList()
val migratedProfiles = rawProfiles.map { profile ->
// Safety: if it's named "По умолчанию" but lacks the flag (legacy), set it.
val isDefault = profile.isDefault || profile.name == "По умолчанию"
profile.copy(config = migrateConfig(profile.config), isDefault = isDefault)
profile.copy(config = migrateConfig(profile.config, context), isDefault = isDefault)
}
val selectedId = proxyPrefs.getString("selectedProfileId", "") ?: ""
// Ensure we always have a selected profile if list is not empty
if (migratedProfiles.isNotEmpty() && selectedId.isEmpty()) {
val firstId = migratedProfiles.first().id
proxyPrefs.edit().putString("selectedProfileId", firstId).apply()
_selectedProfileIdFlow.value = firstId
}
if (migratedProfiles != rawProfiles) {
@@ -1,6 +1,7 @@
package com.vkturn.proxy.models
import java.util.UUID
import com.google.gson.annotations.SerializedName
data class ProxyProfile(
val id: String = UUID.randomUUID().toString(),
@@ -9,23 +10,29 @@ data class ProxyProfile(
val isDefault: Boolean = false
)
const val FLAG_ID_UDP = "flag_udp"
const val FLAG_ID_VLESS = "flag_vless"
const val FLAG_ID_CAPTCHA = "flag_captcha"
const val FLAG_ID_DTLS = "flag_dtls"
const val FLAG_ID_DEBUG = "flag_debug"
data class ProxyFlag(
val id: String = UUID.randomUUID().toString(),
var label: String,
var argument: String,
var enabled: Boolean,
val deletable: Boolean = true
@SerializedName("id") val id: String = UUID.randomUUID().toString(),
@SerializedName("label") var label: String = "",
@SerializedName("argument") var argument: String = "",
@SerializedName("enabled") var enabled: Boolean = false,
@SerializedName("deletable") val deletable: Boolean = true
)
data class ClientConfig(
val serverAddress: String = "",
val vkLink: String = "",
val linkArgument: String = "",
val threads: Int = 8,
val localPort: String = "127.0.0.1:9000",
val isRawMode: Boolean = false,
val rawCommand: String = "",
val customFlags: List<ProxyFlag> = emptyList()
@SerializedName("serverAddress") val serverAddress: String = "",
@SerializedName("vkLink") val vkLink: String = "",
@SerializedName("linkArgument") val linkArgument: String = "",
@SerializedName("threads") val threads: Int = 8,
@SerializedName("localPort") val localPort: String = "127.0.0.1:9000",
@SerializedName("isRawMode") val isRawMode: Boolean = false,
@SerializedName("rawCommand") val rawCommand: String = "",
@SerializedName("customFlags") val customFlags: List<ProxyFlag> = emptyList()
) {
fun generateRawCommand(): String {
val cmds = mutableListOf<String>()
@@ -273,7 +273,14 @@ fun SettingsScreen(viewModel: MainViewModel) {
onValueChange = { rawCommand = it },
label = { Text("Команда (raw format)") },
modifier = Modifier.fillMaxWidth().heightIn(min = 120.dp),
placeholder = { Text("-peer 1.2.3.4:5678 -vk-link ... -listen 127.0.0.1:9000 -n 8") }
placeholder = { Text("-peer 1.2.3.4:5678 -vk-link ... -listen 127.0.0.1:9000 -n 8") },
trailingIcon = if (rawCommand.isNotEmpty()) {
{
IconButton(onClick = { rawCommand = "" }) {
Icon(Icons.Default.Clear, contentDescription = "Очистить")
}
}
} else null
)
} else {
// Standard Mode UI
@@ -293,7 +300,14 @@ fun SettingsScreen(viewModel: MainViewModel) {
},
label = { Text("Ссылка (для Bypass)") },
modifier = Modifier.weight(1f),
singleLine = true
singleLine = true,
trailingIcon = if (link.isNotEmpty()) {
{
IconButton(onClick = { link = "" }) {
Icon(Icons.Default.Clear, contentDescription = "Очистить")
}
}
} else null
)
OutlinedTextField(
@@ -301,7 +315,14 @@ fun SettingsScreen(viewModel: MainViewModel) {
onValueChange = { linkArg = it },
label = { Text("Аргумент") },
modifier = Modifier.width(120.dp),
singleLine = true
singleLine = true,
trailingIcon = if (linkArg.isNotEmpty()) {
{
IconButton(onClick = { linkArg = "" }) {
Icon(Icons.Default.Clear, contentDescription = "Очистить")
}
}
} else null
)
}
@@ -362,9 +383,18 @@ fun SettingsScreen(viewModel: MainViewModel) {
if (flag.argument == "-no-dtls" && isChecked) {
showDtlsWarning = true
} else {
currentFlags = currentFlags.map {
var newFlags = currentFlags.map {
if (it.id == flag.id) it.copy(enabled = isChecked) else it
}
// Взаимоисключение для UDP и VLESS
if (flag.argument == "-vless" && isChecked) {
newFlags = newFlags.map { if (it.argument == "-udp") it.copy(enabled = false) else it }
} else if (flag.argument == "-udp" && isChecked) {
newFlags = newFlags.map { if (it.argument == "-vless") it.copy(enabled = false) else it }
}
currentFlags = newFlags
}
},
modifier = Modifier.scale(0.8f)
@@ -436,7 +466,14 @@ fun SettingsScreen(viewModel: MainViewModel) {
onValueChange = { peer = it },
label = { Text("Адрес сервера (ip:port)") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
singleLine = true,
trailingIcon = if (peer.isNotEmpty()) {
{
IconButton(onClick = { peer = "" }) {
Icon(Icons.Default.Clear, contentDescription = "Очистить")
}
}
} else null
)
OutlinedTextField(
@@ -444,7 +481,14 @@ fun SettingsScreen(viewModel: MainViewModel) {
onValueChange = { listen = it },
label = { Text("Локальный адрес (Listen)") },
modifier = Modifier.fillMaxWidth(),
singleLine = true
singleLine = true,
trailingIcon = if (listen.isNotEmpty()) {
{
IconButton(onClick = { listen = "" }) {
Icon(Icons.Default.Clear, contentDescription = "Очистить")
}
}
} else null
)
}
}
@@ -7,12 +7,9 @@ import androidx.lifecycle.viewModelScope
import com.vkturn.proxy.ProxyService
import com.vkturn.proxy.SSHManager
import com.vkturn.proxy.data.AppPreferences
import com.vkturn.proxy.models.ClientConfig
import com.vkturn.proxy.models.SshConfig
import com.vkturn.proxy.models.*
import com.vkturn.proxy.states.ProxyState
import com.vkturn.proxy.states.SshConnectionState
import com.vkturn.proxy.models.ProxyProfile
import com.vkturn.proxy.models.ProxyFlag
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
@@ -77,13 +74,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
checkForCaptcha(msg)
}
viewModelScope.launch {
profiles.collectLatest { list ->
if (list.isNotEmpty() && selectedProfileId.value.isEmpty()) {
selectProfile(list[0].id)
}
}
}
// Profile selection is now handled robustly in AppPreferences during initialization
viewModelScope.launch {
while (true) {
@@ -371,7 +362,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
suspend fun importKernel(uri: Uri): Result<String> = withContext(Dispatchers.IO) {
try {
val context = getApplication<Application>()
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readNBytes(20) }
val bytes = context.contentResolver.openInputStream(uri)?.use { input ->
val buffer = ByteArray(20)
val read = input.read(buffer, 0, 20)
if (read == -1) null else buffer.sliceArray(0 until read)
}
?: return@withContext Result.failure(Exception("Не удалось прочитать файл"))
if (bytes.size < 20 || bytes[0] != 0x7F.toByte() || bytes[1] != 'E'.code.toByte() || bytes[2] != 'L'.code.toByte() || bytes[3] != 'F'.code.toByte()) {