feat(share): доступы из client-list вместо WG-пиров

Тип доступа задаёт бэкенд сервера, выбор WG/прокси убран. Список пользователей
обновляется жестом.
This commit is contained in:
samosvalishe committed 2026-09-22 10:06:56 +03:00
1 parent 430416251c
commit 0350afaa41
19 files changed
+384 -575

No files matched your search

@@ -27,7 +27,7 @@ data class FreeturnLink(
val kcp: KcpProfile? = null, val kcp: KcpProfile? = null,
val name: String = "", val name: String = "",
/** Ссылка на звонок владельца - опционально, иначе получатель вводит свою. */ /** Ссылка на звонок владельца - опционально, иначе получатель вводит свою. */
val vkLink: String = "", val callLink: String = "",
val wgConf: String = "" val wgConf: String = ""
) { ) {
fun encode(): String { fun encode(): String {
@@ -51,7 +51,7 @@ data class FreeturnLink(
if (manualCaptcha) sb.field("mcap", "true") if (manualCaptcha) sb.field("mcap", "true")
if (kcp != null) sb.field("kcp", kcpJson(kcp)) if (kcp != null) sb.field("kcp", kcpJson(kcp))
if (name.isNotEmpty()) sb.field("name", jsonString(name)) if (name.isNotEmpty()) sb.field("name", jsonString(name))
if (vkLink.isNotEmpty()) sb.field("vk", jsonString(vkLink)) if (callLink.isNotEmpty()) sb.field("vk", jsonString(callLink))
if (wgConf.isNotEmpty()) sb.field("wg", jsonString(wgConf)) if (wgConf.isNotEmpty()) sb.field("wg", jsonString(wgConf))
sb.append('}') sb.append('}')
return SCHEME + Base64.getUrlEncoder().withoutPadding() return SCHEME + Base64.getUrlEncoder().withoutPadding()
@@ -94,7 +94,7 @@ data class FreeturnLink(
manualCaptcha = o.optBoolean("mcap", false), manualCaptcha = o.optBoolean("mcap", false),
kcp = o.optJSONObject("kcp")?.let(::parseKcp), kcp = o.optJSONObject("kcp")?.let(::parseKcp),
name = o.optString("name"), name = o.optString("name"),
vkLink = o.optString("vk"), callLink = o.optString("vk"),
wgConf = o.optString("wg") wgConf = o.optString("wg")
) )
} }
@@ -1,18 +1,17 @@
package com.freeturn.app.data.share package com.freeturn.app.data.share
/** /**
* Фактические параметры запущенного сервера (`share-info`). * Фактические параметры сервера (`client-list` share). Используется вместо локального
* Используется вместо локального [com.freeturn.app.data.server.ServerOpts] для точности. * [com.freeturn.app.data.server.ServerOpts]: гостю нужны значения, с которыми сервер живёт.
*/ */
data class ShareInfo( data class ShareInfo(
/** Режим проброса живого сервера: "udp" | "tcp". */ /** Режим проброса сервера: "udp" | "tcp". */
val mode: String = "", val mode: String = "",
/** Пусто = сервер не запускался из приложения; при живых args хотя бы "none". */ /** Пусто - серверной правды нет (ручной профиль без SSH); иначе хотя бы "none". */
val obfProfile: String = "", val obfProfile: String = "",
val obfKey: String = "", val obfKey: String = "",
/** Есть WG-conf в /etc/wireguard -> шарим VPN-доступ (peer-add). Иначе - прокси. */ /** Свой WG ft-wg0 -> в ссылке WG-конфиг гостя. Иначе - только FreeTurn-часть. */
val wgBackend: Boolean = false val wgBackend: Boolean = false
) { ) {
/** run.args найден - серверным значениям можно верить. */
val hasRunArgs: Boolean get() = obfProfile.isNotEmpty() val hasRunArgs: Boolean get() = obfProfile.isNotEmpty()
} }
@@ -7,7 +7,7 @@ import com.freeturn.app.data.server.Server
/** /**
* Собирает freeturn://-ссылку для пользователя. * Собирает freeturn://-ссылку для пользователя.
* vkLink передаётся вызывающим только по явному согласию владельца, * callLink передаётся вызывающим только по явному согласию владельца,
* иначе получатель вводит свой. * иначе получатель вводит свой.
*/ */
object ShareLinkBuilder { object ShareLinkBuilder {
@@ -18,7 +18,7 @@ object ShareLinkBuilder {
userName: String, userName: String,
wgConf: String?, wgConf: String?,
clientId: String = "", clientId: String = "",
vkLink: String = "" callLink: String = ""
): String { ): String {
val obfProfile = if (info.hasRunArgs) info.obfProfile else server.opts.obfProfile val obfProfile = if (info.hasRunArgs) info.obfProfile else server.opts.obfProfile
val obfKey = if (info.hasRunArgs) info.obfKey else server.opts.obfKey val obfKey = if (info.hasRunArgs) info.obfKey else server.opts.obfKey
@@ -37,7 +37,7 @@ object ShareLinkBuilder {
streamsPerCred = server.client.streamsPerCred, streamsPerCred = server.client.streamsPerCred,
clientId = clientId.trim(), clientId = clientId.trim(),
name = userName.trim(), name = userName.trim(),
vkLink = vkLink.trim(), callLink = callLink.trim(),
wgConf = wgConf?.let(::normalizeConf).orEmpty() wgConf = wgConf?.let(::normalizeConf).orEmpty()
).encode() ).encode()
} }
@@ -1,20 +1,30 @@
package com.freeturn.app.data.share package com.freeturn.app.data.share
import com.freeturn.app.data.control.ShareListData import com.freeturn.app.data.control.ClientDto
import com.freeturn.app.data.control.ClientListData
/** Гость из allowlist без WG-пира (`share-list` clients): свой бэкенд на стороне гостя. */ /** Клиент сервера из `client-list`: запись allowlist, при своём WG - ещё и пир. */
data class SharedClient( data class SharedClient(
/** Имя = ключ на сервере (client-conf/client-remove). */
val name: String,
val clientId: String, val clientId: String,
/** Имя = comment в clients.json. */ /** Хозяин сервера - удалять нельзя (owner_protected). */
val name: String val isSelf: Boolean,
) /** null - пира нет (чужой VPN). */
val wgIp: String?,
/** Epoch-секунды последнего handshake. null - ни разу / интерфейс не поднят. */
val lastHandshakeEpoch: Long?
) {
companion object {
fun from(d: ClientDto) = SharedClient(
name = d.name,
clientId = d.clientId,
isSelf = d.self,
wgIp = d.ip.takeIf { d.pub.isNotBlank() },
lastHandshakeEpoch = d.hs.takeIf { it > 0 }
)
/** Маппинг `share-list` data ([ShareListData]) в доменные [SharedClient]. */ fun list(data: ClientListData): List<SharedClient> =
object SharedClientParser { data.clients.filter { it.name.isNotBlank() }.map(::from)
}
fun from(data: ShareListData): List<SharedClient> =
data.clients.mapNotNull { c ->
val id = c.id.takeIf { it.isNotBlank() } ?: return@mapNotNull null
SharedClient(clientId = id, name = decodeNameB64(c.nameB64))
}
} }
@@ -1,47 +0,0 @@
package com.freeturn.app.data.share
import com.freeturn.app.data.control.ShareListData
import java.util.Base64
/** WG-пир сервера из subcommand `share-list`. */
data class WgPeer(
val pubkey: String,
/** Имя из маркера ft-user. Пусто - пир без маркера (старые установки, ручные правки). */
val name: String,
val ip: String,
/** Epoch-секунды последнего handshake. null - ни разу / интерфейс не поднят. */
val lastHandshakeEpoch: Long?,
/** На сервере сохранён клиентский conf - можно выдать ссылку повторно. */
val hasStoredConf: Boolean,
/** Пир самого владельца (wireguard-client.conf мастера) - не отзываем. */
val isSelf: Boolean
)
/** Маппинг `share-list` data ([ShareListData]) в доменные [WgPeer]. */
object WgPeerParser {
fun from(data: ShareListData): List<WgPeer> {
val selfPub = data.selfPub
return data.peers.mapNotNull { p ->
val pub = p.pub.takeIf { it.isNotBlank() } ?: return@mapNotNull null
WgPeer(
pubkey = pub,
name = decodeNameB64(p.nameB64),
ip = p.ip,
lastHandshakeEpoch = p.hs?.takeIf { it > 0 },
hasStoredConf = p.hasConf,
isSelf = selfPub.isNotEmpty() && pub == selfPub
)
}
}
}
/** base64(UTF-8) -> имя; битое значение -> пусто. Общий хелпер парсеров share-вывода. */
internal fun decodeNameB64(b64: String?): String {
if (b64.isNullOrBlank()) return ""
return try {
String(Base64.getDecoder().decode(b64), Charsets.UTF_8)
} catch (_: IllegalArgumentException) {
""
}
}
@@ -2,86 +2,58 @@ package com.freeturn.app.domain.share
import android.content.Context import android.content.Context
import com.freeturn.app.data.config.SshConfig import com.freeturn.app.data.config.SshConfig
import com.freeturn.app.data.control.PeerAddData import com.freeturn.app.data.control.ClientData
import com.freeturn.app.data.control.PeerConfData import com.freeturn.app.data.control.ClientListData
import com.freeturn.app.data.control.ShareInfoData
import com.freeturn.app.data.control.ShareListData
import com.freeturn.app.data.control.decodeBase64 import com.freeturn.app.data.control.decodeBase64
import com.freeturn.app.data.server.ServerBackend
import com.freeturn.app.data.share.ShareInfo import com.freeturn.app.data.share.ShareInfo
import com.freeturn.app.data.share.SharedClient import com.freeturn.app.data.share.SharedClient
import com.freeturn.app.data.share.SharedClientParser
import com.freeturn.app.data.share.WgPeer
import com.freeturn.app.data.share.WgPeerParser
import com.freeturn.app.domain.server.ServerCommand import com.freeturn.app.domain.server.ServerCommand
import com.freeturn.app.domain.server.ServerCommandException
import com.freeturn.app.domain.server.ServerControl import com.freeturn.app.domain.server.ServerControl
import com.freeturn.app.domain.server.asUnit import com.freeturn.app.domain.server.asUnit
import com.freeturn.app.domain.server.requireData import com.freeturn.app.domain.server.requireData
import com.freeturn.app.domain.ssh.SSHManager import com.freeturn.app.domain.ssh.SSHManager
import java.util.Base64
class ShareRepository(context: Context, ssh: SSHManager) { class ShareRepository(context: Context, ssh: SSHManager) {
private val control = ServerControl(context, ssh) private val control = ServerControl(context, ssh)
data class NewPeer(val pubkey: String, val ip: String, val clientConf: String) data class Snapshot(val info: ShareInfo, val clients: List<SharedClient>)
data class PeerAccess(val clientConf: String, val clientId: String) /** [wgConf] null - у клиента нет пира (чужой VPN): в ссылку идёт только FreeTurn-часть. */
data class Access(val client: SharedClient, val wgConf: String?)
suspend fun shareInfo(cfg: SshConfig): Result<ShareInfo> = suspend fun list(cfg: SshConfig): Result<Snapshot> =
control.run(cfg, ServerCommand.ShareInfo) control.run(cfg, ServerCommand.ClientList)
.requireData<ShareInfoData>() .requireData<ClientListData>()
.map { ShareInfo(it.mode, it.obfProfile, it.obfKey, it.wgBackend) } .map { d ->
val s = d.share
suspend fun addPeer( Snapshot(
cfg: SshConfig, info = ShareInfo(
name: String, mode = s.mode,
endpoint: String, obfProfile = s.obfProfile,
clientId: String obfKey = s.obfKey,
): Result<NewPeer> = wgBackend = s.backend == ServerBackend.NEW
control.run(cfg, ServerCommand.PeerAdd(nameB64(name), endpoint, clientId)) ),
.requireData<PeerAddData>() clients = SharedClient.list(d)
.mapCatching { d -> )
val conf = decodeBase64(d.clientConfB64)
if (d.peer.pub.isBlank() || conf.isNullOrBlank()) {
throw ServerCommandException("server returned no peer config")
}
NewPeer(d.peer.pub, d.peer.ip, conf)
} }
suspend fun listShared(cfg: SshConfig): Result<Pair<List<WgPeer>, List<SharedClient>>> = suspend fun add(cfg: SshConfig, name: String): Result<Access> =
control.run(cfg, ServerCommand.ShareList) control.run(cfg, ServerCommand.ClientAdd(name)).requireData<ClientData>().map(::access)
.requireData<ShareListData>()
.map { WgPeerParser.from(it) to SharedClientParser.from(it) }
/** suspend fun conf(cfg: SshConfig, name: String): Result<Access> =
* Conf пира + его cid. [candidateClientId]/[name] - backfill: пир без control.run(cfg, ServerCommand.ClientConf(name)).requireData<ClientData>().map(::access)
* cid-маппинга (выдан до allowlist) регистрируется этим cid на сервере.
*/
suspend fun peerConf(
cfg: SshConfig,
pubkey: String,
candidateClientId: String,
name: String
): Result<PeerAccess> =
control.run(cfg, ServerCommand.PeerConf(pubkey, candidateClientId, nameB64(name)))
.requireData<PeerConfData>()
.mapCatching { d ->
val conf = decodeBase64(d.clientConfB64)
?: throw ServerCommandException("server returned no peer config")
PeerAccess(conf, d.clientId)
}
suspend fun removePeer(cfg: SshConfig, pubkey: String): Result<Unit> = suspend fun remove(cfg: SshConfig, name: String): Result<Unit> =
control.run(cfg, ServerCommand.PeerRemove(pubkey)).asUnit() control.run(cfg, ServerCommand.ClientRemove(name)).asUnit()
suspend fun addClient(cfg: SshConfig, name: String, clientId: String): Result<Unit> = private fun access(d: ClientData) = Access(SharedClient.from(d.client), decodeBase64(d.confB64))
control.run(cfg, ServerCommand.ClientAdd(nameB64(name), clientId)).asUnit()
suspend fun removeClient(cfg: SshConfig, clientId: String): Result<Unit> = companion object {
control.run(cfg, ServerCommand.ClientRemove(clientId)).asUnit() /** = valid_name в install.sh: имя - ключ на сервере и имя файлов клиента. */
private val NAME = Regex("^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$")
// До 64 символов: влезает в b64-лимит скрипта и не раздувает маркер в conf. fun isValidName(name: String): Boolean = NAME.matches(name)
private fun nameB64(name: String): String = Base64.getEncoder() }
.encodeToString(name.trim().take(64).toByteArray(Charsets.UTF_8))
} }
@@ -19,6 +19,7 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.LoadingIndicator import androidx.compose.material3.LoadingIndicator
@@ -44,6 +45,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.data.config.AccessProtocol import com.freeturn.app.data.config.AccessProtocol
import com.freeturn.app.data.config.ObfProfile import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.config.Provider
import com.freeturn.app.ui.components.EmptyState import com.freeturn.app.ui.components.EmptyState
import com.freeturn.app.ui.components.InlineErrorCard import com.freeturn.app.ui.components.InlineErrorCard
import com.freeturn.app.ui.components.ProtocolPills import com.freeturn.app.ui.components.ProtocolPills
@@ -70,7 +72,7 @@ fun ImportSheet(
title = { Text(stringResource(R.string.import_error_title)) }, title = { Text(stringResource(R.string.import_error_title)) },
text = { Text(stringResource(R.string.import_error_desc)) }, text = { Text(stringResource(R.string.import_error_desc)) },
confirmButton = { confirmButton = {
TextButton(onClick = viewModel::dismiss) { TextButton(shapes = ButtonDefaults.shapes(), onClick = viewModel::dismiss) {
Text(stringResource(R.string.import_error_ok)) Text(stringResource(R.string.import_error_ok))
} }
} }
@@ -141,22 +143,24 @@ fun ImportSheet(
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) )
OutlinedTextField( if (link.provider == Provider.RELAY) {
value = state.vkLink, OutlinedTextField(
onValueChange = viewModel::setVkLink, value = state.callLink,
label = { Text(stringResource(R.string.import_vk_link_label)) }, onValueChange = viewModel::setCallLink,
supportingText = { label = { Text(stringResource(R.string.import_call_link_label)) },
Text( supportingText = {
stringResource( Text(
if (link.vkLink.isNotBlank()) R.string.import_vk_link_from_owner stringResource(
else R.string.import_vk_link_helper if (link.callLink.isNotBlank()) R.string.import_call_link_from_owner
else R.string.import_call_link_helper
)
) )
) },
}, singleLine = true,
singleLine = true, enabled = !state.saving,
enabled = !state.saving, modifier = Modifier.fillMaxWidth()
modifier = Modifier.fillMaxWidth() )
) }
if (state.duplicateConf) { if (state.duplicateConf) {
ImportWarning(stringResource(R.string.import_duplicate_conf)) ImportWarning(stringResource(R.string.import_duplicate_conf))
@@ -169,6 +173,7 @@ fun ImportSheet(
} }
Button( Button(
shapes = ButtonDefaults.shapes(),
onClick = { viewModel.confirm(fallbackName) }, onClick = { viewModel.confirm(fallbackName) },
enabled = state.canConfirm, enabled = state.canConfirm,
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
@@ -25,6 +25,8 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -111,7 +113,7 @@ fun QrScannerScreen(onBack: () -> Unit) {
TopAppBar( TopAppBar(
title = { Text(stringResource(R.string.scanner_title)) }, title = { Text(stringResource(R.string.scanner_title)) },
navigationIcon = { navigationIcon = {
IconButton(onClick = onBack) { IconButton(shapes = IconButtonDefaults.shapes(), onClick = onBack) {
Icon( Icon(
painterResource(R.drawable.arrow_back_24px), painterResource(R.drawable.arrow_back_24px),
contentDescription = stringResource(R.string.back) contentDescription = stringResource(R.string.back)
@@ -275,11 +277,11 @@ private fun CameraPermissionGate(
textAlign = TextAlign.Center textAlign = TextAlign.Center
) )
if (permanentlyDenied) { if (permanentlyDenied) {
TextButton(onClick = onOpenSettings) { TextButton(shapes = ButtonDefaults.shapes(), onClick = onOpenSettings) {
Text(stringResource(R.string.scanner_permission_open_settings)) Text(stringResource(R.string.scanner_permission_open_settings))
} }
} else { } else {
Button(onClick = onRequest, modifier = Modifier.padding(top = Spacing.lg)) { Button(shapes = ButtonDefaults.shapes(), onClick = onRequest, modifier = Modifier.padding(top = Spacing.lg)) {
Text(stringResource(R.string.scanner_permission_grant)) Text(stringResource(R.string.scanner_permission_grant))
} }
} }
@@ -4,6 +4,7 @@ package com.freeturn.app.ui.screens.share
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.LoadingIndicator import androidx.compose.material3.LoadingIndicator
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -14,7 +15,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
/** Подтверждение отзыва доступа: пир/cid удаляется с сервера, доступ получателя умрёт. */ /** Подтверждение отзыва доступа: клиент (cid и пир) удаляется с сервера, доступ получателя умрёт. */
@Composable @Composable
fun RevokeDialog( fun RevokeDialog(
userName: String, userName: String,
@@ -28,7 +29,7 @@ fun RevokeDialog(
title = { Text(stringResource(R.string.share_revoke_title)) }, title = { Text(stringResource(R.string.share_revoke_title)) },
text = { Text(stringResource(R.string.share_revoke_desc, name)) }, text = { Text(stringResource(R.string.share_revoke_desc, name)) },
confirmButton = { confirmButton = {
TextButton(onClick = onConfirm, enabled = !revoking) { TextButton(shapes = ButtonDefaults.shapes(), onClick = onConfirm, enabled = !revoking) {
if (revoking) { if (revoking) {
LoadingIndicator(modifier = Modifier.size(22.dp)) LoadingIndicator(modifier = Modifier.size(22.dp))
} else { } else {
@@ -40,7 +41,7 @@ fun RevokeDialog(
} }
}, },
dismissButton = { dismissButton = {
TextButton(onClick = onDismiss, enabled = !revoking) { TextButton(shapes = ButtonDefaults.shapes(), onClick = onDismiss, enabled = !revoking) {
Text(stringResource(R.string.cancel)) Text(stringResource(R.string.cancel))
} }
} }
@@ -3,7 +3,7 @@
package com.freeturn.app.ui.screens.share package com.freeturn.app.ui.screens.share
import androidx.compose.animation.Crossfade import androidx.compose.animation.Crossfade
import androidx.compose.animation.core.tween import androidx.compose.animation.core.snap
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
@@ -11,22 +11,22 @@ import androidx.compose.foundation.layout.fillMaxWidth
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.material3.LoadingIndicator import androidx.compose.material3.LoadingIndicator
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextButton import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.data.config.ClientId import com.freeturn.app.data.config.ClientId
import com.freeturn.app.ui.components.SectionLabel import com.freeturn.app.ui.components.SectionLabel
import com.freeturn.app.ui.theme.LocalReducedMotion import com.freeturn.app.ui.theme.LocalReducedMotion
@@ -41,7 +41,7 @@ import com.freeturn.app.ui.theme.Spacing
/** /**
* Суб-вкладка "Соединение": имя нового пользователя + сервер. Сам запуск выдачи - * Суб-вкладка "Соединение": имя нового пользователя + сервер. Сам запуск выдачи -
* на FAB экрана. Протокол (WireGuard/прокси) определяет сервер (share-info), * на FAB экрана. Протокол (WireGuard/прокси) определяет бэкенд сервера (client-list),
* не локальный режим владельца. * не локальный режим владельца.
*/ */
@Composable @Composable
@@ -50,12 +50,12 @@ fun ShareConnectionTab(
onSelectServer: (String) -> Unit, onSelectServer: (String) -> Unit,
onUserNameChange: (String) -> Unit, onUserNameChange: (String) -> Unit,
onClientIdChange: (String) -> Unit, onClientIdChange: (String) -> Unit,
onSetMode: (Boolean) -> Unit, onSetShareCallLink: (Boolean) -> Unit,
onSetShareVkLink: (Boolean) -> Unit, onCallLinkChange: (String) -> Unit,
onVkLinkChange: (String) -> Unit,
onRetryInfo: () -> Unit onRetryInfo: () -> Unit
) { ) {
val context = LocalContext.current // Ошибку имени показываем после ухода из поля, не посреди набора.
var nameTouched by remember { mutableStateOf(false) }
Column(verticalArrangement = Arrangement.spacedBy(Spacing.lg)) { Column(verticalArrangement = Arrangement.spacedBy(Spacing.lg)) {
Text( Text(
stringResource(R.string.share_connection_desc), stringResource(R.string.share_connection_desc),
@@ -67,16 +67,21 @@ fun ShareConnectionTab(
value = state.userName, value = state.userName,
onValueChange = onUserNameChange, onValueChange = onUserNameChange,
label = { Text(stringResource(R.string.share_user_name_label)) }, label = { Text(stringResource(R.string.share_user_name_label)) },
isError = nameTouched && state.userName.isNotEmpty() && !state.userNameValid,
singleLine = true, singleLine = true,
enabled = !state.creating, enabled = !state.creating,
supportingText = { supportingText = {
Text( Row {
"${state.userName.length}/${ShareViewModel.MAX_USER_NAME_LEN}", Text(
modifier = Modifier.fillMaxWidth(), if (state.localOnly) "" else stringResource(R.string.share_user_name_hint),
textAlign = TextAlign.End modifier = Modifier.weight(1f)
) )
Text("${state.userName.length}/${ShareViewModel.MAX_USER_NAME_LEN}")
}
}, },
modifier = Modifier.fillMaxWidth() modifier = Modifier
.fillMaxWidth()
.onFocusChanged { if (!it.isFocused && state.userName.isNotEmpty()) nameTouched = true }
) )
ServerSelector( ServerSelector(
@@ -107,51 +112,29 @@ fun ShareConnectionTab(
) )
} }
// WG-сервер умеет оба типа доступа -> выбор. Прокси-only сервер - просто статус. // Тип доступа задаёт бэкенд сервера: свой WG -> WG-конфиг гостя, чужой VPN -> только FreeTurn.
Column(verticalArrangement = Arrangement.spacedBy(Spacing.sm)) { Column(verticalArrangement = Arrangement.spacedBy(Spacing.sm)) {
SectionLabel(stringResource(R.string.share_access_type)) SectionLabel(stringResource(R.string.share_access_type))
if (state.canChooseMode && state.shareInfo != null &&
!state.infoLoading && state.infoError == null
) {
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
SegmentedButton(
selected = state.useWg,
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
onSetMode(false)
},
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2)
) { Text(stringResource(R.string.protocol_wg)) }
SegmentedButton(
selected = !state.useWg,
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
onSetMode(true)
},
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
) { Text(stringResource(R.string.protocol_proxy)) }
}
}
ShareProtocolCard(state = state, onRetryInfo = onRetryInfo) ShareProtocolCard(state = state, onRetryInfo = onRetryInfo)
} }
// Ссылка на звонок уходит вместе с доступом - только по явному согласию владельца. // Ссылка на звонок уходит вместе с доступом - только по явному согласию владельца.
if (state.ownerVkLink.isNotBlank()) { if (state.ownerCallLink.isNotBlank()) {
SettingsCard { SettingsCard {
SettingsSwitchRow( SettingsSwitchRow(
title = stringResource(R.string.share_include_vk_link), title = stringResource(R.string.share_include_call_link),
subtitle = stringResource(R.string.share_include_vk_link_desc), subtitle = stringResource(R.string.share_include_call_link_desc),
iconRes = R.drawable.link_24px, iconRes = R.drawable.link_24px,
checked = state.shareVkLink, checked = state.shareCallLink,
onCheckedChange = onSetShareVkLink, onCheckedChange = onSetShareCallLink,
enabled = !state.creating enabled = !state.creating
) )
if (state.shareVkLink) { if (state.shareCallLink) {
SettingsRowDivider() SettingsRowDivider()
SettingsFieldSlot { SettingsFieldSlot {
OutlinedTextField( OutlinedTextField(
value = state.vkLinkToShare, value = state.callLinkToShare,
onValueChange = onVkLinkChange, onValueChange = onCallLinkChange,
label = { Text(stringResource(R.string.call_link_label)) }, label = { Text(stringResource(R.string.call_link_label)) },
placeholder = { Text(stringResource(R.string.call_link_placeholder)) }, placeholder = { Text(stringResource(R.string.call_link_placeholder)) },
singleLine = true, singleLine = true,
@@ -181,7 +164,7 @@ fun ShareConnectionTab(
} }
} }
/** Статус выбранного сервера: протокол шаринга либо загрузка/ошибка share-info. */ /** Статус выбранного сервера: протокол шаринга либо загрузка/ошибка client-list. */
@Composable @Composable
private fun ShareProtocolCard(state: ShareUiState, onRetryInfo: () -> Unit) { private fun ShareProtocolCard(state: ShareUiState, onRetryInfo: () -> Unit) {
val reducedMotion = LocalReducedMotion.current val reducedMotion = LocalReducedMotion.current
@@ -213,7 +196,7 @@ private fun ShareProtocolCard(state: ShareUiState, onRetryInfo: () -> Unit) {
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
TextButton(onClick = onRetryInfo) { TextButton(shapes = ButtonDefaults.shapes(), onClick = onRetryInfo) {
Text(stringResource(R.string.share_info_retry)) Text(stringResource(R.string.share_info_retry))
} }
} }
@@ -221,7 +204,7 @@ private fun ShareProtocolCard(state: ShareUiState, onRetryInfo: () -> Unit) {
else -> state.shareInfo?.let { else -> state.shareInfo?.let {
Crossfade( Crossfade(
targetState = state.useWg, targetState = state.useWg,
animationSpec = tween(if (reducedMotion) 0 else 250), animationSpec = if (reducedMotion) snap() else MaterialTheme.motionScheme.defaultEffectsSpec(),
label = "protocol_mode" label = "protocol_mode"
) { wg -> ) { wg ->
Column( Column(
@@ -22,6 +22,8 @@ import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.FilledIconButton import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.FilledTonalIconButton import androidx.compose.material3.FilledTonalIconButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -142,6 +144,7 @@ fun ShareResultSheet(result: ShareResult, shareInfo: ShareInfo?, onDismiss: () -
Row(horizontalArrangement = Arrangement.spacedBy(Spacing.lg)) { Row(horizontalArrangement = Arrangement.spacedBy(Spacing.lg)) {
FilledTonalIconButton( FilledTonalIconButton(
shapes = IconButtonDefaults.shapes(),
onClick = { onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK) HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
// Ссылка несёт WG PrivateKey и obf-ключ - прячем из превью буфера. // Ссылка несёт WG PrivateKey и obf-ключ - прячем из превью буфера.
@@ -155,6 +158,7 @@ fun ShareResultSheet(result: ShareResult, shareInfo: ShareInfo?, onDismiss: () -
) )
} }
FilledIconButton( FilledIconButton(
shapes = IconButtonDefaults.shapes(),
onClick = { onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK) HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
val send = Intent(Intent.ACTION_SEND).apply { val send = Intent(Intent.ACTION_SEND).apply {
@@ -16,7 +16,6 @@ import androidx.compose.animation.scaleOut
import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith import androidx.compose.animation.togetherWith
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
@@ -30,12 +29,13 @@ import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.LargeFlexibleTopAppBar import androidx.compose.material3.LargeFlexibleTopAppBar
import androidx.compose.material3.LoadingIndicator import androidx.compose.material3.LoadingIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.pulltorefresh.PullToRefreshDefaults
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
@@ -48,9 +48,12 @@ import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.ui.util.HapticUtil import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.ChoiceOption
import com.freeturn.app.ui.components.ConnectedChoiceRow
import com.freeturn.app.ui.components.EmptyState import com.freeturn.app.ui.components.EmptyState
import com.freeturn.app.ui.components.SettingsContentMaxWidth import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.ui.theme.LocalReducedMotion import com.freeturn.app.ui.theme.LocalReducedMotion
@@ -87,11 +90,6 @@ fun ShareScreen(
if (screenSettled) viewModel.ensureInfoLoaded() if (screenSettled) viewModel.ensureInfoLoaded()
} }
// Список пользователей тянем лениво - только когда открыта их вкладка.
LaunchedEffect(tab, state.selectedServerId) {
if (tab == TAB_USERS) viewModel.refreshPeers()
}
Scaffold( Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
topBar = { topBar = {
@@ -155,68 +153,78 @@ fun ShareScreen(
// Переключатель "Соединение / Пользователи" - только для SSH-серверов: // Переключатель "Соединение / Пользователи" - только для SSH-серверов:
// у ручных нет серверного списка выданных доступов. // у ручных нет серверного списка выданных доступов.
if (state.canManageUsers) { if (state.canManageUsers) {
SingleChoiceSegmentedButtonRow( ConnectedChoiceRow(
modifier = Modifier options = listOf(
.fillMaxWidth() ChoiceOption(TAB_CONNECTION, stringResource(R.string.share_tab_connection)),
.padding(horizontal = Spacing.lg, vertical = Spacing.md) ChoiceOption(TAB_USERS, stringResource(R.string.share_tab_users))
) { ),
SegmentedButton( selected = tab,
selected = tab == TAB_CONNECTION, onSelect = { tab = it },
onClick = { modifier = Modifier.padding(horizontal = Spacing.lg, vertical = Spacing.md)
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON) )
tab = TAB_CONNECTION
},
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2)
) { Text(stringResource(R.string.share_tab_connection)) }
SegmentedButton(
selected = tab == TAB_USERS,
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON)
tab = TAB_USERS
},
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
) { Text(stringResource(R.string.share_tab_users)) }
}
} }
// transitionSpec не composable - спеки motionScheme берём снаружи.
val slideSpec = MaterialTheme.motionScheme.defaultSpatialSpec<IntOffset>()
val fadeInSpec = MaterialTheme.motionScheme.defaultEffectsSpec<Float>()
val fadeOutSpec = MaterialTheme.motionScheme.fastEffectsSpec<Float>()
AnimatedContent( AnimatedContent(
targetState = tab, targetState = tab,
// Shared-axis X: вперёд (к "Пользователям") - въезд справа, назад - слева. // Shared-axis X: вперёд (к "Пользователям") - въезд справа, назад - слева.
transitionSpec = { transitionSpec = {
val forward = targetState > initialState if (reducedMotion) {
val w = { full: Int -> if (forward) full / 5 else -full / 5 } EnterTransition.None togetherWith ExitTransition.None
(slideInHorizontally(tween(260)) { w(it) } + fadeIn(tween(260))) } else {
.togetherWith( val forward = targetState > initialState
slideOutHorizontally(tween(200)) { -w(it) } + fadeOut(tween(120)) val w = { full: Int -> if (forward) full / 5 else -full / 5 }
) (slideInHorizontally(slideSpec) { w(it) } + fadeIn(fadeInSpec))
.togetherWith(slideOutHorizontally(slideSpec) { -w(it) } + fadeOut(fadeOutSpec))
}
}, },
label = "share_tab" label = "share_tab"
) { current -> ) { current ->
Column( val tabModifier = Modifier
modifier = Modifier .fillMaxSize()
.fillMaxSize() .verticalScroll(rememberScrollState())
.verticalScroll(rememberScrollState()) .padding(horizontal = Spacing.lg, vertical = Spacing.lg)
.padding(horizontal = Spacing.lg, vertical = Spacing.lg) when (current) {
) { TAB_CONNECTION -> Column(modifier = tabModifier) {
when (current) { ShareConnectionTab(
TAB_CONNECTION -> ShareConnectionTab(
state = state, state = state,
onSelectServer = viewModel::selectServer, onSelectServer = viewModel::selectServer,
onUserNameChange = viewModel::setUserName, onUserNameChange = viewModel::setUserName,
onClientIdChange = viewModel::setManualClientId, onClientIdChange = viewModel::setManualClientId,
onSetMode = viewModel::setShareMode, onSetShareCallLink = viewModel::setShareCallLink,
onSetShareVkLink = viewModel::setShareVkLink, onCallLinkChange = viewModel::setCallLinkToShare,
onVkLinkChange = viewModel::setVkLinkToShare,
onRetryInfo = viewModel::retryInfo onRetryInfo = viewModel::retryInfo
) )
TAB_USERS -> ShareUsersTab( }
state = state, // Жест - основной путь обновления; кнопка в шапке списка остаётся
onSelectServer = viewModel::selectServer, // доступной альтернативой (TalkBack, клавиатура).
onRefresh = { viewModel.refreshPeers(force = true) }, TAB_USERS -> {
onReshare = viewModel::resharePeer, val pullState = rememberPullToRefreshState()
onRevoke = viewModel::askRevoke, val refreshing = state.clientsLoading
onReshareClient = viewModel::reshareClient, PullToRefreshBox(
onRevokeClient = viewModel::askRevokeClient isRefreshing = refreshing,
) onRefresh = viewModel::refreshClients,
state = pullState,
indicator = {
PullToRefreshDefaults.LoadingIndicator(
state = pullState,
isRefreshing = refreshing,
modifier = Modifier.align(Alignment.TopCenter)
)
}
) {
Column(modifier = tabModifier) {
ShareUsersTab(
state = state,
onSelectServer = viewModel::selectServer,
onRefresh = viewModel::refreshClients,
onReshare = viewModel::reshare,
onRevoke = viewModel::askRevoke
)
}
}
} }
} }
} }
@@ -18,6 +18,8 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
@@ -43,7 +45,6 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import com.freeturn.app.R import com.freeturn.app.R
import com.freeturn.app.data.share.SharedClient import com.freeturn.app.data.share.SharedClient
import com.freeturn.app.data.share.WgPeer
import com.freeturn.app.ui.components.EmptyState import com.freeturn.app.ui.components.EmptyState
import com.freeturn.app.ui.components.SectionLabel import com.freeturn.app.ui.components.SectionLabel
import com.freeturn.app.ui.components.SettingsGroup import com.freeturn.app.ui.components.SettingsGroup
@@ -62,10 +63,8 @@ fun ShareUsersTab(
state: ShareUiState, state: ShareUiState,
onSelectServer: (String) -> Unit, onSelectServer: (String) -> Unit,
onRefresh: () -> Unit, onRefresh: () -> Unit,
onReshare: (WgPeer) -> Unit, onReshare: (SharedClient) -> Unit,
onRevoke: (WgPeer) -> Unit, onRevoke: (SharedClient) -> Unit
onReshareClient: (SharedClient) -> Unit,
onRevokeClient: (SharedClient) -> Unit
) { ) {
// Тикает, чтобы online-статус пира гас сам по времени, а не только при перезагрузке. // Тикает, чтобы online-статус пира гас сам по времени, а не только при перезагрузке.
val nowSec by produceState(System.currentTimeMillis() / 1000) { val nowSec by produceState(System.currentTimeMillis() / 1000) {
@@ -91,12 +90,12 @@ fun ShareUsersTab(
horizontalArrangement = Arrangement.End, horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
if (state.peersLoading) { if (state.clientsLoading || state.infoLoading) {
Box(modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center) { Box(modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center) {
LoadingIndicator(modifier = Modifier.size(24.dp)) LoadingIndicator(modifier = Modifier.size(24.dp))
} }
} else { } else {
IconButton(onClick = onRefresh) { IconButton(shapes = IconButtonDefaults.shapes(), onClick = onRefresh) {
Icon( Icon(
painterResource(R.drawable.refresh_24px), painterResource(R.drawable.refresh_24px),
contentDescription = stringResource(R.string.share_users_refresh), contentDescription = stringResource(R.string.share_users_refresh),
@@ -107,7 +106,7 @@ fun ShareUsersTab(
} }
} }
state.peersError?.let { error -> (state.clientsError ?: state.infoError)?.let { error ->
Text( Text(
error, error,
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
@@ -115,8 +114,8 @@ fun ShareUsersTab(
) )
} }
val total = state.peers.size + state.clients.size val total = state.clients.size
if (state.peersLoaded && total == 0) { if (state.clientsLoaded && total == 0) {
EmptyState( EmptyState(
iconRes = R.drawable.group_off_24px, iconRes = R.drawable.group_off_24px,
desc = stringResource(R.string.share_users_empty), desc = stringResource(R.string.share_users_empty),
@@ -124,38 +123,20 @@ fun ShareUsersTab(
) )
} else if (total > 0) { } else if (total > 0) {
SettingsGroup { SettingsGroup {
state.peers.forEachIndexed { index, peer -> state.clients.forEachIndexed { index, client ->
SettingsGroupItem(index, total) { SettingsGroupItem(index, total) {
UserRow( UserRow(
name = when { name = if (client.isSelf) stringResource(R.string.share_peer_self)
peer.isSelf -> stringResource(R.string.share_peer_self) else client.name,
peer.name.isNotEmpty() -> peer.name subtitle = clientSubtitle(client),
else -> stringResource(R.string.share_peer_unnamed) online = client.lastHandshakeEpoch?.let {
},
subtitle = peerSubtitle(peer),
online = peer.lastHandshakeEpoch?.let {
nowSec - it < ONLINE_WINDOW_SEC nowSec - it < ONLINE_WINDOW_SEC
} ?: false, } ?: false,
resharing = state.resharePubkey == peer.pubkey, resharing = state.reshareName == client.name,
canReshare = peer.hasStoredConf,
canRevoke = !peer.isSelf,
onReshare = { onReshare(peer) },
onRevoke = { onRevoke(peer) }
)
}
}
state.clients.forEachIndexed { index, client ->
SettingsGroupItem(state.peers.size + index, total) {
UserRow(
name = client.name.ifEmpty { stringResource(R.string.share_peer_unnamed) },
subtitle = stringResource(R.string.share_client_proxy_access),
// Прокси-гость без WG-пира - статус подключения серверу неизвестен.
online = false,
resharing = false,
canReshare = true, canReshare = true,
canRevoke = true, canRevoke = !client.isSelf,
onReshare = { onReshareClient(client) }, onReshare = { onReshare(client) },
onRevoke = { onRevokeClient(client) } onRevoke = { onRevoke(client) }
) )
} }
} }
@@ -224,7 +205,7 @@ private fun UserRowMenu(
) { ) {
var expanded by remember { mutableStateOf(false) } var expanded by remember { mutableStateOf(false) }
Box { Box {
IconButton(onClick = { expanded = true }) { IconButton(shapes = IconButtonDefaults.shapes(), onClick = { expanded = true }) {
Icon( Icon(
painterResource(R.drawable.more_vert_24px), painterResource(R.drawable.more_vert_24px),
contentDescription = stringResource(R.string.share_peer_actions), contentDescription = stringResource(R.string.share_peer_actions),
@@ -297,9 +278,11 @@ private fun OnlineDot(modifier: Modifier = Modifier) {
} }
@Composable @Composable
private fun peerSubtitle(peer: WgPeer): String { private fun clientSubtitle(client: SharedClient): String {
// Без пира (чужой VPN) сервер не видит подключений гостя.
if (client.wgIp == null) return stringResource(R.string.share_client_proxy_access)
val context = LocalContext.current val context = LocalContext.current
return peer.lastHandshakeEpoch?.let { epoch -> return client.lastHandshakeEpoch?.let { epoch ->
stringResource( stringResource(
R.string.share_peer_seen, R.string.share_peer_seen,
DateUtils.formatDateTime( DateUtils.formatDateTime(
@@ -9,6 +9,7 @@ import com.freeturn.app.data.config.DnsMode
import com.freeturn.app.data.config.HostPort import com.freeturn.app.data.config.HostPort
import com.freeturn.app.data.config.KcpProfile import com.freeturn.app.data.config.KcpProfile
import com.freeturn.app.data.config.ObfProfile import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.config.Provider
import com.freeturn.app.data.config.ProxyMode import com.freeturn.app.data.config.ProxyMode
import com.freeturn.app.data.server.Server import com.freeturn.app.data.server.Server
import com.freeturn.app.data.server.ServerOpts import com.freeturn.app.data.server.ServerOpts
@@ -31,7 +32,7 @@ import kotlinx.coroutines.launch
data class ImportUiState( data class ImportUiState(
val link: FreeturnLink? = null, val link: FreeturnLink? = null,
val serverName: String = "", val serverName: String = "",
val vkLink: String = "", val callLink: String = "",
val duplicateAddress: Boolean = false, val duplicateAddress: Boolean = false,
val duplicateConf: Boolean = false, val duplicateConf: Boolean = false,
val parseError: Boolean = false, val parseError: Boolean = false,
@@ -40,7 +41,8 @@ data class ImportUiState(
val saved: Boolean = false val saved: Boolean = false
) { ) {
val canConfirm: Boolean val canConfirm: Boolean
get() = link != null && !saving && !saved && vkLink.isNotBlank() get() = link != null && !saving && !saved &&
(link.provider != Provider.RELAY || callLink.isNotBlank())
} }
class ImportViewModel( class ImportViewModel(
@@ -63,14 +65,14 @@ class ImportViewModel(
private suspend fun offer(raw: String) { private suspend fun offer(raw: String) {
if (_uiState.value.saving) return if (_uiState.value.saving) return
FreeturnLink.parse(raw).mapCatching { it.also(::requireUsableObf) }.fold( FreeturnLink.parse(raw).mapCatching { it.also(::requireUsable) }.fold(
onSuccess = { link -> onSuccess = { link ->
val servers = prefs.serversSnapshot.first().list val servers = prefs.serversSnapshot.first().list
val normalizedConf = link.wgConf.trim() val normalizedConf = link.wgConf.trim()
_uiState.value = ImportUiState( _uiState.value = ImportUiState(
link = link, link = link,
serverName = link.name.ifBlank { link.peer.substringBefore(':') }, serverName = link.name.ifBlank { link.peer.substringBefore(':') },
vkLink = link.vkLink.trim(), callLink = link.callLink.trim(),
duplicateAddress = servers.any { duplicateAddress = servers.any {
it.client.serverAddress.equals(link.peer, ignoreCase = true) it.client.serverAddress.equals(link.peer, ignoreCase = true)
}, },
@@ -88,7 +90,7 @@ class ImportViewModel(
fun setServerName(name: String) = _uiState.update { it.copy(serverName = name) } fun setServerName(name: String) = _uiState.update { it.copy(serverName = name) }
fun setVkLink(value: String) = _uiState.update { it.copy(vkLink = value) } fun setCallLink(value: String) = _uiState.update { it.copy(callLink = value) }
fun confirm(fallbackName: String) { fun confirm(fallbackName: String) {
val st = _uiState.value val st = _uiState.value
@@ -118,9 +120,10 @@ class ImportViewModel(
_uiState.value = ImportUiState() _uiState.value = ImportUiState()
} }
// Ссылку с непригодной обфускацией отбиваем на входе: сохранённый сервер // Незнакомый провайдер или непригодную обфускацию отбиваем на входе: профиль
// стартовал бы с конфигом, который отвергнет ядро или сервер. // стартовал бы с конфигом, который отвергнет ядро или сервер.
private fun requireUsableObf(link: FreeturnLink) { private fun requireUsable(link: FreeturnLink) {
require(link.provider in Provider.VALUES) { "unknown provider" }
if (link.obfProfile.isBlank() || link.obfProfile == ObfProfile.NONE) return if (link.obfProfile.isBlank() || link.obfProfile == ObfProfile.NONE) return
require(link.obfProfile in ObfProfile.VALUES) { "unknown obf profile" } require(link.obfProfile in ObfProfile.VALUES) { "unknown obf profile" }
require(ObfProfile.isValidKey(link.obfKey)) { "bad obf key" } require(ObfProfile.isValidKey(link.obfKey)) { "bad obf key" }
@@ -133,7 +136,7 @@ class ImportViewModel(
ssh = SshConfig(), ssh = SshConfig(),
client = ClientConfig( client = ClientConfig(
serverAddress = link.peer, serverAddress = link.peer,
vkLink = st.vkLink.trim(), callLink = st.callLink.trim(),
provider = link.provider, provider = link.provider,
useUdp = link.transport == "udp", useUdp = link.transport == "udp",
threads = link.n.takeIf { it > 0 } ?: ClientConfig.DEFAULT_THREADS, threads = link.n.takeIf { it > 0 } ?: ClientConfig.DEFAULT_THREADS,
@@ -5,13 +5,11 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import com.freeturn.app.data.AppPreferences import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.config.AccessProtocol import com.freeturn.app.data.config.AccessProtocol
import com.freeturn.app.data.config.ClientConfig
import com.freeturn.app.data.config.ClientId import com.freeturn.app.data.config.ClientId
import com.freeturn.app.data.server.Server import com.freeturn.app.data.server.Server
import com.freeturn.app.data.share.ShareInfo import com.freeturn.app.data.share.ShareInfo
import com.freeturn.app.data.share.ShareLinkBuilder import com.freeturn.app.data.share.ShareLinkBuilder
import com.freeturn.app.data.share.SharedClient import com.freeturn.app.data.share.SharedClient
import com.freeturn.app.data.share.WgPeer
import com.freeturn.app.domain.share.ShareRepository import com.freeturn.app.domain.share.ShareRepository
import com.freeturn.app.viewmodel.HapticEvent import com.freeturn.app.viewmodel.HapticEvent
import com.freeturn.app.viewmodel.Haptics import com.freeturn.app.viewmodel.Haptics
@@ -24,12 +22,6 @@ import kotlinx.coroutines.launch
data class ShareResult(val userName: String, val link: String, val protocol: AccessProtocol) data class ShareResult(val userName: String, val link: String, val protocol: AccessProtocol)
data class RevokeTarget(
val name: String,
val pubkey: String? = null,
val clientId: String? = null
)
data class ShareUiState( data class ShareUiState(
val servers: List<Server> = emptyList(), val servers: List<Server> = emptyList(),
val selectedServerId: String? = null, val selectedServerId: String? = null,
@@ -38,42 +30,42 @@ data class ShareUiState(
val infoError: String? = null, val infoError: String? = null,
val userName: String = "", val userName: String = "",
val manualClientId: String = "", val manualClientId: String = "",
val shareAsProxy: Boolean = false, val shareCallLink: Boolean = false,
val shareVkLink: Boolean = false, val callLinkToShare: String = "",
val vkLinkToShare: String = "",
val creating: Boolean = false, val creating: Boolean = false,
val createError: String? = null, val createError: String? = null,
val result: ShareResult? = null, val result: ShareResult? = null,
val peers: List<WgPeer> = emptyList(),
val clients: List<SharedClient> = emptyList(), val clients: List<SharedClient> = emptyList(),
val peersLoaded: Boolean = false, val clientsLoaded: Boolean = false,
val peersLoading: Boolean = false, val clientsLoading: Boolean = false,
val peersError: String? = null, val clientsError: String? = null,
val resharePubkey: String? = null, val reshareName: String? = null,
val revokeTarget: RevokeTarget? = null, val revokeTarget: SharedClient? = null,
val revoking: Boolean = false val revoking: Boolean = false
) { ) {
val selectedServer: Server? get() = servers.firstOrNull { it.id == selectedServerId } val selectedServer: Server? get() = servers.firstOrNull { it.id == selectedServerId }
val localOnly: Boolean get() = selectedServer?.ssh?.ip?.isBlank() == true val localOnly: Boolean get() = selectedServer?.ssh?.ip?.isBlank() == true
val ownerVkLink: String get() = selectedServer?.client?.vkLink?.trim().orEmpty() val ownerCallLink: String get() = selectedServer?.client?.callLink?.trim().orEmpty()
val sharedVkLink: String get() = if (shareVkLink) vkLinkToShare.trim() else "" val sharedCallLink: String get() = if (shareCallLink) callLinkToShare.trim() else ""
val canManageUsers: Boolean get() = selectedServer != null && !localOnly val canManageUsers: Boolean get() = selectedServer != null && !localOnly
val useWg: Boolean get() = shareInfo?.wgBackend == true && !shareAsProxy val useWg: Boolean get() = shareInfo?.wgBackend == true
val canChooseMode: Boolean get() = shareInfo?.wgBackend == true
val missingAddress: Boolean val missingAddress: Boolean
get() = selectedServer?.client?.serverAddress?.isBlank() == true get() = selectedServer?.client?.serverAddress?.isBlank() == true
val manualClientIdValid: Boolean get() = !localOnly || ClientId.isValid(manualClientId.trim()) val manualClientIdValid: Boolean get() = !localOnly || ClientId.isValid(manualClientId.trim())
// Имя - ключ клиента на сервере; у ручного профиля оно только подпись в ссылке.
val userNameValid: Boolean
get() = if (localOnly) userName.isNotBlank() else ShareRepository.isValidName(userName)
val canCreate: Boolean val canCreate: Boolean
get() = !creating && userName.isNotBlank() && selectedServer != null && get() = !creating && userNameValid && selectedServer != null &&
!missingAddress && shareInfo != null && !infoLoading && manualClientIdValid !missingAddress && shareInfo != null && !infoLoading && manualClientIdValid
} }
@@ -87,15 +79,16 @@ class ShareViewModel(
private val appContext = context.applicationContext private val appContext = context.applicationContext
companion object { companion object {
// Строже серверного лимита nameB64 (64): короткое имя плотнее в UI и QR. // = лимит valid_name в install.sh.
const val MAX_USER_NAME_LEN = 32 const val MAX_USER_NAME_LEN = 32
private val NAME_CHARS = Regex("[^A-Za-z0-9._-]")
} }
private val _uiState = MutableStateFlow(ShareUiState()) private val _uiState = MutableStateFlow(ShareUiState())
val uiState: StateFlow<ShareUiState> = _uiState.asStateFlow() val uiState: StateFlow<ShareUiState> = _uiState.asStateFlow()
// share-info по серверам в рамках жизни VM: повторный выбор не дёргает SSH. // client-list по серверам в рамках жизни VM: повторный выбор не дёргает SSH.
private val infoCache = mutableMapOf<String, ShareInfo>() private val cache = mutableMapOf<String, ShareRepository.Snapshot>()
init { init {
viewModelScope.launch { viewModelScope.launch {
@@ -120,58 +113,55 @@ class ShareViewModel(
selectedServerId = id, selectedServerId = id,
shareInfo = null, shareInfo = null,
manualClientId = "", manualClientId = "",
shareAsProxy = false, shareCallLink = false,
shareVkLink = false, callLinkToShare = "",
vkLinkToShare = "",
infoError = null, infoError = null,
createError = null, createError = null,
peers = emptyList(),
clients = emptyList(), clients = emptyList(),
peersLoaded = false, clientsLoaded = false,
peersLoading = false, clientsLoading = false,
peersError = null, clientsError = null,
resharePubkey = null reshareName = null
) )
fun selectServer(id: String) { fun selectServer(id: String) {
if (_uiState.value.selectedServerId == id) return if (_uiState.value.selectedServerId == id) return
_uiState.update { it.resetForServer(id) } _uiState.update { it.resetForServer(id) }
loadInfoIfNeeded(id) loadIfNeeded(id)
} }
fun setUserName(name: String) = fun setUserName(name: String) {
_uiState.update { it.copy(userName = name.take(MAX_USER_NAME_LEN), createError = null) } val v = if (_uiState.value.localOnly) name else name.replace(NAME_CHARS, "")
_uiState.update { it.copy(userName = v.take(MAX_USER_NAME_LEN), createError = null) }
}
fun setManualClientId(id: String) = fun setManualClientId(id: String) =
_uiState.update { it.copy(manualClientId = id.trim().lowercase().take(32), createError = null) } _uiState.update { it.copy(manualClientId = id.trim().lowercase().take(32), createError = null) }
fun setShareMode(proxy: Boolean) = fun setShareCallLink(enabled: Boolean) =
_uiState.update { it.copy(shareAsProxy = proxy, createError = null) }
fun setShareVkLink(enabled: Boolean) =
_uiState.update { _uiState.update {
// Включили - подставляем ссылку сервера как заготовку, её можно перебить своей. // Включили - подставляем ссылку сервера как заготовку, её можно перебить своей.
it.copy( it.copy(
shareVkLink = enabled, shareCallLink = enabled,
vkLinkToShare = if (enabled) it.ownerVkLink else "", callLinkToShare = if (enabled) it.ownerCallLink else "",
createError = null createError = null
) )
} }
fun setVkLinkToShare(value: String) = fun setCallLinkToShare(value: String) =
_uiState.update { it.copy(vkLinkToShare = value, createError = null) } _uiState.update { it.copy(callLinkToShare = value, createError = null) }
fun retryInfo() { fun retryInfo() {
val id = _uiState.value.selectedServerId ?: return val id = _uiState.value.selectedServerId ?: return
infoCache.remove(id) cache.remove(id)
_uiState.update { it.copy(infoError = null) } _uiState.update { it.copy(infoError = null) }
loadInfoIfNeeded(id) loadIfNeeded(id)
} }
fun ensureInfoLoaded() { fun ensureInfoLoaded() {
val st = _uiState.value val st = _uiState.value
if (st.shareInfo == null && !st.infoLoading && st.infoError == null) { if (st.shareInfo == null && !st.infoLoading && st.infoError == null) {
st.selectedServerId?.let(::loadInfoIfNeeded) st.selectedServerId?.let(::loadIfNeeded)
} }
} }
@@ -183,17 +173,22 @@ class ShareViewModel(
val server = st.servers.firstOrNull { it.id == id } ?: return val server = st.servers.firstOrNull { it.id == id } ?: return
if (server.ssh.ip.isBlank()) return // ручной сервер: серверной правды нет if (server.ssh.ip.isBlank()) return // ручной сервер: серверной правды нет
viewModelScope.launch { viewModelScope.launch {
repo.shareInfo(server.ssh).onSuccess { fresh -> repo.list(server.ssh).onSuccess { fresh ->
infoCache[id] = fresh cache[id] = fresh
_uiState.update { cur -> _uiState.update { cur ->
if (cur.selectedServerId == id && cur.shareInfo != fresh) cur.copy(shareInfo = fresh) if (cur.selectedServerId == id) cur.withSnapshot(fresh) else cur
else cur
} }
} }
} }
} }
private fun loadInfoIfNeeded(id: String) { private fun ShareUiState.withSnapshot(s: ShareRepository.Snapshot) = copy(
shareInfo = s.info,
clients = s.clients,
clientsLoaded = true
)
private fun loadIfNeeded(id: String) {
val st = _uiState.value val st = _uiState.value
if (st.selectedServerId != id || st.infoLoading) return if (st.selectedServerId != id || st.infoLoading) return
val server = st.servers.firstOrNull { it.id == id } ?: return val server = st.servers.firstOrNull { it.id == id } ?: return
@@ -204,24 +199,24 @@ class ShareViewModel(
} }
return return
} }
infoCache[id]?.let { cached -> cache[id]?.let { cached ->
if (st.shareInfo != cached) _uiState.update { it.copy(shareInfo = cached) } _uiState.update { it.withSnapshot(cached) }
return return
} }
_uiState.update { it.copy(infoLoading = true, infoError = null) } _uiState.update { it.copy(infoLoading = true, infoError = null) }
viewModelScope.launch { viewModelScope.launch {
val result = repo.shareInfo(server.ssh) val result = repo.list(server.ssh)
result.onSuccess { infoCache[id] = it } result.onSuccess { cache[id] = it }
val current = _uiState.value.selectedServerId val current = _uiState.value.selectedServerId
if (current != id) { if (current != id) {
// Результат SSH относится к уже снятому выбору. // Результат SSH относится к уже снятому выбору.
_uiState.update { it.copy(infoLoading = false) } _uiState.update { it.copy(infoLoading = false) }
current?.let(::loadInfoIfNeeded) current?.let(::loadIfNeeded)
return@launch return@launch
} }
result result
.onSuccess { info -> .onSuccess { snap ->
_uiState.update { it.copy(infoLoading = false, shareInfo = info) } _uiState.update { it.copy(infoLoading = false).withSnapshot(snap) }
} }
.onFailure { e -> .onFailure { e ->
_uiState.update { _uiState.update {
@@ -242,52 +237,29 @@ class ShareViewModel(
serverId = server.id, serverId = server.id,
userName = userName, userName = userName,
link = ShareLinkBuilder.build( link = ShareLinkBuilder.build(
server, info, userName, null, st.manualClientId.trim(), st.sharedVkLink server, info, userName, null, st.manualClientId.trim(), st.sharedCallLink
), ),
wgConf = null wgConf = null
) )
return return
} }
val useWg = st.useWg
_uiState.update { it.copy(creating = true, createError = null) } _uiState.update { it.copy(creating = true, createError = null) }
viewModelScope.launch { viewModelScope.launch {
val cid = ClientId.generate() repo.add(server.ssh, userName)
if (useWg) { .onSuccess { access ->
repo.addPeer(server.ssh, userName, ClientConfig.DEFAULT_LOCAL_PORT, cid) cache.remove(server.id)
.onSuccess { peer -> commitCreated(
commitCreated( serverId = server.id,
serverId = server.id, userName = userName,
userName = userName, link = ShareLinkBuilder.build(
link = ShareLinkBuilder.build( server, info, userName, access.wgConf,
server, info, userName, peer.clientConf, cid, st.sharedVkLink access.client.clientId, st.sharedCallLink
), ),
wgConf = peer.clientConf, wgConf = access.wgConf,
newPeer = WgPeer( newClient = access.client
pubkey = peer.pubkey, )
name = userName, }
ip = peer.ip, .onFailure(::commitCreateError)
lastHandshakeEpoch = null,
hasStoredConf = true,
isSelf = false
)
)
}
.onFailure(::commitCreateError)
} else {
repo.addClient(server.ssh, userName, cid)
.onSuccess {
commitCreated(
serverId = server.id,
userName = userName,
link = ShareLinkBuilder.build(
server, info, userName, null, cid, st.sharedVkLink
),
wgConf = null,
newClient = SharedClient(clientId = cid, name = userName)
)
}
.onFailure(::commitCreateError)
}
} }
} }
@@ -296,18 +268,16 @@ class ShareViewModel(
userName: String, userName: String,
link: String, link: String,
wgConf: String?, wgConf: String?,
newPeer: WgPeer? = null,
newClient: SharedClient? = null newClient: SharedClient? = null
) { ) {
haptics.perform(HapticEvent.SUCCESS) haptics.perform(HapticEvent.SUCCESS)
_uiState.update { cur -> _uiState.update { cur ->
val appendable = cur.selectedServerId == serverId && cur.peersLoaded val appendable = cur.selectedServerId == serverId && cur.clientsLoaded && newClient != null
cur.copy( cur.copy(
creating = false, creating = false,
userName = "", userName = "",
result = ShareResult(userName, link, AccessProtocol.of(wgConf)), result = ShareResult(userName, link, AccessProtocol.of(wgConf)),
peers = if (appendable && newPeer != null) cur.peers + newPeer else cur.peers, clients = if (appendable) cur.clients + newClient else cur.clients
clients = if (appendable && newClient != null) cur.clients + newClient else cur.clients
) )
} }
} }
@@ -319,56 +289,50 @@ class ShareViewModel(
fun dismissResult() = _uiState.update { it.copy(result = null) } fun dismissResult() = _uiState.update { it.copy(result = null) }
fun refreshPeers(force: Boolean = false) { fun refreshClients() {
val st = _uiState.value val st = _uiState.value
val server = st.selectedServer ?: return val server = st.selectedServer ?: return
if (st.peersLoading || (st.peersLoaded && !force)) return if (st.clientsLoading || server.ssh.ip.isBlank()) return
_uiState.update { it.copy(peersLoading = true, peersError = null) } _uiState.update { it.copy(clientsLoading = true, clientsError = null) }
viewModelScope.launch { viewModelScope.launch {
val result = repo.listShared(server.ssh) val result = repo.list(server.ssh)
// Результат SSH относится к уже снятому выбору. // Результат SSH относится к уже снятому выбору.
if (_uiState.value.selectedServerId != server.id) return@launch if (_uiState.value.selectedServerId != server.id) return@launch
result result
.onSuccess { (peers, clients) -> .onSuccess { snap ->
_uiState.update { cache[server.id] = snap
it.copy( _uiState.update { it.copy(clientsLoading = false).withSnapshot(snap) }
peersLoading = false,
peersLoaded = true,
peers = peers,
clients = clients
)
}
} }
.onFailure { e -> .onFailure { e ->
_uiState.update { _uiState.update {
it.copy(peersLoading = false, peersError = e.uiError(appContext)) it.copy(clientsLoading = false, clientsError = e.uiError(appContext))
} }
} }
} }
} }
fun resharePeer(peer: WgPeer) { fun reshare(client: SharedClient) {
val st = _uiState.value val st = _uiState.value
val server = st.selectedServer ?: return val server = st.selectedServer ?: return
val info = st.shareInfo ?: return val info = st.shareInfo ?: return
if (st.resharePubkey != null || !peer.hasStoredConf) return if (st.reshareName != null) return
_uiState.update { it.copy(resharePubkey = peer.pubkey, peersError = null) } _uiState.update { it.copy(reshareName = client.name, clientsError = null) }
viewModelScope.launch { viewModelScope.launch {
val result = repo.peerConf(server.ssh, peer.pubkey, ClientId.generate(), peer.name) val result = repo.conf(server.ssh, client.name)
// Результат SSH относится к уже снятому выбору. // Результат SSH относится к уже снятому выбору.
if (_uiState.value.selectedServerId != server.id) return@launch if (_uiState.value.selectedServerId != server.id) return@launch
result result
.onSuccess { access -> .onSuccess { access ->
_uiState.update { _uiState.update {
it.copy( it.copy(
resharePubkey = null, reshareName = null,
result = ShareResult( result = ShareResult(
userName = peer.name, userName = client.name,
link = ShareLinkBuilder.build( link = ShareLinkBuilder.build(
server, info, peer.name, access.clientConf, server, info, client.name, access.wgConf,
access.clientId, st.sharedVkLink access.client.clientId, it.sharedCallLink
), ),
protocol = AccessProtocol.of(access.clientConf) protocol = AccessProtocol.of(access.wgConf)
) )
) )
} }
@@ -376,34 +340,13 @@ class ShareViewModel(
.onFailure { e -> .onFailure { e ->
haptics.perform(HapticEvent.ERROR) haptics.perform(HapticEvent.ERROR)
_uiState.update { _uiState.update {
it.copy(resharePubkey = null, peersError = e.uiError(appContext)) it.copy(reshareName = null, clientsError = e.uiError(appContext))
} }
} }
} }
} }
fun reshareClient(client: SharedClient) { fun askRevoke(client: SharedClient) = _uiState.update { it.copy(revokeTarget = client) }
val st = _uiState.value
val server = st.selectedServer ?: return
val info = st.shareInfo ?: return
_uiState.update {
it.copy(
result = ShareResult(
userName = client.name,
link = ShareLinkBuilder.build(
server, info, client.name, null, client.clientId, it.sharedVkLink
),
protocol = AccessProtocol.PROXY
)
)
}
}
fun askRevoke(peer: WgPeer) =
_uiState.update { it.copy(revokeTarget = RevokeTarget(name = peer.name, pubkey = peer.pubkey)) }
fun askRevokeClient(client: SharedClient) =
_uiState.update { it.copy(revokeTarget = RevokeTarget(name = client.name, clientId = client.clientId)) }
fun dismissRevoke() { fun dismissRevoke() {
if (_uiState.value.revoking) return if (_uiState.value.revoking) return
@@ -417,18 +360,15 @@ class ShareViewModel(
if (st.revoking) return if (st.revoking) return
_uiState.update { it.copy(revoking = true) } _uiState.update { it.copy(revoking = true) }
viewModelScope.launch { viewModelScope.launch {
val result = repo.remove(server.ssh, target.name)
if (target.pubkey != null) repo.removePeer(server.ssh, target.pubkey)
else repo.removeClient(server.ssh, target.clientId.orEmpty())
result
.onSuccess { .onSuccess {
cache.remove(server.id)
haptics.perform(HapticEvent.SUCCESS) haptics.perform(HapticEvent.SUCCESS)
_uiState.update { _uiState.update {
it.copy( it.copy(
revoking = false, revoking = false,
revokeTarget = null, revokeTarget = null,
peers = it.peers.filterNot { p -> p.pubkey == target.pubkey }, clients = it.clients.filterNot { c -> c.name == target.name }
clients = it.clients.filterNot { c -> c.clientId == target.clientId }
) )
} }
} }
@@ -438,7 +378,7 @@ class ShareViewModel(
it.copy( it.copy(
revoking = false, revoking = false,
revokeTarget = null, revokeTarget = null,
peersError = e.uiError(appContext) clientsError = e.uiError(appContext)
) )
} }
} }
@@ -72,16 +72,16 @@ class FreeturnLinkTest {
dnsServers = "8.8.8.8,8.8.4.4", dnsServers = "8.8.8.8,8.8.4.4",
manualCaptcha = true, manualCaptcha = true,
name = "Тест Юзер", name = "Тест Юзер",
vkLink = "https://vk.com/call/abc", callLink = "https://call.example/call/abc",
wgConf = wgConf wgConf = wgConf
) )
assertEquals(original, FreeturnLink.parse(original.encode()).getOrThrow()) assertEquals(original, FreeturnLink.parse(original.encode()).getOrThrow())
} }
@Test @Test
fun `timing and vk follow go field order`() { fun `timing and call link follow go field order`() {
val goldenJson = """{"v":1,"provider":"vk","peer":"1.2.3.4:56000","obf":"rtpopus",""" + val goldenJson = """{"v":1,"provider":"vk","peer":"1.2.3.4:56000","obf":"rtpopus",""" +
""""key":"${"00".repeat(32)}","timing":20,"name":"Papa","vk":"https://vk.ru/call/join/x"}""" """"key":"${"00".repeat(32)}","timing":20,"name":"Papa","vk":"https://call.example/call/join/x"}"""
val golden = "freeturn://" + Base64.getUrlEncoder().withoutPadding() val golden = "freeturn://" + Base64.getUrlEncoder().withoutPadding()
.encodeToString(goldenJson.toByteArray(Charsets.UTF_8)) .encodeToString(goldenJson.toByteArray(Charsets.UTF_8))
@@ -92,7 +92,7 @@ class FreeturnLinkTest {
obfKey = "00".repeat(32), obfKey = "00".repeat(32),
obfTimingMs = 20, obfTimingMs = 20,
name = "Papa", name = "Papa",
vkLink = "https://vk.ru/call/join/x" callLink = "https://call.example/call/join/x"
) )
assertEquals(golden, link.encode()) assertEquals(golden, link.encode())
} }
@@ -14,14 +14,14 @@ class ShareLinkBuilderTest {
private fun server( private fun server(
useUdp: Boolean = false, useUdp: Boolean = false,
vkLink: String = "", callLink: String = "",
opts: ServerOpts = ServerOpts() opts: ServerOpts = ServerOpts()
) = Server( ) = Server(
name = "Мой сервер", name = "Мой сервер",
client = ClientConfig( client = ClientConfig(
serverAddress = "1.2.3.4:56000", serverAddress = "1.2.3.4:56000",
useUdp = useUdp, useUdp = useUdp,
vkLink = vkLink callLink = callLink
), ),
opts = opts opts = opts
) )
@@ -135,19 +135,19 @@ class ShareLinkBuilderTest {
} }
@Test @Test
fun `vk link stays out of the link by default`() { fun `call link stays out of the link by default`() {
val srv = server(vkLink = "https://vk.com/call/abc") val srv = server(callLink = "https://call.example/call/abc")
val link = FreeturnLink.parse(ShareLinkBuilder.build(srv, ShareInfo(), "u", null)).getOrThrow() val link = FreeturnLink.parse(ShareLinkBuilder.build(srv, ShareInfo(), "u", null)).getOrThrow()
assertEquals("", link.vkLink) assertEquals("", link.callLink)
} }
@Test @Test
fun `vk link from the field carried over`() { fun `call link from the field carried over`() {
val srv = server(vkLink = " https://vk.com/call/abc ") val srv = server(callLink = " https://call.example/call/abc ")
val link = FreeturnLink.parse( val link = FreeturnLink.parse(
ShareLinkBuilder.build(srv, ShareInfo(), "u", null, vkLink = " https://vk.com/call/own ") ShareLinkBuilder.build(srv, ShareInfo(), "u", null, callLink = " https://call.example/call/own ")
).getOrThrow() ).getOrThrow()
assertEquals("https://vk.com/call/own", link.vkLink) assertEquals("https://call.example/call/own", link.callLink)
} }
@Test @Test
@@ -0,0 +1,40 @@
package com.freeturn.app.data.share
import com.freeturn.app.data.control.ClientDto
import com.freeturn.app.data.control.ClientListData
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class SharedClientTest {
@Test
fun `peer fields only with pub`() {
val list = SharedClient.list(
ClientListData(
clients = listOf(
ClientDto(name = "owner", clientId = "a", self = true, ip = "10.13.13.2", pub = "p=", hs = 1700000000),
ClientDto(name = "phone", clientId = "b")
)
)
)
assertEquals(2, list.size)
assertTrue(list[0].isSelf)
assertEquals("10.13.13.2", list[0].wgIp)
assertEquals(1700000000L, list[0].lastHandshakeEpoch)
assertNull(list[1].wgIp)
assertNull(list[1].lastHandshakeEpoch)
}
@Test
fun `zero handshake is never seen`() {
val c = SharedClient.from(ClientDto(name = "x", clientId = "a", ip = "10.0.0.3", pub = "p=", hs = 0))
assertNull(c.lastHandshakeEpoch)
}
@Test
fun `nameless rows are dropped`() {
assertTrue(SharedClient.list(ClientListData(clients = listOf(ClientDto(clientId = "a")))).isEmpty())
}
}
@@ -1,94 +0,0 @@
package com.freeturn.app.data.share
import com.freeturn.app.data.control.ClientDto
import com.freeturn.app.data.control.PeerDto
import com.freeturn.app.data.control.ShareListData
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Base64
class WgPeerParserTest {
private fun nameB64(name: String): String =
Base64.getEncoder().encodeToString(name.toByteArray(Charsets.UTF_8))
@Test
fun `maps peers with names handshake and conf flags`() {
val data = ShareListData(
selfPub = "selfkey=",
peers = listOf(
PeerDto(pub = "selfkey=", ip = "10.13.13.2", hs = 1_760_000_000L, hasConf = false),
PeerDto(pub = "guestkey=", nameB64 = nameB64("Папа"), ip = "10.13.13.3", hs = 0, hasConf = true),
),
)
val peers = WgPeerParser.from(data)
assertEquals(2, peers.size)
val self = peers[0]
assertTrue(self.isSelf)
assertEquals("", self.name)
assertEquals(1_760_000_000L, self.lastHandshakeEpoch)
assertFalse(self.hasStoredConf)
val guest = peers[1]
assertFalse(guest.isSelf)
assertEquals("Папа", guest.name)
assertEquals("10.13.13.3", guest.ip)
assertNull(guest.lastHandshakeEpoch) // hs=0 - ни разу не подключался
assertTrue(guest.hasStoredConf)
}
@Test
fun `broken name b64 falls back to empty`() {
val data = ShareListData(peers = listOf(PeerDto(pub = "k=", nameB64 = "%%%")))
assertEquals("", WgPeerParser.from(data).single().name)
}
@Test
fun `empty data yields empty list`() {
assertTrue(WgPeerParser.from(ShareListData()).isEmpty())
}
@Test
fun `blank pub is skipped`() {
val data = ShareListData(peers = listOf(PeerDto(pub = "")))
assertTrue(WgPeerParser.from(data).isEmpty())
}
@Test
fun `shared clients mapped with names`() {
val data = ShareListData(
clients = listOf(
ClientDto(id = "0123456789abcdef0123456789abcdef", nameB64 = nameB64("Папа")),
ClientDto(id = "fedcba9876543210fedcba9876543210"),
),
)
val clients = SharedClientParser.from(data)
assertEquals(2, clients.size)
assertEquals("0123456789abcdef0123456789abcdef", clients[0].clientId)
assertEquals("Папа", clients[0].name)
assertEquals("", clients[1].name) // без nameB64 -> пусто
}
@Test
fun `shared client without id is skipped`() {
val data = ShareListData(
clients = listOf(
ClientDto(id = ""),
ClientDto(id = "fedcba9876543210fedcba9876543210"),
),
)
assertEquals(
listOf("fedcba9876543210fedcba9876543210"),
SharedClientParser.from(data).map { it.clientId }
)
}
@Test
fun `empty client list yields empty`() {
assertTrue(SharedClientParser.from(ShareListData()).isEmpty())
}
}