refactor: вынести общие хелперы парсинга, буфера и пустого состояния
Дедуп под фичу шаринга: errMessage/asUnit/decodeBase64/ServerCommandException в ServerOutputParser, copyToClipboard, EmptyState — теперь общие для новых и существующих экранов.
This commit is contained in:
1 parent
454e876916
commit
3ba285dbff
7 files changed
+135
-62
No files matched your search
@@ -7,7 +7,9 @@ import com.freeturn.app.domain.server.CmdResult
|
||||
import com.freeturn.app.domain.server.ServerCommand
|
||||
import com.freeturn.app.domain.server.ServerControl
|
||||
import com.freeturn.app.domain.server.ServerOptions
|
||||
import java.util.Base64
|
||||
import com.freeturn.app.domain.server.asUnit
|
||||
import com.freeturn.app.domain.server.decodeBase64
|
||||
import com.freeturn.app.domain.server.toFailure
|
||||
|
||||
/**
|
||||
* SSH-операции мастера добавления self-hosted сервера. Собственный [SSHManager] и
|
||||
@@ -40,14 +42,14 @@ class ServerSetupRepository(context: Context) {
|
||||
/** Проверка SSH-доступа + probe. Ошибка SSH/скрипта — failure с текстом. */
|
||||
suspend fun probe(cfg: SshConfig): Result<ProbeResult> =
|
||||
when (val r = control.run(cfg, ServerCommand.Probe)) {
|
||||
is CmdResult.Err -> Result.failure(SetupCommandException(errMessage(r)))
|
||||
is CmdResult.Err -> r.toFailure()
|
||||
is CmdResult.Ok -> Result.success(
|
||||
ProbeResult(wgPort = r.kv["WG_PORT"]?.toIntOrNull())
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun install(cfg: SshConfig): Result<Unit> =
|
||||
asUnit(control.run(cfg, ServerCommand.Install))
|
||||
control.run(cfg, ServerCommand.Install).asUnit()
|
||||
|
||||
suspend fun wgSetup(
|
||||
cfg: SshConfig,
|
||||
@@ -56,7 +58,7 @@ class ServerSetupRepository(context: Context) {
|
||||
adopt: Boolean = false
|
||||
): Result<WgSetupResult> =
|
||||
when (val r = control.run(cfg, ServerCommand.WgSetup(port, endpoint, adopt))) {
|
||||
is CmdResult.Err -> Result.failure(SetupCommandException(errMessage(r)))
|
||||
is CmdResult.Err -> r.toFailure()
|
||||
is CmdResult.Ok -> Result.success(
|
||||
WgSetupResult(
|
||||
port = r.kv["WG_PORT"]?.toIntOrNull() ?: port,
|
||||
@@ -67,22 +69,5 @@ class ServerSetupRepository(context: Context) {
|
||||
}
|
||||
|
||||
suspend fun startServer(cfg: SshConfig, opts: ServerOptions): Result<Unit> =
|
||||
asUnit(control.run(cfg, ServerCommand.Start(opts)))
|
||||
|
||||
private fun asUnit(r: CmdResult): Result<Unit> = when (r) {
|
||||
is CmdResult.Ok -> Result.success(Unit)
|
||||
is CmdResult.Err -> Result.failure(SetupCommandException(errMessage(r)))
|
||||
}
|
||||
|
||||
/** Текст ошибки + хвост LOG-строк скрипта: без него «wg-quick failed» недиагностируем. */
|
||||
private fun errMessage(r: CmdResult.Err): String {
|
||||
val tail = r.logs.takeLast(2).filter { it.isNotBlank() }
|
||||
return if (tail.isEmpty()) r.message else r.message + "\n" + tail.joinToString("\n")
|
||||
}
|
||||
|
||||
private fun decodeBase64(s: String): String? =
|
||||
runCatching { String(Base64.getDecoder().decode(s.trim()), Charsets.UTF_8) }.getOrNull()
|
||||
control.run(cfg, ServerCommand.Start(opts)).asUnit()
|
||||
}
|
||||
|
||||
/** Ошибка серверной команды мастера; message — текст из скрипта/SSH для UI. */
|
||||
class SetupCommandException(message: String) : Exception(message)
|
||||
@@ -52,3 +52,24 @@ object ServerOutputParser {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Ошибка серверной команды; message — текст из скрипта/SSH для UI. */
|
||||
class ServerCommandException(message: String) : Exception(message)
|
||||
|
||||
/** Текст ошибки + хвост LOG-строк скрипта: без него «wg-quick failed» недиагностируем. */
|
||||
fun CmdResult.Err.errMessage(): String {
|
||||
val tail = logs.takeLast(2).filter { it.isNotBlank() }
|
||||
return if (tail.isEmpty()) message else message + "\n" + tail.joinToString("\n")
|
||||
}
|
||||
|
||||
fun CmdResult.Err.toFailure(): Result<Nothing> =
|
||||
Result.failure(ServerCommandException(errMessage()))
|
||||
|
||||
fun CmdResult.asUnit(): Result<Unit> = when (this) {
|
||||
is CmdResult.Ok -> Result.success(Unit)
|
||||
is CmdResult.Err -> toFailure()
|
||||
}
|
||||
|
||||
/** base64 → UTF-8 текст; битое значение → null. */
|
||||
fun decodeBase64(s: String): String? =
|
||||
runCatching { String(java.util.Base64.getDecoder().decode(s.trim()), Charsets.UTF_8) }.getOrNull()
|
||||
@@ -0,0 +1,74 @@
|
||||
@file:OptIn(androidx.compose.material3.ExperimentalMaterial3ExpressiveApi::class)
|
||||
|
||||
package com.freeturn.app.ui.components
|
||||
|
||||
import androidx.annotation.DrawableRes
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialShapes
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.toShape
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
/** Пустое состояние списка: Cookie9Sided-плашка + текст, опционально заголовок
|
||||
* и CTA. Один вид на всё приложение. */
|
||||
@Composable
|
||||
fun EmptyState(
|
||||
@DrawableRes iconRes: Int,
|
||||
desc: String,
|
||||
modifier: Modifier = Modifier,
|
||||
title: String? = null,
|
||||
actionLabel: String? = null,
|
||||
onAction: (() -> Unit)? = null
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.padding(horizontal = 32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
Surface(
|
||||
shape = MaterialShapes.Cookie9Sided.toShape(),
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
modifier = Modifier.size(104.dp)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
|
||||
Icon(
|
||||
painterResource(iconRes),
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
modifier = Modifier.size(48.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
title?.let {
|
||||
Text(it, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
}
|
||||
Text(
|
||||
desc,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
if (actionLabel != null && onAction != null) {
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Button(onClick = onAction) { Text(actionLabel) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,19 +7,14 @@ 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.shape.CircleShape
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialShapes
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.toShape
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
@@ -30,7 +25,6 @@ import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.selected
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.freeturn.app.R
|
||||
@@ -131,34 +125,12 @@ fun ServerRow(
|
||||
}
|
||||
}
|
||||
|
||||
/** Пустой список серверов: Cookie9Sided-плашка + общая строка. Один вид на всё приложение. */
|
||||
/** Пустой список серверов — общий [EmptyState]. */
|
||||
@Composable
|
||||
fun EmptyServersState(modifier: Modifier = Modifier) {
|
||||
Column(
|
||||
modifier = modifier.padding(horizontal = 32.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center
|
||||
) {
|
||||
Surface(
|
||||
shape = MaterialShapes.Cookie9Sided.toShape(),
|
||||
color = MaterialTheme.colorScheme.primaryContainer,
|
||||
modifier = Modifier.size(104.dp)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
|
||||
Icon(
|
||||
painterResource(R.drawable.database_outlined_24px),
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer,
|
||||
modifier = Modifier.size(48.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Text(
|
||||
stringResource(R.string.settings_empty_servers),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
EmptyState(
|
||||
iconRes = R.drawable.database_outlined_24px,
|
||||
desc = stringResource(R.string.settings_empty_servers),
|
||||
modifier = modifier
|
||||
)
|
||||
}
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
package com.freeturn.app.ui.screens
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
@@ -41,6 +39,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.freeturn.app.R
|
||||
import com.freeturn.app.ui.HapticUtil
|
||||
import com.freeturn.app.ui.theme.extendedColorScheme
|
||||
import com.freeturn.app.ui.util.copyToClipboard
|
||||
import com.freeturn.app.viewmodel.ProxyViewModel
|
||||
|
||||
@Composable
|
||||
@@ -64,8 +63,7 @@ fun LogsScreen(proxyViewModel: ProxyViewModel) {
|
||||
actions = {
|
||||
IconButton(
|
||||
onClick = {
|
||||
val cm = context.getSystemService(ClipboardManager::class.java)
|
||||
cm.setPrimaryClip(ClipData.newPlainText("proxy_logs", logs.joinToString("\n")))
|
||||
context.copyToClipboard("proxy_logs", logs.joinToString("\n"))
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.SUCCESS)
|
||||
},
|
||||
enabled = logs.isNotEmpty()
|
||||
|
||||
@@ -72,6 +72,7 @@ import com.freeturn.app.ui.components.SettingsContentMaxWidth
|
||||
import com.freeturn.app.ui.components.SettingsControlLabel
|
||||
import com.freeturn.app.ui.components.SettingsFieldSlot
|
||||
import com.freeturn.app.ui.components.SettingsRowDivider
|
||||
import com.freeturn.app.ui.util.copyToClipboard
|
||||
import com.freeturn.app.ui.util.redact
|
||||
import com.freeturn.app.viewmodel.ServerState
|
||||
import com.freeturn.app.viewmodel.SshConnectionState
|
||||
@@ -402,8 +403,7 @@ fun ServerManagementScreen(
|
||||
if (effServer.obfKey.isNotBlank() && !privacyMode) {
|
||||
IconButton(onClick = {
|
||||
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
|
||||
val cm = context.getSystemService(android.content.ClipboardManager::class.java)
|
||||
cm?.setPrimaryClip(android.content.ClipData.newPlainText("obf-key", effServer.obfKey))
|
||||
context.copyToClipboard("obf-key", effServer.obfKey, sensitive = true)
|
||||
}) {
|
||||
Icon(
|
||||
painterResource(R.drawable.content_copy_24px),
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.freeturn.app.ui.util
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipDescription
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.PersistableBundle
|
||||
|
||||
/**
|
||||
* Кладёт текст в системный буфер. [sensitive] — для секретов (ключи, ссылки
|
||||
* с WG-конфигом): на Android 13+ скрывает содержимое в превью буфера.
|
||||
*/
|
||||
fun Context.copyToClipboard(label: String, text: String, sensitive: Boolean = false) {
|
||||
val cm = getSystemService(ClipboardManager::class.java) ?: return
|
||||
val clip = ClipData.newPlainText(label, text)
|
||||
if (sensitive && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
clip.description.extras = PersistableBundle().apply {
|
||||
putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true)
|
||||
}
|
||||
}
|
||||
cm.setPrimaryClip(clip)
|
||||
}
|
||||
Reference in new issue
Block a user