update
This commit is contained in:
1 parent
5476d170cc
commit
eb57299d94
34 files changed
+3828
-361
No files matched your search
@@ -17,3 +17,9 @@ local.properties
|
|||||||
# Build outputs
|
# Build outputs
|
||||||
**/build/
|
**/build/
|
||||||
**/release/
|
**/release/
|
||||||
|
|
||||||
|
# Junk and unwanted files
|
||||||
|
.vscode/
|
||||||
|
.kotlin/
|
||||||
|
.gradle/
|
||||||
|
RELEASE_NOTES_v2.0.0.md
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# VK TURN Proxy Android
|
# VK TURN Proxy Android
|
||||||
|
|
||||||
Android-приложение на основе [vk-turn-proxy](https://github.com/cacggghp/vk-turn-proxy).
|
Android-приложение под ядро [vk-turn-proxy](https://github.com/cacggghp/vk-turn-proxy).
|
||||||
|
|
||||||
## О проекте (Good TURN)
|
## О проекте (Good TURN)
|
||||||
|
|
||||||
|
|||||||
+74
-6
@@ -1,6 +1,7 @@
|
|||||||
plugins {
|
plugins {
|
||||||
alias(libs.plugins.android.application)
|
alias(libs.plugins.android.application)
|
||||||
alias(libs.plugins.kotlin.android)
|
alias(libs.plugins.kotlin.android)
|
||||||
|
alias(libs.plugins.compose.compiler)
|
||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
@@ -9,21 +10,56 @@ android {
|
|||||||
|
|
||||||
defaultConfig {
|
defaultConfig {
|
||||||
applicationId = "com.vkturn.proxy"
|
applicationId = "com.vkturn.proxy"
|
||||||
minSdk = 26
|
minSdk = 23
|
||||||
targetSdk = 28
|
targetSdk = 28
|
||||||
versionCode = 1
|
versionCode = 7
|
||||||
versionName = "1.0"
|
versionName = "2.0.0"
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
|
||||||
|
ndk {
|
||||||
|
// Поддержка всех основных архитектур
|
||||||
|
abiFilters.addAll(listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64"))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Красивое именование APK файлов
|
||||||
|
applicationVariants.all {
|
||||||
|
val variantName = name
|
||||||
|
val vName = versionName
|
||||||
|
outputs.all {
|
||||||
|
val output = this as com.android.build.gradle.internal.api.ApkVariantOutputImpl
|
||||||
|
// Извлекаем ABI из имени выхода (например, "arm64-v8aRelease" -> "arm64-v8a")
|
||||||
|
val abiSuffix = name.replace(variantName, "", ignoreCase = true)
|
||||||
|
val finalAbi = if (abiSuffix.isEmpty() || abiSuffix.lowercase() == "universal") "universal" else abiSuffix
|
||||||
|
output.outputFileName = "TurnProxy_v${vName}_${finalAbi}.apk"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
splits {
|
||||||
|
abi {
|
||||||
|
isEnable = true // Включаем разделение
|
||||||
|
reset() // Сбрасываем выбор по умолчанию
|
||||||
|
include("arm64-v8a", "armeabi-v7a", "x86", "x86_64") // Указываем, какие APK собрать отдельно
|
||||||
|
isUniversalApk = true // Генерировать один общий universal APK
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
packaging {
|
||||||
|
resources.excludes += "META-INF/versions/9/OSGI-INF/MANIFEST.MF"
|
||||||
|
jniLibs.useLegacyPackaging = true
|
||||||
|
}
|
||||||
|
// ---------------------------------
|
||||||
|
|
||||||
buildTypes {
|
buildTypes {
|
||||||
release {
|
release {
|
||||||
isMinifyEnabled = false
|
isMinifyEnabled = true // Сжатие кода (R8/Proguard)
|
||||||
|
isShrinkResources = true // Удаление неиспользуемых ресурсов
|
||||||
proguardFiles(
|
proguardFiles(
|
||||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||||
"proguard-rules.pro"
|
"proguard-rules.pro"
|
||||||
)
|
)
|
||||||
|
signingConfig = signingConfigs.getByName("debug")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,6 +70,9 @@ android {
|
|||||||
disable += "ExpiredTargetSdkVersion"
|
disable += "ExpiredTargetSdkVersion"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
}
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility = JavaVersion.VERSION_11
|
sourceCompatibility = JavaVersion.VERSION_11
|
||||||
targetCompatibility = JavaVersion.VERSION_11
|
targetCompatibility = JavaVersion.VERSION_11
|
||||||
@@ -44,12 +83,41 @@ android {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
|
// SSH и Корутины
|
||||||
|
implementation("com.github.mwiede:jsch:0.2.17")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
|
||||||
|
implementation("com.google.code.gson:gson:2.10.1")
|
||||||
|
|
||||||
|
// Стандартные библиотеки Android
|
||||||
implementation(libs.androidx.core.ktx)
|
implementation(libs.androidx.core.ktx)
|
||||||
implementation(libs.androidx.appcompat)
|
implementation(libs.androidx.appcompat)
|
||||||
implementation(libs.material)
|
implementation(libs.material)
|
||||||
implementation(libs.androidx.activity)
|
|
||||||
implementation(libs.androidx.constraintlayout)
|
// Compose
|
||||||
|
implementation(platform(libs.compose.bom))
|
||||||
|
implementation(libs.androidx.compose.ui)
|
||||||
|
implementation(libs.androidx.compose.ui.graphics)
|
||||||
|
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||||
|
implementation(libs.androidx.compose.material3)
|
||||||
|
implementation(libs.androidx.activity.compose)
|
||||||
|
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||||
|
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||||
|
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||||
|
implementation(libs.androidx.navigation.compose)
|
||||||
|
|
||||||
|
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||||
|
debugImplementation(libs.androidx.compose.ui.test.manifest)
|
||||||
|
|
||||||
testImplementation(libs.junit)
|
testImplementation(libs.junit)
|
||||||
androidTestImplementation(libs.androidx.junit)
|
androidTestImplementation(libs.androidx.junit)
|
||||||
androidTestImplementation(libs.androidx.espresso.core)
|
androidTestImplementation(libs.androidx.espresso.core)
|
||||||
|
androidTestImplementation(platform(libs.compose.bom))
|
||||||
|
|
||||||
|
// QR & Camera
|
||||||
|
implementation("com.google.zxing:core:3.5.3")
|
||||||
|
implementation("com.google.mlkit:barcode-scanning:17.3.0")
|
||||||
|
val cameraxVersion = "1.3.4"
|
||||||
|
implementation("androidx.camera:camera-camera2:$cameraxVersion")
|
||||||
|
implementation("androidx.camera:camera-lifecycle:$cameraxVersion")
|
||||||
|
implementation("androidx.camera:camera-view:$cameraxVersion")
|
||||||
}
|
}
|
||||||
Vendored
+33
-18
@@ -1,21 +1,36 @@
|
|||||||
# Add project specific ProGuard rules here.
|
# Сохраняем сигнатуры для корректной работы Generics (исправляет краш TypeToken)
|
||||||
# You can control the set of applied configuration files using the
|
-keepattributes Signature
|
||||||
# proguardFiles setting in build.gradle.
|
-keepattributes *Annotation*
|
||||||
#
|
-keepattributes EnclosingMethod
|
||||||
# For more details, see
|
-keepattributes InnerClasses
|
||||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
|
||||||
|
|
||||||
# If your project uses WebView with JS, uncomment the following
|
# Gson конкретные правила
|
||||||
# and specify the fully qualified class name to the JavaScript interface
|
-keep class com.google.gson.reflect.TypeToken { *; }
|
||||||
# class:
|
-keep class * extends com.google.gson.reflect.TypeToken
|
||||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
-keep public class * implements com.google.gson.TypeAdapterFactory
|
||||||
# public *;
|
-keep public class * implements com.google.gson.JsonSerializer
|
||||||
#}
|
-keep public class * implements com.google.gson.JsonDeserializer
|
||||||
|
-keep class com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter { *; }
|
||||||
|
|
||||||
# Uncomment this to preserve the line number information for
|
# Сохраняем наши модели данных, чтобы Gson мог заполнять их поля
|
||||||
# debugging stack traces.
|
-keep class com.vkturn.proxy.models.** { *; }
|
||||||
#-keepattributes SourceFile,LineNumberTable
|
-keep class com.vkturn.proxy.data.** { *; }
|
||||||
|
|
||||||
# If you keep the line number information, uncomment this to
|
# Сохраняем ViewModel и их конструкторы для корректного создания
|
||||||
# hide the original source file name.
|
-keep class com.vkturn.proxy.viewmodel.** { *; }
|
||||||
#-renamesourcefileattribute SourceFile
|
-keepclassmembers class * extends androidx.lifecycle.ViewModel {
|
||||||
|
<init>(...);
|
||||||
|
}
|
||||||
|
|
||||||
|
# CameraX и ML Kit (для работы QR)
|
||||||
|
-keep class androidx.camera.** { *; }
|
||||||
|
-keep class com.google.mlkit.** { *; }
|
||||||
|
-keep class com.google.android.gms.** { *; }
|
||||||
|
|
||||||
|
# JSch (SSH) правила
|
||||||
|
-keep class com.jcraft.jsch.** { *; }
|
||||||
|
-keep class com.jcraft.jzlib.** { *; }
|
||||||
|
-keep class org.bouncycastle.** { *; }
|
||||||
|
-keep interface com.jcraft.jsch.** { *; }
|
||||||
|
-dontwarn com.jcraft.jsch.**
|
||||||
|
-dontwarn pbkdf2.**
|
||||||
@@ -8,17 +8,19 @@
|
|||||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
|
|
||||||
<application
|
<application
|
||||||
android:extractNativeLibs="true"
|
android:extractNativeLibs="true"
|
||||||
android:allowBackup="true"
|
android:allowBackup="false"
|
||||||
|
android:fullBackupContent="@null"
|
||||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||||
android:fullBackupContent="@xml/backup_rules"
|
|
||||||
android:icon="@mipmap/ic_launcher"
|
android:icon="@mipmap/ic_launcher"
|
||||||
android:label="VK TURN Proxy"
|
android:label="TURN Proxy"
|
||||||
android:roundIcon="@mipmap/ic_launcher_round"
|
android:roundIcon="@mipmap/ic_launcher_round"
|
||||||
android:supportsRtl="true"
|
android:supportsRtl="true"
|
||||||
android:theme="@style/Theme.VkTurnProxy"
|
android:theme="@android:style/Theme.DeviceDefault.NoActionBar"
|
||||||
|
android:usesCleartextTraffic="true"
|
||||||
tools:targetApi="31">
|
tools:targetApi="31">
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
@@ -30,10 +32,30 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
|
|
||||||
<service
|
<service
|
||||||
android:name=".ProxyService"
|
android:name=".ProxyService"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
android:foregroundServiceType="specialUse" />
|
android:foregroundServiceType="specialUse" />
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".ProxyReceiver"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.vkturn.proxy.action.START" />
|
||||||
|
<action android:name="com.vkturn.proxy.action.STOP" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<provider
|
||||||
|
android:authorities="${applicationId}.fileprovider"
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/provider_paths" />
|
||||||
|
</provider>
|
||||||
|
|
||||||
</application>
|
</application>
|
||||||
</manifest>
|
</manifest>
|
||||||
@@ -1,179 +1,49 @@
|
|||||||
package com.vkturn.proxy
|
package com.vkturn.proxy
|
||||||
|
|
||||||
import android.Manifest
|
import android.Manifest
|
||||||
import android.app.Activity
|
|
||||||
import android.content.ClipData
|
|
||||||
import android.content.ClipboardManager
|
|
||||||
import android.content.Context
|
|
||||||
import android.content.Intent
|
|
||||||
import android.content.pm.PackageManager
|
import android.content.pm.PackageManager
|
||||||
import android.net.Uri
|
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.provider.Settings
|
import androidx.activity.ComponentActivity
|
||||||
import android.view.View
|
import androidx.activity.compose.setContent
|
||||||
import android.widget.*
|
import androidx.activity.enableEdgeToEdge
|
||||||
import androidx.activity.result.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.activity.viewModels
|
||||||
import androidx.core.content.ContextCompat
|
import androidx.core.content.ContextCompat
|
||||||
import java.io.File
|
import com.vkturn.proxy.ui.AppNavigation
|
||||||
import java.io.FileOutputStream
|
import com.vkturn.proxy.ui.theme.VkTurnProxyTheme
|
||||||
|
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||||
|
|
||||||
class MainActivity : AppCompatActivity() {
|
class MainActivity : ComponentActivity() {
|
||||||
|
|
||||||
private lateinit var tvLogs: TextView
|
private val viewModel: MainViewModel by viewModels()
|
||||||
private lateinit var logScrollView: ScrollView
|
|
||||||
private lateinit var btnToggle: Button
|
|
||||||
|
|
||||||
// Обработка выбора файла для обновления ядра
|
private val requestPermissionLauncher = registerForActivityResult(
|
||||||
private val filePicker = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
ActivityResultContracts.RequestPermission()
|
||||||
if (result.resultCode == Activity.RESULT_OK) {
|
) { }
|
||||||
result.data?.data?.let { uri ->
|
|
||||||
try {
|
|
||||||
val inputStream = contentResolver.openInputStream(uri)
|
|
||||||
val customBin = File(filesDir, "custom_vkturn")
|
|
||||||
val outputStream = FileOutputStream(customBin)
|
|
||||||
inputStream?.copyTo(outputStream)
|
|
||||||
inputStream?.close()
|
|
||||||
outputStream.close()
|
|
||||||
customBin.setExecutable(true)
|
|
||||||
ProxyService.addLog("СИСТЕМА: Кастомный бинарник установлен в /files/custom_vkturn")
|
|
||||||
Toast.makeText(this, "Ядро обновлено!", Toast.LENGTH_SHORT).show()
|
|
||||||
} catch (e: Exception) {
|
|
||||||
ProxyService.addLog("ОШИБКА ОБНОВЛЕНИЯ: ${e.message}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
|
|
||||||
if (!isGranted) Toast.makeText(this, "Разрешите уведомления для фоновой работы!", Toast.LENGTH_LONG).show()
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
enableEdgeToEdge()
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
setContentView(R.layout.activity_main)
|
|
||||||
|
|
||||||
// Инициализация элементов
|
|
||||||
tvLogs = findViewById(R.id.tvLogs)
|
|
||||||
logScrollView = findViewById(R.id.logScrollView)
|
|
||||||
btnToggle = findViewById(R.id.btnToggle)
|
|
||||||
tvLogs.setTextIsSelectable(true) // Позволяет выделять текст логов
|
|
||||||
|
|
||||||
val switchRawMode = findViewById<Switch>(R.id.switchRawMode)
|
|
||||||
val editRawCommand = findViewById<EditText>(R.id.editRawCommand)
|
|
||||||
val layoutGuiSettings = findViewById<LinearLayout>(R.id.layoutGuiSettings)
|
|
||||||
val editPeer = findViewById<EditText>(R.id.editPeer)
|
|
||||||
val editLink = findViewById<EditText>(R.id.editLink)
|
|
||||||
val editN = findViewById<EditText>(R.id.editN)
|
|
||||||
val checkUdp = findViewById<CheckBox>(R.id.checkUdp)
|
|
||||||
val checkNoDtls = findViewById<CheckBox>(R.id.checkNoDtls)
|
|
||||||
val editListen = findViewById<EditText>(R.id.editListen)
|
|
||||||
|
|
||||||
// Загрузка настроек
|
|
||||||
val prefs = getSharedPreferences("ProxyPrefs", Context.MODE_PRIVATE)
|
|
||||||
switchRawMode.isChecked = prefs.getBoolean("isRaw", false)
|
|
||||||
editRawCommand.setText(prefs.getString("rawCmd", ""))
|
|
||||||
editPeer.setText(prefs.getString("peer", ""))
|
|
||||||
editLink.setText(prefs.getString("link", ""))
|
|
||||||
editN.setText(prefs.getString("n", "8"))
|
|
||||||
checkUdp.isChecked = prefs.getBoolean("udp", true)
|
|
||||||
checkNoDtls.isChecked = prefs.getBoolean("noDtls", false)
|
|
||||||
editListen.setText(prefs.getString("listen", "127.0.0.1:9000"))
|
|
||||||
|
|
||||||
// Переключение режимов интерфейса
|
|
||||||
val updateUiState = {
|
|
||||||
if (switchRawMode.isChecked) {
|
|
||||||
editRawCommand.visibility = View.VISIBLE
|
|
||||||
layoutGuiSettings.visibility = View.GONE
|
|
||||||
} else {
|
|
||||||
editRawCommand.visibility = View.GONE
|
|
||||||
layoutGuiSettings.visibility = View.VISIBLE
|
|
||||||
}
|
|
||||||
}
|
|
||||||
updateUiState()
|
|
||||||
switchRawMode.setOnCheckedChangeListener { _, _ -> updateUiState() }
|
|
||||||
|
|
||||||
// Кнопки управления
|
|
||||||
findViewById<Button>(R.id.btnUpdateBinary).setOnClickListener {
|
|
||||||
val intent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "*/*" }
|
|
||||||
filePicker.launch(intent)
|
|
||||||
}
|
|
||||||
|
|
||||||
findViewById<Button>(R.id.btnBattery).setOnClickListener {
|
|
||||||
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
|
|
||||||
data = Uri.parse("package:$packageName")
|
|
||||||
}
|
|
||||||
startActivity(intent)
|
|
||||||
}
|
|
||||||
|
|
||||||
findViewById<Button>(R.id.btnCopyLogs).setOnClickListener {
|
|
||||||
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
|
||||||
val clip = ClipData.newPlainText("vk_turn_logs", tvLogs.text)
|
|
||||||
clipboard.setPrimaryClip(clip)
|
|
||||||
Toast.makeText(this, "Логи скопированы!", Toast.LENGTH_SHORT).show()
|
|
||||||
}
|
|
||||||
|
|
||||||
findViewById<Button>(R.id.btnClearLogs).setOnClickListener {
|
|
||||||
ProxyService.logBuffer.clear()
|
|
||||||
tvLogs.text = "Консоль очищена."
|
|
||||||
}
|
|
||||||
|
|
||||||
btnToggle.setOnClickListener {
|
|
||||||
if (!ProxyService.isRunning) {
|
|
||||||
// Сохранение перед стартом
|
|
||||||
prefs.edit().apply {
|
|
||||||
putBoolean("isRaw", switchRawMode.isChecked)
|
|
||||||
putString("rawCmd", editRawCommand.text.toString())
|
|
||||||
putString("peer", editPeer.text.toString())
|
|
||||||
putString("link", editLink.text.toString())
|
|
||||||
putString("n", editN.text.toString())
|
|
||||||
putBoolean("udp", checkUdp.isChecked)
|
|
||||||
putBoolean("noDtls", checkNoDtls.isChecked)
|
|
||||||
putString("listen", editListen.text.toString())
|
|
||||||
}.apply()
|
|
||||||
|
|
||||||
checkPermissionsAndStart()
|
|
||||||
} else {
|
|
||||||
stopService(Intent(this, ProxyService::class.java))
|
|
||||||
btnToggle.text = "ЗАПУСТИТЬ ПРОКСИ"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun checkPermissionsAndStart() {
|
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||||
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ProxyService.logBuffer.clear()
|
|
||||||
startForegroundService(Intent(this, ProxyService::class.java))
|
|
||||||
btnToggle.text = "ОСТАНОВИТЬ ПРОКСИ"
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onResume() {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
super.onResume()
|
val pm = getSystemService(android.content.Context.POWER_SERVICE) as android.os.PowerManager
|
||||||
btnToggle.text = if (ProxyService.isRunning) "ОСТАНОВИТЬ ПРОКСИ" else "ЗАПУСТИТЬ ПРОКСИ"
|
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
|
||||||
tvLogs.text = ProxyService.logBuffer.joinToString("\n")
|
val intent = android.content.Intent(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
|
||||||
scrollLogsToEnd()
|
intent.data = android.net.Uri.parse("package:$packageName")
|
||||||
|
startActivity(intent)
|
||||||
ProxyService.onLogReceived = { msg ->
|
}
|
||||||
runOnUiThread {
|
}
|
||||||
if (tvLogs.text.length > 25000) tvLogs.text = tvLogs.text.substring(10000)
|
setContent {
|
||||||
tvLogs.append("\n$msg")
|
VkTurnProxyTheme {
|
||||||
scrollLogsToEnd()
|
AppNavigation(viewModel)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private fun scrollLogsToEnd() {
|
|
||||||
logScrollView.post { logScrollView.fullScroll(View.FOCUS_DOWN) }
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun onPause() {
|
|
||||||
super.onPause()
|
|
||||||
ProxyService.onLogReceived = null
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.vkturn.proxy
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.Build
|
||||||
|
import android.util.Log
|
||||||
|
|
||||||
|
class ProxyReceiver : BroadcastReceiver() {
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val ACTION_START = "com.vkturn.proxy.action.START"
|
||||||
|
const val ACTION_STOP = "com.vkturn.proxy.action.STOP"
|
||||||
|
private const val TAG = "ProxyReceiver"
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onReceive(context: Context, intent: Intent?) {
|
||||||
|
val action = intent?.action ?: return
|
||||||
|
Log.d(TAG, "Received action: $action")
|
||||||
|
|
||||||
|
when (action) {
|
||||||
|
ACTION_START -> {
|
||||||
|
Log.d(TAG, "Starting proxy service via intent")
|
||||||
|
val serviceIntent = Intent(context, ProxyService::class.java)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
context.startForegroundService(serviceIntent)
|
||||||
|
} else {
|
||||||
|
context.startService(serviceIntent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ACTION_STOP -> {
|
||||||
|
Log.d(TAG, "Stopping proxy service via intent")
|
||||||
|
val serviceIntent = Intent(context, ProxyService::class.java)
|
||||||
|
context.stopService(serviceIntent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,9 @@ import java.io.BufferedReader
|
|||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.InputStreamReader
|
import java.io.InputStreamReader
|
||||||
import kotlin.concurrent.thread
|
import kotlin.concurrent.thread
|
||||||
|
import com.vkturn.proxy.utils.DnsResolver
|
||||||
|
import com.vkturn.proxy.models.ClientConfig
|
||||||
|
import com.google.gson.Gson
|
||||||
|
|
||||||
class ProxyService : Service() {
|
class ProxyService : Service() {
|
||||||
|
|
||||||
@@ -20,12 +23,28 @@ class ProxyService : Service() {
|
|||||||
var isRunning = false
|
var isRunning = false
|
||||||
val logBuffer = mutableListOf<String>()
|
val logBuffer = mutableListOf<String>()
|
||||||
var onLogReceived: ((String) -> Unit)? = null
|
var onLogReceived: ((String) -> Unit)? = null
|
||||||
|
var appContext: Context? = null
|
||||||
|
|
||||||
fun addLog(msg: String) {
|
fun addLog(msg: String) {
|
||||||
if (logBuffer.size > 200) logBuffer.removeAt(0)
|
if (logBuffer.size > 200) logBuffer.removeAt(0)
|
||||||
logBuffer.add(msg)
|
logBuffer.add(msg)
|
||||||
onLogReceived?.invoke(msg)
|
onLogReceived?.invoke(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun updateNotification(title: String, text: String) {
|
||||||
|
val ctx = appContext ?: return
|
||||||
|
val openAppIntent = ctx.packageManager.getLaunchIntentForPackage(ctx.packageName)?.let {
|
||||||
|
android.app.PendingIntent.getActivity(ctx, 0, it, android.app.PendingIntent.FLAG_IMMUTABLE)
|
||||||
|
}
|
||||||
|
val notification = NotificationCompat.Builder(ctx, "ProxyChannel")
|
||||||
|
.setContentTitle(title)
|
||||||
|
.setContentText(text)
|
||||||
|
.setSmallIcon(android.R.drawable.ic_menu_preferences)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setContentIntent(openAppIntent)
|
||||||
|
.build()
|
||||||
|
ctx.getSystemService(NotificationManager::class.java).notify(1, notification)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var wakeLock: PowerManager.WakeLock? = null
|
private var wakeLock: PowerManager.WakeLock? = null
|
||||||
@@ -44,10 +63,18 @@ class ProxyService : Service() {
|
|||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
if (isRunning) return START_STICKY
|
if (isRunning) return START_STICKY
|
||||||
|
|
||||||
|
appContext = applicationContext
|
||||||
|
|
||||||
|
val openAppIntent = packageManager.getLaunchIntentForPackage(packageName)?.let {
|
||||||
|
android.app.PendingIntent.getActivity(this, 0, it, android.app.PendingIntent.FLAG_IMMUTABLE)
|
||||||
|
}
|
||||||
|
|
||||||
val notification = NotificationCompat.Builder(this, "ProxyChannel")
|
val notification = NotificationCompat.Builder(this, "ProxyChannel")
|
||||||
.setContentTitle("VK TURN Proxy")
|
.setContentTitle("TURN Proxy")
|
||||||
.setContentText("Работает в фоне")
|
.setContentText("Работает в фоне")
|
||||||
.setSmallIcon(android.R.drawable.ic_menu_preferences)
|
.setSmallIcon(android.R.drawable.ic_menu_preferences)
|
||||||
|
.setContentIntent(openAppIntent)
|
||||||
|
.setOngoing(true)
|
||||||
.build()
|
.build()
|
||||||
startForeground(1, notification)
|
startForeground(1, notification)
|
||||||
isRunning = true
|
isRunning = true
|
||||||
@@ -66,50 +93,77 @@ class ProxyService : Service() {
|
|||||||
val prefs = getSharedPreferences("ProxyPrefs", Context.MODE_PRIVATE)
|
val prefs = getSharedPreferences("ProxyPrefs", Context.MODE_PRIVATE)
|
||||||
val isRaw = prefs.getBoolean("isRaw", false)
|
val isRaw = prefs.getBoolean("isRaw", false)
|
||||||
|
|
||||||
// Ищем обновленный пользователем файл, если его нет - берем вшитый в APK
|
// Ищем импортированное пользователем ядро
|
||||||
val customBin = File(filesDir, "custom_vkturn")
|
val customBin = File(filesDir, "libcustom_kernel.so")
|
||||||
val executable = if (customBin.exists()) {
|
val executable = if (customBin.exists()) {
|
||||||
addLog("Используется кастомное ядро из памяти телефона")
|
|
||||||
customBin.absolutePath
|
customBin.absolutePath
|
||||||
} else {
|
} else {
|
||||||
addLog("Используется стандартное ядро из APK")
|
addLog("ОШИБКА: Ядро не импортировано! Пожалуйста, импортируйте ядро на главном экране.")
|
||||||
"${applicationInfo.nativeLibraryDir}/libvkturn.so"
|
isRunning = false
|
||||||
}
|
stopSelf()
|
||||||
|
return
|
||||||
val cmdArgs = mutableListOf<String>()
|
|
||||||
|
|
||||||
if (isRaw) {
|
|
||||||
val rawCmd = prefs.getString("rawCmd", "") ?: ""
|
|
||||||
// Разбиваем строку по пробелам
|
|
||||||
val parts = rawCmd.trim().split("\\s+".toRegex())
|
|
||||||
cmdArgs.add(executable) // Подменяем вызов "./client" на реальный путь
|
|
||||||
if (parts.size > 1) {
|
|
||||||
cmdArgs.addAll(parts.subList(1, parts.size))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
val peer = prefs.getString("peer", "") ?: ""
|
|
||||||
val link = prefs.getString("link", "") ?: ""
|
|
||||||
val n = prefs.getString("n", "") ?: ""
|
|
||||||
val listen = prefs.getString("listen", "127.0.0.1:9000") ?: ""
|
|
||||||
|
|
||||||
cmdArgs.add(executable)
|
|
||||||
cmdArgs.add("-peer")
|
|
||||||
cmdArgs.add(peer)
|
|
||||||
cmdArgs.add(if (link.contains("yandex")) "-yandex-link" else "-vk-link")
|
|
||||||
cmdArgs.add(link)
|
|
||||||
cmdArgs.add("-listen")
|
|
||||||
cmdArgs.add(listen)
|
|
||||||
|
|
||||||
if (n.isNotEmpty()) {
|
|
||||||
cmdArgs.add("-n")
|
|
||||||
cmdArgs.add(n)
|
|
||||||
}
|
|
||||||
if (prefs.getBoolean("udp", false)) cmdArgs.add("-udp")
|
|
||||||
if (prefs.getBoolean("noDtls", false)) cmdArgs.add("-no-dtls")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
thread {
|
thread {
|
||||||
try {
|
try {
|
||||||
|
val cmdArgs = mutableListOf<String>()
|
||||||
|
|
||||||
|
if (isRaw) {
|
||||||
|
val rawCmd = prefs.getString("rawCmd", "") ?: ""
|
||||||
|
val parts = rawCmd.trim().split("\\s+".toRegex())
|
||||||
|
cmdArgs.add(executable)
|
||||||
|
if (parts.size > 1) {
|
||||||
|
cmdArgs.addAll(parts.subList(1, parts.size))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val gson = Gson()
|
||||||
|
val configJson = prefs.getString("currentConfigJson", null)
|
||||||
|
val config = configJson?.let { gson.fromJson(it, ClientConfig::class.java) } ?: ClientConfig()
|
||||||
|
|
||||||
|
cmdArgs.add(executable)
|
||||||
|
cmdArgs.add("-peer")
|
||||||
|
|
||||||
|
val peer = config.serverAddress
|
||||||
|
val link = config.vkLink
|
||||||
|
val n = config.threads.toString()
|
||||||
|
val listen = config.localPort
|
||||||
|
|
||||||
|
val resolvedPeer = try {
|
||||||
|
if (peer.contains(":")) {
|
||||||
|
val parts = peer.split(":")
|
||||||
|
val host = parts[0]
|
||||||
|
val port = parts[1]
|
||||||
|
val ip = DnsResolver.resolve(host)
|
||||||
|
"$ip:$port"
|
||||||
|
} else {
|
||||||
|
peer
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
peer
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdArgs.add(resolvedPeer)
|
||||||
|
cmdArgs.add(config.linkArgument)
|
||||||
|
cmdArgs.add(link)
|
||||||
|
cmdArgs.add("-listen")
|
||||||
|
cmdArgs.add(listen)
|
||||||
|
|
||||||
|
if (n.isNotEmpty() && n != "0") {
|
||||||
|
cmdArgs.add("-n")
|
||||||
|
cmdArgs.add(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dynamic Flags
|
||||||
|
config.customFlags.forEach { flag ->
|
||||||
|
if (flag.enabled && flag.argument.isNotBlank()) {
|
||||||
|
// Split argument by space in case user put multiple flags in one item
|
||||||
|
flag.argument.trim().split("\\s+".toRegex()).forEach {
|
||||||
|
cmdArgs.add(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
addLog("Команда: ${cmdArgs.joinToString(" ")}")
|
addLog("Команда: ${cmdArgs.joinToString(" ")}")
|
||||||
|
|
||||||
process = ProcessBuilder(cmdArgs)
|
process = ProcessBuilder(cmdArgs)
|
||||||
@@ -135,7 +189,67 @@ class ProxyService : Service() {
|
|||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
isRunning = false
|
isRunning = false
|
||||||
addLog("=== ОСТАНОВКА ИЗ ИНТЕРФЕЙСА ===")
|
addLog("=== ОСТАНОВКА ИЗ ИНТЕРФЕЙСА ===")
|
||||||
process?.destroy()
|
|
||||||
|
// Попытка вежливой остановки (SIGINT)
|
||||||
|
process?.let { p ->
|
||||||
|
thread {
|
||||||
|
try {
|
||||||
|
val pid = getProcessPid(p)
|
||||||
|
if (pid != null) {
|
||||||
|
addLog("Отправка сигнала SIGINT (PID: $pid)...")
|
||||||
|
android.os.Process.sendSignal(pid, 2) // 2 = SIGINT
|
||||||
|
|
||||||
|
// Ждем завершения до 2 секунд
|
||||||
|
var count = 0
|
||||||
|
while (count < 20) { // 20 * 100ms = 2s
|
||||||
|
if (!isProcessAlive(p)) break
|
||||||
|
Thread.sleep(100)
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isProcessAlive(p)) {
|
||||||
|
addLog("Ядро не ответило вовремя, принудительное завершение...")
|
||||||
|
p.destroy()
|
||||||
|
} else {
|
||||||
|
addLog("Ядро успешно завершило работу.")
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
addLog("Ошибка при остановке: ${e.message}")
|
||||||
|
p.destroy()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (wakeLock?.isHeld == true) wakeLock?.release()
|
if (wakeLock?.isHeld == true) wakeLock?.release()
|
||||||
|
appContext = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getProcessPid(process: Process?): Int? {
|
||||||
|
if (process == null) return null
|
||||||
|
return try {
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
|
||||||
|
// В Java 9+ есть нормальный метод, но в Android он появился позже
|
||||||
|
// Пробуем через рефлексию (стандартно для UNIXProcess)
|
||||||
|
val field = process.javaClass.getDeclaredField("pid")
|
||||||
|
field.isAccessible = true
|
||||||
|
field.get(process) as Int
|
||||||
|
} else {
|
||||||
|
val field = process.javaClass.getDeclaredField("pid")
|
||||||
|
field.isAccessible = true
|
||||||
|
field.get(process) as Int
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isProcessAlive(process: Process?): Boolean {
|
||||||
|
return try {
|
||||||
|
process?.exitValue()
|
||||||
|
false // Если exitValue() не выкинул ошибку, значит процесс завершился
|
||||||
|
} catch (e: Exception) {
|
||||||
|
true // Означает, что процесс еще работает
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package com.vkturn.proxy
|
||||||
|
|
||||||
|
import com.jcraft.jsch.ChannelExec
|
||||||
|
import com.jcraft.jsch.ChannelShell
|
||||||
|
import com.jcraft.jsch.JSch
|
||||||
|
import com.jcraft.jsch.Session
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.io.OutputStream
|
||||||
|
import java.util.Properties
|
||||||
|
|
||||||
|
class SSHManager {
|
||||||
|
private var session: Session? = null
|
||||||
|
private var shellChannel: ChannelShell? = null
|
||||||
|
private var shellOutputStream: OutputStream? = null
|
||||||
|
@Volatile private var isShellRunning = false
|
||||||
|
|
||||||
|
fun startShell(ip: String, port: Int, user: String, pass: String, onLogReceived: (String) -> Unit, onDisconnected: (String?) -> Unit) {
|
||||||
|
Thread {
|
||||||
|
try {
|
||||||
|
if (session == null || !session!!.isConnected) {
|
||||||
|
val jsch = JSch()
|
||||||
|
session = jsch.getSession(user, ip, port)
|
||||||
|
session?.setPassword(pass)
|
||||||
|
|
||||||
|
val config = Properties()
|
||||||
|
config.put("StrictHostKeyChecking", "no")
|
||||||
|
session?.setConfig(config)
|
||||||
|
session?.serverAliveInterval = 10000 // Send keep-alive packet every 10 seconds
|
||||||
|
session?.connect(10000)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shellChannel != null && shellChannel!!.isConnected) {
|
||||||
|
return@Thread
|
||||||
|
}
|
||||||
|
|
||||||
|
shellChannel = session?.openChannel("shell") as ChannelShell
|
||||||
|
shellChannel?.setPty(true)
|
||||||
|
|
||||||
|
val inStream: InputStream = shellChannel!!.inputStream
|
||||||
|
shellOutputStream = shellChannel!!.outputStream
|
||||||
|
|
||||||
|
shellChannel?.connect(5000)
|
||||||
|
isShellRunning = true
|
||||||
|
|
||||||
|
val reader = inStream.bufferedReader()
|
||||||
|
val buffer = CharArray(1024)
|
||||||
|
var read = 0
|
||||||
|
|
||||||
|
while (isShellRunning && reader.read(buffer).also { read = it } != -1) {
|
||||||
|
val output = String(buffer, 0, read)
|
||||||
|
onLogReceived(output)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isShellRunning) {
|
||||||
|
// Stream ended unexpectedly (timeout/dropped connection)
|
||||||
|
isShellRunning = false
|
||||||
|
onDisconnected(null)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
onLogReceived("\n[ОШИБКА SHELL]: ${e.message}\n")
|
||||||
|
isShellRunning = false
|
||||||
|
onDisconnected(e.message)
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendShellCommand(command: String) {
|
||||||
|
Thread {
|
||||||
|
try {
|
||||||
|
if (shellOutputStream != null) {
|
||||||
|
shellOutputStream?.write((command + "\r").toByteArray())
|
||||||
|
shellOutputStream?.flush()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
// НОВАЯ ФУНКЦИЯ: Эмуляция Ctrl+C (прерывание процесса)
|
||||||
|
fun sendCtrlC() {
|
||||||
|
Thread {
|
||||||
|
try {
|
||||||
|
if (shellOutputStream != null) {
|
||||||
|
shellOutputStream?.write(3) // Байт 3 = ASCII символ ETX (End of Text) = Ctrl+C
|
||||||
|
shellOutputStream?.flush()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun executeSilentCommand(ip: String, port: Int, user: String, pass: String, command: String): String = withContext(Dispatchers.IO) {
|
||||||
|
var tempSession: Session? = null
|
||||||
|
try {
|
||||||
|
val jsch = JSch()
|
||||||
|
tempSession = jsch.getSession(user, ip, port)
|
||||||
|
tempSession.setPassword(pass)
|
||||||
|
|
||||||
|
val config = Properties()
|
||||||
|
config.put("StrictHostKeyChecking", "no")
|
||||||
|
tempSession.setConfig(config)
|
||||||
|
tempSession.connect(5000)
|
||||||
|
|
||||||
|
val channel = tempSession.openChannel("exec") as ChannelExec
|
||||||
|
channel.setCommand(command)
|
||||||
|
channel.inputStream = null
|
||||||
|
channel.setErrStream(null)
|
||||||
|
|
||||||
|
val inStream: InputStream = channel.inputStream
|
||||||
|
channel.connect()
|
||||||
|
|
||||||
|
val output = StringBuilder()
|
||||||
|
val reader = inStream.bufferedReader()
|
||||||
|
|
||||||
|
var line: String? = null
|
||||||
|
while (reader.readLine().also { line = it } != null) {
|
||||||
|
output.append(line).append("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
channel.disconnect()
|
||||||
|
output.toString().trim()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
"ERROR: ${e.message}"
|
||||||
|
} finally {
|
||||||
|
tempSession?.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun disconnect() {
|
||||||
|
isShellRunning = false
|
||||||
|
try {
|
||||||
|
shellOutputStream?.close()
|
||||||
|
} catch (e: Exception) {}
|
||||||
|
shellChannel?.disconnect()
|
||||||
|
session?.disconnect()
|
||||||
|
shellChannel = null
|
||||||
|
session = null
|
||||||
|
shellOutputStream = null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
package com.vkturn.proxy.data
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import com.vkturn.proxy.models.ProxyProfile
|
||||||
|
import com.vkturn.proxy.models.ClientConfig
|
||||||
|
import com.vkturn.proxy.models.ProxyFlag
|
||||||
|
import com.vkturn.proxy.models.SshConfig
|
||||||
|
import com.google.gson.Gson
|
||||||
|
import com.google.gson.reflect.TypeToken
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
|
||||||
|
class AppPreferences(context: Context) {
|
||||||
|
private val proxyPrefs: SharedPreferences = context.getSharedPreferences("ProxyPrefs", Context.MODE_PRIVATE)
|
||||||
|
private val sshPrefs: SharedPreferences = context.getSharedPreferences("SshPrefs", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
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 {
|
||||||
|
var currentFlags = (config.customFlags ?: emptyList()).toMutableList()
|
||||||
|
var changed = false
|
||||||
|
|
||||||
|
if (currentFlags.isEmpty()) {
|
||||||
|
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)
|
||||||
|
)
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 1. Update labels and identify present mandatory flags
|
||||||
|
mandatoryArgs.forEach { arg ->
|
||||||
|
val label = mandatoryLabels[arg]!!
|
||||||
|
val existing = 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)
|
||||||
|
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) }
|
||||||
|
}
|
||||||
|
val otherFlags = currentFlags.filter { it.argument !in mandatoryArgs }
|
||||||
|
|
||||||
|
if (currentFlags != (orderedFlags + otherFlags)) {
|
||||||
|
currentFlags.clear()
|
||||||
|
currentFlags.addAll(orderedFlags)
|
||||||
|
currentFlags.addAll(otherFlags)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure linkArgument is valid ONLY if link is present
|
||||||
|
var linkArg = config.linkArgument
|
||||||
|
if (linkArg.isEmpty() && config.vkLink.isNotEmpty()) {
|
||||||
|
linkArg = if (config.vkLink.contains("yandex")) "-yandex-link" else "-vk-link"
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure isRawMode is false if rawCommand is empty (safety for legacy profiles)
|
||||||
|
if (config.isRawMode && config.rawCommand.isBlank()) {
|
||||||
|
return config.copy(
|
||||||
|
customFlags = currentFlags,
|
||||||
|
linkArgument = linkArg,
|
||||||
|
isRawMode = false
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return if (changed) config.copy(customFlags = currentFlags, linkArgument = linkArg) else config
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadClientConfig(): ClientConfig {
|
||||||
|
val json = proxyPrefs.getString("currentConfigJson", null)
|
||||||
|
if (json != null) {
|
||||||
|
return try {
|
||||||
|
val config = gson.fromJson(json, ClientConfig::class.java)
|
||||||
|
migrateConfig(config)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
createDefaultConfig()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return createDefaultConfig()
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
)
|
||||||
|
|
||||||
|
return ClientConfig(
|
||||||
|
serverAddress = proxyPrefs.getString("peer", "") ?: "",
|
||||||
|
vkLink = link,
|
||||||
|
linkArgument = 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
|
||||||
|
rawCommand = "",
|
||||||
|
customFlags = flags
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadSshConfig(): SshConfig {
|
||||||
|
return SshConfig(
|
||||||
|
ip = sshPrefs.getString("ip", "") ?: "",
|
||||||
|
port = sshPrefs.getString("port", "22")?.toIntOrNull() ?: 22,
|
||||||
|
username = sshPrefs.getString("user", "root") ?: "root",
|
||||||
|
password = sshPrefs.getString("pass", "") ?: "",
|
||||||
|
proxyListen = sshPrefs.getString("proxyListen", "0.0.0.0:56000") ?: "0.0.0.0:56000",
|
||||||
|
proxyConnect = sshPrefs.getString("proxyConnect", "127.0.0.1:40537") ?: "127.0.0.1:40537"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveClientConfig(config: ClientConfig) {
|
||||||
|
proxyPrefs.edit().apply {
|
||||||
|
putString("peer", config.serverAddress)
|
||||||
|
putString("link", config.vkLink)
|
||||||
|
putString("linkArg", config.linkArgument)
|
||||||
|
putString("n", config.threads.toString())
|
||||||
|
putString("listen", config.localPort)
|
||||||
|
putBoolean("isRaw", config.isRawMode)
|
||||||
|
putString("rawCmd", config.rawCommand)
|
||||||
|
putString("currentConfigJson", gson.toJson(config))
|
||||||
|
}.apply()
|
||||||
|
_clientConfigFlow.value = config
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveSshConfig(config: SshConfig) {
|
||||||
|
sshPrefs.edit().apply {
|
||||||
|
putString("ip", config.ip)
|
||||||
|
putString("port", config.port.toString())
|
||||||
|
putString("user", config.username)
|
||||||
|
putString("pass", config.password)
|
||||||
|
putString("proxyListen", config.proxyListen)
|
||||||
|
putString("proxyConnect", config.proxyConnect)
|
||||||
|
}.apply()
|
||||||
|
_sshConfigFlow.value = config
|
||||||
|
}
|
||||||
|
|
||||||
|
fun loadProfiles(): List<ProxyProfile> {
|
||||||
|
val json = proxyPrefs.getString("profilesJson", null)
|
||||||
|
if (json == null) {
|
||||||
|
val initialProfile = ProxyProfile(name = "По умолчанию", config = loadClientConfig(), isDefault = true)
|
||||||
|
val profiles = listOf(initialProfile)
|
||||||
|
proxyPrefs.edit().putString("profilesJson", gson.toJson(profiles)).apply()
|
||||||
|
if (proxyPrefs.getString("selectedProfileId", "").isNullOrEmpty()) {
|
||||||
|
proxyPrefs.edit().putString("selectedProfileId", initialProfile.id).apply()
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (migratedProfiles != rawProfiles) {
|
||||||
|
proxyPrefs.edit().putString("profilesJson", gson.toJson(migratedProfiles)).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
return migratedProfiles
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveProfiles(profiles: List<ProxyProfile>) {
|
||||||
|
proxyPrefs.edit().putString("profilesJson", gson.toJson(profiles)).apply()
|
||||||
|
_profilesFlow.value = profiles
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveSelectedProfileId(id: String) {
|
||||||
|
proxyPrefs.edit().putString("selectedProfileId", id).apply()
|
||||||
|
_selectedProfileIdFlow.value = id
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package com.vkturn.proxy.models
|
||||||
|
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
data class ProxyProfile(
|
||||||
|
val id: String = UUID.randomUUID().toString(),
|
||||||
|
var name: String,
|
||||||
|
val config: ClientConfig,
|
||||||
|
val isDefault: Boolean = false
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ProxyFlag(
|
||||||
|
val id: String = UUID.randomUUID().toString(),
|
||||||
|
var label: String,
|
||||||
|
var argument: String,
|
||||||
|
var enabled: Boolean,
|
||||||
|
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()
|
||||||
|
) {
|
||||||
|
fun generateRawCommand(): String {
|
||||||
|
val cmds = mutableListOf<String>()
|
||||||
|
if (serverAddress.isNotBlank()) {
|
||||||
|
cmds.add("-peer")
|
||||||
|
cmds.add(serverAddress)
|
||||||
|
}
|
||||||
|
if (vkLink.isNotBlank()) {
|
||||||
|
cmds.add(linkArgument)
|
||||||
|
cmds.add(vkLink)
|
||||||
|
}
|
||||||
|
if (localPort.isNotBlank()) {
|
||||||
|
cmds.add("-listen")
|
||||||
|
cmds.add(localPort)
|
||||||
|
}
|
||||||
|
if (threads > 0) {
|
||||||
|
cmds.add("-n")
|
||||||
|
cmds.add(threads.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
customFlags.filter { it.enabled && it.argument.isNotBlank() }.forEach { flag ->
|
||||||
|
flag.argument.trim().split("\\s+".toRegex()).forEach {
|
||||||
|
cmds.add(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return cmds.joinToString(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun parseFromRawCommand(rawStr: String): ClientConfig {
|
||||||
|
if (rawStr.isBlank()) return this
|
||||||
|
|
||||||
|
val parts = rawStr.trim().split("\\s+".toRegex())
|
||||||
|
var newServerAddress = ""
|
||||||
|
var newVkLink = ""
|
||||||
|
var newLinkArgument = linkArgument // Start with current one
|
||||||
|
var newThreads = 0 // Default to 0 (infinity) if not found in raw
|
||||||
|
var newLocalPort = localPort
|
||||||
|
|
||||||
|
// Map of base flag name -> full argument string (e.g., "-udp" -> "-udp" or "-test" -> "-test val")
|
||||||
|
val encounteredFlags = mutableMapOf<String, String>()
|
||||||
|
|
||||||
|
val knownLinkFlags = listOf("-vk-link", "-yandex-link", "-mail-link", "-link")
|
||||||
|
|
||||||
|
var i = 0
|
||||||
|
while (i < parts.size) {
|
||||||
|
val part = parts[i]
|
||||||
|
when {
|
||||||
|
part == "-peer" && i + 1 < parts.size -> {
|
||||||
|
newServerAddress = parts[++i]
|
||||||
|
}
|
||||||
|
part == "-listen" && i + 1 < parts.size -> {
|
||||||
|
newLocalPort = parts[++i]
|
||||||
|
}
|
||||||
|
part == "-n" && i + 1 < parts.size -> {
|
||||||
|
newThreads = parts[++i].toIntOrNull() ?: threads
|
||||||
|
}
|
||||||
|
part.startsWith("-") -> {
|
||||||
|
val fullArg: String
|
||||||
|
val nextVal = if (i + 1 < parts.size && !parts[i + 1].startsWith("-")) parts[i + 1] else null
|
||||||
|
|
||||||
|
if (nextVal != null) {
|
||||||
|
fullArg = "$part $nextVal"
|
||||||
|
// Check if this is a link flag (either known or followed by a URL)
|
||||||
|
if (part == newLinkArgument || knownLinkFlags.contains(part) || nextVal.startsWith("http")) {
|
||||||
|
newVkLink = nextVal
|
||||||
|
newLinkArgument = part
|
||||||
|
i++ // skip the value part
|
||||||
|
} else {
|
||||||
|
encounteredFlags[part] = fullArg
|
||||||
|
i++ // skip the value part
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fullArg = part
|
||||||
|
encounteredFlags[part] = fullArg
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Smart merge with existing flags
|
||||||
|
val updatedCustomFlags = customFlags.mapNotNull { existing ->
|
||||||
|
// Extract base flag name from existing.argument (e.g. "-udp" from "-udp")
|
||||||
|
val baseName = existing.argument.split("\\s+".toRegex())[0]
|
||||||
|
|
||||||
|
// Skip if this flag is now the link argument or a standard field
|
||||||
|
if (baseName == newLinkArgument || baseName == "-peer" || baseName == "-listen" || baseName == "-n") {
|
||||||
|
return@mapNotNull null
|
||||||
|
}
|
||||||
|
|
||||||
|
val matchedNewArg = encounteredFlags[baseName]
|
||||||
|
|
||||||
|
if (matchedNewArg != null) {
|
||||||
|
// Flag present in raw string -> enable it and update value
|
||||||
|
encounteredFlags.remove(baseName)
|
||||||
|
existing.copy(enabled = true, argument = matchedNewArg)
|
||||||
|
} else {
|
||||||
|
// Flag missing in raw string
|
||||||
|
if (existing.deletable) {
|
||||||
|
// It's a user flag, remove it completely if missing from raw
|
||||||
|
null
|
||||||
|
} else {
|
||||||
|
// It's a system flag, just disable it
|
||||||
|
existing.copy(enabled = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.toMutableList()
|
||||||
|
|
||||||
|
// Add truly NEW flags that weren't in the list before
|
||||||
|
encounteredFlags.forEach { (baseName, fullArg) ->
|
||||||
|
if (baseName != newLinkArgument) {
|
||||||
|
updatedCustomFlags.add(ProxyFlag(
|
||||||
|
label = baseName,
|
||||||
|
argument = fullArg,
|
||||||
|
enabled = true
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.copy(
|
||||||
|
serverAddress = newServerAddress.ifBlank { serverAddress },
|
||||||
|
vkLink = newVkLink.ifBlank { vkLink },
|
||||||
|
linkArgument = newLinkArgument,
|
||||||
|
threads = newThreads,
|
||||||
|
localPort = newLocalPort.ifBlank { localPort },
|
||||||
|
customFlags = updatedCustomFlags
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class SshConfig(
|
||||||
|
val ip: String = "",
|
||||||
|
val port: Int = 22,
|
||||||
|
val username: String = "root",
|
||||||
|
val password: String = "",
|
||||||
|
val proxyListen: String = "0.0.0.0:56000",
|
||||||
|
val proxyConnect: String = "127.0.0.1:40537"
|
||||||
|
)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package com.vkturn.proxy.states
|
||||||
|
|
||||||
|
sealed class ProxyState {
|
||||||
|
object Idle : ProxyState()
|
||||||
|
object Starting : ProxyState()
|
||||||
|
object Running : ProxyState()
|
||||||
|
data class Error(val message: String) : ProxyState()
|
||||||
|
data class CaptchaRequired(val url: String) : ProxyState()
|
||||||
|
}
|
||||||
|
|
||||||
|
sealed class SshConnectionState {
|
||||||
|
object Disconnected : SshConnectionState()
|
||||||
|
object Connecting : SshConnectionState()
|
||||||
|
data class Connected(val ip: String) : SshConnectionState()
|
||||||
|
data class Error(val message: String) : SshConnectionState()
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package com.vkturn.proxy.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material3.Icon
|
||||||
|
import androidx.compose.material3.NavigationBar
|
||||||
|
import androidx.compose.material3.NavigationBarItem
|
||||||
|
import androidx.compose.material3.Scaffold
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.res.painterResource
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.navigation.compose.NavHost
|
||||||
|
import androidx.navigation.compose.composable
|
||||||
|
import androidx.navigation.compose.currentBackStackEntryAsState
|
||||||
|
import androidx.navigation.compose.rememberNavController
|
||||||
|
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||||
|
import com.vkturn.proxy.ui.components.CurrentProfileHeader
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.foundation.layout.Column
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.material3.HorizontalDivider
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun AppNavigation(viewModel: MainViewModel) {
|
||||||
|
val navController = rememberNavController()
|
||||||
|
val backStackEntry by navController.currentBackStackEntryAsState()
|
||||||
|
val currentRoute = backStackEntry?.destination?.route ?: "home"
|
||||||
|
|
||||||
|
val profiles by viewModel.profiles.collectAsStateWithLifecycle()
|
||||||
|
val selectedProfileId by viewModel.selectedProfileId.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
val currentProfileName = remember(profiles, selectedProfileId) {
|
||||||
|
profiles.find { it.id == selectedProfileId }?.name ?: "Не выбран"
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
bottomBar = {
|
||||||
|
NavigationBar {
|
||||||
|
NavigationBarItem(
|
||||||
|
selected = currentRoute == "home",
|
||||||
|
onClick = { navController.navigate("home") { launchSingleTop = true } },
|
||||||
|
icon = { Text("🏠") },
|
||||||
|
label = { Text("Главная") }
|
||||||
|
)
|
||||||
|
NavigationBarItem(
|
||||||
|
selected = currentRoute == "settings",
|
||||||
|
onClick = { navController.navigate("settings") { launchSingleTop = true } },
|
||||||
|
icon = { Text("⚙️") },
|
||||||
|
label = { Text("Настройки") }
|
||||||
|
)
|
||||||
|
NavigationBarItem(
|
||||||
|
selected = currentRoute == "ssh",
|
||||||
|
onClick = { navController.navigate("ssh") { launchSingleTop = true } },
|
||||||
|
icon = { Text("🖥️") },
|
||||||
|
label = { Text("Сервер") }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
topBar = {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.statusBarsPadding()
|
||||||
|
.padding(16.dp)
|
||||||
|
) {
|
||||||
|
CurrentProfileHeader(profileName = currentProfileName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
) { padding ->
|
||||||
|
NavHost(
|
||||||
|
navController = navController,
|
||||||
|
startDestination = "home",
|
||||||
|
modifier = Modifier.padding(padding)
|
||||||
|
) {
|
||||||
|
composable("home") {
|
||||||
|
HomeScreen(viewModel)
|
||||||
|
}
|
||||||
|
composable("settings") {
|
||||||
|
SettingsScreen(viewModel)
|
||||||
|
}
|
||||||
|
composable("ssh") {
|
||||||
|
SshScreen(viewModel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package com.vkturn.proxy.ui
|
||||||
|
|
||||||
|
import android.webkit.CookieManager
|
||||||
|
import android.webkit.WebResourceRequest
|
||||||
|
import android.webkit.WebSettings
|
||||||
|
import android.webkit.WebView
|
||||||
|
import android.webkit.WebViewClient
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.Card
|
||||||
|
import androidx.compose.material3.CardDefaults
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import androidx.compose.ui.window.DialogProperties
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
|
||||||
|
class WebAppInterface(private val onDismiss: () -> Unit) {
|
||||||
|
@android.webkit.JavascriptInterface
|
||||||
|
fun closeDialog() {
|
||||||
|
Handler(Looper.getMainLooper()).post {
|
||||||
|
onDismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun CaptchaWebViewDialog(captchaUrl: String, onDismiss: () -> Unit) {
|
||||||
|
Dialog(
|
||||||
|
onDismissRequest = onDismiss,
|
||||||
|
properties = DialogProperties(usePlatformDefaultWidth = false, dismissOnClickOutside = false)
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxSize().padding(16.dp),
|
||||||
|
shape = RoundedCornerShape(16.dp),
|
||||||
|
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
|
||||||
|
) {
|
||||||
|
AndroidView(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
factory = { context ->
|
||||||
|
WebView(context).apply {
|
||||||
|
settings.javaScriptEnabled = true
|
||||||
|
settings.domStorageEnabled = true
|
||||||
|
settings.cacheMode = WebSettings.LOAD_NO_CACHE
|
||||||
|
CookieManager.getInstance().setAcceptCookie(true)
|
||||||
|
CookieManager.getInstance().setAcceptThirdPartyCookies(this, true)
|
||||||
|
|
||||||
|
addJavascriptInterface(WebAppInterface(onDismiss), "Android")
|
||||||
|
|
||||||
|
webViewClient = object : WebViewClient() {
|
||||||
|
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
|
||||||
|
val url = request.url.toString()
|
||||||
|
// Allow all captcha-related domains to load inside WebView
|
||||||
|
val allowedDomains = listOf("localhost", "fapi.vk.com", "login.vk.com", "api.vk.com", "captcha.vk.com", "vk.com", "vk.ru")
|
||||||
|
val isAllowed = allowedDomains.any { url.contains(it) }
|
||||||
|
// Only dismiss if navigating to a completely unrelated page
|
||||||
|
if (!isAllowed) {
|
||||||
|
onDismiss()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPageFinished(view: WebView?, url: String?) {
|
||||||
|
super.onPageFinished(view, url)
|
||||||
|
val js = """
|
||||||
|
javascript:(function() {
|
||||||
|
var checkInterval = setInterval(function() {
|
||||||
|
if (document.body && document.body.textContent && document.body.textContent.indexOf("Done! You can close the page.") !== -1) {
|
||||||
|
clearInterval(checkInterval);
|
||||||
|
var newBody = document.createElement('body');
|
||||||
|
newBody.style.backgroundColor = '#1e1f22';
|
||||||
|
newBody.style.margin = '0';
|
||||||
|
newBody.innerHTML = '<div style="font-family:sans-serif; text-align:center; padding: 30px; margin: 20px; background-color:#2e3035; color:white; border-radius:12px; font-size:18px;">' +
|
||||||
|
'<h2 style="color:#00e676; margin-top:0;">Капча пройдена!</h2>' +
|
||||||
|
'<p>Сессия успешно подтверждена.</p>' +
|
||||||
|
'<p>Закрытие через <b id="timer" style="color:#2196f3; font-size:24px;">3</b> сек...</p>' +
|
||||||
|
'</div>';
|
||||||
|
document.documentElement.replaceChild(newBody, document.body);
|
||||||
|
|
||||||
|
var count = 3;
|
||||||
|
var timerInterval = setInterval(function() {
|
||||||
|
count--;
|
||||||
|
var t = document.getElementById("timer");
|
||||||
|
if (t) t.innerText = count;
|
||||||
|
if (count <= 0) {
|
||||||
|
clearInterval(timerInterval);
|
||||||
|
Android.closeDialog();
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
|
}, 100);
|
||||||
|
})();
|
||||||
|
""".trimIndent()
|
||||||
|
view?.evaluateJavascript(js, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loadUrl(captchaUrl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
package com.vkturn.proxy.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||||
|
import androidx.compose.ui.text.LinkAnnotation
|
||||||
|
import androidx.compose.ui.text.buildAnnotatedString
|
||||||
|
import androidx.compose.ui.text.withLink
|
||||||
|
import androidx.compose.ui.text.withStyle
|
||||||
|
import androidx.compose.ui.text.SpanStyle
|
||||||
|
import androidx.compose.ui.text.style.TextDecoration
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import android.os.PowerManager
|
||||||
|
import androidx.lifecycle.Lifecycle
|
||||||
|
import androidx.lifecycle.LifecycleEventObserver
|
||||||
|
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||||
|
import com.vkturn.proxy.states.ProxyState
|
||||||
|
import com.vkturn.proxy.ui.theme.*
|
||||||
|
import com.vkturn.proxy.ui.components.CurrentProfileHeader
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import android.widget.Toast
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun HomeScreen(viewModel: MainViewModel) {
|
||||||
|
val proxyState by viewModel.proxyState.collectAsStateWithLifecycle()
|
||||||
|
val proxyLogs by viewModel.proxyLogs.collectAsStateWithLifecycle()
|
||||||
|
val isKernelPresent by viewModel.isKernelPresent.collectAsStateWithLifecycle()
|
||||||
|
val profiles by viewModel.profiles.collectAsStateWithLifecycle()
|
||||||
|
val selectedProfileId by viewModel.selectedProfileId.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
val clipboardManager = remember { context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager }
|
||||||
|
val pm = remember { context.getSystemService(Context.POWER_SERVICE) as PowerManager }
|
||||||
|
|
||||||
|
val kernelLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||||
|
uri?.let {
|
||||||
|
scope.launch {
|
||||||
|
val result = viewModel.importKernel(it)
|
||||||
|
if (result.isSuccess) {
|
||||||
|
Toast.makeText(context, "Ядро импортировано", Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, result.exceptionOrNull()?.message ?: "Ошибка", Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var isIgnoringBattery by remember {
|
||||||
|
mutableStateOf(
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
|
||||||
|
pm.isIgnoringBatteryOptimizations(context.packageName)
|
||||||
|
} else true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(isIgnoringBattery) {
|
||||||
|
if (!isIgnoringBattery) {
|
||||||
|
while (true) {
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
|
||||||
|
val current = pm.isIgnoringBatteryOptimizations(context.packageName)
|
||||||
|
if (current) {
|
||||||
|
isIgnoringBattery = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
kotlinx.coroutines.delay(1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Captcha Dialog handling
|
||||||
|
if (proxyState is ProxyState.CaptchaRequired) {
|
||||||
|
CaptchaWebViewDialog(
|
||||||
|
captchaUrl = (proxyState as ProxyState.CaptchaRequired).url,
|
||||||
|
onDismiss = { viewModel.dismissCaptcha() }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(16.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally
|
||||||
|
) {
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
// Center Button
|
||||||
|
val buttonColor = when {
|
||||||
|
!isKernelPresent -> StatusRed
|
||||||
|
proxyState is ProxyState.Running -> StatusGreenDark
|
||||||
|
proxyState is ProxyState.Starting || proxyState is ProxyState.CaptchaRequired -> StatusYellow
|
||||||
|
else -> MaterialTheme.colorScheme.primary
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
if (proxyState is ProxyState.Running || proxyState is ProxyState.CaptchaRequired) {
|
||||||
|
viewModel.stopProxy()
|
||||||
|
} else {
|
||||||
|
viewModel.startProxy()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
enabled = isKernelPresent,
|
||||||
|
modifier = Modifier
|
||||||
|
.size(150.dp),
|
||||||
|
shape = CircleShape,
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = buttonColor,
|
||||||
|
disabledContainerColor = StatusRed,
|
||||||
|
disabledContentColor = Color.White
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = when {
|
||||||
|
!isKernelPresent -> "НЕТ ЯДРА"
|
||||||
|
proxyState is ProxyState.Running -> "ОСТАНОВИТЬ"
|
||||||
|
proxyState is ProxyState.Starting -> "ЗАПУСК..."
|
||||||
|
proxyState is ProxyState.CaptchaRequired -> "КАПЧА"
|
||||||
|
else -> "ЗАПУСТИТЬ"
|
||||||
|
},
|
||||||
|
color = Color.White,
|
||||||
|
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,
|
||||||
|
softWrap = false,
|
||||||
|
maxLines = 1
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(24.dp))
|
||||||
|
|
||||||
|
if (!isIgnoringBattery) {
|
||||||
|
Card(
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer),
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable {
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
|
||||||
|
val intent = android.content.Intent(android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
|
||||||
|
intent.data = android.net.Uri.parse("package:${context.packageName}")
|
||||||
|
context.startActivity(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "⚠ Внимание! Система может убить прокси. Нажмите, чтобы отключить оптимизацию.",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||||
|
modifier = Modifier.padding(16.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Console logs
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth().weight(1f),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = DarkSurface),
|
||||||
|
shape = RoundedCornerShape(12.dp)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(16.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text("Терминал", color = TextSecondary, style = MaterialTheme.typography.titleMedium)
|
||||||
|
Row {
|
||||||
|
TextButton(onClick = {
|
||||||
|
clipboardManager.setPrimaryClip(ClipData.newPlainText("logs", proxyLogs.joinToString("\n")))
|
||||||
|
}) {
|
||||||
|
Text("Copy", color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
TextButton(onClick = { viewModel.clearProxyLogs() }) {
|
||||||
|
Text("Clear", color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
|
||||||
|
val listState = rememberLazyListState()
|
||||||
|
LaunchedEffect(proxyLogs.size) {
|
||||||
|
if (proxyLogs.isNotEmpty()) {
|
||||||
|
listState.animateScrollToItem(proxyLogs.lastIndex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SelectionContainer(modifier = Modifier.fillMaxSize()) {
|
||||||
|
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
|
||||||
|
items(proxyLogs) { log ->
|
||||||
|
val isError = log.contains("ОШИБКА", ignoreCase = true) || log.contains("ERROR", ignoreCase = true)
|
||||||
|
val textColor = if (isError) StatusRed else StatusGreen
|
||||||
|
|
||||||
|
val urlRegex = "(https?://[A-Za-z0-9-._~:/?#\\[\\]@!$&'()*+,;=]+)".toRegex()
|
||||||
|
val matchResult = urlRegex.find(log)
|
||||||
|
|
||||||
|
if (matchResult != null) {
|
||||||
|
val url = matchResult.value
|
||||||
|
val displayUrl = if (url.length > 60) url.take(55) + "..." else url
|
||||||
|
val start = log.indexOf(url)
|
||||||
|
|
||||||
|
val annotatedStr = buildAnnotatedString {
|
||||||
|
append(log.substring(0, start))
|
||||||
|
withLink(LinkAnnotation.Url(url)) {
|
||||||
|
withStyle(style = SpanStyle(color = StatusBlue, textDecoration = TextDecoration.Underline)) {
|
||||||
|
append(displayUrl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
append(log.substring(start + url.length))
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
text = annotatedStr,
|
||||||
|
style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace, color = textColor),
|
||||||
|
modifier = Modifier.padding(vertical = 2.dp)
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
Text(
|
||||||
|
text = log,
|
||||||
|
color = textColor,
|
||||||
|
fontFamily = FontFamily.Monospace,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
modifier = Modifier.padding(vertical = 2.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,757 @@
|
|||||||
|
package com.vkturn.proxy.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.LazyRow
|
||||||
|
import androidx.compose.foundation.lazy.items
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.PowerManager
|
||||||
|
import android.provider.Settings
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import android.widget.Toast
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import androidx.compose.ui.draw.scale
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.*
|
||||||
|
import com.vkturn.proxy.models.*
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import com.vkturn.proxy.ui.theme.StatusRed
|
||||||
|
import com.vkturn.proxy.ui.theme.StatusGreen
|
||||||
|
import com.vkturn.proxy.ui.theme.DarkSurface
|
||||||
|
import com.vkturn.proxy.ui.theme.TextSecondary
|
||||||
|
import com.vkturn.proxy.ui.theme.PrimaryAccent
|
||||||
|
import com.vkturn.proxy.ui.components.CurrentProfileHeader
|
||||||
|
import com.vkturn.proxy.ui.components.ExpandableSection
|
||||||
|
import com.vkturn.proxy.data.AppPreferences
|
||||||
|
import com.vkturn.proxy.ui.components.QrScannerScreen
|
||||||
|
import com.vkturn.proxy.ui.components.QrExportDialog
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun SettingsScreen(viewModel: MainViewModel) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
|
var showScanner by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
if (showScanner) {
|
||||||
|
QrScannerScreen(
|
||||||
|
onScanResult = { result ->
|
||||||
|
viewModel.handleProfileImport(result)
|
||||||
|
showScanner = false
|
||||||
|
},
|
||||||
|
onCancel = { showScanner = false },
|
||||||
|
onClipboardImportClick = {
|
||||||
|
viewModel.importProfileFromClipboard()
|
||||||
|
showScanner = false
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
val profiles by viewModel.profiles.collectAsStateWithLifecycle()
|
||||||
|
val selectedProfileId by viewModel.selectedProfileId.collectAsStateWithLifecycle()
|
||||||
|
val clientConfig by viewModel.clientConfig.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
var peer by remember(clientConfig) { mutableStateOf(clientConfig.serverAddress) }
|
||||||
|
var link by remember(clientConfig) { mutableStateOf(clientConfig.vkLink) }
|
||||||
|
var linkArg by remember(clientConfig) { mutableStateOf(clientConfig.linkArgument) }
|
||||||
|
var threads by remember(clientConfig) { mutableStateOf(clientConfig.threads.toFloat()) }
|
||||||
|
var listen by remember(clientConfig) { mutableStateOf(clientConfig.localPort) }
|
||||||
|
|
||||||
|
|
||||||
|
var isRawMode by remember(clientConfig) { mutableStateOf(clientConfig.isRawMode) }
|
||||||
|
var rawCommand by remember(clientConfig) { mutableStateOf(clientConfig.rawCommand) }
|
||||||
|
|
||||||
|
var isProfilesExpanded by remember { mutableStateOf(false) }
|
||||||
|
var isFlagsExpanded by remember { mutableStateOf(false) }
|
||||||
|
var isConnectionExpanded by remember { mutableStateOf(false) }
|
||||||
|
var isSystemExpanded by remember { mutableStateOf(false) }
|
||||||
|
var isKernelExpanded by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
var currentFlags by remember(clientConfig) { mutableStateOf(clientConfig.customFlags) }
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// Track unsaved changes
|
||||||
|
val hasUnsavedChanges = remember(peer, link, linkArg, threads, listen, isRawMode, rawCommand, currentFlags, clientConfig) {
|
||||||
|
val standardFieldsChanged = peer != clientConfig.serverAddress ||
|
||||||
|
link != clientConfig.vkLink ||
|
||||||
|
linkArg != clientConfig.linkArgument ||
|
||||||
|
threads.toInt() != clientConfig.threads ||
|
||||||
|
listen != clientConfig.localPort ||
|
||||||
|
currentFlags != clientConfig.customFlags
|
||||||
|
|
||||||
|
if (isRawMode) {
|
||||||
|
if (clientConfig.isRawMode) {
|
||||||
|
// If stored config was already Raw, we just compare the strings
|
||||||
|
rawCommand != clientConfig.rawCommand
|
||||||
|
} else {
|
||||||
|
// If stored config was Standard, compare with what the command *would* be
|
||||||
|
rawCommand != clientConfig.generateRawCommand()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// In standard mode, we only care if the structural fields were modified
|
||||||
|
standardFieldsChanged
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var showSavedFeedback by remember { mutableStateOf(false) }
|
||||||
|
var showExportQrForData by remember { mutableStateOf<Pair<String, String>?>(null) }
|
||||||
|
|
||||||
|
showExportQrForData?.let { (profileName, data) ->
|
||||||
|
QrExportDialog(
|
||||||
|
profileName = profileName,
|
||||||
|
profileData = data,
|
||||||
|
onDismiss = { showExportQrForData = null }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide "Saved" message if user starts editing again
|
||||||
|
LaunchedEffect(hasUnsavedChanges) {
|
||||||
|
if (hasUnsavedChanges) showSavedFeedback = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-hide "Saved" message after 3 seconds
|
||||||
|
LaunchedEffect(showSavedFeedback) {
|
||||||
|
if (showSavedFeedback) {
|
||||||
|
kotlinx.coroutines.delay(3000)
|
||||||
|
showSavedFeedback = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var showNamingDialog by remember { mutableStateOf<String?>(null) } // null = hide, "" = new, "id" = rename
|
||||||
|
var namingValue by remember { mutableStateOf("") }
|
||||||
|
|
||||||
|
var showFlagDialog by remember { mutableStateOf<ProxyFlag?>(null) } // null = hide, id == "" -> new, else edit
|
||||||
|
var flagLabel by remember { mutableStateOf("") }
|
||||||
|
var flagArg by remember { mutableStateOf("") }
|
||||||
|
|
||||||
|
if (showFlagDialog != null) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { showFlagDialog = null },
|
||||||
|
title = { Text(if (showFlagDialog!!.id.isEmpty()) "Новый флаг" else "Редактировать флаг") },
|
||||||
|
text = {
|
||||||
|
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = flagLabel,
|
||||||
|
onValueChange = { flagLabel = it },
|
||||||
|
label = { Text("Название (в UI)") },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = flagArg,
|
||||||
|
onValueChange = { flagArg = it },
|
||||||
|
label = { Text("Аргумент (например -udp)") },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
Button(onClick = {
|
||||||
|
if (flagLabel.isNotBlank() && flagArg.isNotBlank()) {
|
||||||
|
if (showFlagDialog!!.id.isEmpty()) {
|
||||||
|
val newFlag = ProxyFlag(label = flagLabel, argument = flagArg, enabled = true)
|
||||||
|
currentFlags = currentFlags + newFlag
|
||||||
|
} else {
|
||||||
|
currentFlags = currentFlags.map {
|
||||||
|
if (it.id == showFlagDialog!!.id) it.copy(label = flagLabel, argument = flagArg) else it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
showFlagDialog = null
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
Text("OK")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showFlagDialog = null }) { Text("Отмена") }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (showNamingDialog != null) {
|
||||||
|
AlertDialog(
|
||||||
|
onDismissRequest = { showNamingDialog = null },
|
||||||
|
title = { Text(if (showNamingDialog == "") "Новый профиль" else "Переименовать") },
|
||||||
|
text = {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = namingValue,
|
||||||
|
onValueChange = { namingValue = it },
|
||||||
|
label = { Text("Название") },
|
||||||
|
singleLine = true,
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
)
|
||||||
|
},
|
||||||
|
confirmButton = {
|
||||||
|
Button(onClick = {
|
||||||
|
if (namingValue.isNotBlank()) {
|
||||||
|
if (showNamingDialog == "") {
|
||||||
|
viewModel.addProfile(namingValue)
|
||||||
|
} else {
|
||||||
|
viewModel.renameProfile(showNamingDialog!!, namingValue)
|
||||||
|
}
|
||||||
|
showNamingDialog = null
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
Text("OK")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showNamingDialog = null }) { Text("Отмена") }
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(16.dp)
|
||||||
|
.verticalScroll(rememberScrollState()),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
// 1. Client Settings Header
|
||||||
|
Text("Настройки Клиента", style = MaterialTheme.typography.titleLarge)
|
||||||
|
|
||||||
|
Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
|
||||||
|
Text(
|
||||||
|
"Режим своей (Raw) команды",
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
Switch(
|
||||||
|
checked = isRawMode,
|
||||||
|
onCheckedChange = { checked ->
|
||||||
|
if (checked) {
|
||||||
|
// Switching TO Raw: Generate command from fields
|
||||||
|
val tempConfig = clientConfig.copy(
|
||||||
|
serverAddress = peer,
|
||||||
|
vkLink = link,
|
||||||
|
linkArgument = linkArg,
|
||||||
|
threads = threads.toInt(),
|
||||||
|
localPort = listen,
|
||||||
|
customFlags = currentFlags
|
||||||
|
)
|
||||||
|
rawCommand = tempConfig.generateRawCommand()
|
||||||
|
} else {
|
||||||
|
// Switching FROM Raw: Parse command back to fields
|
||||||
|
val updatedConfig = clientConfig.copy(linkArgument = linkArg).parseFromRawCommand(rawCommand)
|
||||||
|
peer = updatedConfig.serverAddress
|
||||||
|
link = updatedConfig.vkLink
|
||||||
|
threads = updatedConfig.threads.toFloat()
|
||||||
|
listen = updatedConfig.localPort
|
||||||
|
currentFlags = updatedConfig.customFlags
|
||||||
|
}
|
||||||
|
isRawMode = checked
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isRawMode) {
|
||||||
|
// Raw Mode UI
|
||||||
|
OutlinedTextField(
|
||||||
|
value = rawCommand,
|
||||||
|
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") }
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Standard Mode UI
|
||||||
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = link,
|
||||||
|
onValueChange = {
|
||||||
|
link = it
|
||||||
|
if (linkArg.isEmpty() && it.isNotEmpty()) {
|
||||||
|
// Auto-fill if empty
|
||||||
|
linkArg = if (it.contains("yandex")) "-yandex-link" else "-vk-link"
|
||||||
|
} else if (linkArg == "-vk-link" && it.contains("yandex")) {
|
||||||
|
linkArg = "-yandex-link"
|
||||||
|
} else if (linkArg == "-yandex-link" && (it.contains("vk") || it.contains("mail"))) {
|
||||||
|
linkArg = "-vk-link"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
label = { Text("Ссылка (для Bypass)") },
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = linkArg,
|
||||||
|
onValueChange = { linkArg = it },
|
||||||
|
label = { Text("Аргумент") },
|
||||||
|
modifier = Modifier.width(120.dp),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Column {
|
||||||
|
Text("Количество потоков (Threads): ${if (threads == 0f) "∞" else threads.toInt()}")
|
||||||
|
Slider(
|
||||||
|
value = threads,
|
||||||
|
onValueChange = { threads = it },
|
||||||
|
valueRange = 0f..8f,
|
||||||
|
steps = 7
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Flags
|
||||||
|
ExpandableSection(
|
||||||
|
title = "Флаги и аргументы",
|
||||||
|
isExpanded = isFlagsExpanded,
|
||||||
|
onExpandChange = { isFlagsExpanded = it }
|
||||||
|
) {
|
||||||
|
var showDtlsWarning by remember { mutableStateOf(false) }
|
||||||
|
|
||||||
|
if (showDtlsWarning) {
|
||||||
|
androidx.compose.material3.AlertDialog(
|
||||||
|
onDismissRequest = { showDtlsWarning = false },
|
||||||
|
title = { Text("Внимание!") },
|
||||||
|
text = { Text("Отключение DTLS с большой вероятностью приведет к блокировке со стороны сервиса. Вы уверены?") },
|
||||||
|
confirmButton = {
|
||||||
|
TextButton(onClick = {
|
||||||
|
currentFlags = currentFlags.map {
|
||||||
|
if (it.argument == "-no-dtls") it.copy(enabled = true) else it
|
||||||
|
}
|
||||||
|
showDtlsWarning = false
|
||||||
|
}) {
|
||||||
|
Text("Продолжить", color = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dismissButton = {
|
||||||
|
TextButton(onClick = { showDtlsWarning = false }) {
|
||||||
|
Text("Отмена")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
currentFlags.forEach { flag ->
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
color = MaterialTheme.colorScheme.surface,
|
||||||
|
shape = MaterialTheme.shapes.small
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(8.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Switch(
|
||||||
|
checked = flag.enabled,
|
||||||
|
onCheckedChange = { isChecked ->
|
||||||
|
if (flag.argument == "-no-dtls" && isChecked) {
|
||||||
|
showDtlsWarning = true
|
||||||
|
} else {
|
||||||
|
currentFlags = currentFlags.map {
|
||||||
|
if (it.id == flag.id) it.copy(enabled = isChecked) else it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.scale(0.8f)
|
||||||
|
)
|
||||||
|
Column(modifier = Modifier.weight(1f).padding(horizontal = 8.dp)) {
|
||||||
|
Text(flag.label, style = MaterialTheme.typography.bodyLarge)
|
||||||
|
Text(flag.argument, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
|
}
|
||||||
|
|
||||||
|
IconButton(onClick = {
|
||||||
|
val index = currentFlags.indexOfFirst { it.id == flag.id }
|
||||||
|
if (index > 0) {
|
||||||
|
val list = currentFlags.toMutableList()
|
||||||
|
val item = list.removeAt(index)
|
||||||
|
list.add(index - 1, item)
|
||||||
|
currentFlags = list
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Default.KeyboardArrowUp, null, modifier = Modifier.size(18.dp))
|
||||||
|
}
|
||||||
|
IconButton(onClick = {
|
||||||
|
val index = currentFlags.indexOfFirst { it.id == flag.id }
|
||||||
|
if (index < currentFlags.size - 1 && index != -1) {
|
||||||
|
val list = currentFlags.toMutableList()
|
||||||
|
val item = list.removeAt(index)
|
||||||
|
list.add(index + 1, item)
|
||||||
|
currentFlags = list
|
||||||
|
}
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Default.KeyboardArrowDown, null, modifier = Modifier.size(18.dp))
|
||||||
|
}
|
||||||
|
IconButton(onClick = {
|
||||||
|
flagLabel = flag.label
|
||||||
|
flagArg = flag.argument
|
||||||
|
showFlagDialog = flag
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Default.Edit, null, modifier = Modifier.size(18.dp))
|
||||||
|
}
|
||||||
|
if (flag.deletable) {
|
||||||
|
IconButton(onClick = {
|
||||||
|
currentFlags = currentFlags.filter { it.id != flag.id }
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Default.Delete, null, modifier = Modifier.size(18.dp), tint = MaterialTheme.colorScheme.error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TextButton(onClick = {
|
||||||
|
flagLabel = ""
|
||||||
|
flagArg = ""
|
||||||
|
showFlagDialog = ProxyFlag(id = "", label = "", argument = "", enabled = true)
|
||||||
|
}) {
|
||||||
|
Icon(Icons.Default.Add, null)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text("Добавить свой флаг")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Connection Parameters
|
||||||
|
ExpandableSection(
|
||||||
|
title = "Параметры подключения",
|
||||||
|
isExpanded = isConnectionExpanded,
|
||||||
|
onExpandChange = { isConnectionExpanded = it }
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = peer,
|
||||||
|
onValueChange = { peer = it },
|
||||||
|
label = { Text("Адрес сервера (ip:port)") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = listen,
|
||||||
|
onValueChange = { listen = it },
|
||||||
|
label = { Text("Локальный адрес (Listen)") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasUnsavedChanges) {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
val finalConfig = if (isRawMode) {
|
||||||
|
// If saving in Raw mode, parse the command first to keep structural fields in sync
|
||||||
|
clientConfig.copy(linkArgument = linkArg)
|
||||||
|
.parseFromRawCommand(rawCommand)
|
||||||
|
.copy(isRawMode = true, rawCommand = rawCommand)
|
||||||
|
} else {
|
||||||
|
clientConfig.copy(
|
||||||
|
serverAddress = peer,
|
||||||
|
vkLink = link,
|
||||||
|
linkArgument = linkArg,
|
||||||
|
threads = threads.toInt(),
|
||||||
|
localPort = listen,
|
||||||
|
isRawMode = false,
|
||||||
|
rawCommand = rawCommand, // keep it for reference
|
||||||
|
customFlags = currentFlags
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
viewModel.saveClientConfig(finalConfig)
|
||||||
|
|
||||||
|
// Update local state in case parsing changed something (only relevant if isRawMode was true)
|
||||||
|
if (isRawMode) {
|
||||||
|
peer = finalConfig.serverAddress
|
||||||
|
link = finalConfig.vkLink
|
||||||
|
threads = finalConfig.threads.toFloat()
|
||||||
|
listen = finalConfig.localPort
|
||||||
|
currentFlags = finalConfig.customFlags
|
||||||
|
}
|
||||||
|
|
||||||
|
showSavedFeedback = true
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary)
|
||||||
|
) {
|
||||||
|
Text("СОХРАНИТЬ ИЗМЕНЕНИЯ", fontWeight = androidx.compose.ui.text.font.FontWeight.Bold)
|
||||||
|
}
|
||||||
|
} else if (showSavedFeedback) {
|
||||||
|
Text(
|
||||||
|
"✓ Сохранено",
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||||
|
color = StatusGreen,
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
|
||||||
|
fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
HorizontalDivider(Modifier.padding(vertical = 4.dp))
|
||||||
|
|
||||||
|
// 4. Profiles & Backup
|
||||||
|
ExpandableSection(
|
||||||
|
title = "Профили и Бэкап",
|
||||||
|
isExpanded = isProfilesExpanded,
|
||||||
|
onExpandChange = { isProfilesExpanded = it },
|
||||||
|
titleColor = Color.White
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||||
|
) {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
val data = viewModel.getAllProfilesExportData()
|
||||||
|
showExportQrForData = "Все профили (${profiles.size})" to data
|
||||||
|
},
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text("Экспорт всех")
|
||||||
|
}
|
||||||
|
Button(
|
||||||
|
onClick = { showScanner = true },
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text("Импорт")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(8.dp)) {
|
||||||
|
profiles.forEach { profile ->
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { viewModel.selectProfile(profile.id) }
|
||||||
|
.padding(vertical = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween
|
||||||
|
) {
|
||||||
|
RadioButton(
|
||||||
|
selected = profile.id == selectedProfileId,
|
||||||
|
onClick = { viewModel.selectProfile(profile.id) }
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = profile.name,
|
||||||
|
modifier = Modifier.weight(1f).padding(start = 8.dp),
|
||||||
|
style = MaterialTheme.typography.bodyLarge
|
||||||
|
)
|
||||||
|
|
||||||
|
var showMenu by remember { mutableStateOf(false) }
|
||||||
|
Box {
|
||||||
|
IconButton(onClick = { showMenu = true }) {
|
||||||
|
Icon(Icons.Default.MoreVert, contentDescription = "Меню")
|
||||||
|
}
|
||||||
|
|
||||||
|
DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Переименовать") },
|
||||||
|
onClick = {
|
||||||
|
namingValue = profile.name
|
||||||
|
showNamingDialog = profile.id
|
||||||
|
showMenu = false
|
||||||
|
}
|
||||||
|
)
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Поделиться") },
|
||||||
|
onClick = {
|
||||||
|
val data = viewModel.getProfileExportData(profile.id)
|
||||||
|
if (data != null) {
|
||||||
|
showExportQrForData = profile.name to data
|
||||||
|
}
|
||||||
|
showMenu = false
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
if (profile.isDefault) {
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Сбросить настройки", color = MaterialTheme.colorScheme.error) },
|
||||||
|
onClick = {
|
||||||
|
viewModel.resetProfile(profile.id)
|
||||||
|
showMenu = false
|
||||||
|
}
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
DropdownMenuItem(
|
||||||
|
text = { Text("Удалить", color = MaterialTheme.colorScheme.error) },
|
||||||
|
onClick = {
|
||||||
|
viewModel.deleteProfile(profile.id)
|
||||||
|
showMenu = false
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TextButton(
|
||||||
|
onClick = {
|
||||||
|
namingValue = ""
|
||||||
|
showNamingDialog = ""
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.Add, contentDescription = null)
|
||||||
|
Spacer(Modifier.width(8.dp))
|
||||||
|
Text("Создать новый профиль")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. System Settings
|
||||||
|
ExpandableSection(
|
||||||
|
title = "Системные настройки",
|
||||||
|
isExpanded = isSystemExpanded,
|
||||||
|
onExpandChange = { isSystemExpanded = it },
|
||||||
|
titleColor = PrimaryAccent
|
||||||
|
) {
|
||||||
|
val isIgnoringBattery = remember(context) {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
|
pm.isIgnoringBatteryOptimizations(context.packageName)
|
||||||
|
} else true
|
||||||
|
}
|
||||||
|
|
||||||
|
Surface(
|
||||||
|
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(12.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text("Оптимизация батареи", style = MaterialTheme.typography.bodyMedium)
|
||||||
|
Text(
|
||||||
|
if (isIgnoringBattery) "Отключена (Рекомендуется)" else "Включена (Может мешать работе)",
|
||||||
|
style = MaterialTheme.typography.bodySmall,
|
||||||
|
color = if (isIgnoringBattery) StatusGreen else StatusRed
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
|
||||||
|
try {
|
||||||
|
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
|
||||||
|
data = Uri.parse("package:${context.packageName}")
|
||||||
|
}
|
||||||
|
context.startActivity(intent)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
|
||||||
|
context.startActivity(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp)
|
||||||
|
) {
|
||||||
|
Text("Инфо")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isIgnoringBattery) {
|
||||||
|
Spacer(Modifier.height(8.dp))
|
||||||
|
Text(
|
||||||
|
"Для стабильной работы в фоне (особенно при выключенном экране) необходимо разрешить приложению работать без ограничений.",
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(12.dp))
|
||||||
|
|
||||||
|
// Tethering Stability Advice
|
||||||
|
Surface(
|
||||||
|
color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.2f),
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.padding(12.dp)) {
|
||||||
|
Text(
|
||||||
|
"Проблема с раздачей интернета?",
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = MaterialTheme.colorScheme.error
|
||||||
|
)
|
||||||
|
Spacer(Modifier.height(4.dp))
|
||||||
|
Text(
|
||||||
|
"Если при выключении экрана пропадает интернет на других устройствах, это работа Android Doze Mode. " +
|
||||||
|
"Для Root-пользователей рекомендуется решение:\n" +
|
||||||
|
"dumpsys deviceidle disable",
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Kernel
|
||||||
|
ExpandableSection(
|
||||||
|
title = "Ядро (Binary)",
|
||||||
|
isExpanded = isKernelExpanded,
|
||||||
|
onExpandChange = { isKernelExpanded = it },
|
||||||
|
titleColor = StatusRed
|
||||||
|
) {
|
||||||
|
val isKernelPresent by viewModel.isKernelPresent.collectAsStateWithLifecycle()
|
||||||
|
val kernelLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||||
|
uri?.let {
|
||||||
|
scope.launch {
|
||||||
|
val result = viewModel.importKernel(it)
|
||||||
|
if (result.isSuccess) {
|
||||||
|
Toast.makeText(context, "Ядро импортировано", Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, result.exceptionOrNull()?.message ?: "Ошибка", Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Surface(
|
||||||
|
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||||
|
shape = RoundedCornerShape(8.dp),
|
||||||
|
modifier = Modifier.fillMaxWidth()
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.padding(12.dp).fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.weight(1f)) {
|
||||||
|
Text(if (isKernelPresent) "Ядро активно" else "Ядро не найдено", style = MaterialTheme.typography.bodyMedium)
|
||||||
|
}
|
||||||
|
if (isKernelPresent) {
|
||||||
|
TextButton(onClick = { viewModel.deleteKernel() }, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error)) {
|
||||||
|
Text("Удалить")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Button(onClick = { kernelLauncher.launch("*/*") }) {
|
||||||
|
Text("Импорт")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
package com.vkturn.proxy.ui
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.rememberScrollState
|
||||||
|
import androidx.compose.foundation.text.KeyboardOptions
|
||||||
|
import androidx.compose.foundation.verticalScroll
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||||
|
import androidx.compose.ui.text.input.KeyboardType
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
|
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||||
|
import com.vkturn.proxy.viewmodel.ServerState
|
||||||
|
import com.vkturn.proxy.states.SshConnectionState
|
||||||
|
import com.vkturn.proxy.ui.theme.*
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun SshScreen(viewModel: MainViewModel) {
|
||||||
|
val sshConfig by viewModel.sshConfig.collectAsStateWithLifecycle()
|
||||||
|
val sshState by viewModel.sshState.collectAsStateWithLifecycle()
|
||||||
|
val serverState by viewModel.serverState.collectAsStateWithLifecycle()
|
||||||
|
val sshLog by viewModel.sshLog.collectAsStateWithLifecycle()
|
||||||
|
|
||||||
|
var ip by remember(sshConfig) { mutableStateOf(sshConfig.ip) }
|
||||||
|
var port by remember(sshConfig) { mutableStateOf(sshConfig.port.toString()) }
|
||||||
|
var user by remember(sshConfig) { mutableStateOf(sshConfig.username) }
|
||||||
|
var pass by remember(sshConfig) { mutableStateOf(sshConfig.password) }
|
||||||
|
var proxyListen by remember(sshConfig) { mutableStateOf(sshConfig.proxyListen) }
|
||||||
|
var proxyConnect by remember(sshConfig) { mutableStateOf(sshConfig.proxyConnect) }
|
||||||
|
|
||||||
|
var customCommand by remember { mutableStateOf("") }
|
||||||
|
val context = LocalContext.current
|
||||||
|
val clipboardManager = remember { context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager }
|
||||||
|
|
||||||
|
LaunchedEffect(ip, port, user, pass, proxyListen, proxyConnect) {
|
||||||
|
viewModel.saveSshConfig(
|
||||||
|
sshConfig.copy(
|
||||||
|
ip = ip,
|
||||||
|
port = port.toIntOrNull() ?: 22,
|
||||||
|
username = user,
|
||||||
|
password = pass,
|
||||||
|
proxyListen = proxyListen,
|
||||||
|
proxyConnect = proxyConnect
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val isConnected = sshState is SshConnectionState.Connected
|
||||||
|
val isConnecting = sshState is SshConnectionState.Connecting
|
||||||
|
val isInstalled = (serverState as? ServerState.Known)?.installed == true
|
||||||
|
val isRunning = (serverState as? ServerState.Known)?.running == true
|
||||||
|
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(16.dp)
|
||||||
|
.verticalScroll(rememberScrollState()),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||||
|
) {
|
||||||
|
Text("SSH Сервер", style = MaterialTheme.typography.titleLarge)
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = ip,
|
||||||
|
onValueChange = { ip = it },
|
||||||
|
label = { Text("IP сервера") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true,
|
||||||
|
enabled = !isConnected
|
||||||
|
)
|
||||||
|
|
||||||
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = port,
|
||||||
|
onValueChange = { port = it },
|
||||||
|
label = { Text("Порт") },
|
||||||
|
modifier = Modifier.weight(0.3f),
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||||
|
enabled = !isConnected
|
||||||
|
)
|
||||||
|
OutlinedTextField(
|
||||||
|
value = user,
|
||||||
|
onValueChange = { user = it },
|
||||||
|
label = { Text("Пользователь") },
|
||||||
|
modifier = Modifier.weight(0.7f),
|
||||||
|
singleLine = true,
|
||||||
|
enabled = !isConnected
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = pass,
|
||||||
|
onValueChange = { pass = it },
|
||||||
|
label = { Text("Пароль") },
|
||||||
|
visualTransformation = PasswordVisualTransformation(),
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true,
|
||||||
|
enabled = !isConnected
|
||||||
|
)
|
||||||
|
|
||||||
|
if (sshState is SshConnectionState.Error) {
|
||||||
|
Text(
|
||||||
|
text = (sshState as SshConnectionState.Error).message,
|
||||||
|
color = StatusRed,
|
||||||
|
style = MaterialTheme.typography.bodyMedium
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
if (isConnected) viewModel.disconnectSsh()
|
||||||
|
else viewModel.connectSsh()
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
enabled = !isConnecting,
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = if (isConnected) StatusRed else MaterialTheme.colorScheme.primary
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
if (isConnecting) "Проверка..."
|
||||||
|
else if (isConnected) "Отключиться"
|
||||||
|
else "Подключиться"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isConnected) {
|
||||||
|
HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||||
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("Управление сервером", style = MaterialTheme.typography.titleMedium)
|
||||||
|
|
||||||
|
val state = serverState // Capture delegated property for stable smart cast
|
||||||
|
if (state is ServerState.Checking) {
|
||||||
|
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||||
|
} else if (state is ServerState.Known) {
|
||||||
|
val statusText = when {
|
||||||
|
state.installed && state.running && state.isService -> "Запущен (systemd)"
|
||||||
|
state.installed && state.running -> "Запущен"
|
||||||
|
state.installed -> "Остановлен"
|
||||||
|
else -> "Не установлен"
|
||||||
|
}
|
||||||
|
Text(
|
||||||
|
text = statusText,
|
||||||
|
color = if (state.running) StatusGreen else if (state.installed) StatusYellow else StatusRed,
|
||||||
|
style = MaterialTheme.typography.labelSmall
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = proxyListen,
|
||||||
|
onValueChange = { proxyListen = it },
|
||||||
|
label = { Text("Слушать (Listen)") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = proxyConnect,
|
||||||
|
onValueChange = { proxyConnect = it },
|
||||||
|
label = { Text("Подключаться к (Connect)") },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
|
||||||
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Button(
|
||||||
|
onClick = { viewModel.installServer() },
|
||||||
|
modifier = Modifier.weight(1f)
|
||||||
|
) {
|
||||||
|
Text(if (isInstalled) "Обновить" else "Установить", maxLines = 1)
|
||||||
|
}
|
||||||
|
Button(
|
||||||
|
onClick = { viewModel.startServer() },
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
enabled = isInstalled && !isRunning,
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = StatusGreenDark)
|
||||||
|
) {
|
||||||
|
Text("Запуск", maxLines = 1)
|
||||||
|
}
|
||||||
|
Button(
|
||||||
|
onClick = { viewModel.stopServer() },
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
enabled = isInstalled && isRunning,
|
||||||
|
colors = ButtonDefaults.buttonColors(containerColor = StatusRed)
|
||||||
|
) {
|
||||||
|
Text("Стоп", maxLines = 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||||
|
Text("Отправить команду", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = customCommand,
|
||||||
|
onValueChange = { customCommand = it },
|
||||||
|
placeholder = { Text("cmd...") },
|
||||||
|
modifier = Modifier.weight(1f),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
Button(onClick = {
|
||||||
|
viewModel.sendSshCommand(customCommand)
|
||||||
|
customCommand = ""
|
||||||
|
}) {
|
||||||
|
Text("Отправить")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sshLog.isNotEmpty()) {
|
||||||
|
HorizontalDivider(Modifier.padding(vertical = 8.dp))
|
||||||
|
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
|
||||||
|
Text("Логи терминала", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Row {
|
||||||
|
TextButton(onClick = {
|
||||||
|
clipboardManager.setPrimaryClip(ClipData.newPlainText("logs", sshLog.joinToString("\n")))
|
||||||
|
}) {
|
||||||
|
Text("Copy", color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
TextButton(onClick = { viewModel.clearSshLogs() }) {
|
||||||
|
Text("Clear", color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Card(colors = CardDefaults.cardColors(containerColor = DarkSurface), modifier = Modifier.fillMaxWidth().height(200.dp)) {
|
||||||
|
val scrollState = rememberScrollState()
|
||||||
|
LaunchedEffect(sshLog.size) {
|
||||||
|
if (sshLog.isNotEmpty()) {
|
||||||
|
scrollState.animateScrollTo(scrollState.maxValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SelectionContainer(modifier = Modifier.fillMaxSize()) {
|
||||||
|
Column(modifier = Modifier.padding(8.dp).verticalScroll(scrollState)) {
|
||||||
|
sshLog.forEach { log ->
|
||||||
|
Text(log, style = MaterialTheme.typography.bodySmall, color = TextSecondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package com.vkturn.proxy.ui.components
|
||||||
|
|
||||||
|
import androidx.compose.animation.*
|
||||||
|
import androidx.compose.foundation.clickable
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||||
|
import androidx.compose.material.icons.filled.KeyboardArrowUp
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import com.vkturn.proxy.ui.theme.StatusRed
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun CurrentProfileHeader(profileName: String) {
|
||||||
|
Column(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text("Текущий профиль:", style = MaterialTheme.typography.titleMedium)
|
||||||
|
Text(profileName, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary)
|
||||||
|
}
|
||||||
|
HorizontalDivider(modifier = Modifier.padding(top = 12.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun ExpandableSection(
|
||||||
|
title: String,
|
||||||
|
isExpanded: Boolean,
|
||||||
|
onExpandChange: (Boolean) -> Unit,
|
||||||
|
titleColor: Color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
|
content: @Composable ColumnScope.() -> Unit
|
||||||
|
) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
colors = CardDefaults.cardColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Column(modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.clickable { onExpandChange(!isExpanded) }
|
||||||
|
.padding(16.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween,
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = title,
|
||||||
|
style = MaterialTheme.typography.titleMedium.copy(
|
||||||
|
fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
|
||||||
|
),
|
||||||
|
color = titleColor
|
||||||
|
)
|
||||||
|
Icon(
|
||||||
|
imageVector = if (isExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
|
||||||
|
contentDescription = null,
|
||||||
|
tint = titleColor
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
AnimatedVisibility(
|
||||||
|
visible = isExpanded,
|
||||||
|
enter = expandVertically() + fadeIn(),
|
||||||
|
exit = shrinkVertically() + fadeOut()
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),
|
||||||
|
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||||
|
) {
|
||||||
|
content()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package com.vkturn.proxy.ui.components
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.content.ClipData
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.net.Uri
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.compose.foundation.Image
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.gestures.detectTapGestures
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.asImageBitmap
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.text.style.TextAlign
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.window.Dialog
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
|
import com.vkturn.proxy.utils.QrUtils
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun QrExportDialog(
|
||||||
|
profileName: String,
|
||||||
|
profileData: String,
|
||||||
|
onDismiss: () -> Unit
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
var qrBitmap by remember { mutableStateOf<Bitmap?>(null) }
|
||||||
|
|
||||||
|
// Brightness control
|
||||||
|
DisposableEffect(Unit) {
|
||||||
|
val activity = context as? Activity
|
||||||
|
val window = activity?.window
|
||||||
|
val layoutParams = window?.attributes
|
||||||
|
val originalBrightness = layoutParams?.screenBrightness
|
||||||
|
|
||||||
|
layoutParams?.screenBrightness = 1.0f // Max brightness
|
||||||
|
window?.attributes = layoutParams
|
||||||
|
|
||||||
|
onDispose {
|
||||||
|
layoutParams?.screenBrightness = originalBrightness ?: -1.0f
|
||||||
|
window?.attributes = layoutParams
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LaunchedEffect(profileData) {
|
||||||
|
withContext(Dispatchers.Default) {
|
||||||
|
qrBitmap = QrUtils.generateQrCode(profileData, context = context)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Dialog(onDismissRequest = onDismiss) {
|
||||||
|
Card(
|
||||||
|
modifier = Modifier.padding(16.dp),
|
||||||
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
|
||||||
|
) {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.padding(24.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
text = "Экспорт профиля",
|
||||||
|
style = MaterialTheme.typography.titleLarge,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = MaterialTheme.colorScheme.onSurface
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
text = profileName,
|
||||||
|
style = MaterialTheme.typography.bodyMedium,
|
||||||
|
color = MaterialTheme.colorScheme.primary,
|
||||||
|
modifier = Modifier.padding(bottom = 16.dp)
|
||||||
|
)
|
||||||
|
|
||||||
|
if (qrBitmap != null) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(250.dp)
|
||||||
|
.background(Color.White)
|
||||||
|
.pointerInput(Unit) {
|
||||||
|
detectTapGestures(
|
||||||
|
onTap = {
|
||||||
|
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
clipboard.setPrimaryClip(ClipData.newPlainText("vk_proxy_profile", profileData))
|
||||||
|
Toast.makeText(context, "Скопировано в буфер обмена", Toast.LENGTH_SHORT).show()
|
||||||
|
},
|
||||||
|
onLongPress = {
|
||||||
|
shareBitmap(context, qrBitmap!!, profileName)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
},
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Image(
|
||||||
|
bitmap = qrBitmap!!.asImageBitmap(),
|
||||||
|
contentDescription = "QR-код",
|
||||||
|
modifier = Modifier.fillMaxSize()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
Text(
|
||||||
|
text = "Нажмите, чтобы скопировать\nУдерживайте, чтобы поделиться",
|
||||||
|
style = MaterialTheme.typography.labelSmall,
|
||||||
|
textAlign = TextAlign.Center,
|
||||||
|
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
CircularProgressIndicator(modifier = Modifier.padding(32.dp))
|
||||||
|
}
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(24.dp))
|
||||||
|
Button(onClick = onDismiss, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Text("Закрыть")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun shareBitmap(context: Context, bitmap: Bitmap, profileName: String) {
|
||||||
|
try {
|
||||||
|
val cachePath = File(context.cacheDir, "images")
|
||||||
|
cachePath.mkdirs()
|
||||||
|
val file = File(cachePath, "profile_qr.png")
|
||||||
|
val stream = FileOutputStream(file)
|
||||||
|
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
|
||||||
|
stream.close()
|
||||||
|
|
||||||
|
val uri: Uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
|
||||||
|
|
||||||
|
val intent = Intent(Intent.ACTION_SEND).apply {
|
||||||
|
type = "image/png"
|
||||||
|
putExtra(Intent.EXTRA_STREAM, uri)
|
||||||
|
putExtra(Intent.EXTRA_TEXT, "Профиль VK Proxy: $profileName")
|
||||||
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
}
|
||||||
|
context.startActivity(Intent.createChooser(intent, "Поделиться профилем"))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
Toast.makeText(context, "Ошибка подготовки изображения", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
package com.vkturn.proxy.ui.components
|
||||||
|
|
||||||
|
import android.Manifest
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import android.net.Uri
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||||
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
|
import androidx.camera.core.CameraSelector
|
||||||
|
import androidx.camera.core.ImageAnalysis
|
||||||
|
import androidx.camera.core.ImageProxy
|
||||||
|
import androidx.camera.core.resolutionselector.ResolutionSelector
|
||||||
|
import androidx.camera.core.resolutionselector.ResolutionStrategy
|
||||||
|
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||||
|
import androidx.camera.view.PreviewView
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Close
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
|
import androidx.core.content.ContextCompat
|
||||||
|
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
|
||||||
|
import com.google.mlkit.vision.barcode.BarcodeScanning
|
||||||
|
import com.google.mlkit.vision.barcode.common.Barcode
|
||||||
|
import com.google.mlkit.vision.common.InputImage
|
||||||
|
import com.vkturn.proxy.utils.QrUtils
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun QrScannerScreen(
|
||||||
|
onScanResult: (String) -> Unit,
|
||||||
|
onCancel: () -> Unit,
|
||||||
|
onClipboardImportClick: () -> Unit
|
||||||
|
) {
|
||||||
|
val context = LocalContext.current
|
||||||
|
val lifecycleOwner = LocalLifecycleOwner.current
|
||||||
|
val coroutineScope = rememberCoroutineScope()
|
||||||
|
|
||||||
|
var hasCameraPermission by remember {
|
||||||
|
mutableStateOf(
|
||||||
|
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val permissionLauncher = rememberLauncherForActivityResult(
|
||||||
|
contract = ActivityResultContracts.RequestPermission(),
|
||||||
|
onResult = { granted -> hasCameraPermission = granted }
|
||||||
|
)
|
||||||
|
|
||||||
|
LaunchedEffect(Unit) {
|
||||||
|
if (!hasCameraPermission) {
|
||||||
|
permissionLauncher.launch(Manifest.permission.CAMERA)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val galleryLauncher = rememberLauncherForActivityResult(
|
||||||
|
contract = ActivityResultContracts.GetContent()
|
||||||
|
) { uri: Uri? ->
|
||||||
|
uri?.let {
|
||||||
|
coroutineScope.launch {
|
||||||
|
try {
|
||||||
|
val inputStream = context.contentResolver.openInputStream(it)
|
||||||
|
val bitmap = BitmapFactory.decodeStream(inputStream)
|
||||||
|
inputStream?.close()
|
||||||
|
if (bitmap != null) {
|
||||||
|
val result = QrUtils.scanQrFromBitmap(bitmap)
|
||||||
|
if (result != null) {
|
||||||
|
onScanResult(result)
|
||||||
|
} else {
|
||||||
|
Toast.makeText(context, "QR-код не найден на изображении", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
Toast.makeText(context, "Ошибка при обработке изображения", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Box(modifier = Modifier.fillMaxSize().background(Color.Black)) {
|
||||||
|
if (hasCameraPermission) {
|
||||||
|
AndroidView(
|
||||||
|
factory = { ctx ->
|
||||||
|
val previewView = PreviewView(ctx)
|
||||||
|
val cameraProviderFuture = ProcessCameraProvider.getInstance(ctx)
|
||||||
|
|
||||||
|
cameraProviderFuture.addListener({
|
||||||
|
val cameraProvider = cameraProviderFuture.get()
|
||||||
|
|
||||||
|
val preview = androidx.camera.core.Preview.Builder().build().also {
|
||||||
|
it.setSurfaceProvider(previewView.surfaceProvider)
|
||||||
|
}
|
||||||
|
|
||||||
|
val resolutionSelector = ResolutionSelector.Builder()
|
||||||
|
.setResolutionStrategy(
|
||||||
|
ResolutionStrategy(
|
||||||
|
android.util.Size(1280, 720),
|
||||||
|
ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val imageAnalysis = ImageAnalysis.Builder()
|
||||||
|
.setResolutionSelector(resolutionSelector)
|
||||||
|
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val scannerOptions = BarcodeScannerOptions.Builder()
|
||||||
|
.setBarcodeFormats(Barcode.FORMAT_QR_CODE)
|
||||||
|
.build()
|
||||||
|
val scanner = BarcodeScanning.getClient(scannerOptions)
|
||||||
|
|
||||||
|
var isScanned = false
|
||||||
|
|
||||||
|
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(ctx)) { imageProxy: ImageProxy ->
|
||||||
|
@androidx.annotation.OptIn(androidx.camera.core.ExperimentalGetImage::class)
|
||||||
|
val mediaImage = imageProxy.image
|
||||||
|
if (mediaImage != null && !isScanned) {
|
||||||
|
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
|
||||||
|
scanner.process(image)
|
||||||
|
.addOnSuccessListener { barcodes ->
|
||||||
|
if (barcodes.isNotEmpty() && !isScanned) {
|
||||||
|
val value = barcodes.first().rawValue
|
||||||
|
if (value != null) {
|
||||||
|
isScanned = true
|
||||||
|
onScanResult(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.addOnCompleteListener {
|
||||||
|
imageProxy.close()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
imageProxy.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
|
||||||
|
|
||||||
|
try {
|
||||||
|
cameraProvider.unbindAll()
|
||||||
|
cameraProvider.bindToLifecycle(
|
||||||
|
lifecycleOwner,
|
||||||
|
cameraSelector,
|
||||||
|
preview,
|
||||||
|
imageAnalysis
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}, ContextCompat.getMainExecutor(ctx))
|
||||||
|
|
||||||
|
previewView
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxSize()
|
||||||
|
)
|
||||||
|
|
||||||
|
// Scanner guide overlay (simple focus area)
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(32.dp),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.size(250.dp)
|
||||||
|
.background(Color.Transparent)
|
||||||
|
) {
|
||||||
|
androidx.compose.foundation.Canvas(modifier = Modifier.fillMaxSize()) {
|
||||||
|
val canvasWidth = size.width
|
||||||
|
val canvasHeight = size.height
|
||||||
|
val strokeWidth = 8.dp.toPx()
|
||||||
|
val length = 40.dp.toPx()
|
||||||
|
val color = Color.White
|
||||||
|
|
||||||
|
// Top left
|
||||||
|
drawLine(color, androidx.compose.ui.geometry.Offset(0f, 0f), androidx.compose.ui.geometry.Offset(length, 0f), strokeWidth)
|
||||||
|
drawLine(color, androidx.compose.ui.geometry.Offset(0f, 0f), androidx.compose.ui.geometry.Offset(0f, length), strokeWidth)
|
||||||
|
// Top right
|
||||||
|
drawLine(color, androidx.compose.ui.geometry.Offset(canvasWidth, 0f), androidx.compose.ui.geometry.Offset(canvasWidth - length, 0f), strokeWidth)
|
||||||
|
drawLine(color, androidx.compose.ui.geometry.Offset(canvasWidth, 0f), androidx.compose.ui.geometry.Offset(canvasWidth, length), strokeWidth)
|
||||||
|
// Bottom left
|
||||||
|
drawLine(color, androidx.compose.ui.geometry.Offset(0f, canvasHeight), androidx.compose.ui.geometry.Offset(length, canvasHeight), strokeWidth)
|
||||||
|
drawLine(color, androidx.compose.ui.geometry.Offset(0f, canvasHeight), androidx.compose.ui.geometry.Offset(0f, canvasHeight - length), strokeWidth)
|
||||||
|
// Bottom right
|
||||||
|
drawLine(color, androidx.compose.ui.geometry.Offset(canvasWidth, canvasHeight), androidx.compose.ui.geometry.Offset(canvasWidth - length, canvasHeight), strokeWidth)
|
||||||
|
drawLine(color, androidx.compose.ui.geometry.Offset(canvasWidth, canvasHeight), androidx.compose.ui.geometry.Offset(canvasWidth, canvasHeight - length), strokeWidth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Column(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
verticalArrangement = Arrangement.Center,
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally
|
||||||
|
) {
|
||||||
|
Text(
|
||||||
|
"Нет доступа к камере",
|
||||||
|
color = Color.White,
|
||||||
|
style = MaterialTheme.typography.titleLarge
|
||||||
|
)
|
||||||
|
Button(
|
||||||
|
onClick = { permissionLauncher.launch(Manifest.permission.CAMERA) },
|
||||||
|
modifier = Modifier.padding(top = 16.dp)
|
||||||
|
) {
|
||||||
|
Text("Запросить разрешение")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Top bar
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.padding(16.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceBetween
|
||||||
|
) {
|
||||||
|
IconButton(
|
||||||
|
onClick = onCancel,
|
||||||
|
colors = IconButtonDefaults.iconButtonColors(contentColor = Color.White)
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.Close, contentDescription = "Закрыть сканер")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bottom toolbar
|
||||||
|
Row(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.align(Alignment.BottomCenter)
|
||||||
|
.padding(bottom = 32.dp, start = 16.dp, end = 16.dp),
|
||||||
|
horizontalArrangement = Arrangement.SpaceEvenly
|
||||||
|
) {
|
||||||
|
Button(
|
||||||
|
onClick = { galleryLauncher.launch("image/*") },
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.surface,
|
||||||
|
contentColor = MaterialTheme.colorScheme.primary
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Text("Галерея")
|
||||||
|
}
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = onClipboardImportClick,
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = MaterialTheme.colorScheme.primary,
|
||||||
|
contentColor = MaterialTheme.colorScheme.onPrimary
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Text("Из буфера")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.vkturn.proxy.ui.theme
|
||||||
|
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
|
||||||
|
val DarkBackground = Color(0xFF101216)
|
||||||
|
val DarkSurface = Color(0xFF1C1E26)
|
||||||
|
val PrimaryAccent = Color(0xFF7C4DFF)
|
||||||
|
val PrimaryAccentDark = Color(0xFF512DA8)
|
||||||
|
val SecondaryAccent = Color(0xFF00E5FF)
|
||||||
|
val TextPrimary = Color(0xFFFFFFFF)
|
||||||
|
val TextSecondary = Color(0xFF8B949E)
|
||||||
|
|
||||||
|
val StatusGreen = Color(0xFF00E676)
|
||||||
|
val StatusGreenDark = Color(0xFF00C853)
|
||||||
|
val StatusRed = Color(0xFFFF1744)
|
||||||
|
val StatusYellow = Color(0xFFFFD600)
|
||||||
|
val StatusBlue = Color(0xFF2979FF)
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package com.vkturn.proxy.ui.theme
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.os.Build
|
||||||
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.darkColorScheme
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.SideEffect
|
||||||
|
import androidx.compose.ui.graphics.toArgb
|
||||||
|
import androidx.compose.ui.platform.LocalView
|
||||||
|
import androidx.core.view.WindowCompat
|
||||||
|
|
||||||
|
private val DarkColorScheme = darkColorScheme(
|
||||||
|
primary = PrimaryAccent,
|
||||||
|
secondary = SecondaryAccent,
|
||||||
|
background = DarkBackground,
|
||||||
|
surface = DarkSurface,
|
||||||
|
onPrimary = TextPrimary,
|
||||||
|
onSecondary = TextPrimary,
|
||||||
|
onBackground = TextPrimary,
|
||||||
|
onSurface = TextPrimary,
|
||||||
|
error = StatusRed,
|
||||||
|
errorContainer = StatusRed.copy(alpha = 0.2f),
|
||||||
|
onErrorContainer = StatusRed,
|
||||||
|
surfaceVariant = DarkSurface.copy(alpha = 0.8f),
|
||||||
|
onSurfaceVariant = TextSecondary
|
||||||
|
)
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun VkTurnProxyTheme(
|
||||||
|
content: @Composable () -> Unit
|
||||||
|
) {
|
||||||
|
val colorScheme = DarkColorScheme
|
||||||
|
|
||||||
|
// В Android 15+ статус-бар и навигация настраиваются автоматически через enableEdgeToEdge() в MainActivity.
|
||||||
|
// Здесь мы просто оставляем MaterialTheme для стилизации компонентов.
|
||||||
|
|
||||||
|
MaterialTheme(
|
||||||
|
colorScheme = colorScheme,
|
||||||
|
typography = Typography,
|
||||||
|
content = content
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package com.vkturn.proxy.ui.theme
|
||||||
|
|
||||||
|
import androidx.compose.material3.Typography
|
||||||
|
import androidx.compose.ui.text.TextStyle
|
||||||
|
import androidx.compose.ui.text.font.FontFamily
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
|
||||||
|
val Typography = Typography(
|
||||||
|
bodyLarge = TextStyle(
|
||||||
|
fontFamily = FontFamily.Default,
|
||||||
|
fontWeight = FontWeight.Normal,
|
||||||
|
fontSize = 16.sp,
|
||||||
|
lineHeight = 24.sp,
|
||||||
|
letterSpacing = 0.5.sp
|
||||||
|
),
|
||||||
|
titleLarge = TextStyle(
|
||||||
|
fontFamily = FontFamily.Default,
|
||||||
|
fontWeight = FontWeight.SemiBold,
|
||||||
|
fontSize = 22.sp,
|
||||||
|
lineHeight = 28.sp,
|
||||||
|
letterSpacing = 0.sp
|
||||||
|
),
|
||||||
|
labelSmall = TextStyle(
|
||||||
|
fontFamily = FontFamily.Default,
|
||||||
|
fontWeight = FontWeight.Medium,
|
||||||
|
fontSize = 11.sp,
|
||||||
|
lineHeight = 16.sp,
|
||||||
|
letterSpacing = 0.5.sp
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package com.vkturn.proxy.utils
|
||||||
|
|
||||||
|
import java.net.DatagramPacket
|
||||||
|
import java.net.DatagramSocket
|
||||||
|
import java.net.InetAddress
|
||||||
|
|
||||||
|
object DnsResolver {
|
||||||
|
private const val DNS_SERVER = "77.88.8.8"
|
||||||
|
private const val DNS_PORT = 53
|
||||||
|
private const val TIMEOUT = 2000
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Преобразует хост в IP-адрес.
|
||||||
|
* Сначала пробует системный резолвер, затем напрямую Яндекс.DNS по UDP.
|
||||||
|
*/
|
||||||
|
fun resolve(host: String): String {
|
||||||
|
if (host.matches(Regex("^[0-9.]+$"))) return host
|
||||||
|
|
||||||
|
return try {
|
||||||
|
// 1. Пробуем системный резолвер
|
||||||
|
InetAddress.getByName(host).hostAddress
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// 2. Если система подвела, идем к Яндексу напрямую
|
||||||
|
try {
|
||||||
|
val ip = resolveViaUdp(host)
|
||||||
|
if (ip == null) {
|
||||||
|
// Мы не логируем тут, чтобы не спамить, если резолвер просто не нашел запись
|
||||||
|
}
|
||||||
|
ip ?: host
|
||||||
|
} catch (ex: Exception) {
|
||||||
|
// Если даже UDP запрос упал (например, сеть совсем мертвая)
|
||||||
|
host
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resolveViaUdp(host: String): String? {
|
||||||
|
var socket: DatagramSocket? = null
|
||||||
|
return try {
|
||||||
|
socket = DatagramSocket()
|
||||||
|
socket.soTimeout = TIMEOUT
|
||||||
|
|
||||||
|
val serverAddress = InetAddress.getByName(DNS_SERVER)
|
||||||
|
val transactionId = (0..65535).random()
|
||||||
|
val query = buildQuery(host, transactionId)
|
||||||
|
val request = DatagramPacket(query, query.size, serverAddress, DNS_PORT)
|
||||||
|
|
||||||
|
socket.send(request)
|
||||||
|
|
||||||
|
val buffer = ByteArray(512)
|
||||||
|
val response = DatagramPacket(buffer, buffer.size)
|
||||||
|
socket.receive(response)
|
||||||
|
|
||||||
|
parseResponse(buffer, response.length, transactionId)
|
||||||
|
} finally {
|
||||||
|
socket?.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildQuery(host: String, transactionId: Int): ByteArray {
|
||||||
|
val out = mutableListOf<Byte>()
|
||||||
|
// Transaction ID
|
||||||
|
out.add((transactionId shr 8).toByte())
|
||||||
|
out.add((transactionId and 0xFF).toByte())
|
||||||
|
// Flags (Standard query, Recursion desired)
|
||||||
|
out.add(0x01.toByte()); out.add(0x00.toByte())
|
||||||
|
// Questions count: 1
|
||||||
|
out.add(0x00.toByte()); out.add(0x01.toByte())
|
||||||
|
// Answer, Authority, Additional RRs (all 0)
|
||||||
|
out.add(0x00.toByte()); out.add(0x00.toByte())
|
||||||
|
out.add(0x00.toByte()); out.add(0x00.toByte())
|
||||||
|
out.add(0x00.toByte()); out.add(0x00.toByte())
|
||||||
|
|
||||||
|
// Labels
|
||||||
|
host.split(".").filter { it.isNotEmpty() }.forEach { label ->
|
||||||
|
out.add(label.length.toByte())
|
||||||
|
label.forEach { out.add(it.code.toByte()) }
|
||||||
|
}
|
||||||
|
out.add(0x00.toByte())
|
||||||
|
|
||||||
|
// Type A (1), Class IN (1)
|
||||||
|
out.add(0x00.toByte()); out.add(0x01.toByte())
|
||||||
|
out.add(0x00.toByte()); out.add(0x01.toByte())
|
||||||
|
|
||||||
|
return out.toByteArray()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseResponse(data: ByteArray, length: Int, expectedId: Int): String? {
|
||||||
|
if (length < 12) return null
|
||||||
|
|
||||||
|
// Проверяем Transaction ID
|
||||||
|
val id = ((data[0].toInt() and 0xFF) shl 8) or (data[1].toInt() and 0xFF)
|
||||||
|
if (id != expectedId) return null
|
||||||
|
|
||||||
|
val questions = ((data[4].toInt() and 0xFF) shl 8) or (data[5].toInt() and 0xFF)
|
||||||
|
val answers = ((data[6].toInt() and 0xFF) shl 8) or (data[7].toInt() and 0xFF)
|
||||||
|
|
||||||
|
if (answers == 0) return null
|
||||||
|
|
||||||
|
var pos = 12
|
||||||
|
// Пропускаем вопросы
|
||||||
|
for (i in 0 until questions) {
|
||||||
|
pos = skipName(data, pos)
|
||||||
|
pos += 4 // Type + Class
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ищем первую живую A-запись
|
||||||
|
for (i in 0 until answers) {
|
||||||
|
pos = skipName(data, pos)
|
||||||
|
val type = ((data[pos].toInt() and 0xFF) shl 8) or (data[pos+1].toInt() and 0xFF)
|
||||||
|
val rdLength = ((data[pos+8].toInt() and 0xFF) shl 8) or (data[pos+9].toInt() and 0xFF)
|
||||||
|
pos += 10
|
||||||
|
|
||||||
|
if (type == 1 && rdLength == 4 && pos + 4 <= length) {
|
||||||
|
return "${data[pos].toInt() and 0xFF}.${data[pos+1].toInt() and 0xFF}.${data[pos+2].toInt() and 0xFF}.${data[pos+3].toInt() and 0xFF}"
|
||||||
|
}
|
||||||
|
pos += rdLength
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun skipName(data: ByteArray, startPos: Int): Int {
|
||||||
|
var pos = startPos
|
||||||
|
while (pos < data.size) {
|
||||||
|
val v = data[pos].toInt() and 0xFF
|
||||||
|
if (v == 0) return pos + 1
|
||||||
|
if ((v and 0xC0) == 0xC0) return pos + 2 // Сжатие (Pointer)
|
||||||
|
pos += v + 1
|
||||||
|
}
|
||||||
|
return pos
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package com.vkturn.proxy.utils
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.Canvas
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.Paint
|
||||||
|
import android.graphics.drawable.Drawable
|
||||||
|
import androidx.core.graphics.drawable.toBitmap
|
||||||
|
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
|
||||||
|
import com.google.mlkit.vision.barcode.BarcodeScanning
|
||||||
|
import com.google.mlkit.vision.barcode.common.Barcode
|
||||||
|
import com.google.mlkit.vision.common.InputImage
|
||||||
|
import com.google.zxing.BarcodeFormat
|
||||||
|
import com.google.zxing.EncodeHintType
|
||||||
|
import com.google.zxing.qrcode.QRCodeWriter
|
||||||
|
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
|
||||||
|
object QrUtils {
|
||||||
|
|
||||||
|
fun generateQrCode(text: String, size: Int = 512, context: Context? = null): Bitmap? {
|
||||||
|
val levels = listOf(ErrorCorrectionLevel.H, ErrorCorrectionLevel.M, ErrorCorrectionLevel.L)
|
||||||
|
|
||||||
|
for (level in levels) {
|
||||||
|
try {
|
||||||
|
val hints = mapOf(
|
||||||
|
EncodeHintType.MARGIN to 0,
|
||||||
|
EncodeHintType.ERROR_CORRECTION to level
|
||||||
|
)
|
||||||
|
// Encode at size 0 to get the pure, minimal QR matrix
|
||||||
|
val bitMatrix = QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, 0, 0, hints)
|
||||||
|
|
||||||
|
val matrixWidth = bitMatrix.width
|
||||||
|
val matrixHeight = bitMatrix.height
|
||||||
|
val scale = (size / matrixWidth).coerceAtLeast(1)
|
||||||
|
val qrWidth = matrixWidth * scale
|
||||||
|
val qrHeight = matrixHeight * scale
|
||||||
|
|
||||||
|
// Add a uniform white padding (2 cells thick) around the QR code
|
||||||
|
val qrPadding = scale * 2
|
||||||
|
val finalWidth = qrWidth + qrPadding * 2
|
||||||
|
val finalHeight = qrHeight + qrPadding * 2
|
||||||
|
|
||||||
|
val bitmap = Bitmap.createBitmap(finalWidth, finalHeight, Bitmap.Config.ARGB_8888)
|
||||||
|
val canvas = Canvas(bitmap)
|
||||||
|
canvas.drawColor(Color.WHITE)
|
||||||
|
|
||||||
|
for (x in 0 until qrWidth) {
|
||||||
|
for (y in 0 until qrHeight) {
|
||||||
|
if (bitMatrix.get(x / scale, y / scale)) {
|
||||||
|
bitmap.setPixel(x + qrPadding, y + qrPadding, Color.BLACK)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only embed the icon if we have high enough error correction redundancy
|
||||||
|
if (context != null && level == ErrorCorrectionLevel.H) {
|
||||||
|
try {
|
||||||
|
val appIcon: Drawable = context.packageManager.getApplicationIcon(context.applicationInfo)
|
||||||
|
|
||||||
|
val iconSize = (finalWidth * 0.25f).toInt() // 25% of the entire QR size
|
||||||
|
val left = (finalWidth - iconSize) / 2
|
||||||
|
val top = (finalHeight - iconSize) / 2
|
||||||
|
|
||||||
|
val iconBitmap = appIcon.toBitmap(iconSize, iconSize)
|
||||||
|
canvas.drawBitmap(iconBitmap, left.toFloat(), top.toFloat(), null)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return bitmap
|
||||||
|
} catch (e: com.google.zxing.WriterException) {
|
||||||
|
if (level == levels.last()) {
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun scanQrFromBitmap(bitmap: Bitmap): String? = suspendCancellableCoroutine { continuation ->
|
||||||
|
try {
|
||||||
|
val image = InputImage.fromBitmap(bitmap, 0)
|
||||||
|
val options = BarcodeScannerOptions.Builder()
|
||||||
|
.setBarcodeFormats(Barcode.FORMAT_QR_CODE)
|
||||||
|
.build()
|
||||||
|
val scanner = BarcodeScanning.getClient(options)
|
||||||
|
|
||||||
|
scanner.process(image)
|
||||||
|
.addOnSuccessListener { barcodes ->
|
||||||
|
if (barcodes.isNotEmpty() && !continuation.isCompleted) {
|
||||||
|
continuation.resume(barcodes[0].rawValue)
|
||||||
|
} else if (!continuation.isCompleted) {
|
||||||
|
continuation.resume(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.addOnFailureListener { e ->
|
||||||
|
e.printStackTrace()
|
||||||
|
if (!continuation.isCompleted) {
|
||||||
|
continuation.resume(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
e.printStackTrace()
|
||||||
|
if (!continuation.isCompleted) {
|
||||||
|
continuation.resume(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,595 @@
|
|||||||
|
package com.vkturn.proxy.viewmodel
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import android.content.Intent
|
||||||
|
import androidx.lifecycle.AndroidViewModel
|
||||||
|
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.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
|
||||||
|
import kotlinx.coroutines.flow.collectLatest
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import com.google.gson.Gson
|
||||||
|
import com.google.gson.reflect.TypeToken
|
||||||
|
import android.content.ClipboardManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.widget.Toast
|
||||||
|
import android.util.Base64
|
||||||
|
import java.util.UUID
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import android.net.Uri
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
import android.os.Build
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
|
sealed class ServerState {
|
||||||
|
object Unknown : ServerState()
|
||||||
|
object Checking : ServerState()
|
||||||
|
data class Known(val installed: Boolean, val running: Boolean, val isService: Boolean = false) : ServerState()
|
||||||
|
data class Error(val message: String) : ServerState()
|
||||||
|
}
|
||||||
|
|
||||||
|
class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||||
|
|
||||||
|
private val prefs = AppPreferences(application)
|
||||||
|
private val sshManager = SSHManager()
|
||||||
|
|
||||||
|
val clientConfig: StateFlow<ClientConfig> = prefs.clientConfigFlow
|
||||||
|
val sshConfig: StateFlow<SshConfig> = prefs.sshConfigFlow
|
||||||
|
|
||||||
|
private val _proxyState = MutableStateFlow<ProxyState>(ProxyState.Idle)
|
||||||
|
val proxyState: StateFlow<ProxyState> = _proxyState.asStateFlow()
|
||||||
|
|
||||||
|
private val _sshState = MutableStateFlow<SshConnectionState>(SshConnectionState.Disconnected)
|
||||||
|
val sshState: StateFlow<SshConnectionState> = _sshState.asStateFlow()
|
||||||
|
|
||||||
|
private val _serverState = MutableStateFlow<ServerState>(ServerState.Unknown)
|
||||||
|
val serverState: StateFlow<ServerState> = _serverState.asStateFlow()
|
||||||
|
|
||||||
|
private val _sshLog = MutableStateFlow<List<String>>(emptyList())
|
||||||
|
val sshLog: StateFlow<List<String>> = _sshLog.asStateFlow()
|
||||||
|
|
||||||
|
private val _proxyLogs = MutableStateFlow<List<String>>(ProxyService.logBuffer.toList())
|
||||||
|
val proxyLogs: StateFlow<List<String>> = _proxyLogs.asStateFlow()
|
||||||
|
|
||||||
|
private val _isKernelPresent = MutableStateFlow<Boolean>(File(application.filesDir, "libcustom_kernel.so").exists())
|
||||||
|
val isKernelPresent: StateFlow<Boolean> = _isKernelPresent.asStateFlow()
|
||||||
|
|
||||||
|
// --- Profiles State --- //
|
||||||
|
val profiles: StateFlow<List<ProxyProfile>> = prefs.profilesFlow
|
||||||
|
val selectedProfileId: StateFlow<String> = prefs.selectedProfileIdFlow
|
||||||
|
private val gson = Gson()
|
||||||
|
|
||||||
|
init {
|
||||||
|
ProxyService.onLogReceived = { msg ->
|
||||||
|
_proxyLogs.value = ProxyService.logBuffer.toList()
|
||||||
|
checkForCaptcha(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
profiles.collectLatest { list ->
|
||||||
|
if (list.isNotEmpty() && selectedProfileId.value.isEmpty()) {
|
||||||
|
selectProfile(list[0].id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
viewModelScope.launch {
|
||||||
|
while (true) {
|
||||||
|
if (_proxyState.value !is ProxyState.CaptchaRequired) {
|
||||||
|
val isServiceRunning = ProxyService.isRunning
|
||||||
|
val currentIsRunning = _proxyState.value is ProxyState.Running
|
||||||
|
if (isServiceRunning && !currentIsRunning) {
|
||||||
|
_proxyState.value = ProxyState.Running
|
||||||
|
} else if (!isServiceRunning && currentIsRunning) {
|
||||||
|
_proxyState.value = ProxyState.Idle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delay(1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun checkForCaptcha(log: String) {
|
||||||
|
val urlPattern = "(https?://(localhost:\\d+|login\\.vk\\.com)\\S*)".toRegex()
|
||||||
|
val match = urlPattern.find(log)
|
||||||
|
if (match != null) {
|
||||||
|
_proxyState.value = ProxyState.CaptchaRequired(match.value)
|
||||||
|
ProxyService.updateNotification("Требуется авторизация", "Нажмите сюда, чтобы пройти капчу!")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return to Running if successfully solved
|
||||||
|
if (log.contains("Captcha Solved") || log.contains("Manual captcha solved")) {
|
||||||
|
if (_proxyState.value is ProxyState.CaptchaRequired) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
delay(3000)
|
||||||
|
_proxyState.value = ProxyState.Running
|
||||||
|
ProxyService.updateNotification("TURN Proxy", "Работает в фоне")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveClientConfig(config: ClientConfig) {
|
||||||
|
prefs.saveClientConfig(config)
|
||||||
|
// Обновляем конфиг в текущем выбранном профиле
|
||||||
|
val currentProfiles = profiles.value.toMutableList()
|
||||||
|
val index = currentProfiles.indexOfFirst { it.id == selectedProfileId.value }
|
||||||
|
if (index != -1) {
|
||||||
|
currentProfiles[index] = currentProfiles[index].copy(config = config)
|
||||||
|
prefs.saveProfiles(currentProfiles)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun saveSshConfig(config: SshConfig) {
|
||||||
|
prefs.saveSshConfig(config)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Profiles Operations --- //
|
||||||
|
|
||||||
|
fun selectProfile(id: String) {
|
||||||
|
val profile = profiles.value.find { it.id == id }
|
||||||
|
if (profile != null) {
|
||||||
|
prefs.saveSelectedProfileId(id)
|
||||||
|
prefs.saveClientConfig(profile.config)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addProfile(name: String, config: ClientConfig = clientConfig.value) {
|
||||||
|
val newProfile = ProxyProfile(name = name, config = config)
|
||||||
|
val newProfiles = profiles.value + newProfile
|
||||||
|
prefs.saveProfiles(newProfiles)
|
||||||
|
selectProfile(newProfile.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteProfile(id: String) {
|
||||||
|
if (profiles.value.size <= 1) return // Нельзя удалить последний
|
||||||
|
val newProfiles = profiles.value.filter { it.id != id }
|
||||||
|
prefs.saveProfiles(newProfiles)
|
||||||
|
if (selectedProfileId.value == id) {
|
||||||
|
selectProfile(newProfiles.first().id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun resetProfile(id: String) {
|
||||||
|
val currentProfiles = profiles.value.toMutableList()
|
||||||
|
val index = currentProfiles.indexOfFirst { it.id == id }
|
||||||
|
if (index != -1) {
|
||||||
|
val defaultConfig = prefs.createDefaultConfig()
|
||||||
|
currentProfiles[index] = currentProfiles[index].copy(config = defaultConfig)
|
||||||
|
prefs.saveProfiles(currentProfiles)
|
||||||
|
if (id == selectedProfileId.value) {
|
||||||
|
prefs.saveClientConfig(defaultConfig)
|
||||||
|
}
|
||||||
|
Toast.makeText(getApplication(), "Настройки профиля '${currentProfiles[index].name}' сброшены", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun renameProfile(id: String, newName: String) {
|
||||||
|
val newProfiles = profiles.value.map {
|
||||||
|
if (it.id == id) it.copy(name = newName) else it
|
||||||
|
}
|
||||||
|
prefs.saveProfiles(newProfiles)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Flag Management --- //
|
||||||
|
|
||||||
|
fun toggleFlag(flagId: String) {
|
||||||
|
val currentFlags = clientConfig.value.customFlags.toMutableList()
|
||||||
|
val index = currentFlags.indexOfFirst { it.id == flagId }
|
||||||
|
if (index != -1) {
|
||||||
|
currentFlags[index] = currentFlags[index].copy(enabled = !currentFlags[index].enabled)
|
||||||
|
saveClientConfig(clientConfig.value.copy(customFlags = currentFlags))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addCustomFlag(label: String, argument: String) {
|
||||||
|
val currentFlags = clientConfig.value.customFlags.toMutableList()
|
||||||
|
currentFlags.add(ProxyFlag(label = label, argument = argument, enabled = true))
|
||||||
|
saveClientConfig(clientConfig.value.copy(customFlags = currentFlags))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteFlag(flagId: String) {
|
||||||
|
val currentFlags = clientConfig.value.customFlags.filter {
|
||||||
|
it.id != flagId || !it.deletable // Prevent deletion if not deletable anyway, but we'll hide the button in UI
|
||||||
|
}
|
||||||
|
val protectedFlag = clientConfig.value.customFlags.find { it.id == flagId }
|
||||||
|
if (protectedFlag?.deletable == false) return
|
||||||
|
|
||||||
|
saveClientConfig(clientConfig.value.copy(customFlags = currentFlags))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun moveFlag(flagId: String, up: Boolean) {
|
||||||
|
val currentFlags = clientConfig.value.customFlags.toMutableList()
|
||||||
|
val index = currentFlags.indexOfFirst { it.id == flagId }
|
||||||
|
if (index == -1) return
|
||||||
|
|
||||||
|
val newIndex = if (up) index - 1 else index + 1
|
||||||
|
if (newIndex in currentFlags.indices) {
|
||||||
|
val item = currentFlags.removeAt(index)
|
||||||
|
currentFlags.add(newIndex, item)
|
||||||
|
saveClientConfig(clientConfig.value.copy(customFlags = currentFlags))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun updateFlag(flagId: String, label: String, argument: String) {
|
||||||
|
val currentFlags = clientConfig.value.customFlags.toMutableList()
|
||||||
|
val index = currentFlags.indexOfFirst { it.id == flagId }
|
||||||
|
if (index != -1) {
|
||||||
|
currentFlags[index] = currentFlags[index].copy(label = label, argument = argument)
|
||||||
|
saveClientConfig(clientConfig.value.copy(customFlags = currentFlags))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Import / Export --- //
|
||||||
|
|
||||||
|
fun getProfileExportData(id: String): String? {
|
||||||
|
val profile = profiles.value.find { it.id == id } ?: return null
|
||||||
|
val json = gson.toJson(profile)
|
||||||
|
return compressAndEncode(json)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getAllProfilesExportData(): String {
|
||||||
|
val json = gson.toJson(profiles.value)
|
||||||
|
return compressAndEncode(json)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun compressAndEncode(data: String): String {
|
||||||
|
val bytes = data.toByteArray(Charsets.UTF_8)
|
||||||
|
val baos = java.io.ByteArrayOutputStream()
|
||||||
|
java.util.zip.GZIPOutputStream(baos).use { it.write(bytes) }
|
||||||
|
val prefix = "VKTGZ:"
|
||||||
|
return prefix + Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun exportProfile(id: String) {
|
||||||
|
val base64 = getProfileExportData(id) ?: return
|
||||||
|
val clipboard = getApplication<Application>().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
val clip = android.content.ClipData.newPlainText("VK Turn Profile", base64)
|
||||||
|
clipboard.setPrimaryClip(clip)
|
||||||
|
Toast.makeText(getApplication(), "Профиль скопирован", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun exportAllProfiles() {
|
||||||
|
val base64 = getAllProfilesExportData()
|
||||||
|
val clipboard = getApplication<Application>().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
val clip = android.content.ClipData.newPlainText("VK Turn All Profiles", base64)
|
||||||
|
clipboard.setPrimaryClip(clip)
|
||||||
|
Toast.makeText(getApplication(), "Все профили (${profiles.value.size}) скопированы", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun generateUniqueName(baseName: String): String {
|
||||||
|
val existingNames = profiles.value.map { it.name }
|
||||||
|
if (!existingNames.contains(baseName)) return baseName
|
||||||
|
|
||||||
|
var counter = 2
|
||||||
|
while (existingNames.contains("$baseName $counter")) {
|
||||||
|
counter++
|
||||||
|
}
|
||||||
|
return "$baseName $counter"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun handleProfileImport(text: String, showToast: Boolean = true) {
|
||||||
|
if (text.isBlank()) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
val decoded = try {
|
||||||
|
if (text.startsWith("VKTGZ:")) {
|
||||||
|
val base64Str = text.substring(6)
|
||||||
|
val compressed = Base64.decode(base64Str, Base64.DEFAULT)
|
||||||
|
val bais = java.io.ByteArrayInputStream(compressed)
|
||||||
|
val resultBytes = java.util.zip.GZIPInputStream(bais).readBytes()
|
||||||
|
String(resultBytes, Charsets.UTF_8)
|
||||||
|
} else {
|
||||||
|
val data = Base64.decode(text, Base64.DEFAULT)
|
||||||
|
String(data)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
text
|
||||||
|
}
|
||||||
|
|
||||||
|
if (decoded.trim().startsWith("[")) {
|
||||||
|
val type = object : TypeToken<List<ProxyProfile>>() {}.type
|
||||||
|
val importedList: List<ProxyProfile> = gson.fromJson(decoded, type)
|
||||||
|
val currentProfiles = profiles.value.toMutableList()
|
||||||
|
|
||||||
|
importedList.forEach { imported ->
|
||||||
|
val migratedConfig = AppPreferences.migrateConfig(imported.config)
|
||||||
|
val uniqueName = generateUniqueName(imported.name)
|
||||||
|
currentProfiles.add(ProxyProfile(
|
||||||
|
name = uniqueName,
|
||||||
|
config = migratedConfig,
|
||||||
|
isDefault = false // Ensure imported is NEVER default
|
||||||
|
))
|
||||||
|
}
|
||||||
|
prefs.saveProfiles(currentProfiles)
|
||||||
|
if (showToast) Toast.makeText(getApplication(), "Импортировано профилей: ${importedList.size}", Toast.LENGTH_SHORT).show()
|
||||||
|
} else {
|
||||||
|
val imported: ProxyProfile = gson.fromJson(decoded, ProxyProfile::class.java)
|
||||||
|
val migratedConfig = AppPreferences.migrateConfig(imported.config)
|
||||||
|
val uniqueName = generateUniqueName(imported.name)
|
||||||
|
addProfile(uniqueName, migratedConfig)
|
||||||
|
if (showToast) Toast.makeText(getApplication(), "Профиль '$uniqueName' импортирован", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
if (showToast) Toast.makeText(getApplication(), "Ошибка импорта: ${e.message}", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun importProfileFromClipboard() {
|
||||||
|
val clipboard = getApplication<Application>().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||||
|
val text = clipboard.primaryClip?.getItemAt(0)?.text?.toString() ?: return
|
||||||
|
handleProfileImport(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun startProxy() {
|
||||||
|
if (_proxyState.value is ProxyState.Running) return
|
||||||
|
_proxyState.value = ProxyState.Starting
|
||||||
|
val intent = Intent(getApplication(), ProxyService::class.java)
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
|
||||||
|
getApplication<Application>().startForegroundService(intent)
|
||||||
|
} else {
|
||||||
|
getApplication<Application>().startService(intent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopProxy() {
|
||||||
|
val intent = Intent(getApplication(), ProxyService::class.java)
|
||||||
|
getApplication<Application>().stopService(intent)
|
||||||
|
_proxyState.value = ProxyState.Idle
|
||||||
|
}
|
||||||
|
|
||||||
|
fun dismissCaptcha() {
|
||||||
|
_proxyState.value = if (ProxyService.isRunning) ProxyState.Running else ProxyState.Idle
|
||||||
|
ProxyService.updateNotification("TURN Proxy", "Работает в фоне")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearProxyLogs() {
|
||||||
|
ProxyService.logBuffer.clear()
|
||||||
|
_proxyLogs.value = emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clearSshLogs() {
|
||||||
|
_sshLog.value = emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Kernel Management --- //
|
||||||
|
|
||||||
|
private fun getKernelFile() = File(getApplication<Application>().filesDir, "libcustom_kernel.so")
|
||||||
|
|
||||||
|
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) }
|
||||||
|
?: 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()) {
|
||||||
|
return@withContext Result.failure(Exception("Файл не является ELF-бинарником"))
|
||||||
|
}
|
||||||
|
|
||||||
|
val machine = bytes[18].toInt() and 0xFF
|
||||||
|
val primaryAbi = Build.SUPPORTED_ABIS[0]
|
||||||
|
|
||||||
|
val isCompatible = when {
|
||||||
|
primaryAbi.contains("arm64") -> machine == 183 // EM_AARCH64
|
||||||
|
primaryAbi.contains("armeabi") -> machine == 40 // EM_ARM
|
||||||
|
primaryAbi.contains("x86_64") -> machine == 62 // EM_X86_64
|
||||||
|
primaryAbi.contains("x86") -> machine == 3 // EM_386
|
||||||
|
else -> true // Unknown ABI, let it try
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isCompatible) {
|
||||||
|
val foundArch = when(machine) {
|
||||||
|
183 -> "ARM 64-bit"
|
||||||
|
40 -> "ARM 32-bit"
|
||||||
|
62 -> "x86 64-bit"
|
||||||
|
3 -> "x86 32-bit"
|
||||||
|
else -> "Unknown ($machine)"
|
||||||
|
}
|
||||||
|
return@withContext Result.failure(Exception("Несовместимая архитектура: $foundArch. Ваше устройство: $primaryAbi"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy file
|
||||||
|
context.contentResolver.openInputStream(uri)?.use { input ->
|
||||||
|
FileOutputStream(getKernelFile()).use { output ->
|
||||||
|
input.copyTo(output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
getKernelFile().setExecutable(true)
|
||||||
|
_isKernelPresent.value = true
|
||||||
|
Result.success("Ядро успешно импортировано")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Result.failure(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteKernel() {
|
||||||
|
getKernelFile().delete()
|
||||||
|
_isKernelPresent.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- SSH Logic --- //
|
||||||
|
|
||||||
|
fun connectSsh() {
|
||||||
|
val config = sshConfig.value
|
||||||
|
if (config.ip.isEmpty() || config.password.isEmpty()) return
|
||||||
|
|
||||||
|
_sshState.value = SshConnectionState.Connecting
|
||||||
|
sshManager.disconnect()
|
||||||
|
_sshLog.value = listOf("[Система]: Проверка доступа к серверу...")
|
||||||
|
|
||||||
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
|
val checkAuth = sshManager.executeSilentCommand(config.ip, config.port, config.username, config.password, "echo OK")
|
||||||
|
if (checkAuth.contains("ERROR:") || !checkAuth.contains("OK")) {
|
||||||
|
var errorMessage = checkAuth.replace("ERROR:", "").trim()
|
||||||
|
if (errorMessage.contains("Connection refused", ignoreCase = true) || errorMessage.contains("ECONNREFUSED", ignoreCase = true)) {
|
||||||
|
errorMessage += "\n\nПохоже, сервер отклонил соединение. Возможно, в вашем регионе принудительно включены «белые списки» (БС) или SSH-сервис на сервере временно недоступен."
|
||||||
|
} else if (errorMessage.contains("Auth fail", ignoreCase = true) || errorMessage.contains("Auth cancel", ignoreCase = true)) {
|
||||||
|
errorMessage = "Неверный пароль или имя пользователя"
|
||||||
|
}
|
||||||
|
_sshState.value = SshConnectionState.Error("Ошибка: $errorMessage")
|
||||||
|
_sshLog.value = _sshLog.value + "[Ошибка]: ${errorMessage.take(60)}..."
|
||||||
|
} else {
|
||||||
|
_sshState.value = SshConnectionState.Connected(config.ip)
|
||||||
|
_sshLog.value = _sshLog.value + "[Система]: Доступ разрешен. Устанавливаем терминал..."
|
||||||
|
checkServerState()
|
||||||
|
|
||||||
|
sshManager.startShell(config.ip, config.port, config.username, config.password, onLogReceived = { output ->
|
||||||
|
if (output.contains("\u001B[H") || output.contains("\u001B[2J") || output.contains("\u001B[c")) {
|
||||||
|
_sshLog.value = emptyList()
|
||||||
|
}
|
||||||
|
val clean = output.replace(Regex("\\x1B\\[[0-9;?]*[a-zA-Z]"), "").replace("\r", "")
|
||||||
|
if (clean.isNotBlank()) {
|
||||||
|
val lines = clean.split("\n").filter { it.isNotBlank() }
|
||||||
|
_sshLog.value = (_sshLog.value + lines).takeLast(200)
|
||||||
|
}
|
||||||
|
}, onDisconnected = { error ->
|
||||||
|
_sshState.value = SshConnectionState.Error("Связь разорвана: ${error ?: "Таймаут/Обрыв соединения"}")
|
||||||
|
_sshLog.value = _sshLog.value + "[Система]: Сессия SSH прервана. Требуется переподключение."
|
||||||
|
_serverState.value = ServerState.Unknown
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun checkServerState() {
|
||||||
|
if (_sshState.value !is SshConnectionState.Connected) return
|
||||||
|
_serverState.value = ServerState.Checking
|
||||||
|
val config = sshConfig.value
|
||||||
|
|
||||||
|
viewModelScope.launch(Dispatchers.IO) {
|
||||||
|
val checkInstall = sshManager.executeSilentCommand(config.ip, config.port, config.username, config.password, "ls /opt/vk-turn/server-linux-* 2>/dev/null")
|
||||||
|
val installed = checkInstall.contains("server-linux") && !checkInstall.contains("ERROR:")
|
||||||
|
|
||||||
|
// Проверяем статус через systemctl или ps
|
||||||
|
val checkService = sshManager.executeSilentCommand(config.ip, config.port, config.username, config.password, "systemctl is-active vk-turn-proxy 2>/dev/null")
|
||||||
|
val isService = checkService.trim() == "active"
|
||||||
|
var running = isService
|
||||||
|
|
||||||
|
if (!running) {
|
||||||
|
val checkPs = sshManager.executeSilentCommand(config.ip, config.port, config.username, config.password, "ps aux | grep server-linux | grep -v grep")
|
||||||
|
running = checkPs.contains("server-linux") && !checkPs.contains("ERROR:")
|
||||||
|
}
|
||||||
|
|
||||||
|
_serverState.value = ServerState.Known(installed, running, isService)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun disconnectSsh() {
|
||||||
|
sshManager.disconnect()
|
||||||
|
_sshState.value = SshConnectionState.Disconnected
|
||||||
|
_serverState.value = ServerState.Unknown
|
||||||
|
val log = _sshLog.value.toMutableList()
|
||||||
|
log.add("[Система]: Отключено.")
|
||||||
|
_sshLog.value = log
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendSshCommand(command: String) {
|
||||||
|
if (_sshState.value is SshConnectionState.Connected) {
|
||||||
|
sshManager.sendShellCommand(command)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun installServer() {
|
||||||
|
val config = sshConfig.value
|
||||||
|
val l = config.proxyListen
|
||||||
|
val c = config.proxyConnect
|
||||||
|
|
||||||
|
val script = """
|
||||||
|
mkdir -p /opt/vk-turn && cd /opt/vk-turn &&
|
||||||
|
pkill -9 -f "server-linux-" 2>/dev/null;
|
||||||
|
ARCH=${'$'}(uname -m);
|
||||||
|
if [ "${'$'}ARCH" = "x86_64" ]; then BIN="server-linux-amd64"; else BIN="server-linux-arm64"; fi;
|
||||||
|
wget -qO ${'$'}BIN https://github.com/cacggghp/vk-turn-proxy/releases/latest/download/${'$'}BIN &&
|
||||||
|
chmod +x ${'$'}BIN &&
|
||||||
|
|
||||||
|
# Попытка создать systemd сервис
|
||||||
|
(
|
||||||
|
cat <<EOF > vk-turn-proxy.service
|
||||||
|
[Unit]
|
||||||
|
Description=VK Turn Proxy Service
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=/opt/vk-turn/${'$'}BIN -listen $l -connect $c
|
||||||
|
KillMode=process
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
User=nobody
|
||||||
|
Group=nogroup
|
||||||
|
StandardOutput=append:/var/log/vk-turn/server.log
|
||||||
|
StandardError=append:/var/log/vk-turn/error.log
|
||||||
|
SyslogIdentifier=vk-turn-proxy
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
mkdir -p /var/log/vk-turn && chown nobody:nogroup /var/log/vk-turn 2>/dev/null
|
||||||
|
cp vk-turn-proxy.service /etc/systemd/system/ 2>/dev/null && \
|
||||||
|
systemctl daemon-reload 2>/dev/null && \
|
||||||
|
systemctl enable vk-turn-proxy 2>/dev/null && \
|
||||||
|
echo "Сервис Systemd настроен!"
|
||||||
|
) || echo "Продолжаем без системного сервиса (нет прав root)"
|
||||||
|
|
||||||
|
echo "Установка завершена!"
|
||||||
|
""".trimIndent()
|
||||||
|
sshManager.sendShellCommand(script)
|
||||||
|
// Wait a bit and check state
|
||||||
|
viewModelScope.launch {
|
||||||
|
delay(5000)
|
||||||
|
checkServerState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun startServer() {
|
||||||
|
val config = sshConfig.value
|
||||||
|
val l = config.proxyListen
|
||||||
|
val c = config.proxyConnect
|
||||||
|
val script = """
|
||||||
|
if systemctl is-enabled vk-turn-proxy >/dev/null 2>&1; then
|
||||||
|
systemctl restart vk-turn-proxy && echo "Сервис запущен (systemd)"
|
||||||
|
else
|
||||||
|
cd /opt/vk-turn &&
|
||||||
|
ARCH=${'$'}(uname -m);
|
||||||
|
if [ "${'$'}ARCH" = "x86_64" ]; then BIN="server-linux-amd64"; else BIN="server-linux-arm64"; fi;
|
||||||
|
nohup ./${'$'}BIN -listen $l -connect $c > server.log 2>&1 &
|
||||||
|
echo ${'$'}! > proxy.pid && echo "Сервер запущен вручную (PID: ${'$'}(cat proxy.pid))"
|
||||||
|
fi
|
||||||
|
""".trimIndent()
|
||||||
|
sshManager.sendShellCommand(script)
|
||||||
|
viewModelScope.launch {
|
||||||
|
delay(2000)
|
||||||
|
checkServerState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopServer() {
|
||||||
|
val script = """
|
||||||
|
if systemctl is-active vk-turn-proxy >/dev/null 2>&1; then
|
||||||
|
systemctl stop vk-turn-proxy && echo "Сервис остановлен"
|
||||||
|
else
|
||||||
|
cd /opt/vk-turn &&
|
||||||
|
if [ -f proxy.pid ]; then kill -9 ${'$'}(cat proxy.pid) 2>/dev/null; rm -f proxy.pid; fi;
|
||||||
|
pkill -9 -f "server-linux-" 2>/dev/null;
|
||||||
|
echo "Остановлено вручную."
|
||||||
|
fi
|
||||||
|
""".trimIndent()
|
||||||
|
sshManager.sendShellCommand(script)
|
||||||
|
viewModelScope.launch {
|
||||||
|
delay(2000)
|
||||||
|
checkServerState()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
@@ -1,129 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="match_parent"
|
|
||||||
android:orientation="vertical"
|
|
||||||
android:fitsSystemWindows="true"
|
|
||||||
android:background="#121212"> <ScrollView
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="0dp"
|
|
||||||
android:layout_weight="1"
|
|
||||||
android:padding="16dp">
|
|
||||||
|
|
||||||
<LinearLayout
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:orientation="vertical">
|
|
||||||
|
|
||||||
<Button
|
|
||||||
android:id="@+id/btnUpdateBinary"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:backgroundTint="#37474F"
|
|
||||||
android:text="ЗАГРУЗИТЬ НОВОЕ ЯДРО (ФАЙЛ)"
|
|
||||||
android:textColor="#FFFFFF" />
|
|
||||||
|
|
||||||
<Button
|
|
||||||
android:id="@+id/btnBattery"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_marginTop="8dp"
|
|
||||||
android:backgroundTint="#BF360C"
|
|
||||||
android:text="ОТКЛЮЧИТЬ ОПТИМИЗАЦИЮ БАТАРЕИ"
|
|
||||||
android:textColor="#FFFFFF" />
|
|
||||||
|
|
||||||
<Switch
|
|
||||||
android:id="@+id/switchRawMode"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_marginTop="16dp"
|
|
||||||
android:text="Режим своей (Raw) команды"
|
|
||||||
android:textColor="#E0E0E0"
|
|
||||||
android:textStyle="bold" />
|
|
||||||
|
|
||||||
<EditText
|
|
||||||
android:id="@+id/editRawCommand"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_marginTop="8dp"
|
|
||||||
android:background="#1E1E1E"
|
|
||||||
android:fontFamily="monospace"
|
|
||||||
android:hint="./client -n 8 -udp -peer IP:56000 ..."
|
|
||||||
android:padding="12dp"
|
|
||||||
android:textColor="#FFFFFF"
|
|
||||||
android:textColorHint="#757575"
|
|
||||||
android:textSize="14sp"
|
|
||||||
android:visibility="gone" />
|
|
||||||
|
|
||||||
<LinearLayout
|
|
||||||
android:id="@+id/layoutGuiSettings"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:orientation="vertical">
|
|
||||||
|
|
||||||
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Peer (IP:Port сервера)" android:textColor="#B0BEC5" android:textStyle="bold" android:layout_marginTop="12dp"/>
|
|
||||||
<EditText android:id="@+id/editPeer" android:layout_width="match_parent" android:layout_height="wrap_content" android:backgroundTint="#455A64" android:textColor="#FFFFFF" android:hint="11.22.33.44:00000" android:textColorHint="#616161"/>
|
|
||||||
|
|
||||||
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Ссылка (VK Calls)" android:textColor="#B0BEC5" android:textStyle="bold" android:layout_marginTop="12dp"/>
|
|
||||||
<EditText android:id="@+id/editLink" android:layout_width="match_parent" android:layout_height="wrap_content" android:backgroundTint="#455A64" android:textColor="#FFFFFF" android:hint="https://vk.com/call/join/..." android:textColorHint="#616161"/>
|
|
||||||
|
|
||||||
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Потоки (-n)" android:textColor="#B0BEC5" android:textStyle="bold" android:layout_marginTop="12dp"/>
|
|
||||||
<EditText android:id="@+id/editN" android:layout_width="match_parent" android:layout_height="wrap_content" android:backgroundTint="#455A64" android:textColor="#FFFFFF" android:inputType="number" android:text="8" />
|
|
||||||
|
|
||||||
<CheckBox android:id="@+id/checkUdp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Использовать UDP (-udp)" android:textColor="#E0E0E0" android:checked="true" />
|
|
||||||
<CheckBox android:id="@+id/checkNoDtls" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Без обфускации (-no-dtls)" android:textColor="#E0E0E0" />
|
|
||||||
|
|
||||||
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Локальный порт" android:textColor="#B0BEC5" android:textStyle="bold" android:layout_marginTop="12dp"/>
|
|
||||||
<EditText android:id="@+id/editListen" android:layout_width="match_parent" android:layout_height="wrap_content" android:backgroundTint="#455A64" android:textColor="#FFFFFF" android:text="127.0.0.1:9000" />
|
|
||||||
</LinearLayout>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
android:id="@+id/btnToggle"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="60dp"
|
|
||||||
android:layout_marginTop="24dp"
|
|
||||||
android:text="ЗАПУСТИТЬ ПРОКСИ"
|
|
||||||
android:textSize="18sp"
|
|
||||||
android:textStyle="bold"
|
|
||||||
android:backgroundTint="#2E7D32" />
|
|
||||||
</LinearLayout>
|
|
||||||
</ScrollView>
|
|
||||||
|
|
||||||
<LinearLayout
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:background="#263238"
|
|
||||||
android:orientation="horizontal"
|
|
||||||
android:padding="4dp"
|
|
||||||
android:gravity="center_vertical">
|
|
||||||
|
|
||||||
<TextView
|
|
||||||
android:layout_width="0dp"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:layout_weight="1"
|
|
||||||
android:textColor="#CFD8DC"
|
|
||||||
android:padding="8dp"
|
|
||||||
android:text="ТЕРМИНАЛ ЛОГОВ:"
|
|
||||||
android:textSize="10sp"
|
|
||||||
android:textStyle="bold" />
|
|
||||||
|
|
||||||
<Button android:id="@+id/btnCopyLogs" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="COPY" android:textSize="10sp" android:backgroundTint="#455A64"/>
|
|
||||||
<Button android:id="@+id/btnClearLogs" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="4dp" android:text="CLEAR" android:textSize="10sp" android:backgroundTint="#455A64"/>
|
|
||||||
</LinearLayout>
|
|
||||||
|
|
||||||
<ScrollView
|
|
||||||
android:id="@+id/logScrollView"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="220dp"
|
|
||||||
android:background="#000000">
|
|
||||||
<TextView
|
|
||||||
android:id="@+id/tvLogs"
|
|
||||||
android:layout_width="match_parent"
|
|
||||||
android:layout_height="wrap_content"
|
|
||||||
android:textColor="#4CAF50"
|
|
||||||
android:textSize="12sp"
|
|
||||||
android:padding="10dp"
|
|
||||||
android:fontFamily="monospace"
|
|
||||||
android:text="Ожидание запуска..." />
|
|
||||||
</ScrollView>
|
|
||||||
</LinearLayout>
|
|
||||||
File renamed without changes.
File renamed without changes.
@@ -1,3 +1,3 @@
|
|||||||
<resources>
|
<resources>
|
||||||
<string name="app_name">VkTurnProxy</string>
|
<string name="app_name">TURN Proxy</string>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
|
||||||
<!-- Base application theme. -->
|
|
||||||
<style name="Base.Theme.VkTurnProxy" parent="Theme.Material3.DayNight.NoActionBar">
|
|
||||||
<!-- Customize your light theme here. -->
|
|
||||||
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<style name="Theme.VkTurnProxy" parent="Base.Theme.VkTurnProxy" />
|
|
||||||
</resources>
|
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<paths>
|
||||||
|
<cache-path name="shared_images" path="images/" />
|
||||||
|
</paths>
|
||||||
@@ -9,6 +9,9 @@ appcompat = "1.7.1"
|
|||||||
material = "1.13.0"
|
material = "1.13.0"
|
||||||
activity = "1.12.1"
|
activity = "1.12.1"
|
||||||
constraintlayout = "2.2.1"
|
constraintlayout = "2.2.1"
|
||||||
|
composeBom = "2024.10.00"
|
||||||
|
lifecycle = "2.8.6"
|
||||||
|
navigationCompose = "2.8.2"
|
||||||
|
|
||||||
[libraries]
|
[libraries]
|
||||||
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
|
||||||
@@ -19,8 +22,21 @@ androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version
|
|||||||
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
|
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
|
||||||
androidx-activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
|
androidx-activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
|
||||||
androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
|
androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
|
||||||
|
compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
|
||||||
|
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
|
||||||
|
androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
|
||||||
|
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
|
||||||
|
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
|
||||||
|
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
|
||||||
|
androidx-compose-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
|
||||||
|
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
|
||||||
|
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
|
||||||
|
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
|
||||||
|
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activity" }
|
||||||
|
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
android-application = { id = "com.android.application", version.ref = "agp" }
|
android-application = { id = "com.android.application", version.ref = "agp" }
|
||||||
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
|
||||||
|
compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
|
||||||
|
|
||||||
Reference in new issue
Block a user