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