Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion app/src/main/java/com/freeturn/app/data/config/ClientConfig.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package com.freeturn.app.data.config

import java.net.URI

internal fun isWorkspaceCallLink(link: String): Boolean = runCatching {
val uri = URI(link.trim())
uri.scheme == "https" && uri.host.equals("calls.myteam.mail.ru", ignoreCase = true)
}.getOrDefault(false)

data class ClientConfig(
val serverAddress: String = "",
val callLink: String = "",
Expand Down Expand Up @@ -28,8 +35,33 @@ data class ClientConfig(
/** true - правила берутся из общего набора (AppPreferences.splitSharedFlow). */
val splitTunnelShared: Boolean = false,
val logsEnabled: Boolean = true,
val clientId: String = ""
val clientId: String = "",
// Empty in older profiles: infer the initial selection from the saved link.
val relaySource: String = "",
val otherRelayCallLink: String = ""
) {
val usesWorkspace: Boolean
get() = provider == Provider.RELAY && workspaceSelected

private val workspaceSelected: Boolean
get() = relaySource == "workspace" ||
(relaySource.isBlank() && isWorkspaceCallLink(callLink))

fun selectWorkspace(selected: Boolean): ClientConfig {
val source = if (selected) "workspace" else "vk"
return if (selected == workspaceSelected) copy(relaySource = source)
else copy(relaySource = source, callLink = otherRelayCallLink, otherRelayCallLink = callLink)
}

fun withCallLink(link: String): ClientConfig {
val trimmed = link.trim()
val target = if (trimmed.isBlank()) this else selectWorkspace(isWorkspaceCallLink(trimmed))
return target.copy(callLink = trimmed)
}

val requiresVkAccount: Boolean
get() = provider == Provider.RELAY && !usesWorkspace

val wireGuardActive: Boolean
get() = tunnelTransport == TunnelTransport.WIREGUARD && wireGuardConfig.isNotBlank()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ fun ClientConfig.toCoreJson(
clientId = clientId.ifBlank { ownClientId },
// Подписок в приложении нет: узел всегда задан руками или ссылкой.
subUrl = "",
provider = provider,
provider = if (usesWorkspace) "workspace" else provider,
// Маршрутами на Android рулит VpnService.
routes = false,
turn = CoreConfigJson.Turn(
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/com/freeturn/app/data/server/ServerJson.kt
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ internal object ServerJson {
put("client", JSONObject().apply {
put("serverAddress", p.client.serverAddress)
put("callLink", p.client.callLink)
put("relaySource", p.client.relaySource)
put("otherRelayCallLink", p.client.otherRelayCallLink)
put("provider", p.client.provider)
put("threads", p.client.threads)
put("streamsPerCred", p.client.streamsPerCred)
Expand Down Expand Up @@ -115,6 +117,8 @@ internal object ServerJson {
client = ClientConfig(
serverAddress = cliO.optString("serverAddress"),
callLink = cliO.optString("callLink"),
relaySource = cliO.optString("relaySource").takeIf { it == "vk" || it == "workspace" }.orEmpty(),
otherRelayCallLink = cliO.optString("otherRelayCallLink"),
provider = cliO.optString("provider", Provider.RELAY).let {
if (it in Provider.VALUES) it else Provider.RELAY
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,11 @@ class ProxyEngine(
* а его хвост не должен оживлять выключённый UI.
*/
private inner class CoreEventSink : EventSink {
override fun onCaptcha(url: String, manual: Boolean) {
if (running == 0L) return
store.setCaptcha(url)
}


override fun onState(state: String, streams: Long, total: Long, errMsg: String) {
val session = running
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ enum class ProxyPhase { Idle, Starting, Connecting, Connected, AuthRequired, Err
*/
@Immutable
data class ProxyStatus(
val captchaUrl: String = "",
val captchaId: Long = 0,
val phase: ProxyPhase = ProxyPhase.Idle,
val active: Int = 0,
val total: Int = 0,
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/java/com/freeturn/app/domain/proxy/ProxyStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ import java.util.concurrent.atomic.AtomicLong
* поэтому пересоздание сервиса состояние не роняет.
*/
class ProxyStore {
private val captchaSeq = AtomicLong(0)
fun setCaptcha(url: String) {
_status.update { it.copy(captchaUrl = url, captchaId = captchaSeq.incrementAndGet()) }
}


private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())

Expand Down
11 changes: 11 additions & 0 deletions app/src/main/java/com/freeturn/app/service/ProxyService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ServiceInfo
import com.freeturn.app.ui.screens.captcha.AutomaticCaptchaWebViewHostController
import android.net.VpnService
import android.os.Build
import android.os.ParcelFileDescriptor
Expand Down Expand Up @@ -382,8 +383,16 @@ class ProxyService : VpnService() {
}

/** Нотификация ведётся тем же состоянием, что видит UI. */
private var autoCaptchaActive = false

private suspend fun observeStatus() {
store.status.collect { status ->
if (status.busy && status.captchaUrl.isNotBlank()) {
AutomaticCaptchaWebViewHostController.show(this@ProxyService, status.captchaUrl, status.captchaId)
} else if (autoCaptchaActive) {
AutomaticCaptchaWebViewHostController.clear()
}
autoCaptchaActive = status.busy && status.captchaUrl.isNotBlank()
// После решения об остановке молчим: нотификация уже снята.
if (stopping.get()) return@collect
notifier.update(status, tunnelMode, provider)
Expand Down Expand Up @@ -484,6 +493,8 @@ class ProxyService : VpnService() {

@Synchronized
private fun teardown(reason: String) {
AutomaticCaptchaWebViewHostController.clear()
store.setCaptcha("")
val session = this.session
notifier.cancelAuthAlert()
// Причина обязательна: по логу после гибернации надо отличать команду пользователя
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.freeturn.app.ui.screens.captcha

import android.annotation.SuppressLint
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.webkit.WebView
import android.webkit.WebViewClient
import java.net.URI
import java.util.Locale

internal fun isLocalCaptchaUrl(url: String): Boolean = runCatching {
val uri = URI(url)
val host = uri.host?.lowercase(Locale.ROOT)
uri.scheme?.lowercase(Locale.ROOT) == "http" &&
uri.rawUserInfo == null &&
uri.port == 8765 &&
(host == "127.0.0.1" || host == "localhost")
}.getOrDefault(false)

object AutomaticCaptchaWebViewHostController {
private val main = Handler(Looper.getMainLooper())
private var webView: WebView? = null
private var loadedChallengeId = Long.MIN_VALUE

fun show(context: android.content.Context, url: String, challengeId: Long) {
val safeUrl = url.takeIf(::isLocalCaptchaUrl).orEmpty()
main.post {
if (safeUrl.isBlank()) return@post
if (loadedChallengeId == challengeId) return@post
destroyWebView()
loadedChallengeId = challengeId
clearCaptchaCookies {
if (loadedChallengeId == challengeId) {
webView = createCaptchaWebView(context.applicationContext).also { view ->
view.onResume()
view.loadUrl(safeUrl)
}
}
}
}
}

fun clear() {
main.post {
loadedChallengeId = Long.MIN_VALUE
destroyWebView()
clearCaptchaCookies()
}
}

private fun destroyWebView() {
webView?.apply {
stopLoading()
loadUrl("about:blank")
onPause()
destroy()
}
webView = null
}

private fun clearCaptchaCookies(onCleared: () -> Unit = {}) {
// The CAPTCHA proxy has its own cookie jar. VK account login uses the
// shared Android cookie store, which must survive challenge cleanup.
onCleared()
}
}

@SuppressLint("SetJavaScriptEnabled")
private fun createCaptchaWebView(context: android.content.Context) = WebView(context).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Keep the renderer bound to this app while the VPN foreground service is active,
// even though the hidden CAPTCHA view is not on screen.
setRendererPriorityPolicy(WebView.RENDERER_PRIORITY_BOUND, false)
}
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.allowContentAccess = false
settings.allowFileAccess = false
settings.userAgentString = settings.userAgentString.replace("; wv)", ")")
webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView,
request: android.webkit.WebResourceRequest
): Boolean = !isLocalCaptchaUrl(request.url.toString())
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,8 @@ fun ClientSetupScreen(

fun persistFields() {
clientEdit { current ->
current.copy(
current.withCallLink(callLink).copy(
serverAddress = serverAddress.trim(),
callLink = callLink.trim(),
threads = threads.roundToInt(),
streamsPerCred = streamsPerCred.roundToInt(),
localPort = localPort.trim(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ fun HomeScreen(
},
onSaveCallLink = { serverConfigViewModel.setActiveCallLink(it) },
onSetProvider = { serverConfigViewModel.setActiveProvider(it) },
onSetWorkspace = { serverConfigViewModel.setActiveWorkspace(it) },
onOpenVkAccount = {
scope.launch { sheetScaffoldState.bottomSheetState.partialExpand() }
vkAuthViewModel.openAccountSheet()
Expand Down Expand Up @@ -196,7 +197,7 @@ fun HomeScreen(
if (status.busy) {
HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_OFF)
proxyViewModel.stop()
} else if (clientConfig.provider == Provider.RELAY && !vkAuth.sessionActive) {
} else if (clientConfig.requiresVkAccount && !vkAuth.sessionActive) {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
vkAuthViewModel.openWebLogin(startProxyOnSuccess = true)
} else {
Expand All @@ -207,7 +208,7 @@ fun HomeScreen(
)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
val reducedMotion = LocalReducedMotion.current
val showVkBanner = clientConfig.provider == Provider.RELAY &&
val showVkBanner = clientConfig.requiresVkAccount &&
(!vkAuth.sessionActive || status.phase == ProxyPhase.AuthRequired)
AnimatedVisibility(
visible = showVkBanner,
Expand Down
86 changes: 50 additions & 36 deletions app/src/main/java/com/freeturn/app/ui/screens/home/ServersSheet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ internal fun ServersSheetContent(
onOpenServerSettings: (String) -> Unit = {},
onSaveCallLink: (String) -> Unit = {},
onSetProvider: (String) -> Unit = {},
onSetWorkspace: (Boolean) -> Unit = {},
onOpenVkAccount: () -> Unit = {}
) {
val active = snapshot.active
Expand Down Expand Up @@ -146,11 +147,12 @@ internal fun ServersSheetContent(
current = active?.client?.provider ?: Provider.RELAY,
editable = providerEditable,
showLockHint = active != null && providerLocked,
callLink = callLink,
usesWorkspace = active?.client?.usesWorkspace == true,
vkSessionActive = vkSessionActive,
vkDisplayName = vkDisplayName,
vkAvatarPath = vkAvatarPath,
onProvider = onSetProvider,
onWorkspace = onSetWorkspace,
onEditCallLink = { showCallLinkDialog = true },
onOpenVkAccount = onOpenVkAccount,
modifier = Modifier.padding(horizontal = Spacing.lg)
Expand Down Expand Up @@ -213,11 +215,12 @@ private fun ProviderPicker(
current: String,
editable: Boolean,
showLockHint: Boolean,
callLink: String,
usesWorkspace: Boolean,
vkSessionActive: Boolean,
vkDisplayName: String,
vkAvatarPath: String,
onProvider: (String) -> Unit,
onWorkspace: (Boolean) -> Unit,
onEditCallLink: () -> Unit,
onOpenVkAccount: () -> Unit,
modifier: Modifier = Modifier
Expand Down Expand Up @@ -250,40 +253,51 @@ private fun ProviderPicker(
else shrinkVertically(MaterialTheme.motionScheme.fastSpatialSpec()) +
fadeOut(MaterialTheme.motionScheme.fastEffectsSpec())
) {
SettingsGroup {
Surface(
shape = settingsItemShape(0, 2),
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier.fillMaxWidth()
) {
SettingsEntryRow(
iconRes = R.drawable.link_24px,
title = stringResource(R.string.call_link_label),
trailingRes = if (editable) R.drawable.edit_24px else null,
enabled = editable,
onClick = onEditCallLink
)
}
Surface(
shape = settingsItemShape(1, 2),
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier.fillMaxWidth()
) {
SettingsEntryRow(
iconRes = R.drawable.person_24px,
title = stringResource(R.string.vk_account_title),
subtitle = if (vkSessionActive) {
vkDisplayName.ifBlank { stringResource(R.string.vk_account_status_active) }
} else {
stringResource(R.string.vk_account_status_required)
},
iconContainer = if (vkSessionActive) extended.successContainer
else MaterialTheme.colorScheme.tertiaryContainer,
iconTint = if (vkSessionActive) extended.onSuccessContainer
else MaterialTheme.colorScheme.onTertiaryContainer,
iconBitmap = vkAvatar,
onClick = onOpenVkAccount
)
Column(verticalArrangement = Arrangement.spacedBy(Spacing.sm)) {
ConnectedChoiceRow(
options = listOf(
ChoiceOption(false, stringResource(R.string.vk_account_title)),
ChoiceOption(true, stringResource(R.string.workspace_source_label))
),
selected = usesWorkspace,
onSelect = onWorkspace,
enabled = editable
)
SettingsGroup {
Surface(
shape = settingsItemShape(0, if (usesWorkspace) 1 else 2),
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier.fillMaxWidth()
) {
SettingsEntryRow(
iconRes = R.drawable.link_24px,
title = stringResource(if (usesWorkspace) R.string.workspace_call_link_label else R.string.call_link_label),
trailingRes = if (editable) R.drawable.edit_24px else null,
enabled = editable,
onClick = onEditCallLink
)
}
if (!usesWorkspace) Surface(
shape = settingsItemShape(1, 2),
color = MaterialTheme.colorScheme.surfaceContainerHigh,
modifier = Modifier.fillMaxWidth()
) {
SettingsEntryRow(
iconRes = R.drawable.person_24px,
title = stringResource(R.string.vk_account_title),
subtitle = if (vkSessionActive) {
vkDisplayName.ifBlank { stringResource(R.string.vk_account_status_active) }
} else {
stringResource(R.string.vk_account_status_required)
},
iconContainer = if (vkSessionActive) extended.successContainer
else MaterialTheme.colorScheme.tertiaryContainer,
iconTint = if (vkSessionActive) extended.onSuccessContainer
else MaterialTheme.colorScheme.onTertiaryContainer,
iconBitmap = vkAvatar,
onClick = onOpenVkAccount
)
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ class ServerConfigViewModel(
}
}

fun setActiveCallLink(link: String) = updateActiveClient { it.copy(callLink = link.trim()) }
fun setActiveCallLink(link: String) = updateActiveClient { it.withCallLink(link) }

fun setActiveWorkspace(selected: Boolean) = updateActiveClient { it.selectWorkspace(selected) }

fun setActiveProvider(provider: String) = updateActiveClient { it.copy(provider = provider) }

Expand Down
Loading
Loading