feat: new design
This commit is contained in:
1 parent
c603f1b5cf
commit
3e93e5337c
25 files changed
+2389
-568
No files matched your search
+25
-12
@@ -1,6 +1,7 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
}
|
||||
|
||||
android {
|
||||
@@ -9,10 +10,10 @@ android {
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.vkturn.proxy"
|
||||
minSdk = 23
|
||||
targetSdk = 28
|
||||
versionCode = 2
|
||||
versionName = "1.1.0"
|
||||
minSdk = 26
|
||||
targetSdk = 35
|
||||
versionCode = 3
|
||||
versionName = "2.0.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
@@ -21,7 +22,10 @@ android {
|
||||
resources.excludes += "META-INF/versions/9/OSGI-INF/MANIFEST.MF"
|
||||
jniLibs.useLegacyPackaging = true
|
||||
}
|
||||
// ---------------------------------
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
@@ -33,10 +37,8 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// Отключаем проверку lint для релизных сборок, чтобы сборка release не падала из‑за ExpiredTargetSdkVersion
|
||||
lint {
|
||||
checkReleaseBuilds = false
|
||||
// при желании можно только отключить конкретное правило:
|
||||
disable += "ExpiredTargetSdkVersion"
|
||||
}
|
||||
|
||||
@@ -50,16 +52,27 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// SSH и Корутины
|
||||
implementation("com.github.mwiede:jsch:0.2.17")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
|
||||
|
||||
// Стандартные библиотеки Android
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.appcompat)
|
||||
implementation(libs.material)
|
||||
implementation(libs.androidx.activity)
|
||||
implementation(libs.androidx.constraintlayout)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(libs.androidx.datastore.preferences)
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
implementation(libs.androidx.compose.ui)
|
||||
implementation(libs.androidx.compose.ui.graphics)
|
||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||
// Явно пиним M3 1.4.0-alpha10+ для WavyProgressIndicator и ExperimentalMaterial3ExpressiveApi
|
||||
implementation("androidx.compose.material3:material3:1.4.0-alpha10")
|
||||
implementation(libs.androidx.compose.material.icons.extended)
|
||||
|
||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||
|
||||
testImplementation(libs.junit)
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
|
||||
<application
|
||||
android:extractNativeLibs="true"
|
||||
android:allowBackup="true"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="@xml/backup_rules"
|
||||
@@ -23,15 +22,14 @@
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
android:exported="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity android:name=".SettingsActivity" android:exported="false" />
|
||||
|
||||
<service
|
||||
android:name=".ProxyService"
|
||||
android:exported="false"
|
||||
|
||||
@@ -1,187 +1,54 @@
|
||||
package com.vkturn.proxy
|
||||
|
||||
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.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.activity.viewModels
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.core.content.ContextCompat
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import com.vkturn.proxy.ui.navigation.AppNavigation
|
||||
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 lateinit var logScrollView: ScrollView
|
||||
private lateinit var btnToggle: Button
|
||||
private val viewModel: MainViewModel by viewModels()
|
||||
|
||||
// Обработка выбора файла для обновления ядра
|
||||
private val filePicker = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
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 notificationPermissionLauncher =
|
||||
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* no-op */ }
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
requestNotificationPermissionIfNeeded()
|
||||
|
||||
setContent {
|
||||
VkTurnProxyTheme {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = MaterialTheme.colorScheme.background
|
||||
) {
|
||||
AppNavigation(viewModel = viewModel)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
|
||||
if (!isGranted) Toast.makeText(this, "Разрешите уведомления для фоновой работы!", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
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 = "Консоль очищена."
|
||||
}
|
||||
|
||||
// --- ДОБАВЛЕННЫЙ КОД ДЛЯ КНОПКИ "НАСТРОЙКИ" ---
|
||||
val btnSettings = findViewById<Button>(R.id.btnSettings)
|
||||
btnSettings.setOnClickListener {
|
||||
val intent = Intent(this, SettingsActivity::class.java)
|
||||
startActivity(intent)
|
||||
}
|
||||
// ----------------------------------------------
|
||||
|
||||
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() {
|
||||
private fun requestNotificationPermissionIfNeeded() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
return
|
||||
}
|
||||
}
|
||||
ProxyService.logBuffer.clear()
|
||||
startForegroundService(Intent(this, ProxyService::class.java))
|
||||
btnToggle.text = "ОСТАНОВИТЬ ПРОКСИ"
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
btnToggle.text = if (ProxyService.isRunning) "ОСТАНОВИТЬ ПРОКСИ" else "ЗАПУСТИТЬ ПРОКСИ"
|
||||
tvLogs.text = ProxyService.logBuffer.joinToString("\n")
|
||||
scrollLogsToEnd()
|
||||
|
||||
ProxyService.onLogReceived = { msg ->
|
||||
runOnUiThread {
|
||||
if (tvLogs.text.length > 25000) tvLogs.text = tvLogs.text.substring(10000)
|
||||
tvLogs.append("\n$msg")
|
||||
scrollLogsToEnd()
|
||||
if (ContextCompat.checkSelfPermission(
|
||||
this, Manifest.permission.POST_NOTIFICATIONS
|
||||
) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun scrollLogsToEnd() {
|
||||
logScrollView.post { logScrollView.fullScroll(View.FOCUS_DOWN) }
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
ProxyService.onLogReceived = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
package com.vkturn.proxy
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.widget.*
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import kotlinx.coroutines.*
|
||||
|
||||
class SettingsActivity : AppCompatActivity() {
|
||||
|
||||
private val sshManager = SSHManager()
|
||||
private lateinit var tvSshLog: TextView
|
||||
private lateinit var scrollSshLog: ScrollView
|
||||
private lateinit var btnInstallServer: Button
|
||||
private lateinit var btnStartProxy: Button
|
||||
private lateinit var btnStopProxy: Button
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_settings)
|
||||
|
||||
val editIp = findViewById<EditText>(R.id.editSshIp)
|
||||
val editPort = findViewById<EditText>(R.id.editSshPort)
|
||||
val editUser = findViewById<EditText>(R.id.editSshUser)
|
||||
val editPass = findViewById<EditText>(R.id.editSshPass)
|
||||
val editProxyListen = findViewById<EditText>(R.id.editProxyListen)
|
||||
val editProxyConnect = findViewById<EditText>(R.id.editProxyConnect)
|
||||
val editCustomCmd = findViewById<EditText>(R.id.editCustomCmd)
|
||||
val btnSendCmd = findViewById<Button>(R.id.btnSendCmd)
|
||||
val btnConnectSsh = findViewById<Button>(R.id.btnConnectSsh)
|
||||
val btnCtrlC = findViewById<Button>(R.id.btnCtrlC)
|
||||
|
||||
btnInstallServer = findViewById(R.id.btnInstallServer)
|
||||
btnStartProxy = findViewById(R.id.btnStartProxy)
|
||||
btnStopProxy = findViewById(R.id.btnStopProxy)
|
||||
tvSshLog = findViewById(R.id.tvSshLog)
|
||||
scrollSshLog = findViewById(R.id.scrollSshLog)
|
||||
|
||||
val prefs = getSharedPreferences("SshPrefs", Context.MODE_PRIVATE)
|
||||
editIp.setText(prefs.getString("ip", ""))
|
||||
editPort.setText(prefs.getString("port", "22"))
|
||||
editUser.setText(prefs.getString("user", "root"))
|
||||
editPass.setText(prefs.getString("pass", ""))
|
||||
editProxyListen.setText(prefs.getString("proxyListen", "0.0.0.0:56000"))
|
||||
editProxyConnect.setText(prefs.getString("proxyConnect", "127.0.0.1:40537"))
|
||||
|
||||
val savePrefs = {
|
||||
prefs.edit().apply {
|
||||
putString("ip", editIp.text.toString())
|
||||
putString("port", editPort.text.toString())
|
||||
putString("user", editUser.text.toString())
|
||||
putString("pass", editPass.text.toString())
|
||||
putString("proxyListen", editProxyListen.text.toString())
|
||||
putString("proxyConnect", editProxyConnect.text.toString())
|
||||
}.apply()
|
||||
}
|
||||
|
||||
findViewById<Button>(R.id.btnBack).setOnClickListener { savePrefs(); finish() }
|
||||
findViewById<Button>(R.id.btnCopySshLog).setOnClickListener {
|
||||
val cb = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
cb.setPrimaryClip(ClipData.newPlainText("ssh_logs", tvSshLog.text))
|
||||
Toast.makeText(this, "Логи скопированы!", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
findViewById<Button>(R.id.btnClearSshLog).setOnClickListener { tvSshLog.text = "" }
|
||||
|
||||
// 1. ПОДКЛЮЧИТЬСЯ
|
||||
btnConnectSsh.setOnClickListener {
|
||||
savePrefs()
|
||||
val ip = editIp.text.toString()
|
||||
val pass = editPass.text.toString()
|
||||
if (ip.isEmpty() || pass.isEmpty()) return@setOnClickListener
|
||||
|
||||
sshManager.disconnect()
|
||||
tvSshLog.text = "[Система]: Подключение к серверу...\n"
|
||||
sshManager.startShell(ip, editPort.text.toString().toIntOrNull() ?: 22, editUser.text.toString(), pass) { output ->
|
||||
val clean = output.replace(Regex("\\x1B\\[[0-9;?]*[a-zA-Z]"), "").replace("\r", "")
|
||||
runOnUiThread {
|
||||
tvSshLog.append(clean)
|
||||
scrollSshLog.post { scrollSshLog.fullScroll(ScrollView.FOCUS_DOWN) }
|
||||
}
|
||||
}
|
||||
checkServerState(ip, editPort.text.toString().toIntOrNull() ?: 22, editUser.text.toString(), pass, "connect")
|
||||
}
|
||||
|
||||
// 2. УСТАНОВИТЬ (Используем pkill -f по маске для очистки старых версий)
|
||||
btnInstallServer.setOnClickListener {
|
||||
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 && echo "Установка завершена!"
|
||||
""".trimIndent()
|
||||
|
||||
sshManager.sendShellCommand(script)
|
||||
CoroutineScope(Dispatchers.Main).launch {
|
||||
delay(6000)
|
||||
checkServerState(editIp.text.toString(), editPort.text.toString().toIntOrNull() ?: 22, editUser.text.toString(), editPass.text.toString(), "silent")
|
||||
}
|
||||
}
|
||||
|
||||
// 3. ЗАПУСТИТЬ
|
||||
btnStartProxy.setOnClickListener {
|
||||
val l = editProxyListen.text.toString().ifEmpty { "0.0.0.0:56000" }
|
||||
val c = editProxyConnect.text.toString().ifEmpty { "127.0.0.1:40537" }
|
||||
|
||||
val script = """
|
||||
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))"
|
||||
""".trimIndent()
|
||||
|
||||
sshManager.sendShellCommand(script)
|
||||
CoroutineScope(Dispatchers.Main).launch {
|
||||
delay(2000)
|
||||
checkServerState(editIp.text.toString(), editPort.text.toString().toIntOrNull() ?: 22, editUser.text.toString(), editPass.text.toString(), "silent")
|
||||
}
|
||||
}
|
||||
|
||||
// 4. ОСТАНОВИТЬ (Сначала по PID, потом по маске - 100% результат)
|
||||
btnStopProxy.setOnClickListener {
|
||||
val script = """
|
||||
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 "Остановлено."
|
||||
""".trimIndent()
|
||||
|
||||
sshManager.sendShellCommand(script)
|
||||
CoroutineScope(Dispatchers.Main).launch {
|
||||
delay(2000)
|
||||
checkServerState(editIp.text.toString(), editPort.text.toString().toIntOrNull() ?: 22, editUser.text.toString(), editPass.text.toString(), "silent")
|
||||
}
|
||||
}
|
||||
|
||||
btnCtrlC.setOnClickListener { sshManager.sendCtrlC(); tvSshLog.append("^C\n") }
|
||||
|
||||
btnSendCmd.setOnClickListener {
|
||||
val cmd = editCustomCmd.text.toString().trim()
|
||||
if (cmd.isNotEmpty()) {
|
||||
savePrefs()
|
||||
if (cmd.lowercase() == "clear") tvSshLog.text = "" else sshManager.sendShellCommand(cmd)
|
||||
editCustomCmd.text.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Умная проверка: проверяет наличие любых файлов server-linux-* и живой процесс (без самообнаружения)
|
||||
private fun checkServerState(ip: String, port: Int, user: String, pass: String, mode: String) {
|
||||
val checkCmd = """
|
||||
if ls /opt/vk-turn/server-linux-* >/dev/null 2>&1; then echo "INSTALLED:YES"; else echo "INSTALLED:NO"; fi
|
||||
if ps aux | grep -v grep | grep -q "server-linux-"; then echo "RUNNING:YES"; else echo "RUNNING:NO"; fi
|
||||
""".trimIndent()
|
||||
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
val result = sshManager.executeSilentCommand(ip, port, user, pass, checkCmd)
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
if (result.contains("ERROR")) return@withContext
|
||||
|
||||
val isInst = result.contains("INSTALLED:YES")
|
||||
val isRun = result.contains("RUNNING:YES")
|
||||
|
||||
btnInstallServer.isEnabled = true
|
||||
|
||||
if (isInst) {
|
||||
btnStartProxy.isEnabled = !isRun
|
||||
btnStopProxy.isEnabled = isRun
|
||||
} else {
|
||||
btnStartProxy.isEnabled = false
|
||||
btnStopProxy.isEnabled = false
|
||||
}
|
||||
|
||||
if (mode == "connect") {
|
||||
val s = if (isRun) "РАБОТАЕТ" else "ОСТАНОВЛЕН"
|
||||
val i = if (isInst) "УСТАНОВЛЕН" else "НЕ НАЙДЕН"
|
||||
tvSshLog.append("\n[Система]: vk-turn-proxy $i. Статус: $s.\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() { super.onDestroy(); sshManager.disconnect() }
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.vkturn.proxy.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.*
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.map
|
||||
import java.io.IOException
|
||||
|
||||
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_prefs")
|
||||
|
||||
data class SshConfig(
|
||||
val ip: String = "",
|
||||
val port: Int = 22,
|
||||
val username: String = "root",
|
||||
val password: String = "",
|
||||
val authType: String = "PASSWORD",
|
||||
val sshKey: String = ""
|
||||
)
|
||||
|
||||
data class ClientConfig(
|
||||
val serverAddress: String = "",
|
||||
val vkLink: String = "",
|
||||
val threads: Int = 4,
|
||||
val useUdp: Boolean = true,
|
||||
val noDtls: Boolean = false,
|
||||
val localPort: String = "127.0.0.1:9000",
|
||||
val isRawMode: Boolean = false,
|
||||
val rawCommand: String = ""
|
||||
)
|
||||
|
||||
class AppPreferences(private val context: Context) {
|
||||
|
||||
companion object {
|
||||
val SSH_IP = stringPreferencesKey("ssh_ip")
|
||||
val SSH_PORT = intPreferencesKey("ssh_port")
|
||||
val SSH_USER = stringPreferencesKey("ssh_user")
|
||||
val SSH_PASS = stringPreferencesKey("ssh_pass")
|
||||
val SSH_AUTH_TYPE = stringPreferencesKey("ssh_auth_type")
|
||||
val SSH_KEY = stringPreferencesKey("ssh_key")
|
||||
val ONBOARDING_DONE = booleanPreferencesKey("onboarding_done")
|
||||
val CLIENT_SERVER_ADDR = stringPreferencesKey("client_server_addr")
|
||||
val CLIENT_VK_LINK = stringPreferencesKey("client_vk_link")
|
||||
val CLIENT_THREADS = intPreferencesKey("client_threads")
|
||||
val CLIENT_UDP = booleanPreferencesKey("client_udp")
|
||||
val CLIENT_NO_DTLS = booleanPreferencesKey("client_no_dtls")
|
||||
val CLIENT_LOCAL_PORT = stringPreferencesKey("client_local_port")
|
||||
val CLIENT_IS_RAW = booleanPreferencesKey("client_is_raw")
|
||||
val CLIENT_RAW_CMD = stringPreferencesKey("client_raw_cmd")
|
||||
val PROXY_LISTEN = stringPreferencesKey("proxy_listen")
|
||||
val PROXY_CONNECT = stringPreferencesKey("proxy_connect")
|
||||
}
|
||||
|
||||
val sshConfigFlow: Flow<SshConfig> = context.dataStore.data
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs ->
|
||||
SshConfig(
|
||||
ip = prefs[SSH_IP] ?: "",
|
||||
port = prefs[SSH_PORT] ?: 22,
|
||||
username = prefs[SSH_USER] ?: "root",
|
||||
password = prefs[SSH_PASS] ?: "",
|
||||
authType = prefs[SSH_AUTH_TYPE] ?: "PASSWORD",
|
||||
sshKey = prefs[SSH_KEY] ?: ""
|
||||
)
|
||||
}
|
||||
|
||||
val clientConfigFlow: Flow<ClientConfig> = context.dataStore.data
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs ->
|
||||
ClientConfig(
|
||||
serverAddress = prefs[CLIENT_SERVER_ADDR] ?: "",
|
||||
vkLink = prefs[CLIENT_VK_LINK] ?: "",
|
||||
threads = prefs[CLIENT_THREADS] ?: 4,
|
||||
useUdp = prefs[CLIENT_UDP] ?: true,
|
||||
noDtls = prefs[CLIENT_NO_DTLS] ?: false,
|
||||
localPort = prefs[CLIENT_LOCAL_PORT] ?: "127.0.0.1:9000",
|
||||
isRawMode = prefs[CLIENT_IS_RAW] ?: false,
|
||||
rawCommand = prefs[CLIENT_RAW_CMD] ?: ""
|
||||
)
|
||||
}
|
||||
|
||||
val onboardingDoneFlow: Flow<Boolean> = context.dataStore.data
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs -> prefs[ONBOARDING_DONE] ?: false }
|
||||
|
||||
val proxyListenFlow: Flow<String> = context.dataStore.data
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs -> prefs[PROXY_LISTEN] ?: "0.0.0.0:56000" }
|
||||
|
||||
val proxyConnectFlow: Flow<String> = context.dataStore.data
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs -> prefs[PROXY_CONNECT] ?: "127.0.0.1:40537" }
|
||||
|
||||
suspend fun saveSshConfig(config: SshConfig) {
|
||||
context.dataStore.edit { prefs ->
|
||||
prefs[SSH_IP] = config.ip
|
||||
prefs[SSH_PORT] = config.port
|
||||
prefs[SSH_USER] = config.username
|
||||
prefs[SSH_PASS] = config.password
|
||||
prefs[SSH_AUTH_TYPE] = config.authType
|
||||
prefs[SSH_KEY] = config.sshKey
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveClientConfig(config: ClientConfig) {
|
||||
context.dataStore.edit { prefs ->
|
||||
prefs[CLIENT_SERVER_ADDR] = config.serverAddress
|
||||
prefs[CLIENT_VK_LINK] = config.vkLink
|
||||
prefs[CLIENT_THREADS] = config.threads
|
||||
prefs[CLIENT_UDP] = config.useUdp
|
||||
prefs[CLIENT_NO_DTLS] = config.noDtls
|
||||
prefs[CLIENT_LOCAL_PORT] = config.localPort
|
||||
prefs[CLIENT_IS_RAW] = config.isRawMode
|
||||
prefs[CLIENT_RAW_CMD] = config.rawCommand
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun setOnboardingDone(done: Boolean) {
|
||||
context.dataStore.edit { prefs -> prefs[ONBOARDING_DONE] = done }
|
||||
}
|
||||
|
||||
suspend fun saveProxyConfig(listen: String, connect: String) {
|
||||
context.dataStore.edit { prefs ->
|
||||
prefs[PROXY_LISTEN] = listen
|
||||
prefs[PROXY_CONNECT] = connect
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.vkturn.proxy.ui.navigation
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.navigation.compose.NavHost
|
||||
import androidx.navigation.compose.composable
|
||||
import androidx.navigation.compose.rememberNavController
|
||||
import com.vkturn.proxy.ui.screens.ClientSetupScreen
|
||||
import com.vkturn.proxy.ui.screens.HomeScreen
|
||||
import com.vkturn.proxy.ui.screens.OnboardingScreen
|
||||
import com.vkturn.proxy.ui.screens.ServerManagementScreen
|
||||
import com.vkturn.proxy.ui.screens.SshSetupScreen
|
||||
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||
|
||||
object Routes {
|
||||
const val ONBOARDING = "onboarding"
|
||||
const val SSH_SETUP = "ssh_setup"
|
||||
const val SERVER_MANAGEMENT = "server_management"
|
||||
const val CLIENT_SETUP = "client_setup"
|
||||
const val HOME = "home"
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AppNavigation(viewModel: MainViewModel) {
|
||||
val isInitialized by viewModel.isInitialized.collectAsStateWithLifecycle()
|
||||
val onboardingDone by viewModel.onboardingDone.collectAsStateWithLifecycle()
|
||||
|
||||
if (!isInitialized) {
|
||||
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
val navController = rememberNavController()
|
||||
val startDestination = if (onboardingDone) Routes.HOME else Routes.ONBOARDING
|
||||
|
||||
NavHost(navController = navController, startDestination = startDestination) {
|
||||
|
||||
composable(Routes.ONBOARDING) {
|
||||
OnboardingScreen(
|
||||
onSetupServer = { navController.navigate(Routes.SSH_SETUP) },
|
||||
onSkip = {
|
||||
viewModel.setOnboardingDone()
|
||||
navController.navigate(Routes.HOME) {
|
||||
popUpTo(Routes.ONBOARDING) { inclusive = true }
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
composable(Routes.SSH_SETUP) {
|
||||
SshSetupScreen(
|
||||
viewModel = viewModel,
|
||||
onConnected = { navController.navigate(Routes.SERVER_MANAGEMENT) },
|
||||
onBack = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
|
||||
composable(Routes.SERVER_MANAGEMENT) {
|
||||
ServerManagementScreen(
|
||||
viewModel = viewModel,
|
||||
onContinue = { navController.navigate(Routes.CLIENT_SETUP) },
|
||||
onBack = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
|
||||
composable(Routes.CLIENT_SETUP) {
|
||||
ClientSetupScreen(
|
||||
viewModel = viewModel,
|
||||
onFinish = {
|
||||
viewModel.setOnboardingDone()
|
||||
navController.navigate(Routes.HOME) {
|
||||
popUpTo(Routes.ONBOARDING) { inclusive = true }
|
||||
}
|
||||
},
|
||||
onBack = { navController.popBackStack() }
|
||||
)
|
||||
}
|
||||
|
||||
composable(Routes.HOME) {
|
||||
HomeScreen(
|
||||
viewModel = viewModel,
|
||||
onNavigateToSshSetup = { navController.navigate(Routes.SSH_SETUP) },
|
||||
onNavigateToClientSetup = { navController.navigate(Routes.CLIENT_SETUP) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)
|
||||
|
||||
package com.vkturn.proxy.ui.screens
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Divider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Slider
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableFloatStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.vkturn.proxy.data.ClientConfig
|
||||
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||
|
||||
@Composable
|
||||
fun ClientSetupScreen(
|
||||
viewModel: MainViewModel,
|
||||
onFinish: () -> Unit,
|
||||
onBack: () -> Unit
|
||||
) {
|
||||
val saved by viewModel.clientConfig.collectAsStateWithLifecycle()
|
||||
|
||||
var serverAddress by rememberSaveable(saved.serverAddress) { mutableStateOf(saved.serverAddress) }
|
||||
var vkLink by rememberSaveable(saved.vkLink) { mutableStateOf(saved.vkLink) }
|
||||
var threads by rememberSaveable(saved.threads) { mutableFloatStateOf(saved.threads.toFloat()) }
|
||||
var useUdp by rememberSaveable(saved.useUdp) { mutableStateOf(saved.useUdp) }
|
||||
var noDtls by rememberSaveable(saved.noDtls) { mutableStateOf(saved.noDtls) }
|
||||
var localPort by rememberSaveable(saved.localPort) { mutableStateOf(saved.localPort) }
|
||||
var showAdvanced by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Настройка клиента") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.Filled.ArrowBack, contentDescription = "Назад")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(horizontal = 24.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
|
||||
// ── Сервер ───────────────────────────────────────────────────
|
||||
Text("Подключение", style = MaterialTheme.typography.titleMedium)
|
||||
|
||||
OutlinedTextField(
|
||||
value = serverAddress,
|
||||
onValueChange = { serverAddress = it },
|
||||
label = { Text("Адрес vk-turn-proxy сервера") },
|
||||
placeholder = { Text("1.2.3.4:56000") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
supportingText = {
|
||||
Text("IP и порт, на котором запущен vk-turn-proxy на вашем VPS")
|
||||
}
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = vkLink,
|
||||
onValueChange = { vkLink = it },
|
||||
label = { Text("Ссылка VK-звонок / Yandex Telemost") },
|
||||
placeholder = { Text("https://vk.com/call/...") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
minLines = 2,
|
||||
maxLines = 4,
|
||||
supportingText = {
|
||||
Text("VK: Звонки → Создать → Скопировать ссылку (не нажимайте «Завершить»). Тип определяется автоматически.")
|
||||
}
|
||||
)
|
||||
|
||||
Divider()
|
||||
|
||||
// ── Параметры ─────────────────────────────────────────────────
|
||||
Text("Параметры", style = MaterialTheme.typography.titleMedium)
|
||||
|
||||
Column {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Column {
|
||||
Text("Потоки: ${threads.toInt()}", style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
"Рекомендуется 4–8",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f)
|
||||
)
|
||||
}
|
||||
}
|
||||
Slider(
|
||||
value = threads,
|
||||
onValueChange = { threads = it },
|
||||
valueRange = 1f..8f,
|
||||
steps = 6,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
}
|
||||
|
||||
SwitchRow(
|
||||
label = "UDP-режим",
|
||||
description = "Снижает задержки и повышает стабильность",
|
||||
checked = useUdp,
|
||||
onCheckedChange = { useUdp = it }
|
||||
)
|
||||
|
||||
SwitchRow(
|
||||
label = "Без DTLS-шифрования",
|
||||
description = "Может ускорить соединение, повышает риск блокировки",
|
||||
checked = noDtls,
|
||||
onCheckedChange = { noDtls = it }
|
||||
)
|
||||
|
||||
Divider()
|
||||
|
||||
// ── Дополнительно (сворачиваемый блок) ───────────────────────
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant
|
||||
),
|
||||
onClick = { showAdvanced = !showAdvanced }
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Text("Дополнительно", style = MaterialTheme.typography.labelLarge)
|
||||
Icon(
|
||||
if (showAdvanced) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
AnimatedVisibility(visible = showAdvanced) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedTextField(
|
||||
value = localPort,
|
||||
onValueChange = { localPort = it },
|
||||
label = { Text("Локальный адрес прослушивания") },
|
||||
placeholder = { Text("127.0.0.1:9000") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
supportingText = {
|
||||
Text("Адрес, на котором клиент принимает трафик от WireGuard/Hysteria")
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
viewModel.saveClientConfig(
|
||||
ClientConfig(
|
||||
serverAddress = serverAddress.trim(),
|
||||
vkLink = vkLink.trim(),
|
||||
threads = threads.toInt(),
|
||||
useUdp = useUdp,
|
||||
noDtls = noDtls,
|
||||
localPort = localPort.trim()
|
||||
)
|
||||
)
|
||||
onFinish()
|
||||
},
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(56.dp),
|
||||
enabled = serverAddress.isNotBlank() && vkLink.isNotBlank(),
|
||||
shape = MaterialTheme.shapes.large
|
||||
) {
|
||||
Text("Завершить настройку", style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SwitchRow(
|
||||
label: String,
|
||||
description: String,
|
||||
checked: Boolean,
|
||||
onCheckedChange: (Boolean) -> Unit
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(label, style = MaterialTheme.typography.bodyMedium)
|
||||
Text(
|
||||
description,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f)
|
||||
)
|
||||
}
|
||||
Switch(checked = checked, onCheckedChange = onCheckedChange)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
@file:OptIn(
|
||||
androidx.compose.material3.ExperimentalMaterial3Api::class,
|
||||
androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class
|
||||
)
|
||||
|
||||
package com.vkturn.proxy.ui.screens
|
||||
|
||||
import androidx.compose.animation.animateColorAsState
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.CloudDownload
|
||||
import androidx.compose.material.icons.filled.Error
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.Settings
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.CircularWavyProgressIndicator
|
||||
import androidx.compose.material3.Divider
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.LinearWavyProgressIndicator
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.ModalBottomSheet
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.material3.rememberModalBottomSheetState
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.vkturn.proxy.ui.theme.StatusGreen
|
||||
import com.vkturn.proxy.ui.theme.StatusGreenDark
|
||||
import com.vkturn.proxy.ui.theme.StatusRed
|
||||
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||
import com.vkturn.proxy.viewmodel.ProxyState
|
||||
import com.vkturn.proxy.viewmodel.ServerState
|
||||
import com.vkturn.proxy.viewmodel.SshConnectionState
|
||||
|
||||
@Composable
|
||||
fun HomeScreen(
|
||||
viewModel: MainViewModel,
|
||||
onNavigateToSshSetup: () -> Unit,
|
||||
onNavigateToClientSetup: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val proxyState by viewModel.proxyState.collectAsStateWithLifecycle()
|
||||
val sshState by viewModel.sshState.collectAsStateWithLifecycle()
|
||||
val serverState by viewModel.serverState.collectAsStateWithLifecycle()
|
||||
val clientConfig by viewModel.clientConfig.collectAsStateWithLifecycle()
|
||||
val logs by viewModel.logs.collectAsStateWithLifecycle()
|
||||
|
||||
var showBottomSheet by rememberSaveable { mutableStateOf(false) }
|
||||
var showOverflowMenu by remember { mutableStateOf(false) }
|
||||
val bottomSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("VK TURN Proxy") },
|
||||
actions = {
|
||||
IconButton(onClick = { showOverflowMenu = true }) {
|
||||
Icon(Icons.Filled.MoreVert, contentDescription = "Меню")
|
||||
}
|
||||
DropdownMenu(
|
||||
expanded = showOverflowMenu,
|
||||
onDismissRequest = { showOverflowMenu = false }
|
||||
) {
|
||||
DropdownMenuItem(
|
||||
text = { Text("Настройки сервера") },
|
||||
leadingIcon = { Icon(Icons.Filled.Settings, null, Modifier.size(18.dp)) },
|
||||
onClick = { showOverflowMenu = false; onNavigateToSshSetup() }
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text("Настройки клиента") },
|
||||
leadingIcon = { Icon(Icons.Filled.Settings, null, Modifier.size(18.dp)) },
|
||||
onClick = { showOverflowMenu = false; onNavigateToClientSetup() }
|
||||
)
|
||||
DropdownMenuItem(
|
||||
text = { Text("Все настройки") },
|
||||
leadingIcon = { Icon(Icons.Filled.Info, null, Modifier.size(18.dp)) },
|
||||
onClick = { showOverflowMenu = false; showBottomSheet = true }
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) }
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Spacer(Modifier.height(40.dp))
|
||||
|
||||
// Big power button
|
||||
ProxyToggleButton(
|
||||
state = proxyState,
|
||||
onClick = {
|
||||
when (proxyState) {
|
||||
is ProxyState.Idle, is ProxyState.Error -> viewModel.startProxy(context)
|
||||
is ProxyState.Running -> viewModel.stopProxy(context)
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
|
||||
// State label
|
||||
Text(
|
||||
text = when (proxyState) {
|
||||
is ProxyState.Running -> "Прокси активен"
|
||||
is ProxyState.Starting -> "Подключение..."
|
||||
is ProxyState.Error -> (proxyState as ProxyState.Error).message
|
||||
else -> "Нажмите для запуска"
|
||||
},
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
color = when (proxyState) {
|
||||
is ProxyState.Running -> StatusGreen
|
||||
is ProxyState.Error -> MaterialTheme.colorScheme.error
|
||||
else -> MaterialTheme.colorScheme.onBackground.copy(alpha = 0.65f)
|
||||
},
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(40.dp))
|
||||
|
||||
// Config summary card
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp),
|
||||
onClick = { showBottomSheet = true },
|
||||
elevation = CardDefaults.cardElevation(2.dp)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text("Текущие настройки", style = MaterialTheme.typography.titleSmall)
|
||||
Icon(
|
||||
Icons.Filled.Settings,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
if (clientConfig.serverAddress.isNotBlank()) {
|
||||
ConfigRow("Сервер", clientConfig.serverAddress)
|
||||
ConfigRow("Потоки", "${clientConfig.threads}")
|
||||
ConfigRow("UDP", if (clientConfig.useUdp) "Вкл" else "Выкл")
|
||||
ConfigRow("Локальный порт", clientConfig.localPort)
|
||||
} else {
|
||||
Text(
|
||||
"Не настроено. Нажмите для настройки.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
// SSH status row
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 24.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(8.dp)
|
||||
.background(
|
||||
if (sshState is SshConnectionState.Connected) StatusGreen
|
||||
else MaterialTheme.colorScheme.outline,
|
||||
CircleShape
|
||||
)
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
when (sshState) {
|
||||
is SshConnectionState.Connected -> "SSH: ${(sshState as SshConnectionState.Connected).ip}"
|
||||
is SshConnectionState.Connecting -> "SSH: подключение..."
|
||||
is SshConnectionState.Error -> "SSH: ошибка"
|
||||
else -> "SSH: не подключено"
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f)
|
||||
)
|
||||
if (sshState !is SshConnectionState.Connected) {
|
||||
Spacer(Modifier.width(8.dp))
|
||||
TextButton(onClick = { viewModel.reconnectSsh() }, modifier = Modifier.height(28.dp)) {
|
||||
Text("Переподключить", style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(32.dp))
|
||||
}
|
||||
}
|
||||
|
||||
// Bottom sheet with all settings
|
||||
if (showBottomSheet) {
|
||||
ModalBottomSheet(
|
||||
onDismissRequest = { showBottomSheet = false },
|
||||
sheetState = bottomSheetState
|
||||
) {
|
||||
SettingsBottomSheet(
|
||||
viewModel = viewModel,
|
||||
onNavigateToSshSetup = { showBottomSheet = false; onNavigateToSshSetup() },
|
||||
onNavigateToClientSetup = { showBottomSheet = false; onNavigateToClientSetup() },
|
||||
onDismiss = { showBottomSheet = false }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) {
|
||||
val containerColor by animateColorAsState(
|
||||
targetValue = when (state) {
|
||||
is ProxyState.Running -> StatusGreenDark
|
||||
is ProxyState.Error -> MaterialTheme.colorScheme.errorContainer
|
||||
is ProxyState.Starting -> MaterialTheme.colorScheme.secondaryContainer
|
||||
else -> MaterialTheme.colorScheme.primaryContainer
|
||||
},
|
||||
animationSpec = tween(600),
|
||||
label = "btn_bg"
|
||||
)
|
||||
val contentColor by animateColorAsState(
|
||||
targetValue = when (state) {
|
||||
is ProxyState.Running -> StatusGreen
|
||||
is ProxyState.Error -> MaterialTheme.colorScheme.error
|
||||
is ProxyState.Starting -> MaterialTheme.colorScheme.secondary
|
||||
else -> MaterialTheme.colorScheme.primary
|
||||
},
|
||||
animationSpec = tween(600),
|
||||
label = "btn_fg"
|
||||
)
|
||||
val scale by animateFloatAsState(
|
||||
targetValue = if (state is ProxyState.Starting) 0.96f else 1f,
|
||||
animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
|
||||
label = "btn_scale"
|
||||
)
|
||||
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
modifier = Modifier
|
||||
.size(148.dp)
|
||||
.scale(scale)
|
||||
.clip(CircleShape),
|
||||
shape = CircleShape,
|
||||
color = containerColor,
|
||||
shadowElevation = if (state is ProxyState.Running) 12.dp else 4.dp
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
when (state) {
|
||||
is ProxyState.Starting -> CircularWavyProgressIndicator(color = contentColor)
|
||||
is ProxyState.Running -> Icon(
|
||||
Icons.Filled.CheckCircle, null,
|
||||
Modifier.size(52.dp), tint = contentColor
|
||||
)
|
||||
is ProxyState.Error -> Icon(
|
||||
Icons.Filled.Error, null,
|
||||
Modifier.size(52.dp), tint = contentColor
|
||||
)
|
||||
else -> Icon(
|
||||
Icons.Filled.PlayArrow, null,
|
||||
Modifier.size(52.dp), tint = contentColor
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SettingsBottomSheet(
|
||||
viewModel: MainViewModel,
|
||||
onNavigateToSshSetup: () -> Unit,
|
||||
onNavigateToClientSetup: () -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val sshState by viewModel.sshState.collectAsStateWithLifecycle()
|
||||
val serverState by viewModel.serverState.collectAsStateWithLifecycle()
|
||||
val clientConfig by viewModel.clientConfig.collectAsStateWithLifecycle()
|
||||
val logs by viewModel.logs.collectAsStateWithLifecycle()
|
||||
|
||||
val isConnected = sshState is SshConnectionState.Connected
|
||||
val isWorking = serverState is ServerState.Working || serverState is ServerState.Checking
|
||||
val serverKnown = serverState as? ServerState.Known
|
||||
var showLogs by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 32.dp)
|
||||
.verticalScroll(rememberScrollState())
|
||||
) {
|
||||
// ── Сервер ────────────────────────────────────────────────────────
|
||||
ListItem(
|
||||
headlineContent = { Text("Сервер", style = MaterialTheme.typography.titleSmall) },
|
||||
trailingContent = {
|
||||
TextButton(onClick = onNavigateToSshSetup) { Text("Изменить") }
|
||||
}
|
||||
)
|
||||
Divider()
|
||||
|
||||
ListItem(
|
||||
headlineContent = { Text("SSH-соединение") },
|
||||
supportingContent = {
|
||||
Text(
|
||||
when (sshState) {
|
||||
is SshConnectionState.Connected -> "Подключено: ${(sshState as SshConnectionState.Connected).ip}"
|
||||
is SshConnectionState.Connecting -> "Подключение..."
|
||||
is SshConnectionState.Error -> "Ошибка: ${(sshState as SshConnectionState.Error).message}"
|
||||
else -> "Не подключено"
|
||||
}
|
||||
)
|
||||
},
|
||||
trailingContent = {
|
||||
if (sshState !is SshConnectionState.Connected) {
|
||||
IconButton(onClick = { viewModel.reconnectSsh() }) {
|
||||
Icon(Icons.Filled.Refresh, null)
|
||||
}
|
||||
} else {
|
||||
Box(Modifier.size(10.dp).background(StatusGreen, CircleShape))
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
ListItem(
|
||||
headlineContent = { Text("vk-turn-proxy") },
|
||||
supportingContent = {
|
||||
Text(
|
||||
when {
|
||||
serverKnown?.running == true -> "Запущен"
|
||||
serverKnown?.installed == true -> "Установлен, не запущен"
|
||||
serverKnown?.installed == false -> "Не установлен"
|
||||
isWorking -> (serverState as? ServerState.Working)?.action ?: "Проверка..."
|
||||
else -> "Статус неизвестен"
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
if (isWorking) {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp))
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
FilledTonalButton(
|
||||
onClick = { viewModel.installServer() },
|
||||
enabled = isConnected && !isWorking,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Icon(Icons.Filled.CloudDownload, null, Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text("Обновить", style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
Button(
|
||||
onClick = { viewModel.startServer() },
|
||||
enabled = isConnected && !isWorking && serverKnown?.installed == true && serverKnown?.running == false,
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Icon(Icons.Filled.PlayArrow, null, Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text("Запустить", style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { viewModel.stopServer() },
|
||||
enabled = isConnected && !isWorking && serverKnown?.running == true,
|
||||
modifier = Modifier.weight(1f),
|
||||
colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.error)
|
||||
) {
|
||||
Icon(Icons.Filled.Stop, null, Modifier.size(16.dp))
|
||||
Spacer(Modifier.width(4.dp))
|
||||
Text("Стоп", style = MaterialTheme.typography.labelSmall)
|
||||
}
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
// ── Клиент ────────────────────────────────────────────────────────
|
||||
ListItem(
|
||||
headlineContent = { Text("Клиент", style = MaterialTheme.typography.titleSmall) },
|
||||
trailingContent = {
|
||||
TextButton(onClick = onNavigateToClientSetup) { Text("Изменить") }
|
||||
}
|
||||
)
|
||||
Divider()
|
||||
|
||||
if (clientConfig.serverAddress.isNotBlank()) {
|
||||
ListItem(headlineContent = { Text("Сервер") },
|
||||
supportingContent = { Text(clientConfig.serverAddress) })
|
||||
ListItem(headlineContent = { Text("Ссылка VK/Yandex") },
|
||||
supportingContent = {
|
||||
Text(
|
||||
clientConfig.vkLink.take(60) + if (clientConfig.vkLink.length > 60) "..." else "",
|
||||
maxLines = 2
|
||||
)
|
||||
})
|
||||
ListItem(headlineContent = { Text("Потоки / UDP / DTLS") },
|
||||
supportingContent = {
|
||||
Text("${clientConfig.threads} потоков · UDP: ${if (clientConfig.useUdp) "вкл" else "выкл"} · DTLS: ${if (clientConfig.noDtls) "выкл" else "вкл"}")
|
||||
})
|
||||
} else {
|
||||
ListItem(
|
||||
headlineContent = { Text("Не настроено") },
|
||||
supportingContent = { Text("Нажмите «Изменить» для настройки клиента") }
|
||||
)
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
// ── Логи ─────────────────────────────────────────────────────────
|
||||
ListItem(
|
||||
headlineContent = { Text("Логи", style = MaterialTheme.typography.titleSmall) },
|
||||
trailingContent = {
|
||||
Row {
|
||||
TextButton(onClick = { viewModel.clearLogs() }) { Text("Очистить") }
|
||||
TextButton(onClick = { showLogs = !showLogs }) {
|
||||
Text(if (showLogs) "Скрыть" else "Показать")
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (showLogs) {
|
||||
val recentLogs = logs.takeLast(30)
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant
|
||||
)
|
||||
) {
|
||||
Column(modifier = Modifier.padding(12.dp)) {
|
||||
if (recentLogs.isEmpty()) {
|
||||
Text(
|
||||
"Нет логов",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
|
||||
)
|
||||
} else {
|
||||
recentLogs.forEach { line ->
|
||||
Text(
|
||||
line,
|
||||
style = MaterialTheme.typography.bodySmall.copy(
|
||||
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace
|
||||
),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConfigRow(label: String, value: String) {
|
||||
Row(
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text(label, style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f))
|
||||
Text(value, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package com.vkturn.proxy.ui.screens
|
||||
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.RepeatMode
|
||||
import androidx.compose.animation.core.animateFloat
|
||||
import androidx.compose.animation.core.infiniteRepeatable
|
||||
import androidx.compose.animation.core.rememberInfiniteTransition
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Security
|
||||
import androidx.compose.material.icons.filled.Wifi
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun OnboardingScreen(
|
||||
onSetupServer: () -> Unit,
|
||||
onSkip: () -> Unit
|
||||
) {
|
||||
val infiniteTransition = rememberInfiniteTransition(label = "icon_pulse")
|
||||
val pulseScale by infiniteTransition.animateFloat(
|
||||
initialValue = 1f,
|
||||
targetValue = 1.08f,
|
||||
animationSpec = infiniteRepeatable(
|
||||
animation = tween(1600, easing = FastOutSlowInEasing),
|
||||
repeatMode = RepeatMode.Reverse
|
||||
),
|
||||
label = "pulse"
|
||||
)
|
||||
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.background(
|
||||
Brush.verticalGradient(
|
||||
listOf(
|
||||
MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.25f),
|
||||
MaterialTheme.colorScheme.background
|
||||
)
|
||||
)
|
||||
)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Spacer(Modifier.height(56.dp))
|
||||
|
||||
// Illustration + text
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(148.dp)
|
||||
.scale(pulseScale)
|
||||
.background(MaterialTheme.colorScheme.primaryContainer, CircleShape),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Filled.Security,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(80.dp),
|
||||
tint = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(40.dp))
|
||||
|
||||
Text(
|
||||
text = "VK TURN Proxy",
|
||||
style = MaterialTheme.typography.displaySmall,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(12.dp))
|
||||
|
||||
Text(
|
||||
text = "Проксируйте WireGuard и Hysteria‑трафик\nчерез TURN‑серверы VK Calls и Yandex Telemost",
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.65f),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(28.dp))
|
||||
|
||||
// Privacy notice
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(16.dp),
|
||||
verticalAlignment = Alignment.Top
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Security,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.secondary,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
"Мы не собираем никаких данных. Все настройки (SSH-доступ, параметры прокси) хранятся исключительно на вашем устройстве.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Action buttons
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Button(
|
||||
onClick = onSetupServer,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(56.dp),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
elevation = ButtonDefaults.buttonElevation(defaultElevation = 4.dp)
|
||||
) {
|
||||
Icon(Icons.Filled.Wifi, contentDescription = null)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text("Настроить сервер", style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(12.dp))
|
||||
|
||||
TextButton(onClick = onSkip) {
|
||||
Text("У меня уже есть настройки")
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
@file:OptIn(
|
||||
androidx.compose.material3.ExperimentalMaterial3Api::class,
|
||||
androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class
|
||||
)
|
||||
|
||||
package com.vkturn.proxy.ui.screens
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.ArrowForward
|
||||
import androidx.compose.material.icons.filled.CloudDownload
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.FilledTonalButton
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.LinearWavyProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.SnackbarHost
|
||||
import androidx.compose.material3.SnackbarHostState
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.vkturn.proxy.ui.theme.StatusGreen
|
||||
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||
import com.vkturn.proxy.viewmodel.ServerState
|
||||
import com.vkturn.proxy.viewmodel.SshConnectionState
|
||||
|
||||
@Composable
|
||||
fun ServerManagementScreen(
|
||||
viewModel: MainViewModel,
|
||||
onContinue: () -> Unit,
|
||||
onBack: () -> Unit
|
||||
) {
|
||||
val sshState by viewModel.sshState.collectAsStateWithLifecycle()
|
||||
val serverState by viewModel.serverState.collectAsStateWithLifecycle()
|
||||
val sshConfig by viewModel.sshConfig.collectAsStateWithLifecycle()
|
||||
val savedListen by viewModel.proxyListen.collectAsStateWithLifecycle()
|
||||
val savedConnect by viewModel.proxyConnect.collectAsStateWithLifecycle()
|
||||
|
||||
var proxyListen by rememberSaveable(savedListen) { mutableStateOf(savedListen) }
|
||||
var proxyConnect by rememberSaveable(savedConnect) { mutableStateOf(savedConnect) }
|
||||
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
val isConnected = sshState is SshConnectionState.Connected
|
||||
val isWorking = serverState is ServerState.Working || serverState is ServerState.Checking
|
||||
val serverKnown = serverState as? ServerState.Known
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Управление сервером") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.Filled.ArrowBack, contentDescription = "Назад")
|
||||
}
|
||||
},
|
||||
actions = {
|
||||
SshStatusBadge(sshState = sshState, ip = sshConfig.ip)
|
||||
}
|
||||
)
|
||||
},
|
||||
snackbarHost = { SnackbarHost(snackbarHostState) }
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(horizontal = 24.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
|
||||
// Status card
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(20.dp)) {
|
||||
Text("Статус сервера", style = MaterialTheme.typography.titleMedium)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
StatusRow("SSH‑соединение", isConnected)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
StatusRow("vk‑turn‑proxy", serverKnown?.running == true)
|
||||
|
||||
when (serverState) {
|
||||
is ServerState.Checking -> {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
is ServerState.Working -> {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
(serverState as ServerState.Working).action,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.secondary
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
LinearWavyProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
is ServerState.Error -> {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
"Ошибка: ${(serverState as ServerState.Error).message}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Server config
|
||||
Text("Конфигурация сервера", style = MaterialTheme.typography.titleMedium)
|
||||
|
||||
OutlinedTextField(
|
||||
value = proxyListen,
|
||||
onValueChange = { proxyListen = it },
|
||||
label = { Text("Порт прослушивания") },
|
||||
placeholder = { Text("0.0.0.0:56000") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
supportingText = { Text("Порт, на котором сервер принимает подключения от клиентов") }
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = proxyConnect,
|
||||
onValueChange = { proxyConnect = it },
|
||||
label = { Text("Адрес TURN‑клиента") },
|
||||
placeholder = { Text("127.0.0.1:40537") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
supportingText = { Text("Локальный WireGuard/Hysteria-клиент на стороне сервера") }
|
||||
)
|
||||
|
||||
// Action buttons
|
||||
FilledTonalButton(
|
||||
onClick = {
|
||||
viewModel.saveProxyServerConfig(proxyListen, proxyConnect)
|
||||
viewModel.installServer()
|
||||
},
|
||||
enabled = isConnected && !isWorking,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(52.dp),
|
||||
shape = MaterialTheme.shapes.large
|
||||
) {
|
||||
Icon(Icons.Filled.CloudDownload, null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Установить / Обновить vk‑turn‑proxy")
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
viewModel.saveProxyServerConfig(proxyListen, proxyConnect)
|
||||
viewModel.startServer()
|
||||
},
|
||||
enabled = isConnected && !isWorking
|
||||
&& serverKnown?.installed == true
|
||||
&& serverKnown?.running == false,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(52.dp),
|
||||
shape = MaterialTheme.shapes.large
|
||||
) {
|
||||
Icon(Icons.Filled.PlayArrow, null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Запустить сервер")
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
onClick = { viewModel.stopServer() },
|
||||
enabled = isConnected && !isWorking && serverKnown?.running == true,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(52.dp),
|
||||
shape = MaterialTheme.shapes.large,
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
contentColor = MaterialTheme.colorScheme.error
|
||||
)
|
||||
) {
|
||||
Icon(Icons.Filled.Stop, null)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Остановить сервер")
|
||||
}
|
||||
|
||||
if (serverKnown?.running == true) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Button(
|
||||
onClick = onContinue,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(56.dp),
|
||||
shape = MaterialTheme.shapes.large
|
||||
) {
|
||||
Text("Продолжить настройку клиента")
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Icon(Icons.Filled.ArrowForward, null)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SshStatusBadge(sshState: SshConnectionState, ip: String) {
|
||||
val connected = sshState is SshConnectionState.Connected
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
modifier = Modifier.padding(end = 16.dp)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(8.dp)
|
||||
.background(if (connected) StatusGreen else MaterialTheme.colorScheme.error, CircleShape)
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
if (connected) ip else "Не подключено",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusRow(label: String, isActive: Boolean) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Text(label, style = MaterialTheme.typography.bodyMedium)
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(8.dp)
|
||||
.background(
|
||||
if (isActive) StatusGreen else MaterialTheme.colorScheme.outline,
|
||||
CircleShape
|
||||
)
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
if (isActive) "Активно" else "Неактивно",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = if (isActive) StatusGreen else MaterialTheme.colorScheme.outline
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
@file:OptIn(
|
||||
androidx.compose.material3.ExperimentalMaterial3Api::class,
|
||||
androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class
|
||||
)
|
||||
|
||||
package com.vkturn.proxy.ui.screens
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.ArrowBack
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.Error
|
||||
import androidx.compose.material.icons.filled.RadioButtonChecked
|
||||
import androidx.compose.material.icons.filled.RadioButtonUnchecked
|
||||
import androidx.compose.material.icons.filled.Visibility
|
||||
import androidx.compose.material.icons.filled.VisibilityOff
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CardDefaults
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExposedDropdownMenuBox
|
||||
import androidx.compose.material3.ExposedDropdownMenuDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.LinearWavyProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.MenuAnchorType
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Scaffold
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.vkturn.proxy.data.SshConfig
|
||||
import com.vkturn.proxy.viewmodel.MainViewModel
|
||||
import com.vkturn.proxy.viewmodel.SshConnectionState
|
||||
|
||||
@Composable
|
||||
fun SshSetupScreen(
|
||||
viewModel: MainViewModel,
|
||||
onConnected: () -> Unit,
|
||||
onBack: () -> Unit
|
||||
) {
|
||||
val sshState by viewModel.sshState.collectAsStateWithLifecycle()
|
||||
val savedConfig by viewModel.sshConfig.collectAsStateWithLifecycle()
|
||||
|
||||
var ip by rememberSaveable(savedConfig.ip) { mutableStateOf(savedConfig.ip) }
|
||||
var port by rememberSaveable(savedConfig.port) { mutableStateOf(savedConfig.port.toString()) }
|
||||
var username by rememberSaveable(savedConfig.username) { mutableStateOf(savedConfig.username) }
|
||||
var password by rememberSaveable { mutableStateOf(savedConfig.password) }
|
||||
var authType by rememberSaveable(savedConfig.authType) { mutableStateOf(savedConfig.authType) }
|
||||
var sshKey by rememberSaveable(savedConfig.sshKey) { mutableStateOf(savedConfig.sshKey) }
|
||||
var showPassword by remember { mutableStateOf(false) }
|
||||
var authDropdownExpanded by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(sshState) {
|
||||
if (sshState is SshConnectionState.Connected) onConnected()
|
||||
}
|
||||
|
||||
val isConnecting = sshState is SshConnectionState.Connecting
|
||||
|
||||
Scaffold(
|
||||
topBar = {
|
||||
TopAppBar(
|
||||
title = { Text("Подключение к серверу") },
|
||||
navigationIcon = {
|
||||
IconButton(onClick = onBack) {
|
||||
Icon(Icons.Filled.ArrowBack, contentDescription = "Назад")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
) { padding ->
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.padding(horizontal = 24.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
|
||||
if (!isConnecting) {
|
||||
FormSection(
|
||||
ip = ip, onIpChange = { ip = it },
|
||||
port = port, onPortChange = { port = it },
|
||||
username = username, onUsernameChange = { username = it },
|
||||
password = password, onPasswordChange = { password = it },
|
||||
showPassword = showPassword, onTogglePassword = { showPassword = !showPassword },
|
||||
authType = authType, onAuthTypeChange = { authType = it },
|
||||
sshKey = sshKey, onSshKeyChange = { sshKey = it },
|
||||
authDropdownExpanded = authDropdownExpanded,
|
||||
onAuthDropdownChange = { authDropdownExpanded = it },
|
||||
sshState = sshState,
|
||||
onConnect = {
|
||||
viewModel.connectSsh(
|
||||
SshConfig(
|
||||
ip = ip.trim(),
|
||||
port = port.toIntOrNull() ?: 22,
|
||||
username = username.trim(),
|
||||
password = password,
|
||||
authType = authType,
|
||||
sshKey = sshKey
|
||||
)
|
||||
)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
Spacer(Modifier.height(32.dp))
|
||||
ConnectionProgressCard(step = (sshState as SshConnectionState.Connecting).step)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FormSection(
|
||||
ip: String, onIpChange: (String) -> Unit,
|
||||
port: String, onPortChange: (String) -> Unit,
|
||||
username: String, onUsernameChange: (String) -> Unit,
|
||||
password: String, onPasswordChange: (String) -> Unit,
|
||||
showPassword: Boolean, onTogglePassword: () -> Unit,
|
||||
authType: String, onAuthTypeChange: (String) -> Unit,
|
||||
sshKey: String, onSshKeyChange: (String) -> Unit,
|
||||
authDropdownExpanded: Boolean, onAuthDropdownChange: (Boolean) -> Unit,
|
||||
sshState: SshConnectionState,
|
||||
onConnect: () -> Unit
|
||||
) {
|
||||
Text("Данные сервера", style = MaterialTheme.typography.titleMedium)
|
||||
|
||||
OutlinedTextField(
|
||||
value = ip,
|
||||
onValueChange = onIpChange,
|
||||
label = { Text("IP-адрес сервера") },
|
||||
placeholder = { Text("1.2.3.4") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri)
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = port,
|
||||
onValueChange = onPortChange,
|
||||
label = { Text("SSH порт") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = onUsernameChange,
|
||||
label = { Text("Имя пользователя") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true
|
||||
)
|
||||
|
||||
ExposedDropdownMenuBox(
|
||||
expanded = authDropdownExpanded,
|
||||
onExpandedChange = onAuthDropdownChange,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
OutlinedTextField(
|
||||
value = if (authType == "PASSWORD") "Пароль" else "Приватный ключ",
|
||||
onValueChange = {},
|
||||
readOnly = true,
|
||||
label = { Text("Аутентификация") },
|
||||
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = authDropdownExpanded) },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.menuAnchor(MenuAnchorType.PrimaryNotEditable)
|
||||
)
|
||||
ExposedDropdownMenu(
|
||||
expanded = authDropdownExpanded,
|
||||
onDismissRequest = { onAuthDropdownChange(false) }
|
||||
) {
|
||||
DropdownMenuItem(text = { Text("Пароль") },
|
||||
onClick = { onAuthTypeChange("PASSWORD"); onAuthDropdownChange(false) })
|
||||
DropdownMenuItem(text = { Text("Приватный ключ") },
|
||||
onClick = { onAuthTypeChange("SSH_KEY"); onAuthDropdownChange(false) })
|
||||
}
|
||||
}
|
||||
|
||||
if (authType == "PASSWORD") {
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = onPasswordChange,
|
||||
label = { Text("Пароль") },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
singleLine = true,
|
||||
visualTransformation = if (showPassword) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
trailingIcon = {
|
||||
IconButton(onClick = onTogglePassword) {
|
||||
Icon(
|
||||
if (showPassword) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
|
||||
contentDescription = null
|
||||
)
|
||||
}
|
||||
},
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)
|
||||
)
|
||||
} else {
|
||||
OutlinedTextField(
|
||||
value = sshKey,
|
||||
onValueChange = onSshKeyChange,
|
||||
label = { Text("Приватный ключ (PEM)") },
|
||||
placeholder = { Text("-----BEGIN RSA PRIVATE KEY-----\n...") },
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(160.dp),
|
||||
maxLines = 10
|
||||
)
|
||||
}
|
||||
|
||||
if (sshState is SshConnectionState.Error) {
|
||||
Card(
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)
|
||||
) {
|
||||
Row(modifier = Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Filled.Error, null, tint = MaterialTheme.colorScheme.error)
|
||||
Spacer(Modifier.width(12.dp))
|
||||
Text(
|
||||
sshState.message,
|
||||
color = MaterialTheme.colorScheme.onErrorContainer,
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = onConnect,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(56.dp),
|
||||
enabled = ip.isNotBlank() && when (authType) {
|
||||
"SSH_KEY" -> sshKey.isNotBlank()
|
||||
else -> password.isNotBlank()
|
||||
},
|
||||
shape = MaterialTheme.shapes.large
|
||||
) {
|
||||
Text("Подключиться", style = MaterialTheme.typography.labelLarge)
|
||||
}
|
||||
|
||||
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
|
||||
TextButton(onClick = { /* show help info */ }) {
|
||||
Text("Как получить SSH-доступ к серверу?")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConnectionProgressCard(step: String) {
|
||||
val steps = listOf(
|
||||
"Подключение к серверу...",
|
||||
"Аутентификация...",
|
||||
"Проверка SSH..."
|
||||
)
|
||||
val currentIndex = steps.indexOf(step).coerceAtLeast(0)
|
||||
|
||||
Card(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
elevation = CardDefaults.cardElevation(4.dp)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(20.dp)
|
||||
) {
|
||||
LinearWavyProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
|
||||
Text(
|
||||
text = step,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
|
||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||
steps.forEachIndexed { index, label ->
|
||||
val isDone = index < currentIndex
|
||||
val isActive = index == currentIndex
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = when {
|
||||
isDone -> Icons.Filled.CheckCircle
|
||||
isActive -> Icons.Filled.RadioButtonChecked
|
||||
else -> Icons.Filled.RadioButtonUnchecked
|
||||
},
|
||||
contentDescription = null,
|
||||
tint = when {
|
||||
isDone -> MaterialTheme.colorScheme.primary
|
||||
isActive -> MaterialTheme.colorScheme.secondary
|
||||
else -> MaterialTheme.colorScheme.outline
|
||||
},
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = if (isActive || isDone) MaterialTheme.colorScheme.onSurface
|
||||
else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.vkturn.proxy.ui.theme
|
||||
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
// Seed / brand colors used when dynamic color is unavailable
|
||||
val VkBlue = Color(0xFF0077FF)
|
||||
val VkBlueDark = Color(0xFF0055CC)
|
||||
val VkTeal = Color(0xFF19C29F)
|
||||
val StatusGreen = Color(0xFF4CAF50)
|
||||
val StatusGreenDark = Color(0xFF1B5E20)
|
||||
val StatusRed = Color(0xFFE53935)
|
||||
@@ -0,0 +1,60 @@
|
||||
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.material3.dynamicDarkColorScheme
|
||||
import androidx.compose.material3.dynamicLightColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.core.view.WindowCompat
|
||||
|
||||
private val DarkColorScheme = darkColorScheme(
|
||||
primary = VkBlue,
|
||||
secondary = VkTeal,
|
||||
tertiary = VkBlueDark
|
||||
)
|
||||
|
||||
private val LightColorScheme = lightColorScheme(
|
||||
primary = VkBlue,
|
||||
secondary = VkTeal,
|
||||
tertiary = VkBlueDark
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun VkTurnProxyTheme(
|
||||
darkTheme: Boolean = isSystemInDarkTheme(),
|
||||
// Material You dynamic color — enabled on Android 12+
|
||||
dynamicColor: Boolean = true,
|
||||
content: @Composable () -> Unit
|
||||
) {
|
||||
val colorScheme = when {
|
||||
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
|
||||
val context = LocalContext.current
|
||||
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
|
||||
}
|
||||
darkTheme -> DarkColorScheme
|
||||
else -> LightColorScheme
|
||||
}
|
||||
|
||||
val view = LocalView.current
|
||||
if (!view.isInEditMode) {
|
||||
SideEffect {
|
||||
val window = (view.context as Activity).window
|
||||
window.statusBarColor = colorScheme.background.toArgb()
|
||||
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
|
||||
}
|
||||
}
|
||||
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = Typography,
|
||||
content = content
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
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(
|
||||
displaySmall = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Bold,
|
||||
fontSize = 36.sp,
|
||||
lineHeight = 44.sp,
|
||||
letterSpacing = (-0.25).sp
|
||||
),
|
||||
titleLarge = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 22.sp,
|
||||
lineHeight = 28.sp,
|
||||
letterSpacing = 0.sp
|
||||
),
|
||||
titleMedium = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp,
|
||||
letterSpacing = 0.15.sp
|
||||
),
|
||||
bodyLarge = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 24.sp,
|
||||
letterSpacing = 0.5.sp
|
||||
),
|
||||
bodyMedium = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 20.sp,
|
||||
letterSpacing = 0.25.sp
|
||||
),
|
||||
bodySmall = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Normal,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 16.sp,
|
||||
letterSpacing = 0.4.sp
|
||||
),
|
||||
labelLarge = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 14.sp,
|
||||
lineHeight = 20.sp,
|
||||
letterSpacing = 0.1.sp
|
||||
),
|
||||
labelMedium = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 16.sp,
|
||||
letterSpacing = 0.5.sp
|
||||
),
|
||||
labelSmall = TextStyle(
|
||||
fontFamily = FontFamily.Default,
|
||||
fontWeight = FontWeight.Medium,
|
||||
fontSize = 11.sp,
|
||||
lineHeight = 16.sp,
|
||||
letterSpacing = 0.5.sp
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,272 @@
|
||||
package com.vkturn.proxy.viewmodel
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
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.data.ClientConfig
|
||||
import com.vkturn.proxy.data.SshConfig
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
// ── SSH connection states ──────────────────────────────────────────────────
|
||||
sealed class SshConnectionState {
|
||||
object Disconnected : SshConnectionState()
|
||||
data class Connecting(val step: String = "Подключение к серверу...") : SshConnectionState()
|
||||
data class Connected(val ip: String) : SshConnectionState()
|
||||
data class Error(val message: String) : SshConnectionState()
|
||||
}
|
||||
|
||||
// ── Remote server states ───────────────────────────────────────────────────
|
||||
sealed class ServerState {
|
||||
object Unknown : ServerState()
|
||||
object Checking : ServerState()
|
||||
data class Known(val installed: Boolean, val running: Boolean) : ServerState()
|
||||
data class Working(val action: String) : ServerState()
|
||||
data class Error(val message: String) : ServerState()
|
||||
}
|
||||
|
||||
// ── Local proxy client states ──────────────────────────────────────────────
|
||||
sealed class ProxyState {
|
||||
object Idle : ProxyState()
|
||||
object Starting : ProxyState()
|
||||
object Running : ProxyState()
|
||||
data class Error(val message: String) : ProxyState()
|
||||
}
|
||||
|
||||
class MainViewModel(application: Application) : AndroidViewModel(application) {
|
||||
|
||||
private val prefs = AppPreferences(application)
|
||||
private val sshManager = SSHManager()
|
||||
|
||||
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 _proxyState = MutableStateFlow<ProxyState>(ProxyState.Idle)
|
||||
val proxyState: StateFlow<ProxyState> = _proxyState.asStateFlow()
|
||||
|
||||
private val _logs = MutableStateFlow<List<String>>(emptyList())
|
||||
val logs: StateFlow<List<String>> = _logs.asStateFlow()
|
||||
|
||||
private val _isInitialized = MutableStateFlow(false)
|
||||
val isInitialized: StateFlow<Boolean> = _isInitialized.asStateFlow()
|
||||
|
||||
val sshConfig: StateFlow<SshConfig> = prefs.sshConfigFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig())
|
||||
|
||||
val clientConfig: StateFlow<ClientConfig> = prefs.clientConfigFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ClientConfig())
|
||||
|
||||
val onboardingDone: StateFlow<Boolean> = prefs.onboardingDoneFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
|
||||
|
||||
val proxyListen: StateFlow<String> = prefs.proxyListenFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "0.0.0.0:56000")
|
||||
|
||||
val proxyConnect: StateFlow<String> = prefs.proxyConnectFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "127.0.0.1:40537")
|
||||
|
||||
init {
|
||||
viewModelScope.launch {
|
||||
// Wait for first real emit from DataStore before showing UI
|
||||
onboardingDone.collect { _isInitialized.value = true }
|
||||
}
|
||||
|
||||
ProxyService.onLogReceived = { msg ->
|
||||
_logs.value = (_logs.value + msg).takeLast(200)
|
||||
}
|
||||
_logs.value = ProxyService.logBuffer.toList()
|
||||
|
||||
if (ProxyService.isRunning) _proxyState.value = ProxyState.Running
|
||||
}
|
||||
|
||||
// ── SSH ────────────────────────────────────────────────────────────────
|
||||
|
||||
fun connectSsh(config: SshConfig) {
|
||||
viewModelScope.launch {
|
||||
prefs.saveSshConfig(config)
|
||||
}
|
||||
sshManager.disconnect()
|
||||
_sshState.value = SshConnectionState.Connecting("Подключение к серверу...")
|
||||
|
||||
viewModelScope.launch {
|
||||
delay(400)
|
||||
_sshState.value = SshConnectionState.Connecting("Аутентификация...")
|
||||
delay(300)
|
||||
_sshState.value = SshConnectionState.Connecting("Проверка SSH...")
|
||||
|
||||
val result = sshManager.executeSilentCommand(
|
||||
config.ip, config.port, config.username, config.password, "echo OK"
|
||||
)
|
||||
if (result.trim() == "OK") {
|
||||
_sshState.value = SshConnectionState.Connected(config.ip)
|
||||
checkServerState(config)
|
||||
} else {
|
||||
_sshState.value = SshConnectionState.Error(result.removePrefix("ERROR: "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun reconnectSsh() {
|
||||
val cfg = sshConfig.value
|
||||
if (cfg.ip.isNotEmpty()) connectSsh(cfg)
|
||||
}
|
||||
|
||||
// ── Server management ──────────────────────────────────────────────────
|
||||
|
||||
fun checkServerState(config: SshConfig? = null) {
|
||||
val cfg = config ?: sshConfig.value
|
||||
if (cfg.ip.isEmpty()) return
|
||||
_serverState.value = ServerState.Checking
|
||||
|
||||
val checkCmd = """
|
||||
if ls /opt/vk-turn/server-linux-* >/dev/null 2>&1; then echo "INSTALLED:YES"; else echo "INSTALLED:NO"; fi
|
||||
if ps aux | grep -v grep | grep -q "server-linux-"; then echo "RUNNING:YES"; else echo "RUNNING:NO"; fi
|
||||
""".trimIndent()
|
||||
|
||||
viewModelScope.launch {
|
||||
val result = sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, checkCmd)
|
||||
_serverState.value = if (result.startsWith("ERROR")) {
|
||||
ServerState.Error(result.removePrefix("ERROR: "))
|
||||
} else {
|
||||
ServerState.Known(
|
||||
installed = result.contains("INSTALLED:YES"),
|
||||
running = result.contains("RUNNING:YES")
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun installServer() {
|
||||
val cfg = sshConfig.value
|
||||
if (cfg.ip.isEmpty()) return
|
||||
_serverState.value = ServerState.Working("Установка vk-turn-proxy...")
|
||||
|
||||
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 && echo "DONE"
|
||||
""".trimIndent()
|
||||
|
||||
viewModelScope.launch {
|
||||
sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script)
|
||||
delay(1000)
|
||||
checkServerState(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
fun startServer() {
|
||||
val cfg = sshConfig.value
|
||||
if (cfg.ip.isEmpty()) return
|
||||
_serverState.value = ServerState.Working("Запуск сервера...")
|
||||
|
||||
val l = proxyListen.value
|
||||
val c = proxyConnect.value
|
||||
val script = """
|
||||
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 "STARTED"
|
||||
""".trimIndent()
|
||||
|
||||
viewModelScope.launch {
|
||||
sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script)
|
||||
delay(2000)
|
||||
checkServerState(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
fun stopServer() {
|
||||
val cfg = sshConfig.value
|
||||
if (cfg.ip.isEmpty()) return
|
||||
_serverState.value = ServerState.Working("Остановка сервера...")
|
||||
|
||||
val script = """
|
||||
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 "STOPPED"
|
||||
""".trimIndent()
|
||||
|
||||
viewModelScope.launch {
|
||||
sshManager.executeSilentCommand(cfg.ip, cfg.port, cfg.username, cfg.password, script)
|
||||
delay(2000)
|
||||
checkServerState(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Local proxy ────────────────────────────────────────────────────────
|
||||
|
||||
fun startProxy(context: Context) {
|
||||
if (ProxyService.isRunning) return
|
||||
_proxyState.value = ProxyState.Starting
|
||||
|
||||
viewModelScope.launch {
|
||||
// Write to legacy SharedPreferences so ProxyService can read them
|
||||
val cfg = clientConfig.value
|
||||
context.getSharedPreferences("ProxyPrefs", Context.MODE_PRIVATE).edit().apply {
|
||||
putString("peer", cfg.serverAddress)
|
||||
putString("link", cfg.vkLink)
|
||||
putString("n", cfg.threads.toString())
|
||||
putBoolean("udp", cfg.useUdp)
|
||||
putBoolean("noDtls", cfg.noDtls)
|
||||
putString("listen", cfg.localPort)
|
||||
putBoolean("isRaw", cfg.isRawMode)
|
||||
putString("rawCmd", cfg.rawCommand)
|
||||
}.apply()
|
||||
|
||||
ProxyService.logBuffer.clear()
|
||||
context.startForegroundService(Intent(context, ProxyService::class.java))
|
||||
|
||||
delay(1500)
|
||||
_proxyState.value = if (ProxyService.isRunning) ProxyState.Running
|
||||
else ProxyState.Error("Не удалось запустить прокси")
|
||||
}
|
||||
}
|
||||
|
||||
fun stopProxy(context: Context) {
|
||||
context.stopService(Intent(context, ProxyService::class.java))
|
||||
_proxyState.value = ProxyState.Idle
|
||||
}
|
||||
|
||||
// ── Preferences ────────────────────────────────────────────────────────
|
||||
|
||||
fun saveClientConfig(config: ClientConfig) {
|
||||
viewModelScope.launch { prefs.saveClientConfig(config) }
|
||||
}
|
||||
|
||||
fun saveProxyServerConfig(listen: String, connect: String) {
|
||||
viewModelScope.launch { prefs.saveProxyConfig(listen, connect) }
|
||||
}
|
||||
|
||||
fun setOnboardingDone() {
|
||||
viewModelScope.launch { prefs.setOnboardingDone(true) }
|
||||
}
|
||||
|
||||
fun clearLogs() {
|
||||
ProxyService.logBuffer.clear()
|
||||
_logs.value = emptyList()
|
||||
}
|
||||
|
||||
override fun onCleared() {
|
||||
super.onCleared()
|
||||
ProxyService.onLogReceived = null
|
||||
sshManager.disconnect()
|
||||
}
|
||||
}
|
||||
@@ -1,131 +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/btnSettings" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="4dp" android:text="SETTINGS" android:textSize="10sp" android:backgroundTint="#00796B"/>
|
||||
|
||||
<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>
|
||||
@@ -1,54 +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:padding="16dp"
|
||||
android:background="#121212">
|
||||
|
||||
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Настройки SSH" android:textColor="#FFFFFF" android:textSize="14sp" android:textStyle="bold" android:layout_marginBottom="8dp"/>
|
||||
|
||||
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
|
||||
<EditText android:id="@+id/editSshIp" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="IP сервера" android:textColor="#FFFFFF" android:textColorHint="#757575" android:backgroundTint="#455A64" android:layout_marginEnd="8dp"/>
|
||||
<EditText android:id="@+id/editSshPort" android:layout_width="80dp" android:layout_height="wrap_content" android:hint="Порт" android:text="22" android:inputType="number" android:textColor="#FFFFFF" android:textColorHint="#757575" android:backgroundTint="#455A64"/>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
|
||||
<EditText android:id="@+id/editSshUser" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="Пользователь" android:text="root" android:textColor="#FFFFFF" android:textColorHint="#757575" android:backgroundTint="#455A64" android:layout_marginEnd="8dp"/>
|
||||
<EditText android:id="@+id/editSshPass" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="Пароль" android:inputType="textPassword" android:textColor="#FFFFFF" android:textColorHint="#757575" android:backgroundTint="#455A64"/>
|
||||
</LinearLayout>
|
||||
|
||||
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Настройки vk-turn-proxy (Сервер)" android:textColor="#FFFFFF" android:textSize="14sp" android:textStyle="bold" android:layout_marginTop="8dp" android:layout_marginBottom="4dp"/>
|
||||
|
||||
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
|
||||
<EditText android:id="@+id/editProxyListen" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="Listen (напр. 0.0.0.0:56000)" android:textColor="#FFFFFF" android:textColorHint="#757575" android:backgroundTint="#455A64" android:layout_marginEnd="8dp" android:textSize="12sp"/>
|
||||
<EditText android:id="@+id/editProxyConnect" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="Connect (напр. 127.0.0.1:40537)" android:textColor="#FFFFFF" android:textColorHint="#757575" android:backgroundTint="#455A64" android:textSize="12sp"/>
|
||||
</LinearLayout>
|
||||
|
||||
<Button android:id="@+id/btnConnectSsh" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ПОДКЛЮЧИТЬСЯ И ОТКРЫТЬ ТЕРМИНАЛ" android:backgroundTint="#F57C00" android:layout_marginTop="8dp"/>
|
||||
|
||||
<Button android:id="@+id/btnInstallServer" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="УСТАНОВИТЬ / ОБНОВИТЬ VK-TURN-PROXY" android:backgroundTint="#2E7D32" android:enabled="false" android:layout_marginTop="4dp"/>
|
||||
|
||||
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="4dp">
|
||||
<Button android:id="@+id/btnStartProxy" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="ЗАПУСТИТЬ" android:backgroundTint="#43A047" android:enabled="false" android:layout_marginEnd="4dp"/>
|
||||
<Button android:id="@+id/btnStopProxy" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="ОСТАНОВИТЬ" android:backgroundTint="#D32F2F" android:enabled="false" android:layout_marginStart="4dp"/>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="8dp" android:gravity="center_vertical">
|
||||
<EditText android:id="@+id/editCustomCmd" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:hint="Команда" android:textColor="#FFFFFF" android:textColorHint="#757575" android:backgroundTint="#455A64" android:fontFamily="monospace"/>
|
||||
<Button android:id="@+id/btnCtrlC" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="CTRL+C" android:backgroundTint="#B71C1C" android:layout_marginStart="4dp" android:textSize="12sp" android:padding="8dp"/>
|
||||
<Button android:id="@+id/btnSendCmd" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="SEND" android:backgroundTint="#1976D2" android:layout_marginStart="4dp" android:textSize="12sp"/>
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="#263238" android:padding="4dp" android:layout_marginTop="8dp" android:gravity="center_vertical">
|
||||
<TextView android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:textColor="#CFD8DC" android:padding="4dp" android:text="SSH ТЕРМИНАЛ:" android:textSize="12sp" android:textStyle="bold" />
|
||||
<Button android:id="@+id/btnCopySshLog" 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/btnClearSshLog" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="CLEAR" android:layout_marginStart="4dp" android:textSize="10sp" android:backgroundTint="#455A64"/>
|
||||
</LinearLayout>
|
||||
|
||||
<ScrollView android:id="@+id/scrollSshLog" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#000000">
|
||||
<TextView android:id="@+id/tvSshLog" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#4CAF50" android:textSize="12sp" android:padding="10dp" android:fontFamily="monospace" android:textIsSelectable="true" android:text="Ожидание действий...\n" />
|
||||
</ScrollView>
|
||||
|
||||
<Button android:id="@+id/btnBack" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="НАЗАД" android:backgroundTint="#455A64" android:layout_marginTop="8dp"/>
|
||||
</LinearLayout>
|
||||
@@ -1,6 +1,6 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Base.Theme.VkTurnProxy" parent="Theme.Material3.DayNight.NoActionBar">
|
||||
<style name="Base.Theme.VkTurnProxy" parent="Theme.AppCompat.DayNight.NoActionBar">
|
||||
<!-- Customize your dark theme here. -->
|
||||
<!-- <item name="colorPrimary">@color/my_dark_primary</item> -->
|
||||
</style>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Base.Theme.VkTurnProxy" parent="Theme.Material3.DayNight.NoActionBar">
|
||||
<style name="Base.Theme.VkTurnProxy" parent="Theme.AppCompat.DayNight.NoActionBar">
|
||||
<!-- Customize your light theme here. -->
|
||||
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
|
||||
</style>
|
||||
|
||||
Reference in new issue
Block a user