refactor: замена callback-паттерна на StateFlow, фикс багов логов и дублирования ошибок
This commit is contained in:
1 parent
97e90e1526
commit
df553f17e3
5 files changed
+95
-153
No files matched your search
@@ -15,23 +15,23 @@ import androidx.core.app.NotificationCompat
|
|||||||
import java.io.BufferedReader
|
import java.io.BufferedReader
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.InputStreamReader
|
import java.io.InputStreamReader
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
import kotlin.concurrent.thread
|
import kotlin.concurrent.thread
|
||||||
import kotlin.random.Random
|
import kotlin.random.Random
|
||||||
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
|
||||||
class ProxyService : Service() {
|
class ProxyService : Service() {
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
const val MAX_RESTARTS = 8
|
const val MAX_RESTARTS = 8
|
||||||
var isRunning = false
|
val isRunning = MutableStateFlow(false)
|
||||||
var restartCount = 0
|
val logs = MutableStateFlow<List<String>>(emptyList())
|
||||||
val logBuffer = mutableListOf<String>()
|
val proxyFailed = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
|
||||||
var onLogReceived: ((String) -> Unit)? = null
|
|
||||||
var onProxyFailed: (() -> Unit)? = null
|
|
||||||
|
|
||||||
fun addLog(msg: String) {
|
fun addLog(msg: String) {
|
||||||
if (logBuffer.size > 200) logBuffer.removeAt(0)
|
logs.update { (it + msg).takeLast(200) }
|
||||||
logBuffer.add(msg)
|
|
||||||
onLogReceived?.invoke(msg)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,8 +41,8 @@ class ProxyService : Service() {
|
|||||||
@Volatile private var sessionKillScheduled = false
|
@Volatile private var sessionKillScheduled = false
|
||||||
private val handler = Handler(Looper.getMainLooper())
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
||||||
// Игнорируем первый onAvailable (текущая сеть при регистрации)
|
|
||||||
@Volatile private var networkInitialized = false
|
@Volatile private var networkInitialized = false
|
||||||
|
private var restartCount = 0
|
||||||
|
|
||||||
override fun onBind(intent: Intent?): IBinder? = null
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
|
||||||
@@ -53,7 +53,7 @@ class ProxyService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||||
if (isRunning) return START_STICKY
|
if (isRunning.value) return START_STICKY
|
||||||
|
|
||||||
val notification = NotificationCompat.Builder(this, "ProxyChannel")
|
val notification = NotificationCompat.Builder(this, "ProxyChannel")
|
||||||
.setContentTitle("VK TURN Proxy")
|
.setContentTitle("VK TURN Proxy")
|
||||||
@@ -62,13 +62,14 @@ class ProxyService : Service() {
|
|||||||
.build()
|
.build()
|
||||||
startForeground(1, notification)
|
startForeground(1, notification)
|
||||||
|
|
||||||
isRunning = true
|
isRunning.value = true
|
||||||
userStopped = false
|
userStopped = false
|
||||||
restartCount = 0
|
restartCount = 0
|
||||||
|
|
||||||
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
|
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VkTurn::BgLock")
|
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VkTurn::BgLock")
|
||||||
wakeLock?.acquire()
|
@Suppress("WakelockTimeout")
|
||||||
|
wakeLock?.acquire() // foreground service сам управляет временем жизни; release() в onDestroy()
|
||||||
|
|
||||||
registerNetworkCallback()
|
registerNetworkCallback()
|
||||||
|
|
||||||
@@ -124,27 +125,28 @@ class ProxyService : Service() {
|
|||||||
.start()
|
.start()
|
||||||
process = proc
|
process = proc
|
||||||
|
|
||||||
val reader = BufferedReader(InputStreamReader(proc.inputStream))
|
BufferedReader(InputStreamReader(proc.inputStream)).use { reader ->
|
||||||
var line: String?
|
var line: String?
|
||||||
while (reader.readLine().also { line = it } != null) {
|
while (reader.readLine().also { line = it } != null) {
|
||||||
val l = line ?: continue
|
val l = line ?: continue
|
||||||
addLog(l)
|
addLog(l)
|
||||||
|
|
||||||
// Session Killer: обнаружение ошибки квоты → сброс сессии
|
// Session Killer: обнаружение ошибки квоты → сброс сессии
|
||||||
if (!sessionKillScheduled && isQuotaError(l)) {
|
if (!sessionKillScheduled && isQuotaError(l)) {
|
||||||
sessionKillScheduled = true
|
sessionKillScheduled = true
|
||||||
addLog(">>> QUOTA ERROR — сброс сессии через 2с")
|
addLog(">>> QUOTA ERROR — сброс сессии через 2с")
|
||||||
handler.postDelayed({
|
handler.postDelayed({
|
||||||
sessionKillScheduled = false
|
sessionKillScheduled = false
|
||||||
if (!userStopped) {
|
if (!userStopped) {
|
||||||
restartCount = 0 // сброс бэкоффа — квота не краш
|
restartCount = 0 // сброс бэкоффа — квота не краш
|
||||||
process?.destroy()
|
process?.destroy()
|
||||||
}
|
}
|
||||||
}, 2_000)
|
}, 2_000)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
exitCode = proc.waitFor()
|
exitCode = if (proc.waitFor(5, TimeUnit.MINUTES)) proc.exitValue() else -1
|
||||||
addLog("=== ПРОЦЕСС ОСТАНОВЛЕН (Код: $exitCode) ===")
|
addLog("=== ПРОЦЕСС ОСТАНОВЛЕН (Код: $exitCode) ===")
|
||||||
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -153,19 +155,17 @@ class ProxyService : Service() {
|
|||||||
process = null
|
process = null
|
||||||
when {
|
when {
|
||||||
userStopped -> {
|
userStopped -> {
|
||||||
isRunning = false
|
isRunning.value = false
|
||||||
stopSelf()
|
stopSelf()
|
||||||
}
|
}
|
||||||
exitCode == 0 -> {
|
exitCode == 0 -> {
|
||||||
val uptime = System.currentTimeMillis() - startedAt
|
val uptime = System.currentTimeMillis() - startedAt
|
||||||
if (uptime < 5_000L) {
|
if (uptime < 5_000L) {
|
||||||
// Мгновенный выход — скорее всего истекла ссылка или неверные аргументы
|
|
||||||
addLog("=== Быстрый выход (${uptime}мс) — проверьте VK-ссылку и настройки ===")
|
addLog("=== Быстрый выход (${uptime}мс) — проверьте VK-ссылку и настройки ===")
|
||||||
} else {
|
} else {
|
||||||
addLog("=== Сессия завершена нормально ===")
|
addLog("=== Сессия завершена нормально ===")
|
||||||
}
|
}
|
||||||
isRunning = false
|
isRunning.value = false
|
||||||
onProxyFailed?.invoke()
|
|
||||||
stopSelf()
|
stopSelf()
|
||||||
}
|
}
|
||||||
else -> scheduleWatchdogRestart()
|
else -> scheduleWatchdogRestart()
|
||||||
@@ -179,8 +179,8 @@ class ProxyService : Service() {
|
|||||||
restartCount++
|
restartCount++
|
||||||
if (restartCount > MAX_RESTARTS) {
|
if (restartCount > MAX_RESTARTS) {
|
||||||
addLog("=== WATCHDOG: превышен лимит попыток ($MAX_RESTARTS), остановка ===")
|
addLog("=== WATCHDOG: превышен лимит попыток ($MAX_RESTARTS), остановка ===")
|
||||||
isRunning = false
|
isRunning.value = false
|
||||||
onProxyFailed?.invoke()
|
proxyFailed.tryEmit(Unit)
|
||||||
stopSelf()
|
stopSelf()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -236,7 +236,7 @@ class ProxyService : Service() {
|
|||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
userStopped = true
|
userStopped = true
|
||||||
isRunning = false
|
isRunning.value = false
|
||||||
handler.removeCallbacksAndMessages(null)
|
handler.removeCallbacksAndMessages(null)
|
||||||
unregisterNetworkCallback()
|
unregisterNetworkCallback()
|
||||||
addLog("=== ОСТАНОВКА ИЗ ИНТЕРФЕЙСА ===")
|
addLog("=== ОСТАНОВКА ИЗ ИНТЕРФЕЙСА ===")
|
||||||
|
|||||||
@@ -1,90 +1,17 @@
|
|||||||
package com.freeturn.app
|
package com.freeturn.app
|
||||||
|
|
||||||
import com.jcraft.jsch.ChannelExec
|
import com.jcraft.jsch.ChannelExec
|
||||||
import com.jcraft.jsch.ChannelShell
|
|
||||||
import com.jcraft.jsch.JSch
|
import com.jcraft.jsch.JSch
|
||||||
import com.jcraft.jsch.Session
|
import com.jcraft.jsch.Session
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import java.io.InputStream
|
|
||||||
import java.io.OutputStream
|
|
||||||
import java.util.Properties
|
import java.util.Properties
|
||||||
|
|
||||||
class SSHManager {
|
class SSHManager {
|
||||||
private var session: Session? = null
|
|
||||||
private var shellChannel: ChannelShell? = null
|
|
||||||
private var shellOutputStream: OutputStream? = null
|
|
||||||
@Volatile private var isShellRunning = false
|
|
||||||
|
|
||||||
fun startShell(ip: String, port: Int, user: String, pass: String, onLogReceived: (String) -> Unit) {
|
suspend fun executeSilentCommand(
|
||||||
Thread {
|
ip: String, port: Int, user: String, pass: String, command: String
|
||||||
try {
|
): String = withContext(Dispatchers.IO) {
|
||||||
if (session == null || !session!!.isConnected) {
|
|
||||||
val jsch = JSch()
|
|
||||||
session = jsch.getSession(user, ip, port)
|
|
||||||
session?.setPassword(pass)
|
|
||||||
|
|
||||||
val config = Properties()
|
|
||||||
config.put("StrictHostKeyChecking", "no")
|
|
||||||
session?.setConfig(config)
|
|
||||||
session?.connect(10000)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shellChannel != null && shellChannel!!.isConnected) {
|
|
||||||
return@Thread
|
|
||||||
}
|
|
||||||
|
|
||||||
shellChannel = session?.openChannel("shell") as ChannelShell
|
|
||||||
shellChannel?.setPty(true)
|
|
||||||
|
|
||||||
val inStream: InputStream = shellChannel!!.inputStream
|
|
||||||
shellOutputStream = shellChannel!!.outputStream
|
|
||||||
|
|
||||||
shellChannel?.connect(5000)
|
|
||||||
isShellRunning = true
|
|
||||||
|
|
||||||
val reader = inStream.bufferedReader()
|
|
||||||
val buffer = CharArray(1024)
|
|
||||||
var read = 0
|
|
||||||
|
|
||||||
while (isShellRunning && reader.read(buffer).also { read = it } != -1) {
|
|
||||||
val output = String(buffer, 0, read)
|
|
||||||
onLogReceived(output)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
onLogReceived("\n[ОШИБКА SHELL]: ${e.message}\n")
|
|
||||||
}
|
|
||||||
}.start()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun sendShellCommand(command: String) {
|
|
||||||
Thread {
|
|
||||||
try {
|
|
||||||
if (shellOutputStream != null) {
|
|
||||||
shellOutputStream?.write((command + "\r").toByteArray())
|
|
||||||
shellOutputStream?.flush()
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
e.printStackTrace()
|
|
||||||
}
|
|
||||||
}.start()
|
|
||||||
}
|
|
||||||
|
|
||||||
// НОВАЯ ФУНКЦИЯ: Эмуляция Ctrl+C (прерывание процесса)
|
|
||||||
fun sendCtrlC() {
|
|
||||||
Thread {
|
|
||||||
try {
|
|
||||||
if (shellOutputStream != null) {
|
|
||||||
shellOutputStream?.write(3) // Байт 3 = ASCII символ ETX (End of Text) = Ctrl+C
|
|
||||||
shellOutputStream?.flush()
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
|
||||||
e.printStackTrace()
|
|
||||||
}
|
|
||||||
}.start()
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun executeSilentCommand(ip: String, port: Int, user: String, pass: String, command: String): String = withContext(Dispatchers.IO) {
|
|
||||||
var tempSession: Session? = null
|
var tempSession: Session? = null
|
||||||
try {
|
try {
|
||||||
val jsch = JSch()
|
val jsch = JSch()
|
||||||
@@ -92,28 +19,28 @@ class SSHManager {
|
|||||||
tempSession.setPassword(pass)
|
tempSession.setPassword(pass)
|
||||||
|
|
||||||
val config = Properties()
|
val config = Properties()
|
||||||
config.put("StrictHostKeyChecking", "no")
|
config["StrictHostKeyChecking"] = "no"
|
||||||
tempSession.setConfig(config)
|
tempSession.setConfig(config)
|
||||||
tempSession.connect(5000)
|
tempSession.connect(5000)
|
||||||
|
|
||||||
val channel = tempSession.openChannel("exec") as ChannelExec
|
val channel = tempSession.openChannel("exec") as ChannelExec
|
||||||
channel.setCommand(command)
|
channel.setCommand(command)
|
||||||
channel.inputStream = null
|
channel.inputStream = null // не подключать stdin
|
||||||
channel.setErrStream(null)
|
channel.setErrStream(null)
|
||||||
|
|
||||||
val inStream: InputStream = channel.inputStream
|
val inStream = channel.inputStream
|
||||||
channel.connect()
|
channel.connect()
|
||||||
|
|
||||||
val output = StringBuilder()
|
val output = inStream.bufferedReader().use { reader ->
|
||||||
val reader = inStream.bufferedReader()
|
buildString {
|
||||||
|
var line: String?
|
||||||
var line: String? = null
|
while (reader.readLine().also { line = it } != null) {
|
||||||
while (reader.readLine().also { line = it } != null) {
|
append(line).append("\n")
|
||||||
output.append(line).append("\n")
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
channel.disconnect()
|
channel.disconnect()
|
||||||
output.toString().trim()
|
output.trim()
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
"ERROR: ${e.message}"
|
"ERROR: ${e.message}"
|
||||||
} finally {
|
} finally {
|
||||||
@@ -122,14 +49,6 @@ class SSHManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun disconnect() {
|
fun disconnect() {
|
||||||
isShellRunning = false
|
// Все сессии в executeSilentCommand временные и закрываются в finally-блоке
|
||||||
try {
|
|
||||||
shellOutputStream?.close()
|
|
||||||
} catch (e: Exception) {}
|
|
||||||
shellChannel?.disconnect()
|
|
||||||
session?.disconnect()
|
|
||||||
shellChannel = null
|
|
||||||
session = null
|
|
||||||
shellOutputStream = null
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -17,6 +17,7 @@ import androidx.compose.foundation.layout.Spacer
|
|||||||
import androidx.compose.foundation.layout.fillMaxSize
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
import androidx.compose.foundation.layout.fillMaxWidth
|
import androidx.compose.foundation.layout.fillMaxWidth
|
||||||
import androidx.compose.foundation.layout.height
|
import androidx.compose.foundation.layout.height
|
||||||
|
import androidx.compose.foundation.layout.heightIn
|
||||||
import androidx.compose.foundation.layout.padding
|
import androidx.compose.foundation.layout.padding
|
||||||
import androidx.compose.foundation.layout.size
|
import androidx.compose.foundation.layout.size
|
||||||
import androidx.compose.foundation.layout.width
|
import androidx.compose.foundation.layout.width
|
||||||
@@ -520,11 +521,20 @@ private fun RepoLinkItem(
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun LogsPanel(logs: List<String>, modifier: Modifier = Modifier) {
|
private fun LogsPanel(logs: List<String>, modifier: Modifier = Modifier) {
|
||||||
|
val scrollState = rememberScrollState()
|
||||||
|
LaunchedEffect(logs.size) {
|
||||||
|
scrollState.animateScrollTo(scrollState.maxValue)
|
||||||
|
}
|
||||||
Card(
|
Card(
|
||||||
modifier = modifier,
|
modifier = modifier,
|
||||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
|
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)
|
||||||
) {
|
) {
|
||||||
Column(modifier = Modifier.padding(vertical = 8.dp)) {
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.heightIn(max = 320.dp)
|
||||||
|
.verticalScroll(scrollState)
|
||||||
|
.padding(vertical = 8.dp)
|
||||||
|
) {
|
||||||
if (logs.isEmpty()) {
|
if (logs.isEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
"Нет логов",
|
"Нет логов",
|
||||||
@@ -533,7 +543,7 @@ private fun LogsPanel(logs: List<String>, modifier: Modifier = Modifier) {
|
|||||||
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
|
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.4f)
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
logs.takeLast(50).forEachIndexed { index, line ->
|
logs.forEachIndexed { index, line ->
|
||||||
LogLine(line = line, isEven = index % 2 == 0)
|
LogLine(line = line, isEven = index % 2 == 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -585,7 +595,7 @@ private fun LogLine(line: String, isEven: Boolean) {
|
|||||||
Spacer(Modifier.width(11.dp))
|
Spacer(Modifier.width(11.dp))
|
||||||
}
|
}
|
||||||
Text(
|
Text(
|
||||||
text = line.removePrefix("=== ").removeSuffix(" ==="),
|
text = line,
|
||||||
style = MaterialTheme.typography.bodySmall.copy(
|
style = MaterialTheme.typography.bodySmall.copy(
|
||||||
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
|
fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
|
||||||
fontWeight = if (isHeader) androidx.compose.ui.text.font.FontWeight.SemiBold
|
fontWeight = if (isHeader) androidx.compose.ui.text.font.FontWeight.SemiBold
|
||||||
|
|||||||
@@ -67,8 +67,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
private val _proxyState = MutableStateFlow<ProxyState>(ProxyState.Idle)
|
private val _proxyState = MutableStateFlow<ProxyState>(ProxyState.Idle)
|
||||||
val proxyState: StateFlow<ProxyState> = _proxyState.asStateFlow()
|
val proxyState: StateFlow<ProxyState> = _proxyState.asStateFlow()
|
||||||
|
|
||||||
private val _logs = MutableStateFlow<List<String>>(emptyList())
|
val logs: StateFlow<List<String>> = ProxyService.logs
|
||||||
val logs: StateFlow<List<String>> = _logs.asStateFlow()
|
|
||||||
|
|
||||||
private val _isInitialized = MutableStateFlow(false)
|
private val _isInitialized = MutableStateFlow(false)
|
||||||
val isInitialized: StateFlow<Boolean> = _isInitialized.asStateFlow()
|
val isInitialized: StateFlow<Boolean> = _isInitialized.asStateFlow()
|
||||||
@@ -98,15 +97,22 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
_isInitialized.value = true
|
_isInitialized.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
ProxyService.onLogReceived = { msg ->
|
viewModelScope.launch {
|
||||||
_logs.value = (_logs.value + msg).takeLast(200)
|
ProxyService.proxyFailed.collect {
|
||||||
|
setErrorWithAutoReset("Прокси упал ${ProxyService.MAX_RESTARTS} раз — проверьте настройки")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ProxyService.onProxyFailed = {
|
|
||||||
setErrorWithAutoReset("Прокси упал ${ProxyService.MAX_RESTARTS} раз — проверьте настройки")
|
|
||||||
}
|
|
||||||
_logs.value = ProxyService.logBuffer.toList()
|
|
||||||
|
|
||||||
if (ProxyService.isRunning) _proxyState.value = ProxyState.Running
|
// Сбрасываем состояние когда сервис остановился (нормальный выход, не краш)
|
||||||
|
viewModelScope.launch {
|
||||||
|
ProxyService.isRunning.collect { running ->
|
||||||
|
if (!running && _proxyState.value == ProxyState.Running) {
|
||||||
|
_proxyState.value = ProxyState.Idle
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ProxyService.isRunning.value) _proxyState.value = ProxyState.Running
|
||||||
|
|
||||||
_customKernelExists.value =
|
_customKernelExists.value =
|
||||||
File(getApplication<Application>().filesDir, "custom_vkturn").exists()
|
File(getApplication<Application>().filesDir, "custom_vkturn").exists()
|
||||||
@@ -253,7 +259,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
// ── Local proxy ────────────────────────────────────────────────────────
|
// ── Local proxy ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
fun startProxy(context: Context) {
|
fun startProxy(context: Context) {
|
||||||
if (ProxyService.isRunning) return
|
if (ProxyService.isRunning.value) return
|
||||||
|
|
||||||
// Сброс предыдущей ошибки перед повторной попыткой
|
// Сброс предыдущей ошибки перед повторной попыткой
|
||||||
if (_proxyState.value is ProxyState.Error) _proxyState.value = ProxyState.Idle
|
if (_proxyState.value is ProxyState.Error) _proxyState.value = ProxyState.Idle
|
||||||
@@ -284,19 +290,28 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
putString("rawCmd", cfg.rawCommand)
|
putString("rawCmd", cfg.rawCommand)
|
||||||
}
|
}
|
||||||
|
|
||||||
ProxyService.logBuffer.clear()
|
ProxyService.logs.value = emptyList()
|
||||||
context.startForegroundService(Intent(context, ProxyService::class.java))
|
context.startForegroundService(Intent(context, ProxyService::class.java))
|
||||||
|
|
||||||
// Ждём запуска: проверяем логи на ошибку или успех вместо простого isRunning
|
// Ждём запуска: проверяем логи на ошибку или успех вместо простого isRunning
|
||||||
delay(2500)
|
delay(2500)
|
||||||
val logText = ProxyService.logBuffer.joinToString("\n").lowercase()
|
// Если proxyFailed уже обработал ошибку — не дублируем
|
||||||
|
if (_proxyState.value is ProxyState.Error) return@launch
|
||||||
|
val logText = ProxyService.logs.value.joinToString("\n").lowercase()
|
||||||
when {
|
when {
|
||||||
!ProxyService.isRunning ->
|
!ProxyService.isRunning.value ->
|
||||||
setErrorWithAutoReset("Прокси не запустился")
|
setErrorWithAutoReset("Прокси не запустился")
|
||||||
logText.contains("panic") || logText.contains("fatal") ||
|
logText.contains("panic") || logText.contains("fatal") ||
|
||||||
logText.contains("rate limit") || logText.contains("критическая") -> {
|
logText.contains("rate limit") || logText.contains("критическая") -> {
|
||||||
context.stopService(Intent(context, ProxyService::class.java))
|
context.stopService(Intent(context, ProxyService::class.java))
|
||||||
setErrorWithAutoReset("Ошибка запуска — проверьте настройки")
|
val errorLine = ProxyService.logs.value
|
||||||
|
.lastOrNull { line ->
|
||||||
|
val l = line.lowercase()
|
||||||
|
l.contains("error") || l.contains("ошибка") ||
|
||||||
|
l.contains("panic") || l.contains("fatal") ||
|
||||||
|
l.contains("критическая")
|
||||||
|
}
|
||||||
|
setErrorWithAutoReset(errorLine ?: "Ошибка запуска — проверьте настройки")
|
||||||
}
|
}
|
||||||
else ->
|
else ->
|
||||||
_proxyState.value = ProxyState.Running
|
_proxyState.value = ProxyState.Running
|
||||||
@@ -333,8 +348,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun clearLogs() {
|
fun clearLogs() {
|
||||||
ProxyService.logBuffer.clear()
|
ProxyService.logs.value = emptyList()
|
||||||
_logs.value = emptyList()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Custom kernel ──────────────────────────────────────────────────────
|
// ── Custom kernel ──────────────────────────────────────────────────────
|
||||||
@@ -364,8 +378,6 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
|
|||||||
|
|
||||||
override fun onCleared() {
|
override fun onCleared() {
|
||||||
super.onCleared()
|
super.onCleared()
|
||||||
ProxyService.onLogReceived = null
|
|
||||||
ProxyService.onProxyFailed = null
|
|
||||||
sshManager.disconnect()
|
sshManager.disconnect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,4 +23,5 @@ kotlin.code.style=official
|
|||||||
android.nonTransitiveRClass=true
|
android.nonTransitiveRClass=true
|
||||||
android.uniquePackageNames=false
|
android.uniquePackageNames=false
|
||||||
android.dependency.useConstraints=true
|
android.dependency.useConstraints=true
|
||||||
|
android.generateSyncIssueWhenLibraryConstraintsAreEnabled=false
|
||||||
android.r8.strictFullModeForKeepRules=false
|
android.r8.strictFullModeForKeepRules=false
|
||||||
Reference in new issue
Block a user