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