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
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ dependencies {
implementation(files(layout.projectDirectory.file("libs/freeturn.aar")))

implementation(libs.androidx.core.splashscreen)
implementation(libs.androidx.webkit)
implementation(libs.jsch)
implementation(libs.bouncycastle)
implementation(libs.kotlinx.coroutines.android)
Expand Down
5 changes: 4 additions & 1 deletion app/src/main/java/com/freeturn/app/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,10 @@ class App : Application() {
// без прогрева эта задержка достаётся первому нажатию "Запустить".
private fun warmUpCore() {
scope.launch(Dispatchers.IO) {
runCatching { engine.version }
runCatching {
engine.version
engine.refreshVkSession()
}
// Обычно это провал загрузки нативной библиотеки - запуск всё равно
// упадёт, но уже без внятной причины в логе.
.onFailure { log.add("Ядро не загрузилось: ${it.message}", LogLevel.Error) }
Expand Down
54 changes: 47 additions & 7 deletions app/src/main/java/com/freeturn/app/data/AppPreferences.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import com.freeturn.app.data.server.Server
import com.freeturn.app.data.server.ServerJson
import com.freeturn.app.data.server.ServerOpts
import com.freeturn.app.data.server.ServersSnapshot
import com.freeturn.app.domain.proxy.VkAccountProfile
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
Expand Down Expand Up @@ -48,7 +49,6 @@ class AppPreferences(context: Context) {
private val V5_SETUP_NOTICE_PENDING = booleanPreferencesKey("v5_setup_notice_pending")
val DYNAMIC_THEME = booleanPreferencesKey("dynamic_theme")
val NERD_MODE = booleanPreferencesKey("nerd_mode")
val ADVANCED_CAPTCHA = booleanPreferencesKey("advanced_captcha")
val PRIVACY_MODE = booleanPreferencesKey("privacy_mode")
val SEASONAL_DECOR = booleanPreferencesKey("seasonal_decor")
val TG_SUBSCRIBE_SHOWN = booleanPreferencesKey("tg_subscribe_shown")
Expand All @@ -71,8 +71,13 @@ class AppPreferences(context: Context) {
val OWN_CLIENT_ID = stringPreferencesKey("own_client_id")
val PROXY_DESIRED = booleanPreferencesKey("proxy_desired")
val AUTO_CONNECT = booleanPreferencesKey("auto_connect")
val NOTIFICATION_SPEED = booleanPreferencesKey("notification_speed")
val CLEAN_EXIT = booleanPreferencesKey("clean_exit")
val REPORTED_PROCESS_EXITS = stringSetPreferencesKey("reported_process_exits")
val VK_ACCOUNT_NAME = stringPreferencesKey("vk_account_name")
val VK_ACCOUNT_SCREEN_NAME = stringPreferencesKey("vk_account_screen_name")
val VK_ACCOUNT_USER_ID = longPreferencesKey("vk_account_user_id")
val VK_ACCOUNT_AVATAR_PATH = stringPreferencesKey("vk_account_avatar_path")
}

// Намерение пользователя переживает смерть процесса, поэтому пишется своим scope:
Expand Down Expand Up @@ -192,8 +197,6 @@ class AppPreferences(context: Context) {

val nerdModeFlow: Flow<Boolean> = prefFlow { prefs -> prefs[NERD_MODE] ?: true }

val advancedCaptchaFlow: Flow<Boolean> = prefFlow { prefs -> prefs[ADVANCED_CAPTCHA] ?: false }

val privacyModeFlow: Flow<Boolean> = prefFlow { prefs -> prefs[PRIVACY_MODE] ?: false }

// Сезонное оформление главного экрана. По умолчанию включено: это часть облика
Expand Down Expand Up @@ -238,6 +241,41 @@ class AppPreferences(context: Context) {
// приложения поднимало VPN, которого пользователь не просил (и отбирало tun у чужого).
val autoConnectFlow: Flow<Boolean> = prefFlow { prefs -> prefs[AUTO_CONNECT] ?: false }

// Показ скорости и трафика в постоянном уведомлении. По умолчанию выключен:
// без него сервис не опрашивает счётчики и не перерисовывает нотификацию каждые 2 с.
val notificationSpeedFlow: Flow<Boolean> = prefFlow { prefs -> prefs[NOTIFICATION_SPEED] ?: false }

val vkAccountProfileFlow: Flow<VkAccountProfile> = prefFlow { prefs ->
VkAccountProfile(
displayName = prefs[VK_ACCOUNT_NAME].orEmpty(),
screenName = prefs[VK_ACCOUNT_SCREEN_NAME].orEmpty(),
userId = prefs[VK_ACCOUNT_USER_ID] ?: 0L,
avatarPath = prefs[VK_ACCOUNT_AVATAR_PATH].orEmpty(),
)
}.distinctUntilChanged()

suspend fun setVkAccountProfile(profile: VkAccountProfile) {
context.dataStore.edit { prefs ->
prefs[VK_ACCOUNT_NAME] = profile.displayName
prefs[VK_ACCOUNT_SCREEN_NAME] = profile.screenName
prefs[VK_ACCOUNT_USER_ID] = profile.userId
if (profile.avatarPath.isNotBlank()) {
prefs[VK_ACCOUNT_AVATAR_PATH] = profile.avatarPath
} else {
prefs.remove(VK_ACCOUNT_AVATAR_PATH)
}
}
}

suspend fun clearVkAccountProfile() {
context.dataStore.edit { prefs ->
prefs.remove(VK_ACCOUNT_NAME)
prefs.remove(VK_ACCOUNT_SCREEN_NAME)
prefs.remove(VK_ACCOUNT_USER_ID)
prefs.remove(VK_ACCOUNT_AVATAR_PATH)
}
}

/** Не suspend: зовётся с путей, где вызывающий вот-вот умрёт (см. [desiredScope]). */
fun setProxyDesired(desired: Boolean) {
desiredScope.launch {
Expand Down Expand Up @@ -385,10 +423,6 @@ class AppPreferences(context: Context) {
context.dataStore.edit { prefs -> prefs[NERD_MODE] = enabled }
}

suspend fun setAdvancedCaptcha(enabled: Boolean) {
context.dataStore.edit { prefs -> prefs[ADVANCED_CAPTCHA] = enabled }
}

suspend fun setPrivacyMode(enabled: Boolean) {
context.dataStore.edit { prefs -> prefs[PRIVACY_MODE] = enabled }
}
Expand All @@ -405,6 +439,10 @@ class AppPreferences(context: Context) {
context.dataStore.edit { it[AUTO_CONNECT] = enabled }
}

suspend fun setNotificationSpeed(enabled: Boolean) {
context.dataStore.edit { it[NOTIFICATION_SPEED] = enabled }
}

suspend fun setHotspotProxyEnabled(enabled: Boolean) {
context.dataStore.edit { it[HOTSPOT_PROXY] = enabled }
}
Expand Down Expand Up @@ -478,6 +516,7 @@ class AppPreferences(context: Context) {
seasonalDecor = seasonalDecorFlow.first(),
restartServerOnSwitch = restartServerOnSwitchFlow.first(),
autoConnect = autoConnectFlow.first(),
notificationSpeed = notificationSpeedFlow.first(),
hotspotProxy = hotspotProxyEnabledFlow.first(),
suppressUpdatePrompt = suppressUpdatePromptFlow.first(),
suppressTgPrompt = suppressTgPromptFlow.first(),
Expand Down Expand Up @@ -511,6 +550,7 @@ class AppPreferences(context: Context) {
prefs[SEASONAL_DECOR] = data.seasonalDecor
prefs[RESTART_SERVER_ON_SWITCH] = data.restartServerOnSwitch
prefs[AUTO_CONNECT] = data.autoConnect
prefs[NOTIFICATION_SPEED] = data.notificationSpeed
prefs[HOTSPOT_PROXY] = data.hotspotProxy
prefs[SUPPRESS_UPDATE_PROMPT] = data.suppressUpdatePrompt
prefs[SUPPRESS_TG_PROMPT] = data.suppressTgPrompt
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ data class BackupData(
val splitSharedMode: String? = null,
val splitSharedApps: String = "",
val themeMode: String = ThemeMode.SYSTEM,
val amoled: Boolean = false
val amoled: Boolean = false,
val notificationSpeed: Boolean = false
)

/** Сериализация [BackupData] в JSON (серверы - через тот же [ServerJson], что и в DataStore). */
Expand All @@ -53,6 +54,7 @@ object SettingsBackup {
}
put("themeMode", data.themeMode)
put("amoled", data.amoled)
put("notificationSpeed", data.notificationSpeed)
}.toString()

fun decode(json: String): BackupData {
Expand Down Expand Up @@ -85,7 +87,8 @@ object SettingsBackup {
splitSharedMode = o.optString("splitSharedMode").takeIf { it.isNotBlank() },
splitSharedApps = o.optString("splitSharedApps"),
themeMode = ThemeMode.normalize(o.optString("themeMode")),
amoled = o.optBoolean("amoled", false)
amoled = o.optBoolean("amoled", false),
notificationSpeed = o.optBoolean("notificationSpeed", false)
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ data class ClientConfig(
val streamsPerCred: Int = DEFAULT_STREAMS_PER_CRED,
val useUdp: Boolean = false,
val bond: Boolean = false,
val manualCaptcha: Boolean = false,
val localPort: String = DEFAULT_LOCAL_PORT,
val debugMode: Boolean = false,
val useCarrierDns: Boolean = true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,6 @@ data class CoreConfigJson(
data class Relay(
val links: List<String>,
val streamsPerCred: Int,
val manualCaptcha: Boolean,
val autoCaptcha: Boolean = true,
val advancedCaptcha: Boolean = false,
val platform: String,
)

Expand Down Expand Up @@ -112,7 +109,6 @@ fun ClientConfig.toCoreJson(
srv: ServerOpts,
carrierDns: String? = null,
ownClientId: String = "",
advancedCaptchaEnabled: Boolean = false,
): String {
val dnsServers = coreDnsServers { carrierDns }

Expand Down Expand Up @@ -149,9 +145,6 @@ fun ClientConfig.toCoreJson(
links = listOf(callLink),
streamsPerCred = streamsPerCred.takeIf { it > 0 }
?: ClientConfig.DEFAULT_STREAMS_PER_CRED,
manualCaptcha = manualCaptcha,
autoCaptcha = true,
advancedCaptcha = advancedCaptchaEnabled && !manualCaptcha,
platform = CoreConfigJson.PLATFORM_MOBILE,
),
obf = CoreConfigJson.Obf(
Expand Down
2 changes: 0 additions & 2 deletions app/src/main/java/com/freeturn/app/data/server/ServerJson.kt
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ internal object ServerJson {
put("streamsPerCred", p.client.streamsPerCred)
put("useUdp", p.client.useUdp)
put("bond", p.client.bond)
put("manualCaptcha", p.client.manualCaptcha)
put("localPort", p.client.localPort)
put("debugMode", p.client.debugMode)
put("useCarrierDns", p.client.useCarrierDns)
Expand Down Expand Up @@ -123,7 +122,6 @@ internal object ServerJson {
streamsPerCred = cliO.optInt("streamsPerCred", ClientConfig.DEFAULT_STREAMS_PER_CRED),
useUdp = cliO.optBoolean("useUdp", false),
bond = cliO.optBoolean("bond", false),
manualCaptcha = cliO.optBoolean("manualCaptcha", false),
localPort = cliO.optString("localPort", ClientConfig.DEFAULT_LOCAL_PORT),
debugMode = cliO.optBoolean("debugMode", false),
useCarrierDns = cliO.optBoolean("useCarrierDns", true),
Expand Down
3 changes: 0 additions & 3 deletions app/src/main/java/com/freeturn/app/data/share/FreeturnLink.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ data class FreeturnLink(
val listen: String = "",
val dnsMode: String = "",
val dnsServers: String = "",
val manualCaptcha: Boolean = false,
/** ARQ tcp-режима; null - у получателя останется дефолт ядра. */
val kcp: KcpProfile? = null,
val name: String = "",
Expand All @@ -50,7 +49,6 @@ data class FreeturnLink(
if (listen.isNotEmpty()) sb.field("listen", jsonString(listen))
if (dnsMode.isNotEmpty()) sb.field("dns", jsonString(dnsMode))
if (dnsServers.isNotEmpty()) sb.field("dnss", jsonString(dnsServers))
if (manualCaptcha) sb.field("mcap", "true")
if (kcp != null) sb.field("kcp", kcpJson(kcp))
if (name.isNotEmpty()) sb.field("name", jsonString(name))
if (callLink.isNotEmpty()) sb.field("vk", jsonString(callLink))
Expand Down Expand Up @@ -94,7 +92,6 @@ data class FreeturnLink(
listen = o.optString("listen"),
dnsMode = o.optString("dns"),
dnsServers = o.optString("dnss"),
manualCaptcha = o.optBoolean("mcap", false),
kcp = o.optJSONObject("kcp")?.let(::parseKcp),
name = o.optString("name"),
callLink = o.optString("vk"),
Expand Down
6 changes: 6 additions & 0 deletions app/src/main/java/com/freeturn/app/di/AppModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,16 @@ import com.freeturn.app.domain.proxy.ProxyLog
import com.freeturn.app.domain.proxy.ProxyOrchestrator
import com.freeturn.app.domain.proxy.ProxyServiceLauncher
import com.freeturn.app.domain.proxy.ProxyStore
import com.freeturn.app.domain.proxy.VkSessionVerifier
import com.freeturn.app.domain.proxy.VkVerifier
import com.freeturn.app.service.AndroidProxyServiceLauncher
import com.freeturn.app.domain.ssh.SSHManager
import com.freeturn.app.domain.server.ServerSetupRepository
import com.freeturn.app.domain.share.ShareRepository
import com.freeturn.app.domain.ssh.SshRepository
import com.freeturn.app.viewmodel.share.ImportViewModel
import com.freeturn.app.viewmodel.proxy.ProxyViewModel
import com.freeturn.app.viewmodel.proxy.VkAuthViewModel
import com.freeturn.app.viewmodel.server.ServerSetupViewModel
import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
Expand All @@ -26,6 +29,7 @@ import com.freeturn.app.viewmodel.share.ShareViewModel
import com.freeturn.app.ui.util.AndroidHaptics
import com.freeturn.app.viewmodel.Haptics
import org.koin.android.ext.koin.androidContext
import org.koin.core.module.dsl.viewModel
import org.koin.core.module.dsl.viewModelOf
import org.koin.dsl.module
import java.io.File
Expand All @@ -34,6 +38,7 @@ val appModule = module {
single { AppPreferences(androidContext()) }
single { ProxyStore() }
single { PingMeter(androidContext()) }
single<VkVerifier> { VkSessionVerifier(androidContext()) }
single { ProxyLog(File(androidContext().filesDir, "logs")) }
single<ProxyServiceLauncher> { AndroidProxyServiceLauncher(androidContext(), get(), get()) }
// Ядро одно на процесс: сессия переживает пересоздание сервиса.
Expand All @@ -54,6 +59,7 @@ val appModule = module {
single<Haptics> { AndroidHaptics(androidContext()) }

viewModelOf(::ProxyViewModel)
viewModel { VkAuthViewModel(get(), get(), get(), get(), get()) }
viewModelOf(::ServerViewModel)
viewModelOf(::SettingsViewModel)
viewModelOf(::ServerConfigViewModel)
Expand Down
9 changes: 7 additions & 2 deletions app/src/main/java/com/freeturn/app/domain/proxy/LogFile.kt
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ internal class LogFile(dir: File) {
is Cmd.Line -> batch.appendEntry(stamp, cmd.at, cmd.level, cmd.text)
is Cmd.Clear -> {
batch.setLength(0)
runCatching { current.delete(); previous.delete() }
try {
current.delete()
previous.delete()
} catch (_: Exception) {
}
}
is Cmd.Export -> {
flush(stamp, batch)
Expand Down Expand Up @@ -106,12 +110,13 @@ internal class LogFile(dir: File) {
}.getOrDefault(false)

private fun write(text: String) {
runCatching {
try {
if (current.length() > MAX_BYTES) {
previous.delete()
current.renameTo(previous)
}
current.appendText(text)
} catch (_: Exception) {
}
}

Expand Down
37 changes: 37 additions & 0 deletions app/src/main/java/com/freeturn/app/domain/proxy/PhysicalNetwork.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.freeturn.app.domain.proxy

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities

/**
* Выбирает лучшую физическую (не VPN) сеть с выходом в интернет:
* Ethernet -> Wi-Fi -> Cellular -> прочие.
*/
@Suppress("DEPRECATION")
internal fun findPhysicalNetwork(cm: ConnectivityManager): Network? {
val candidates = cm.allNetworks.mapNotNull { net ->
val caps = cm.getNetworkCapabilities(net) ?: return@mapNotNull null
if (caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN) ||
!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ||
!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
) {
return@mapNotNull null
}
val rank = when {
caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> 0
caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> 1
caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> 2
else -> 3
}
rank to net
}
return candidates.minByOrNull { it.first }?.second
}

internal fun findPhysicalNetwork(context: Context): Network? {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
?: return null
return findPhysicalNetwork(cm)
}
Loading